This commit is contained in:
Dobie Wollert
2015-12-16 09:12:35 -08:00
parent f9c9672818
commit f94ca33b9e
805 changed files with 67409 additions and 24609 deletions

4
node_modules/bluebird/LICENSE generated vendored
View File

@ -1,13 +1,13 @@
The MIT License (MIT)
Copyright (c) 2014 Petka Antonov
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:</p>
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.

644
node_modules/bluebird/README.md generated vendored
View File

@ -5,657 +5,25 @@
[![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](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance
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.
# Topics
- [Features](#features)
- [Quick start](#quick-start)
- [API Reference and examples](API.md)
- [Support](#support)
- [What are promises and why should I use them?](#what-are-promises-and-why-should-i-use-them)
- [Questions and issues](#questions-and-issues)
- [Error handling](#error-handling)
- [Development](#development)
- [Testing](#testing)
- [Benchmarking](#benchmarks)
- [Custom builds](#custom-builds)
- [For library authors](#for-library-authors)
- [What is the sync build?](#what-is-the-sync-build)
- [License](#license)
- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)
- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)
- [Changelog](changelog.md)
- [Optimization guide](#optimization-guide)
# Features
<img src="http://petkaantonov.github.io/bluebird/logo.png" alt="bluebird logo" align="right" />
- [Promises A+](http://promisesaplus.com)
- [Synchronous inspection](API.md#synchronous-inspection)
- [Concurrency coordination](API.md#collections)
- [Promisification on steroids](API.md#promisification)
- [Resource management through a parallel of python `with`/C# `using`](API.md#resource-management)
- [Cancellation and timeouts](API.md#cancellation)
- [Parallel for C# `async` and `await`](API.md#generators)
- Mind blowing utilities such as
- [`.bind()`](API.md#binddynamic-thisarg---promise)
- [`.call()`](API.md#callstring-propertyname--dynamic-arg---promise)
- [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise)
- [And](API.md#core) [much](API.md#timers) [more](API.md#utility)!
- [Practical debugging solutions and sane defaults](#error-handling)
- [Sick performance](benchmark/)
<hr>
# Quick start
## Node.js
npm install bluebird
Then:
```js
var Promise = require("bluebird");
```
## Browsers
There are many ways to use bluebird in browsers:
- Direct downloads
- Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js)
- Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js)
- You may use browserify on the main export
- You may use the [bower](http://bower.io) package.
When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available.
A [minimal bluebird browser build](#custom-builds) is &asymp;38.92KB minified*, 11.65KB gzipped and has no external dependencies.
*Google Closure Compiler using Simple.
#### Browser support
Browsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported.
[![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov)
**Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`.
Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+.
After quick start, see [API Reference and examples](API.md)
<hr>
# Support
- Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js)
- IRC: #promises @freenode
- StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird)
- Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open)
<hr>
# What are promises and why should I use them?
You should use promises to turn this:
```js
fs.readFile("file.json", function(err, val) {
if( err ) {
console.error("unable to read file");
}
else {
try {
val = JSON.parse(val);
console.log(val.success);
}
catch( e ) {
console.error("invalid json in file");
}
}
});
```
Into this:
```js
fs.readFileAsync("file.json").then(JSON.parse).then(function(val) {
console.log(val.success);
})
.catch(SyntaxError, function(e) {
console.error("invalid json in file");
})
.catch(function(e) {
console.error("unable to read file")
});
```
*If you are wondering "there is no `readFileAsync` method on `fs` that returns a promise", see [promisification](API.md#promisification)*
Actually you might notice the latter has a lot in common with code that would do the same using synchronous I/O:
```js
try {
var val = JSON.parse(fs.readFileSync("file.json"));
console.log(val.success);
}
//Syntax actually not supported in JS but drives the point
catch(SyntaxError e) {
console.error("invalid json in file");
}
catch(Error e) {
console.error("unable to read file")
}
```
And that is the point - being able to have something that is a lot like `return` and `throw` in synchronous code.
You can also use promises to improve code that was written with callback helpers:
```js
//Copyright Plato http://stackoverflow.com/a/19385911/995876
//CC BY-SA 2.5
mapSeries(URLs, function (URL, done) {
var options = {};
needle.get(URL, options, function (error, response, body) {
if (error) {
return done(error)
}
try {
var ret = JSON.parse(body);
return done(null, ret);
}
catch (e) {
done(e);
}
});
}, function (err, results) {
if (err) {
console.log(err)
} else {
console.log('All Needle requests successful');
// results is a 1 to 1 mapping in order of URLs > needle.body
processAndSaveAllInDB(results, function (err) {
if (err) {
return done(err)
}
console.log('All Needle requests saved');
done(null);
});
}
});
```
Is more pleasing to the eye when done with promises:
```js
Promise.promisifyAll(needle);
var options = {};
var current = Promise.resolve();
Promise.map(URLs, function(URL) {
current = current.then(function () {
return needle.getAsync(URL, options);
});
return current;
}).map(function(responseAndBody){
return JSON.parse(responseAndBody[1]);
}).then(function (results) {
return processAndSaveAllInDB(results);
}).then(function(){
console.log('All Needle requests saved');
}).catch(function (e) {
console.log(e);
});
```
Also promises don't just give you correspondences for synchronous features but can also be used as limited event emitters or callback aggregators.
More reading:
- [Promise nuggets](https://promise-nuggets.github.io/)
- [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html)
- [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1)
- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)
- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)
For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x).
# Questions and issues
If you find a bug in bluebird or have a feature request, file an issue in the [github issue tracker](https://github.com/petkaantonov/bluebird/issues). 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`.
# Error handling
This is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled.
There are two common pragmatic attempts at solving the problem that promise libraries do.
The more popular one is to have the user explicitly communicate that they are done and any unhandled rejections should be thrown, like so:
```js
download().then(...).then(...).done();
```
For handling this problem, in my opinion, this is completely unacceptable and pointless. The user must remember to explicitly call `.done` and that cannot be justified when the problem is forgetting to create an error handler in the first place.
The second approach, which is what bluebird by default takes, is to call a registered handler if a rejection is unhandled by the start of a second turn. The default handler is to write the stack trace to `stderr` or `console.error` in browsers. This is close to what happens with synchronous code - your code doesn't work as expected and you open console and see a stack trace. Nice.
Of course this is not perfect, if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages. In that case you can use the `.done()` method to signal that any hanging exceptions should be thrown.
If you want to override the default handler for these possibly unhandled rejections, you can pass yours like so:
```js
Promise.onPossiblyUnhandledRejection(function(error){
throw error;
});
```
If you want to also enable long stack traces, call:
```js
Promise.longStackTraces();
```
right after the library is loaded.
In node.js use the environment flag `BLUEBIRD_DEBUG`:
```
BLUEBIRD_DEBUG=1 node server.js
```
to enable long stack traces in all instances of bluebird.
Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, even after using every trick to optimize them.
Long stack traces are enabled by default in the debug build.
#### Expected and unexpected errors
A practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about.
Now, Javascript does have a perfectly fine and working way of creating error type hierarchies. It is still quite awkward to use them with the built-in `try-catch` however:
```js
try {
//code
}
catch(e) {
if( e instanceof WhatIWantError) {
//handle
}
else {
throw e;
}
}
```
Without such checking, unexpected errors would be silently swallowed. However, with promises, bluebird brings the future (hopefully) here now and extends the `.catch` to [accept potential error type eligibility](API.md#catchfunction-errorclass-function-handler---promise).
For instance here it is expected that some evil or incompetent entity will try to crash our server from `SyntaxError` by providing syntactically invalid JSON:
```js
getJSONFromSomewhere().then(function(jsonString) {
return JSON.parse(jsonString);
}).then(function(object) {
console.log("it was valid json: ", object);
}).catch(SyntaxError, function(e){
console.log("don't be evil");
});
```
Here any kind of unexpected error will automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`.
Ok, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors?
Bluebird defines a special error type `OperationalError` (you can get a reference from `Promise.OperationalError`). This type of error is given as rejection reason by promisified methods when
their underlying library gives an untyped, but expected error. Primitives such as strings, and error objects that are directly created like `new Error("database didn't respond")` are considered untyped.
Example of such library is the node core library `fs`. So if we promisify it, we can catch just the errors we want pretty easily and have programmer errors be redirected to unhandled rejection handler so that we notice them:
```js
//Read more about promisification in the API Reference:
//API.md
var fs = Promise.promisifyAll(require("fs"));
fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
console.log("Successful json")
}).catch(SyntaxError, function (e) {
console.error("file contains invalid json");
}).catch(Promise.OperationalError, function (e) {
console.error("unable to read file, because: ", e.message);
});
```
The last `catch` handler is only invoked when the `fs` module explicitly used the `err` argument convention of async callbacks to inform of an expected error. The `OperationalError` instance will contain the original error in its `.cause` property but it does have a direct copy of the `.message` and `.stack` too. In this code any unexpected error - be it in our code or the `fs` module - would not be caught by these handlers and therefore not swallowed.
Since a `catch` handler typed to `Promise.OperationalError` is expected to be used very often, it has a neat shorthand:
```js
.error(function (e) {
console.error("unable to read file, because: ", e.message);
});
```
See [API documentation for `.error()`](API.md#error-rejectedhandler----promise)
Finally, Bluebird also supports predicate-based filters. If you pass a
predicate function instead of an error type, the predicate will receive
the error as an argument. The return result will be used to determine whether
the error handler should be called.
Predicates should allow for very fine grained control over caught errors:
pattern matching, error typesets with set operations and many other techniques
can be implemented on top of them.
Example of using a predicate-based filter:
```js
var Promise = require("bluebird");
var request = Promise.promisify(require("request"));
function clientError(e) {
return e.code >= 400 && e.code < 500;
}
request("http://www.google.com").then(function(contents){
console.log(contents);
}).catch(clientError, function(e){
//A client error like 400 Bad Request happened
});
```
**Danger:** The JavaScript language allows throwing primitive values like strings. Throwing primitives can lead to worse or no stack traces. Primitives [are not exceptions](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/). You should consider always throwing Error objects when handling exceptions.
<hr>
#### How do long stack traces differ from e.g. Q?
Bluebird attempts to have more elaborate traces. Consider:
```js
Error.stackTraceLimit = 25;
Q.longStackSupport = true;
Q().then(function outer() {
return Q().then(function inner() {
return Q().then(function evenMoreInner() {
a.b.c.d();
}).catch(function catcher(e){
console.error(e.stack);
});
})
});
```
You will see
ReferenceError: a is not defined
at evenMoreInner (<anonymous>:7:13)
From previous event:
at inner (<anonymous>:6:20)
Compare to:
```js
Error.stackTraceLimit = 25;
Promise.longStackTraces();
Promise.resolve().then(function outer() {
return Promise.resolve().then(function inner() {
return Promise.resolve().then(function evenMoreInner() {
a.b.c.d()
}).catch(function catcher(e){
console.error(e.stack);
});
});
});
```
ReferenceError: a is not defined
at evenMoreInner (<anonymous>:7:13)
From previous event:
at inner (<anonymous>:6:36)
From previous event:
at outer (<anonymous>:5:32)
From previous event:
at <anonymous>:4:21
at Object.InjectedScript._evaluateOn (<anonymous>:572:39)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:531:52)
at Object.InjectedScript.evaluate (<anonymous>:450:21)
A better and more practical example of the differences can be seen in gorgikosev's [debuggability competition](https://github.com/spion/async-compare#debuggability).
<hr>
# Development
For development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies.
Install [node](http://nodejs.org/) and [npm](https://npmjs.org/)
git clone git@github.com:petkaantonov/bluebird.git
cd bluebird
npm install
## Testing
To run all tests, run
node tools/test
If you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+:
node-dev --harmony tools/test
You may specify an individual test file to run with the `--run` script flag:
node tools/test --run=cancel.js
This enables output from the test and may give a better idea where the test is failing. The paramter to `--run` can be any file name located in `test/mocha` folder.
#### Testing in browsers
To run the test in a browser instead of node, pass the flag `--browser` to the test tool
node tools/test --run=cancel.js --browser
This will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled.
Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active.
#### Supported options by the test tool
The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`.
- `--run=String`. Which tests to run (or compile when testing in browser). Default `"all"`. Can also be a glob string (relative to ./test/mocha folder)
- `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `"html"` (use `--cover` to use default reporter).
- `--browser` - Whether to compile tests for browsers. Default `false`.
- `--port=Number` - Whe port where local server is hosted when testing in browser. Default `9999`
- `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`.
- `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`.
- `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`.
- `--js-hint` - Whether to run JSHint on source files. Default `true`.
- `--saucelabs` Wheter to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser.Default `false`.
## Benchmarks
To run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too).
Node 0.11.2+ is required to run the generator examples.
### 1\. DoxBee sequential
Currently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections.
Command: `bench doxbee`
### 2\. Made-up parallel
This made-up scenario runs 15 shimmed queries in parallel.
Command: `bench parallel`
## Custom builds
Custom builds for browsers are supported through a command-line utility.
<table>
<caption>The following features can be disabled</caption>
<thead>
<tr>
<th>Feature(s)</th>
<th>Command line identifier</th>
</tr>
</thead>
<tbody>
<tr><td><a href="API.md#any---promise"><code>.any</code></a> and <a href="API.md#promiseanyarraydynamicpromise-values---promise"><code>Promise.any</code></a></td><td><code>any</code></td></tr>
<tr><td><a href="API.md#race---promise"><code>.race</code></a> and <a href="API.md#promiseracearraypromise-promises---promise"><code>Promise.race</code></a></td><td><code>race</code></td></tr>
<tr><td><a href="API.md#callstring-propertyname--dynamic-arg---promise"><code>.call</code></a> and <a href="API.md#getstring-propertyname---promise"><code>.get</code></a></td><td><code>call_get</code></td></tr>
<tr><td><a href="API.md#filterfunction-filterer---promise"><code>.filter</code></a> and <a href="API.md#promisefilterarraydynamicpromise-values-function-filterer---promise"><code>Promise.filter</code></a></td><td><code>filter</code></td></tr>
<tr><td><a href="API.md#mapfunction-mapper---promise"><code>.map</code></a> and <a href="API.md#promisemaparraydynamicpromise-values-function-mapper---promise"><code>Promise.map</code></a></td><td><code>map</code></td></tr>
<tr><td><a href="API.md#reducefunction-reducer--dynamic-initialvalue---promise"><code>.reduce</code></a> and <a href="API.md#promisereducearraydynamicpromise-values-function-reducer--dynamic-initialvalue---promise"><code>Promise.reduce</code></a></td><td><code>reduce</code></td></tr>
<tr><td><a href="API.md#props---promise"><code>.props</code></a> and <a href="API.md#promisepropsobjectpromise-object---promise"><code>Promise.props</code></a></td><td><code>props</code></td></tr>
<tr><td><a href="API.md#settle---promise"><code>.settle</code></a> and <a href="API.md#promisesettlearraydynamicpromise-values---promise"><code>Promise.settle</code></a></td><td><code>settle</code></td></tr>
<tr><td><a href="API.md#someint-count---promise"><code>.some</code></a> and <a href="API.md#promisesomearraydynamicpromise-values-int-count---promise"><code>Promise.some</code></a></td><td><code>some</code></td></tr>
<tr><td><a href="API.md#nodeifyfunction-callback---promise"><code>.nodeify</code></a></td><td><code>nodeify</code></td></tr>
<tr><td><a href="API.md#promisecoroutinegeneratorfunction-generatorfunction---function"><code>Promise.coroutine</code></a> and <a href="API.md#promisespawngeneratorfunction-generatorfunction---promise"><code>Promise.spawn</code></a></td><td><code>generators</code></td></tr>
<tr><td><a href="API.md#progression">Progression</a></td><td><code>progress</code></td></tr>
<tr><td><a href="API.md#promisification">Promisification</a></td><td><code>promisify</code></td></tr>
<tr><td><a href="API.md#cancellation">Cancellation</a></td><td><code>cancel</code></td></tr>
<tr><td><a href="API.md#timers">Timers</a></td><td><code>timers</code></td></tr>
<tr><td><a href="API.md#resource-management">Resource management</a></td><td><code>using</code></td></tr>
</tbody>
</table>
Make sure you have cloned the repo somewhere and did `npm install` successfully.
After that you can run:
node tools/build --features="core"
The above builds the most minimal build you can get. You can add more features separated by spaces from the above list:
node tools/build --features="core filter map reduce"
The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features.
Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build
a full version afterwards (after having taken a copy of the bluebird.js somewhere):
node tools/build --debug --main --zalgo --browser --minify
#### Supported options by the build tool
The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`.
- `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`.
- `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`.
- `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`.
- `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`.
- `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`.
- `--features=String` - See [custom builds](#custom-builds)
<hr>
## For library authors
Building a library that depends on bluebird? You should know about a few features.
If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file
that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains:
```js
//NOTE the function call right after
module.exports = require("bluebird/js/main/promise")();
```
Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic.
You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API.
<hr>
## What is the sync build?
You may now use sync build by:
var Promise = require("bluebird/zalgo");
The sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards.
The normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility
of stack overflow errors and non-deterministic behavior.
The sync build skips the async call trampoline completely, e.g code like:
async.invoke( this.fn, this, val );
Appears as this in the sync build:
this.fn(val);
This should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism.
Note that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads.
```js
var cache = new Map(); //ES6 Map or DataStructures/Map or whatever...
function getResult(url) {
var resolver = Promise.pending();
if (cache.has(url)) {
resolver.resolve(cache.get(url));
}
else {
http.get(url, function(err, content) {
if (err) resolver.reject(err);
else {
cache.set(url, content);
resolver.resolve(content);
}
});
}
return resolver.promise;
}
//The result of console.log is truly random without async guarantees
function guessWhatItPrints( url ) {
var i = 3;
getResult(url).then(function(){
i = 4;
});
console.log(i);
}
```
# Optimization guide
Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome.
A single cohesive guide compiled from the articles will probably be done eventually.
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`.
# License
The MIT License (MIT)
Copyright (c) 2014 Petka Antonov
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

1
node_modules/bluebird/changelog.md generated vendored Normal file
View File

@ -0,0 +1 @@
[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html)

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

55
node_modules/bluebird/js/release/assert.js generated vendored Normal file
View File

@ -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($_len - 2); 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;
};
})();

157
node_modules/bluebird/js/release/async.js generated vendored Normal file
View File

@ -0,0 +1,157 @@
"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._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.isStatic ? schedule(this.drainQueues) : schedule;
}
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));
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 {
if (schedule.isStatic) {
schedule = function(fn) { setTimeout(fn, 0); };
}
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;

67
node_modules/bluebird/js/release/bind.js generated vendored Normal file
View File

@ -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);
};
};

11
node_modules/bluebird/js/release/bluebird.js generated vendored Normal file
View File

@ -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;

123
node_modules/bluebird/js/release/call_get.js generated vendored Normal file
View File

@ -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($_len - 1); 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);
};
};

125
node_modules/bluebird/js/release/cancel.js generated vendored Normal file
View File

@ -0,0 +1,125 @@
"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();
child = promise;
promise = parent;
}
}
};
Promise.prototype._branchHasCancelled = function() {
this._branchesRemainingToCancel--;
};
Promise.prototype._enoughBranchesHaveCancelled = function() {
return this._branchesRemainingToCancel === undefined ||
this._branchesRemainingToCancel <= 0;
};
Promise.prototype._cancelBy = function(canceller) {
if (canceller === this) {
this._branchesRemainingToCancel = 0;
this._invokeOnCancel();
return true;
} else {
this._branchHasCancelled();
if (this._enoughBranchesHaveCancelled()) {
this._invokeOnCancel();
return true;
}
}
return false;
};
Promise.prototype._cancelBranched = function() {
if (this._enoughBranchesHaveCancelled()) {
this._cancel();
}
};
Promise.prototype._cancel = function() {
if (!this.isCancellable()) return;
this._setCancelled();
async.invoke(this._cancelPromises, this, undefined);
};
Promise.prototype._cancelPromises = function() {
if (this._length() > 0) this._settlePromises();
};
Promise.prototype._unsetOnCancel = function() {
this._onCancelField = undefined;
};
Promise.prototype.isCancellable = function() {
return this.isPending() && !this.isCancelled();
};
Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
if (util.isArray(onCancelCallback)) {
for (var i = 0; i < onCancelCallback.length; ++i) {
this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
}
} else if (onCancelCallback !== undefined) {
if (typeof onCancelCallback === "function") {
if (!internalOnly) {
var e = tryCatch(onCancelCallback).call(this._boundValue());
if (e === errorObj) {
this._attachExtraTrace(e.e);
async.throwLater(e.e);
}
}
} else {
onCancelCallback._resultCancelled(this);
}
}
};
Promise.prototype._invokeOnCancel = function() {
var onCancelCallback = this._onCancel();
this._unsetOnCancel();
async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
};
Promise.prototype._invokeInternalOnCancel = function() {
if (this.isCancellable()) {
this._doInvokeOnCancel(this._onCancel(), true);
this._unsetOnCancel();
}
};
Promise.prototype._resultCancelled = function() {
this.cancel();
};
};

42
node_modules/bluebird/js/release/catch_filter.js generated vendored Normal file
View File

@ -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;
};

69
node_modules/bluebird/js/release/context.js generated vendored Normal file
View File

@ -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;
};

812
node_modules/bluebird/js/release/debuggability.js generated vendored Normal file
View File

@ -0,0 +1,812 @@
"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 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")));
Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
2097152);
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 2097152) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue();
this._setUnhandledRejectionIsNotified();
fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 262144;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~262144);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 1048576;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~1048576);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
return warn(message, shouldUseOwnTrace, promise || this);
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
var disableLongStackTraces = function() {};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
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) {
config.warnings = !!opts.warnings;
}
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;
}
};
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) {
if (returnValue === undefined &&
promiseCreated !== null &&
config.longStackTraces &&
config.warnings) {
var msg = "a promise was created in a " + name +
" handler but was not returned from it";
promise._warn(msg, true, promiseCreated);
}
}
function deprecated(name, replacement) {
var message = name +
" is deprecated and will be removed in a future version.";
if (replacement) message += " Use " + replacement + " instead.";
return warn(message);
}
function warn(message, shouldUseOwnTrace, promise) {
if (!config.warnings) return;
var warning = new Warning(message);
var ctx;
if (shouldUseOwnTrace) {
promise._attachExtraTrace(warning);
} else if (config.longStackTraces && (ctx = Promise._peekContext())) {
ctx.attachExtraTrace(warning);
} else {
var parsed = parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
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);
}
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent(name, reason, promise);
} catch (e) {
globalEventFired = true;
async.throwLater(e);
}
var domEventFired = false;
if (fireDomEvent) {
try {
domEventFired = fireDomEvent(name.toLowerCase(), {
reason: reason,
promise: promise
});
} catch (e) {
domEventFired = true;
async.throwLater(e);
}
}
if (!globalEventFired && !localEventFired && !domEventFired &&
name === "unhandledRejection") {
formatAndLogError(reason, "Unhandled rejection ");
}
}
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;
})([]);
var fireDomEvent;
var fireGlobalEvent = (function() {
if (util.isNode) {
return function(name, reason, promise) {
if (name === "rejectionHandled") {
return process.emit(name, promise);
} else {
return process.emit(name, reason, promise);
}
};
} else {
var customEventWorks = false;
var anyEventWorks = true;
try {
var ev = new self.CustomEvent("test");
customEventWorks = ev instanceof CustomEvent;
} catch (e) {}
if (!customEventWorks) {
try {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
self.dispatchEvent(event);
} catch (e) {
anyEventWorks = false;
}
}
if (anyEventWorks) {
fireDomEvent = function(type, detail) {
var event;
if (customEventWorks) {
event = new self.CustomEvent(type, {
detail: detail,
bubbles: false,
cancelable: true
});
} else if (self.dispatchEvent) {
event = document.createEvent("CustomEvent");
event.initCustomEvent(type, false, true, detail);
}
return event ? !self.dispatchEvent(event) : false;
};
}
var toWindowMethodNameMap = {};
toWindowMethodNameMap["unhandledRejection"] = ("on" +
"unhandledRejection").toLowerCase();
toWindowMethodNameMap["rejectionHandled"] = ("on" +
"rejectionHandled").toLowerCase();
return function(name, reason, promise) {
var methodName = toWindowMethodNameMap[name];
var method = self[methodName];
if (!method) return false;
if (name === "rejectionHandled") {
method.call(self, promise);
} else {
method.call(self, reason, promise);
}
return true;
};
}
})();
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
};
if (longStackTraces) Promise.longStackTraces();
return {
longStackTraces: function() {
return config.longStackTraces;
},
warnings: function() {
return config.warnings;
},
cancellation: function() {
return config.cancellation;
},
propagateFromFunction: function() {
return propagateFromFunction;
},
boundValueFunction: function() {
return boundValueFunction;
},
checkForgottenReturns: checkForgottenReturns,
setBounds: setBounds,
warn: warn,
deprecated: deprecated,
CapturedTrace: CapturedTrace
};
};

46
node_modules/bluebird/js/release/direct_resolve.js generated vendored Normal file
View File

@ -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);
}
};
};

29
node_modules/bluebird/js/release/each.js generated vendored Normal file
View File

@ -0,0 +1,29 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
var PromiseAll = Promise.all;
function promiseAllThis() {
return PromiseAll(this);
}
function PromiseMapSeries(promises, fn) {
return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
}
Promise.prototype.each = function (fn) {
return this.mapSeries(fn)
._then(promiseAllThis, undefined, undefined, this, undefined);
};
Promise.prototype.mapSeries = function (fn) {
return PromiseReduce(this, fn, INTERNAL, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseMapSeries(promises, fn)
._then(promiseAllThis, undefined, undefined, promises, undefined);
};
Promise.mapSeries = PromiseMapSeries;
};

111
node_modules/bluebird/js/release/errors.js generated vendored Normal file
View File

@ -0,0 +1,111 @@
"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
});
notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};

100
node_modules/bluebird/js/release/finally.js generated vendored Normal file
View File

@ -0,0 +1,100 @@
"use strict";
module.exports = function(Promise, tryConvertToPromise) {
var util = require("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
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.type === 0
? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue);
if (ret !== undefined) {
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, {
promise: this,
handler: handler,
called: false,
cancelPromise: null,
type: type
}, 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 finallyHandler;
};

204
node_modules/bluebird/js/release/generators.js generated vendored Normal file
View File

@ -0,0 +1,204 @@
"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) {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
promise._setOnCancel(this);
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function"
? [yieldHandler].concat(yieldHandlers)
: yieldHandlers;
this._yieldedPromise = null;
}
util.inherits(PromiseSpawn, Proxyable);
PromiseSpawn.prototype._isResolved = function() {
return this.promise === null;
};
PromiseSpawn.prototype._cleanup = function() {
this._promise = this._generator = 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();
if (result === errorObj && result.e === reason) {
result = null;
}
} else {
this._promise._pushContext();
result = tryCatch(this._generator["return"]).call(this._generator,
undefined);
this._promise._popContext();
}
var promise = this._promise;
this._cleanup();
if (result === errorObj) {
promise._rejectCallback(result.e, false);
} else {
promise.cancel();
}
};
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();
return promise._rejectCallback(result.e, false);
}
var value = result.value;
if (result.done === true) {
this._cleanup();
return promise._resolveCallback(value);
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise =
promiseFromYieldHandler(maybePromise,
this._yieldHandlers,
this._promise);
if (maybePromise === null) {
this._promiseRejected(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)
);
return;
}
}
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
this._yieldedPromise = maybePromise;
maybePromise._proxy(this, null);
} else if (((bitField & 33554432) !== 0)) {
this._promiseFulfilled(maybePromise._value());
} else if (((bitField & 16777216) !== 0)) {
this._promiseRejected(maybePromise._reason());
} else {
this._promiseCancelled();
}
}
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
var ret = spawn.promise();
spawn._generator = generator;
spawn._promiseFulfilled(undefined);
return ret;
};
};
Promise.coroutine.addYieldHandler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
debug.deprecated("Promise.spawn()", "Promise.coroutine()");
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};

149
node_modules/bluebird/js/release/join.js generated vendored Normal file
View File

@ -0,0 +1,149 @@
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
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) { \n\
'use strict'; \n\
function [TheName](fn) { \n\
[TheProperties] \n\
this.fn = fn; \n\
this.now = 0; \n\
} \n\
[TheName].prototype.checkFulfillment = function(promise) { \n\
var now = ++this.now; \n\
if (now === [TheTotal]) { \n\
promise._pushContext(); \n\
var callback = this.fn; \n\
var ret = tryCatch(callback)([ThePassedArguments]); \n\
promise._popContext(); \n\
if (ret === errorObj) { \n\
promise._rejectCallback(ret.e, false); \n\
} else { \n\
promise._resolveCallback(ret); \n\
} \n\
} \n\
}; \n\
\n\
[TheName].prototype._resultCancelled = function() { \n\
[CancellationCode] \n\
}; \n\
\n\
return [TheName]; \n\
}(tryCatch, errorObj, Promise); \n\
";
code = code.replace(/\[TheName\]/g, name)
.replace(/\[TheTotal\]/g, total)
.replace(/\[ThePassedArguments\]/g, passedArguments)
.replace(/\[TheProperties\]/g, assignment)
.replace(/\[CancellationCode\]/g, cancellationCode);
return new Function("tryCatch", "errorObj", "Promise", code)
(tryCatch, errorObj, Promise);
};
var holderClasses = [];
var thenCallbacks = [];
var promiseSetters = [];
for (var i = 0; i < 8; ++i) {
holderClasses.push(generateHolderClass(i + 1));
thenCallbacks.push(thenCallback(i + 1));
promiseSetters.push(promiseSetter(i + 1));
}
reject = function (reason) {
this._reject(reason);
};
}}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!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);
} else if (((bitField & 33554432) !== 0)) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else if (((bitField & 16777216) !== 0)) {
ret._reject(maybePromise._reason());
} else {
ret._cancel();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
if (!ret._isFateSealed()) {
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
}
return ret;
}
}
}
var $_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;
};
};

151
node_modules/bluebird/js/release/map.js generated vendored Normal file
View File

@ -0,0 +1,151 @@
"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 EMPTY_ARRAY = [];
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : domain.bind(fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
this._init$(undefined, -2);
}
util.inherits(MappingPromiseArray, PromiseArray);
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (index < 0) {
index = (index * -1) - 1;
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return true;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return false;
}
if (preservedValues !== null) preservedValues[index] = value;
var promise = this._promise;
var callback = this._callback;
var receiver = promise._boundValue();
promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
preservedValues !== null ? "Promise.filter" : "Promise.map",
promise
);
if (ret === errorObj) {
this._reject(ret.e);
return true;
}
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
if (limit >= 1) this._inFlight++;
values[index] = maybePromise;
maybePromise._proxy(this, (index + 1) * -1);
return false;
} else if (((bitField & 33554432) !== 0)) {
ret = maybePromise._value();
} else if (((bitField & 16777216) !== 0)) {
this._reject(maybePromise._reason());
return true;
} else {
this._cancel();
return true;
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
return true;
}
return false;
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var limit = typeof options === "object" && options !== null
? options.concurrency
: 0;
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);
};
};

55
node_modules/bluebird/js/release/method.js generated vendored Normal file
View File

@ -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);
}
};
};

51
node_modules/bluebird/js/release/nodeback.js generated vendored Normal file
View File

@ -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($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];};
promise._fulfill(args);
}
promise = null;
};
}
module.exports = nodebackForPromise;

58
node_modules/bluebird/js/release/nodeify.js generated vendored Normal file
View File

@ -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;
};
};

755
node_modules/bluebird/js/release/promise.js generated vendored Normal file
View File

@ -0,0 +1,755 @@
"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 finallyHandler = 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();
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
return this._then(reflectHandler,
reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, undefined, undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject) {
var promise =
this._then(didFulfill, didReject, undefined, undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
return this.all()._then(fn, undefined, undefined, APPLY, undefined);
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
if (arguments.length > 0) {
this._warn(".all() was passed arguments but it does not take any");
}
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = Promise.fromCallback = function(fn) {
var ret = new Promise(INTERNAL);
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));
}
var prev = async._schedule;
async._schedule = fn;
return prev;
};
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;
}
}
}
var domain = getDomain();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
value = target._rejectionHandler0;
handler = didFulfill;
} else if (((bitField & 16777216) !== 0)) {
value = target._fulfillmentHandler0;
handler = didReject;
target._unsetRejectionIsUnhandled();
} else {
settler = target._settlePromiseLateCancellationObserver;
value = new CancellationError("late cancellation observer");
target._attachExtraTrace(value);
handler = didReject;
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" && domain.bind(handler)),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
}
return promise;
};
Promise.prototype._length = function () {
return this._bitField & 65535;
};
Promise.prototype._isFateSealed = function () {
return (this._bitField & 117506048) !== 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 67108864) === 67108864;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -65536) |
(len & 65535);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 33554432;
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 16777216;
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 67108864;
};
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;
};
Promise.prototype._setAsyncGuaranteed = function() {
this._bitField = this._bitField | 134217728;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0 ? this._receiver0 : this[
index * 4 - 4 + 3];
if (ret === UNDEFINED_BINDING) {
return undefined;
} else if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return this[
index * 4 - 4 + 2];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return this[
index * 4 - 4 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return this[
index * 4 - 4 + 1];
};
Promise.prototype._boundValue = function() {};
Promise.prototype._migrateCallback0 = function (follower) {
var bitField = follower._bitField;
var fulfill = follower._fulfillmentHandler0;
var reject = follower._rejectionHandler0;
var promise = follower._promise0;
var receiver = follower._receiverAt(0);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._migrateCallbackAt = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
promise,
receiver,
domain
) {
var index = this._length();
if (index >= 65535 - 4) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : domain.bind(reject);
}
} else {
var base = index * 4 - 4;
this[base + 2] = promise;
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : domain.bind(reject);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._proxy = function (proxyable, arg) {
this._addCallbacks(undefined, undefined, arg, proxyable, null);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (((this._bitField & 117506048) !== 0)) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
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 || x === promise) {
var err = x === promise ? makeSelfResolutionError() : x.e;
promise._rejectCallback(err, false);
} else {
debug.checkForgottenReturns(x, promiseCreated, "", promise);
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 (handler === finallyHandler) {
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) {
if (((bitField & 134217728) !== 0)) {
this._settlePromises();
} else {
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, debug);
Promise.Promise = Promise;
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
require('./timers.js')(Promise, INTERNAL);
require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
require('./nodeify.js')(Promise);
require('./call_get.js')(Promise);
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('./promisify.js')(Promise, INTERNAL);
require('./any.js')(Promise);
require('./each.js')(Promise, INTERNAL);
require('./filter.js')(Promise, INTERNAL);
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;
};

184
node_modules/bluebird/js/release/promise_array.js generated vendored Normal file
View File

@ -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;
};

314
node_modules/bluebird/js/release/promisify.js generated vendored Normal file
View File

@ -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);
};
};

118
node_modules/bluebird/js/release/props.js generated vendored Normal file
View File

@ -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);
};
};

49
node_modules/bluebird/js/release/race.js generated vendored Normal file
View File

@ -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);
};
};

162
node_modules/bluebird/js/release/reduce.js generated vendored Normal file
View File

@ -0,0 +1,162 @@
"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 : domain.bind(fn);
if (initialValue !== undefined) {
initialValue = Promise.resolve(initialValue);
initialValue._attachCancellationCallback(this);
}
this._initialValue = initialValue;
this._currentCancellable = null;
this._eachValues = _each === INTERNAL ? [] : undefined;
this._promise._captureStackTrace();
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._gotAccum = function(accum) {
if (this._eachValues !== undefined && accum !== INTERNAL) {
this._eachValues.push(accum);
}
};
ReductionPromiseArray.prototype._eachComplete = function(value) {
this._eachValues.push(value);
return this._eachValues;
};
ReductionPromiseArray.prototype._init = function() {};
ReductionPromiseArray.prototype._resolveEmptyArray = function() {
this._resolve(this._eachValues !== undefined ? this._eachValues
: this._initialValue);
};
ReductionPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
ReductionPromiseArray.prototype._resolve = function(value) {
this._promise._resolveCallback(value);
this._values = null;
};
ReductionPromiseArray.prototype._resultCancelled = function(sender) {
if (sender === this._initialValue) return this._cancel();
if (this._isResolved()) return;
this._resultCancelled$();
if (this._currentCancellable instanceof Promise) {
this._currentCancellable.cancel();
}
if (this._initialValue instanceof Promise) {
this._initialValue.cancel();
}
};
ReductionPromiseArray.prototype._iterate = function (values) {
this._values = values;
var value;
var i;
var length = values.length;
if (this._initialValue !== undefined) {
value = this._initialValue;
i = 0;
} else {
value = Promise.resolve(values[0]);
i = 1;
}
this._currentCancellable = value;
if (!value.isRejected()) {
for (; i < length; ++i) {
var ctx = {
accum: null,
value: values[i],
index: i,
length: length,
array: this
};
value = value._then(gotAccum, undefined, undefined, ctx, undefined);
}
}
if (this._eachValues !== undefined) {
value = value
._then(this._eachComplete, undefined, undefined, this, undefined);
}
value._then(completed, completed, undefined, value, this);
};
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
function completed(valueOrReason, array) {
if (this.isFulfilled()) {
array._resolve(valueOrReason);
} else {
array._reject(valueOrReason);
}
}
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
function gotAccum(accum) {
this.accum = accum;
this.array._gotAccum(accum);
var value = tryConvertToPromise(this.value, this.array._promise);
if (value instanceof Promise) {
this.array._currentCancellable = value;
return value._then(gotValue, undefined, undefined, this, undefined);
} else {
return gotValue.call(this, value);
}
}
function gotValue(value) {
var array = this.array;
var promise = array._promise;
var fn = tryCatch(array._fn);
promise._pushContext();
var ret;
if (array._eachValues !== undefined) {
ret = fn.call(promise._boundValue(), value, this.index, this.length);
} else {
ret = fn.call(promise._boundValue(),
this.accum, value, this.index, this.length);
}
if (ret instanceof Promise) {
array._currentCancellable = ret;
}
var promiseCreated = promise._popContext();
debug.checkForgottenReturns(
ret,
promiseCreated,
array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
promise
);
return ret;
}
};

35
node_modules/bluebird/js/release/schedule.js generated vendored Normal file
View File

@ -0,0 +1,35 @@
"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");
};
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 MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
window.navigator.standalone)) {
schedule = function(fn) {
var div = document.createElement("div");
var observer = new MutationObserver(fn);
observer.observe(div, {attributes: true});
return function() { div.classList.toggle("foo"); };
};
schedule.isStatic = true;
} 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;

43
node_modules/bluebird/js/release/settle.js generated vendored Normal file
View File

@ -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);
};
};

148
node_modules/bluebird/js/release/some.js generated vendored Normal file
View File

@ -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;
};

View File

@ -0,0 +1,96 @@
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}
PromiseInspection.prototype._settledValue = function() {
return this._settledValueField;
};
var value = PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var reason = PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
return (this._bitField & 33554432) !== 0;
};
var isRejected = PromiseInspection.prototype.isRejected = function () {
return (this._bitField & 16777216) !== 0;
};
var isPending = PromiseInspection.prototype.isPending = function () {
return (this._bitField & 50397184) === 0;
};
var isResolved = PromiseInspection.prototype.isResolved = function () {
return (this._bitField & 50331648) !== 0;
};
PromiseInspection.prototype.isCancelled =
Promise.prototype._isCancelled = function() {
return (this._bitField & 65536) === 65536;
};
Promise.prototype.isCancelled = function() {
return this._target()._isCancelled();
};
Promise.prototype.isPending = function() {
return isPending.call(this._target());
};
Promise.prototype.isRejected = function() {
return isRejected.call(this._target());
};
Promise.prototype.isFulfilled = function() {
return isFulfilled.call(this._target());
};
Promise.prototype.isResolved = function() {
return isResolved.call(this._target());
};
Promise.prototype.value = function() {
return value.call(this._target());
};
Promise.prototype.reason = function() {
var target = this._target();
target._unsetRejectionIsUnhandled();
return reason.call(target);
};
Promise.prototype._value = function() {
return this._settledValue();
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue();
};
Promise.PromiseInspection = PromiseInspection;
};

82
node_modules/bluebird/js/release/thenables.js generated vendored Normal file
View File

@ -0,0 +1,82 @@
"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) {
return hasProp.call(obj, "_promise0");
}
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;
};

66
node_modules/bluebird/js/release/timers.js generated vendored Normal file
View File

@ -0,0 +1,66 @@
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = require("./util");
var TimeoutError = Promise.TimeoutError;
var afterTimeout = function (promise, message, parent) {
if (!promise.isPending()) return;
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);
parent.cancel();
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (ms, value) {
var ret;
if (value !== undefined) {
ret = Promise.resolve(value)
._then(afterValue, null, null, ms, undefined);
} else {
ret = new Promise(INTERNAL);
setTimeout(function() { ret._fulfill(); }, +ms);
}
ret._setAsyncGuaranteed();
return ret;
};
Promise.prototype.delay = function (ms) {
return delay(ms, this);
};
function successClear(value) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
return value;
}
function failureClear(reason) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var parent = this.then();
var ret = parent.then();
var handle = setTimeout(function timeoutTimeout() {
afterTimeout(ret, message, parent);
}, ms);
return ret._then(successClear, failureClear, undefined, handle, undefined);
};
};

225
node_modules/bluebird/js/release/using.js generated vendored Normal file
View File

@ -0,0 +1,225 @@
"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;
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();
};
};

344
node_modules/bluebird/js/release/util.js generated vendored Normal file
View File

@ -0,0 +1,344 @@
"use strict";
var es5 = require("./es5");
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
var tryCatchTarget;
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 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 obj instanceof Error && 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;
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
asArray: asArray,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
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
};
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;

135
node_modules/bluebird/package.json generated vendored

File diff suppressed because one or more lines are too long

6
node_modules/colors/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,6 @@
language: node_js
node_js:
- "0.11"
- "0.10"
- "0.8"
- "0.6"

23
node_modules/colors/MIT-LICENSE.txt generated vendored Normal file
View File

@ -0,0 +1,23 @@
Original Library
- Copyright (c) Marak Squires
Additional Functionality
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.

167
node_modules/colors/ReadMe.md generated vendored Normal file
View File

@ -0,0 +1,167 @@
# colors.js
## get color and style in your node.js console
<img src="https://github.com/Marak/colors.js/raw/master/screenshots/colors.png"/>
## Installation
npm install colors
## colors and styles!
### text colors
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
- gray
- grey
### background colors
- bgBlack
- bgRed
- bgGreen
- bgYellow
- bgBlue
- bgMagenta
- bgCyan
- bgWhite
### styles
- reset
- bold
- dim
- italic
- underline
- inverse
- hidden
- strikethrough
### extras
- rainbow
- zebra
- america
- trap
- random
## Usage
By popular demand, `colors` now ships with two types of usages!
The super nifty way
```js
var colors = require('colors');
console.log('hello'.green); // outputs green text
console.log('i like cake and pies'.underline.red) // outputs red underlined text
console.log('inverse the color'.inverse); // inverses the color
console.log('OMG Rainbows!'.rainbow); // rainbow
console.log('Run the trap'.trap); // Drops the bass
```
or a slightly less nifty way which doesn't extend `String.prototype`
```js
var colors = require('colors/safe');
console.log(colors.green('hello')); // outputs green text
console.log(colors.red.underline('i like cake and pies')) // outputs red underlined text
console.log(colors.inverse('inverse the color')); // inverses the color
console.log(colors.rainbow('OMG Rainbows!')); // rainbow
console.log(colors.trap('Run the trap')); // Drops the bass
```
I prefer the first way. Some people seem to be afraid of extending `String.prototype` and prefer the second way.
If you are writing good code you will never have an issue with the first approach. If you really don't want to touch `String.prototype`, the second usage will not touch `String` native object.
## Disabling Colors
To disable colors you can pass the following arguments in the command line to your application:
```bash
node myapp.js --no-color
```
## Console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data)
```js
var name = 'Marak';
console.log(colors.green('Hello %s'), name);
// outputs -> 'Hello Marak'
```
## Custom themes
### Using standard API
```js
var colors = require('colors');
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
```
### Using string safe API
```js
var colors = require('colors/safe');
// set single property
var error = colors.red;
error('this is red');
// set theme
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log(colors.error("this is an error"));
// outputs yellow text
console.log(colors.warn("this is a warning"));
```
*Protip: There is a secret undocumented style in `colors`. If you find the style you can summon him.*

74
node_modules/colors/examples/normal-usage.js generated vendored Normal file
View File

@ -0,0 +1,74 @@
var colors = require('../lib/index');
console.log("First some yellow text".yellow);
console.log("Underline that text".yellow.underline);
console.log("Make it bold and red".red.bold);
console.log(("Double Raindows All Day Long").rainbow)
console.log("Drop the bass".trap)
console.log("DROP THE RAINBOW BASS".trap.rainbow)
console.log('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported
console.log('So '.green + 'are'.underline + ' ' + 'inverse'.inverse + ' styles! '.yellow.bold); // styles not widely supported
console.log("Zebras are so fun!".zebra);
//
// Remark: .strikethrough may not work with Mac OS Terminal App
//
console.log("This is " + "not".strikethrough + " fun.");
console.log('Background color attack!'.black.bgWhite)
console.log('Use random styles on everything!'.random)
console.log('America, Heck Yeah!'.america)
console.log('Setting themes is useful')
//
// Custom themes
//
console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
// outputs grey text
console.log("this is an input".input);
console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
colors.setTheme(__dirname + '/../themes/generic-logging.js');
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
// outputs grey text
console.log("this is an input".input);
//console.log("Don't summon".zalgo)

76
node_modules/colors/examples/safe-string.js generated vendored Normal file
View File

@ -0,0 +1,76 @@
var colors = require('../safe');
console.log(colors.yellow("First some yellow text"));
console.log(colors.yellow.underline("Underline that text"));
console.log(colors.red.bold("Make it bold and red"));
console.log(colors.rainbow("Double Raindows All Day Long"))
console.log(colors.trap("Drop the bass"))
console.log(colors.rainbow(colors.trap("DROP THE RAINBOW BASS")));
console.log(colors.bold.italic.underline.red('Chains are also cool.')); // styles not widely supported
console.log(colors.green('So ') + colors.underline('are') + ' ' + colors.inverse('inverse') + colors.yellow.bold(' styles! ')); // styles not widely supported
console.log(colors.zebra("Zebras are so fun!"));
console.log("This is " + colors.strikethrough("not") + " fun.");
console.log(colors.black.bgWhite('Background color attack!'));
console.log(colors.random('Use random styles on everything!'))
console.log(colors.america('America, Heck Yeah!'));
console.log('Setting themes is useful')
//
// Custom themes
//
//console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log(colors.error("this is an error"));
// outputs yellow text
console.log(colors.warn("this is a warning"));
// outputs grey text
console.log(colors.input("this is an input"));
// console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
colors.setTheme(__dirname + '/../themes/generic-logging.js');
// outputs red text
console.log(colors.error("this is an error"));
// outputs yellow text
console.log(colors.warn("this is a warning"));
// outputs grey text
console.log(colors.input("this is an input"));
// console.log(colors.zalgo("Don't summon him"))

176
node_modules/colors/lib/colors.js generated vendored Normal file
View File

@ -0,0 +1,176 @@
/*
The MIT License (MIT)
Original Library
- Copyright (c) Marak Squires
Additional functionality
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.
*/
var colors = {};
module['exports'] = colors;
colors.themes = {};
var ansiStyles = colors.styles = require('./styles');
var defineProps = Object.defineProperties;
colors.supportsColor = require('./system/supports-colors');
if (typeof colors.enabled === "undefined") {
colors.enabled = colors.supportsColor;
}
colors.stripColors = colors.strip = function(str){
return ("" + str).replace(/\x1B\[\d+m/g, '');
};
var stylize = colors.stylize = function stylize (str, style) {
return ansiStyles[style].open + str + ansiStyles[style].close;
}
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
var escapeStringRegexp = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
}
function build(_styles) {
var builder = function builder() {
return applyStyle.apply(builder, arguments);
};
builder._styles = _styles;
// __proto__ is used because we must return a function, but there is
// no way to create a function with a different prototype.
builder.__proto__ = proto;
return builder;
}
var styles = (function () {
var ret = {};
ansiStyles.grey = ansiStyles.gray;
Object.keys(ansiStyles).forEach(function (key) {
ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
ret[key] = {
get: function () {
return build(this._styles.concat(key));
}
};
});
return ret;
})();
var proto = defineProps(function colors() {}, styles);
function applyStyle() {
var args = arguments;
var argsLen = args.length;
var str = argsLen !== 0 && String(arguments[0]);
if (argsLen > 1) {
for (var a = 1; a < argsLen; a++) {
str += ' ' + args[a];
}
}
if (!colors.enabled || !str) {
return str;
}
var nestedStyles = this._styles;
var i = nestedStyles.length;
while (i--) {
var code = ansiStyles[nestedStyles[i]];
str = code.open + str.replace(code.closeRe, code.open) + code.close;
}
return str;
}
function applyTheme (theme) {
for (var style in theme) {
(function(style){
colors[style] = function(str){
return colors[theme[style]](str);
};
})(style)
}
}
colors.setTheme = function (theme) {
if (typeof theme === 'string') {
try {
colors.themes[theme] = require(theme);
applyTheme(colors.themes[theme]);
return colors.themes[theme];
} catch (err) {
console.log(err);
return err;
}
} else {
applyTheme(theme);
}
};
function init() {
var ret = {};
Object.keys(styles).forEach(function (name) {
ret[name] = {
get: function () {
return build([name]);
}
};
});
return ret;
}
var sequencer = function sequencer (map, str) {
var exploded = str.split(""), i = 0;
exploded = exploded.map(map);
return exploded.join("");
};
// custom formatter methods
colors.trap = require('./custom/trap');
colors.zalgo = require('./custom/zalgo');
// maps
colors.maps = {};
colors.maps.america = require('./maps/america');
colors.maps.zebra = require('./maps/zebra');
colors.maps.rainbow = require('./maps/rainbow');
colors.maps.random = require('./maps/random')
for (var map in colors.maps) {
(function(map){
colors[map] = function (str) {
return sequencer(colors.maps[map], str);
}
})(map)
}
defineProps(colors, init());

45
node_modules/colors/lib/custom/trap.js generated vendored Normal file
View File

@ -0,0 +1,45 @@
module['exports'] = function runTheTrap (text, options) {
var result = "";
text = text || "Run the trap, drop the bass";
text = text.split('');
var trap = {
a: ["\u0040", "\u0104", "\u023a", "\u0245", "\u0394", "\u039b", "\u0414"],
b: ["\u00df", "\u0181", "\u0243", "\u026e", "\u03b2", "\u0e3f"],
c: ["\u00a9", "\u023b", "\u03fe"],
d: ["\u00d0", "\u018a", "\u0500" , "\u0501" ,"\u0502", "\u0503"],
e: ["\u00cb", "\u0115", "\u018e", "\u0258", "\u03a3", "\u03be", "\u04bc", "\u0a6c"],
f: ["\u04fa"],
g: ["\u0262"],
h: ["\u0126", "\u0195", "\u04a2", "\u04ba", "\u04c7", "\u050a"],
i: ["\u0f0f"],
j: ["\u0134"],
k: ["\u0138", "\u04a0", "\u04c3", "\u051e"],
l: ["\u0139"],
m: ["\u028d", "\u04cd", "\u04ce", "\u0520", "\u0521", "\u0d69"],
n: ["\u00d1", "\u014b", "\u019d", "\u0376", "\u03a0", "\u048a"],
o: ["\u00d8", "\u00f5", "\u00f8", "\u01fe", "\u0298", "\u047a", "\u05dd", "\u06dd", "\u0e4f"],
p: ["\u01f7", "\u048e"],
q: ["\u09cd"],
r: ["\u00ae", "\u01a6", "\u0210", "\u024c", "\u0280", "\u042f"],
s: ["\u00a7", "\u03de", "\u03df", "\u03e8"],
t: ["\u0141", "\u0166", "\u0373"],
u: ["\u01b1", "\u054d"],
v: ["\u05d8"],
w: ["\u0428", "\u0460", "\u047c", "\u0d70"],
x: ["\u04b2", "\u04fe", "\u04fc", "\u04fd"],
y: ["\u00a5", "\u04b0", "\u04cb"],
z: ["\u01b5", "\u0240"]
}
text.forEach(function(c){
c = c.toLowerCase();
var chars = trap[c] || [" "];
var rand = Math.floor(Math.random() * chars.length);
if (typeof trap[c] !== "undefined") {
result += trap[c][rand];
} else {
result += c;
}
});
return result;
}

104
node_modules/colors/lib/custom/zalgo.js generated vendored Normal file
View File

@ -0,0 +1,104 @@
// please no
module['exports'] = function zalgo(text, options) {
text = text || " he is here ";
var soul = {
"up" : [
'̍', '̎', '̄', '̅',
'̿', '̑', '̆', '̐',
'͒', '͗', '͑', '̇',
'̈', '̊', '͂', '̓',
'̈', '͊', '͋', '͌',
'̃', '̂', '̌', '͐',
'̀', '́', '̋', '̏',
'̒', '̓', '̔', '̽',
'̉', 'ͣ', 'ͤ', 'ͥ',
'ͦ', 'ͧ', 'ͨ', 'ͩ',
'ͪ', 'ͫ', 'ͬ', 'ͭ',
'ͮ', 'ͯ', '̾', '͛',
'͆', '̚'
],
"down" : [
'̖', '̗', '̘', '̙',
'̜', '̝', '̞', '̟',
'̠', '̤', '̥', '̦',
'̩', '̪', '̫', '̬',
'̭', '̮', '̯', '̰',
'̱', '̲', '̳', '̹',
'̺', '̻', '̼', 'ͅ',
'͇', '͈', '͉', '͍',
'͎', '͓', '͔', '͕',
'͖', '͙', '͚', '̣'
],
"mid" : [
'̕', '̛', '̀', '́',
'͘', '̡', '̢', '̧',
'̨', '̴', '̵', '̶',
'͜', '͝', '͞',
'͟', '͠', '͢', '̸',
'̷', '͡', ' ҉'
]
},
all = [].concat(soul.up, soul.down, soul.mid),
zalgo = {};
function randomNumber(range) {
var r = Math.floor(Math.random() * range);
return r;
}
function is_char(character) {
var bool = false;
all.filter(function (i) {
bool = (i === character);
});
return bool;
}
function heComes(text, options) {
var result = '', counts, l;
options = options || {};
options["up"] = options["up"] || true;
options["mid"] = options["mid"] || true;
options["down"] = options["down"] || true;
options["size"] = options["size"] || "maxi";
text = text.split('');
for (l in text) {
if (is_char(l)) {
continue;
}
result = result + text[l];
counts = {"up" : 0, "down" : 0, "mid" : 0};
switch (options.size) {
case 'mini':
counts.up = randomNumber(8);
counts.min = randomNumber(2);
counts.down = randomNumber(8);
break;
case 'maxi':
counts.up = randomNumber(16) + 3;
counts.min = randomNumber(4) + 1;
counts.down = randomNumber(64) + 3;
break;
default:
counts.up = randomNumber(8) + 1;
counts.mid = randomNumber(6) / 2;
counts.down = randomNumber(8) + 1;
break;
}
var arr = ["up", "mid", "down"];
for (var d in arr) {
var index = arr[d];
for (var i = 0 ; i <= counts[index]; i++) {
if (options[index]) {
result = result + soul[index][randomNumber(soul[index].length)];
}
}
}
}
return result;
}
// don't summon him
return heComes(text);
}

118
node_modules/colors/lib/extendStringPrototype.js generated vendored Normal file
View File

@ -0,0 +1,118 @@
var colors = require('./colors'),
styles = require('./styles');
module['exports'] = function () {
//
// Extends prototype of native string object to allow for "foo".red syntax
//
var addProperty = function (color, func) {
String.prototype.__defineGetter__(color, func);
};
var sequencer = function sequencer (map, str) {
return function () {
var exploded = this.split(""), i = 0;
exploded = exploded.map(map);
return exploded.join("");
}
};
var stylize = function stylize (str, style) {
return styles[style].open + str + styles[style].close;
}
addProperty('strip', function () {
return colors.strip(this);
});
addProperty('stripColors', function () {
return colors.strip(this);
});
addProperty("trap", function(){
return colors.trap(this);
});
addProperty("zalgo", function(){
return colors.zalgo(this);
});
addProperty("zebra", function(){
return colors.zebra(this);
});
addProperty("rainbow", function(){
return colors.rainbow(this);
});
addProperty("random", function(){
return colors.random(this);
});
addProperty("america", function(){
return colors.america(this);
});
//
// Iterate through all default styles and colors
//
var x = Object.keys(colors.styles);
x.forEach(function (style) {
addProperty(style, function () {
return stylize(this, style);
});
});
function applyTheme(theme) {
//
// Remark: This is a list of methods that exist
// on String that you should not overwrite.
//
var stringPrototypeBlacklist = [
'__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'charAt', 'constructor',
'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'charCodeAt',
'indexOf', 'lastIndexof', 'length', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substring',
'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight'
];
Object.keys(theme).forEach(function (prop) {
if (stringPrototypeBlacklist.indexOf(prop) !== -1) {
console.log('warn: '.red + ('String.prototype' + prop).magenta + ' is probably something you don\'t want to override. Ignoring style name');
}
else {
if (typeof(theme[prop]) === 'string') {
colors[prop] = colors[theme[prop]];
addProperty(prop, function () {
return colors[theme[prop]](this);
});
}
else {
addProperty(prop, function () {
var ret = this;
for (var t = 0; t < theme[prop].length; t++) {
ret = exports[theme[prop][t]](ret);
}
return ret;
});
}
}
});
}
colors.setTheme = function (theme) {
if (typeof theme === 'string') {
try {
colors.themes[theme] = require(theme);
applyTheme(colors.themes[theme]);
return colors.themes[theme];
} catch (err) {
console.log(err);
return err;
}
} else {
applyTheme(theme);
}
};
};

12
node_modules/colors/lib/index.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
var colors = require('./colors');
module['exports'] = colors;
// Remark: By default, colors will add style properties to String.prototype
//
// If you don't wish to extend String.prototype you can do this instead and native String will not be touched
//
// var colors = require('colors/safe);
// colors.red("foo")
//
//
var extendStringPrototype = require('./extendStringPrototype')();

12
node_modules/colors/lib/maps/america.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
var colors = require('../colors');
module['exports'] = (function() {
return function (letter, i, exploded) {
if(letter === " ") return letter;
switch(i%3) {
case 0: return colors.red(letter);
case 1: return colors.white(letter)
case 2: return colors.blue(letter)
}
}
})();

13
node_modules/colors/lib/maps/rainbow.js generated vendored Normal file
View File

@ -0,0 +1,13 @@
var colors = require('../colors');
module['exports'] = (function () {
var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV
return function (letter, i, exploded) {
if (letter === " ") {
return letter;
} else {
return colors[rainbowColors[i++ % rainbowColors.length]](letter);
}
};
})();

8
node_modules/colors/lib/maps/random.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
var colors = require('../colors');
module['exports'] = (function () {
var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'];
return function(letter, i, exploded) {
return letter === " " ? letter : colors[available[Math.round(Math.random() * (available.length - 1))]](letter);
};
})();

5
node_modules/colors/lib/maps/zebra.js generated vendored Normal file
View File

@ -0,0 +1,5 @@
var colors = require('../colors');
module['exports'] = function (letter, i, exploded) {
return i % 2 === 0 ? letter : colors.inverse(letter);
};

77
node_modules/colors/lib/styles.js generated vendored Normal file
View File

@ -0,0 +1,77 @@
/*
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.
*/
var styles = {};
module['exports'] = styles;
var codes = {
reset: [0, 0],
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
grey: [90, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// legacy styles for colors pre v1.0.0
blackBG: [40, 49],
redBG: [41, 49],
greenBG: [42, 49],
yellowBG: [43, 49],
blueBG: [44, 49],
magentaBG: [45, 49],
cyanBG: [46, 49],
whiteBG: [47, 49]
};
Object.keys(codes).forEach(function (key) {
var val = codes[key];
var style = styles[key] = [];
style.open = '\u001b[' + val[0] + 'm';
style.close = '\u001b[' + val[1] + 'm';
});

61
node_modules/colors/lib/system/supports-colors.js generated vendored Normal file
View File

@ -0,0 +1,61 @@
/*
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.
*/
var argv = process.argv;
module.exports = (function () {
if (argv.indexOf('--no-color') !== -1 ||
argv.indexOf('--color=false') !== -1) {
return false;
}
if (argv.indexOf('--color') !== -1 ||
argv.indexOf('--color=true') !== -1 ||
argv.indexOf('--color=always') !== -1) {
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;
})();

79
node_modules/colors/package.json generated vendored Normal file
View File

@ -0,0 +1,79 @@
{
"_args": [
[
"colors@1.0.x",
"/Users/akira/src/biomedjs/node_modules/winston"
]
],
"_from": "colors@>=1.0.0 <1.1.0",
"_id": "colors@1.0.3",
"_inCache": true,
"_installable": true,
"_location": "/colors",
"_nodeVersion": "0.11.13",
"_npmUser": {
"email": "marak.squires@gmail.com",
"name": "marak"
},
"_npmVersion": "2.0.2",
"_phantomChildren": {},
"_requested": {
"name": "colors",
"raw": "colors@1.0.x",
"rawSpec": "1.0.x",
"scope": null,
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/winston"
],
"_resolved": "https://registry.npmjs.org/colors/-/colors-1.0.3.tgz",
"_shasum": "0433f44d809680fdeb60ed260f1b0c262e82a40b",
"_shrinkwrap": null,
"_spec": "colors@1.0.x",
"_where": "/Users/akira/src/biomedjs/node_modules/winston",
"author": {
"name": "Marak Squires"
},
"bugs": {
"url": "https://github.com/Marak/colors.js/issues"
},
"dependencies": {},
"description": "get colors in your node.js console",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "0433f44d809680fdeb60ed260f1b0c262e82a40b",
"tarball": "http://registry.npmjs.org/colors/-/colors-1.0.3.tgz"
},
"engines": {
"node": ">=0.1.90"
},
"gitHead": "e9e6557cc0fa26dba1a20b0d45e92de982f4047c",
"homepage": "https://github.com/Marak/colors.js",
"keywords": [
"ansi",
"colors",
"terminal"
],
"license": "MIT",
"main": "./lib/index",
"maintainers": [
{
"name": "marak",
"email": "marak.squires@gmail.com"
}
],
"name": "colors",
"optionalDependencies": {},
"readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/Marak/colors.js.git"
},
"scripts": {
"test": "node tests/basic-test.js && node tests/safe-test.js"
},
"version": "1.0.3"
}

9
node_modules/colors/safe.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
//
// Remark: Requiring this file will use the "safe" colors API which will not touch String.prototype
//
// var colors = require('colors/safe);
// colors.red("foo")
//
//
var colors = require('./lib/colors');
module['exports'] = colors;

BIN
node_modules/colors/screenshots/colors.png generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

50
node_modules/colors/tests/basic-test.js generated vendored Normal file
View File

@ -0,0 +1,50 @@
var assert = require('assert'),
colors = require('../lib/index');
var s = 'string';
function a(s, code) {
return '\x1B[' + code.toString() + 'm' + s + '\x1B[39m';
}
function aE(s, color, code) {
assert.equal(s[color], a(s, code));
assert.equal(colors[color](s), a(s, code));
assert.equal(s[color], colors[color](s));
assert.equal(s[color].strip, s);
assert.equal(s[color].strip, colors.strip(s));
}
function h(s, color) {
return '<span style="color:' + color + ';">' + s + '</span>';
}
var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow'];
var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']);
colors.mode = 'console';
assert.equal(s.bold, '\x1B[1m' + s + '\x1B[22m');
assert.equal(s.italic, '\x1B[3m' + s + '\x1B[23m');
assert.equal(s.underline, '\x1B[4m' + s + '\x1B[24m');
assert.equal(s.strikethrough, '\x1B[9m' + s + '\x1B[29m');
assert.equal(s.inverse, '\x1B[7m' + s + '\x1B[27m');
assert.ok(s.rainbow);
aE(s, 'white', 37);
aE(s, 'grey', 90);
aE(s, 'black', 30);
aE(s, 'blue', 34);
aE(s, 'cyan', 36);
aE(s, 'green', 32);
aE(s, 'magenta', 35);
aE(s, 'red', 31);
aE(s, 'yellow', 33);
assert.equal(s, 'string');
colors.setTheme({error:'red'});
assert.equal(typeof("astring".red),'string');
assert.equal(typeof("astring".error),'string');

45
node_modules/colors/tests/safe-test.js generated vendored Normal file
View File

@ -0,0 +1,45 @@
var assert = require('assert'),
colors = require('../safe');
var s = 'string';
function a(s, code) {
return '\x1B[' + code.toString() + 'm' + s + '\x1B[39m';
}
function aE(s, color, code) {
assert.equal(colors[color](s), a(s, code));
assert.equal(colors.strip(s), s);
}
function h(s, color) {
return '<span style="color:' + color + ';">' + s + '</span>';
}
var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow'];
var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']);
colors.mode = 'console';
assert.equal(colors.bold(s), '\x1B[1m' + s + '\x1B[22m');
assert.equal(colors.italic(s), '\x1B[3m' + s + '\x1B[23m');
assert.equal(colors.underline(s), '\x1B[4m' + s + '\x1B[24m');
assert.equal(colors.strikethrough(s), '\x1B[9m' + s + '\x1B[29m');
assert.equal(colors.inverse(s), '\x1B[7m' + s + '\x1B[27m');
assert.ok(colors.rainbow);
aE(s, 'white', 37);
aE(s, 'grey', 90);
aE(s, 'black', 30);
aE(s, 'blue', 34);
aE(s, 'cyan', 36);
aE(s, 'green', 32);
aE(s, 'magenta', 35);
aE(s, 'red', 31);
aE(s, 'yellow', 33);
assert.equal(s, 'string');
colors.setTheme({error:'red'});
assert.equal(typeof(colors.red("astring")), 'string');
assert.equal(typeof(colors.error("astring")), 'string');

12
node_modules/colors/themes/generic-logging.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
module['exports'] = {
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
};

49
node_modules/cycle/README.md generated vendored Normal file
View File

@ -0,0 +1,49 @@
Fork of https://github.com/douglascrockford/JSON-js, maintained in npm as `cycle`.
# Contributors
* Douglas Crockford
* Nuno Job
* Justin Warkentin
# JSON in JavaScript
Douglas Crockford
douglas@crockford.com
2010-11-18
JSON is a light-weight, language independent, data interchange format.
See http://www.JSON.org/
The files in this collection implement JSON encoders/decoders in JavaScript.
JSON became a built-in feature of JavaScript when the ECMAScript Programming
Language Standard - Fifth Edition was adopted by the ECMA General Assembly
in December 2009. Most of the files in this collection are for applications
that are expected to run in obsolete web browsers. For most purposes, json2.js
is the best choice.
json2.js: This file creates a JSON property in the global object, if there
isn't already one, setting its value to an object containing a stringify
method and a parse method. The parse method uses the eval method to do the
parsing, guarding it with several regular expressions to defend against
accidental code execution hazards. On current browsers, this file does nothing,
prefering the built-in JSON object.
json.js: This file does everything that json2.js does. It also adds a
toJSONString method and a parseJSON method to Object.prototype. Use of this
file is not recommended.
json_parse.js: This file contains an alternative JSON parse function that
uses recursive descent instead of eval.
json_parse_state.js: This files contains an alternative JSON parse function that
uses a state machine instead of eval.
cycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle,
which make it possible to encode cyclical structures and dags in JSON, and to
then recover them. JSONPath is used to represent the links.
http://GOESSNER.net/articles/JsonPath/

170
node_modules/cycle/cycle.js generated vendored Normal file
View File

@ -0,0 +1,170 @@
/*
cycle.js
2013-02-19
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
*/
/*jslint evil: true, regexp: true */
/*members $ref, apply, call, decycle, hasOwnProperty, length, prototype, push,
retrocycle, stringify, test, toString
*/
var cycle = exports;
cycle.decycle = function decycle(object) {
'use strict';
// Make a deep copy of an object or array, assuring that there is at most
// one instance of each object or array in the resulting structure. The
// duplicate references (which might be forming cycles) are replaced with
// an object of the form
// {$ref: PATH}
// where the PATH is a JSONPath string that locates the first occurance.
// So,
// var a = [];
// a[0] = a;
// return JSON.stringify(JSON.decycle(a));
// produces the string '[{"$ref":"$"}]'.
// JSONPath is used to locate the unique object. $ indicates the top level of
// the object or array. [NUMBER] or [STRING] indicates a child member or
// property.
var objects = [], // Keep a reference to each unique object or array
paths = []; // Keep the path to each unique object or array
return (function derez(value, path) {
// The derez recurses through the object, producing the deep copy.
var i, // The loop counter
name, // Property name
nu; // The new object or array
// typeof null === 'object', so go on if this value is really an object but not
// one of the weird builtin objects.
if (typeof value === 'object' && value !== null &&
!(value instanceof Boolean) &&
!(value instanceof Date) &&
!(value instanceof Number) &&
!(value instanceof RegExp) &&
!(value instanceof String)) {
// If the value is an object or array, look to see if we have already
// encountered it. If so, return a $ref/path object. This is a hard way,
// linear search that will get slower as the number of unique objects grows.
for (i = 0; i < objects.length; i += 1) {
if (objects[i] === value) {
return {$ref: paths[i]};
}
}
// Otherwise, accumulate the unique value and its path.
objects.push(value);
paths.push(path);
// If it is an array, replicate the array.
if (Object.prototype.toString.apply(value) === '[object Array]') {
nu = [];
for (i = 0; i < value.length; i += 1) {
nu[i] = derez(value[i], path + '[' + i + ']');
}
} else {
// If it is an object, replicate the object.
nu = {};
for (name in value) {
if (Object.prototype.hasOwnProperty.call(value, name)) {
nu[name] = derez(value[name],
path + '[' + JSON.stringify(name) + ']');
}
}
}
return nu;
}
return value;
}(object, '$'));
};
cycle.retrocycle = function retrocycle($) {
'use strict';
// Restore an object that was reduced by decycle. Members whose values are
// objects of the form
// {$ref: PATH}
// are replaced with references to the value found by the PATH. This will
// restore cycles. The object will be mutated.
// The eval function is used to locate the values described by a PATH. The
// root object is kept in a $ variable. A regular expression is used to
// assure that the PATH is extremely well formed. The regexp contains nested
// * quantifiers. That has been known to have extremely bad performance
// problems on some browsers for very long strings. A PATH is expected to be
// reasonably short. A PATH is allowed to belong to a very restricted subset of
// Goessner's JSONPath.
// So,
// var s = '[{"$ref":"$"}]';
// return JSON.retrocycle(JSON.parse(s));
// produces an array containing a single element which is the array itself.
var px =
/^\$(?:\[(?:\d+|\"(?:[^\\\"\u0000-\u001f]|\\([\\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*\")\])*$/;
(function rez(value) {
// The rez function walks recursively through the object looking for $ref
// properties. When it finds one that has a value that is a path, then it
// replaces the $ref object with a reference to the value that is found by
// the path.
var i, item, name, path;
if (value && typeof value === 'object') {
if (Object.prototype.toString.apply(value) === '[object Array]') {
for (i = 0; i < value.length; i += 1) {
item = value[i];
if (item && typeof item === 'object') {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[i] = eval(path);
} else {
rez(item);
}
}
}
} else {
for (name in value) {
if (typeof value[name] === 'object') {
item = value[name];
if (item) {
path = item.$ref;
if (typeof path === 'string' && px.test(path)) {
value[name] = eval(path);
} else {
rez(item);
}
}
}
}
}
}
}($));
return $;
};

73
node_modules/cycle/package.json generated vendored Normal file
View File

@ -0,0 +1,73 @@
{
"_args": [
[
"cycle@1.0.x",
"/Users/akira/src/biomedjs/node_modules/winston"
]
],
"_from": "cycle@>=1.0.0 <1.1.0",
"_id": "cycle@1.0.3",
"_inCache": true,
"_installable": true,
"_location": "/cycle",
"_npmUser": {
"email": "nunojobpinto@gmail.com",
"name": "dscape"
},
"_npmVersion": "1.2.32",
"_phantomChildren": {},
"_requested": {
"name": "cycle",
"raw": "cycle@1.0.x",
"rawSpec": "1.0.x",
"scope": null,
"spec": ">=1.0.0 <1.1.0",
"type": "range"
},
"_requiredBy": [
"/winston"
],
"_resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz",
"_shasum": "21e80b2be8580f98b468f379430662b046c34ad2",
"_shrinkwrap": null,
"_spec": "cycle@1.0.x",
"_where": "/Users/akira/src/biomedjs/node_modules/winston",
"author": "",
"bugs": {
"url": "http://github.com/douglascrockford/JSON-js/issues"
},
"dependencies": {},
"description": "decycle your json",
"devDependencies": {},
"directories": {},
"dist": {
"shasum": "21e80b2be8580f98b468f379430662b046c34ad2",
"tarball": "http://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz"
},
"engines": {
"node": ">=0.4.0"
},
"homepage": "https://github.com/douglascrockford/JSON-js",
"keywords": [
"cycle",
"json",
"parse",
"stringify"
],
"main": "./cycle.js",
"maintainers": [
{
"name": "dscape",
"email": "nunojobpinto@gmail.com"
}
],
"name": "cycle",
"optionalDependencies": {},
"readme": "Fork of https://github.com/douglascrockford/JSON-js, maintained in npm as `cycle`.\n\n# Contributors\n\n* Douglas Crockford\n* Nuno Job\n* Justin Warkentin\n\n# JSON in JavaScript\n\nDouglas Crockford\ndouglas@crockford.com\n\n2010-11-18\n\n\nJSON is a light-weight, language independent, data interchange format.\nSee http://www.JSON.org/\n\nThe files in this collection implement JSON encoders/decoders in JavaScript.\n\nJSON became a built-in feature of JavaScript when the ECMAScript Programming\nLanguage Standard - Fifth Edition was adopted by the ECMA General Assembly\nin December 2009. Most of the files in this collection are for applications\nthat are expected to run in obsolete web browsers. For most purposes, json2.js\nis the best choice.\n\n\njson2.js: This file creates a JSON property in the global object, if there\nisn't already one, setting its value to an object containing a stringify\nmethod and a parse method. The parse method uses the eval method to do the\nparsing, guarding it with several regular expressions to defend against\naccidental code execution hazards. On current browsers, this file does nothing,\nprefering the built-in JSON object.\n\njson.js: This file does everything that json2.js does. It also adds a\ntoJSONString method and a parseJSON method to Object.prototype. Use of this\nfile is not recommended.\n\njson_parse.js: This file contains an alternative JSON parse function that\nuses recursive descent instead of eval.\n\njson_parse_state.js: This files contains an alternative JSON parse function that\nuses a state machine instead of eval.\n\ncycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle,\nwhich make it possible to encode cyclical structures and dags in JSON, and to\nthen recover them. JSONPath is used to represent the links.\nhttp://GOESSNER.net/articles/JsonPath/\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/dscape/cycle.git"
},
"version": "1.0.3"
}

11
node_modules/express-validator/.editorconfig generated vendored Normal file
View File

@ -0,0 +1,11 @@
# This file is for unifying the coding style for different editors and IDEs.
# More information at http://EditorConfig.org
# No .editorconfig files above the root directory
root = true
[*]
indent_style = space
indent_size = 2
charset = utf-8
trim_trailing_whitespace = true

56
node_modules/express-validator/.jscsrc generated vendored Normal file
View File

@ -0,0 +1,56 @@
{
"excludeFiles": ["node_modules/**"],
"disallowEmptyBlocks": true,
"disallowKeywordsOnNewLine": ["else"],
"disallowKeywords": ["with"],
"disallowMixedSpacesAndTabs": true,
"disallowNewlineBeforeBlockStatements": true,
"disallowSpaceAfterObjectKeys": true,
"disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"],
"disallowSpaceBeforeBinaryOperators": [","],
"disallowSpaceBeforePostfixUnaryOperators": ["++", "--"],
"disallowSpacesInAnonymousFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInCallExpression": true,
"disallowSpacesInFunctionDeclaration": {
"beforeOpeningRoundBrace": true
},
"disallowSpacesInNamedFunctionExpression": {
"beforeOpeningRoundBrace": true
},
"disallowTrailingComma": true,
"disallowTrailingWhitespace": true,
"requireCommaBeforeLineBreak": true,
"requireCurlyBraces": [
"if",
"else",
"for",
"while",
"do",
"try",
"catch"
],
"requireSpaceAfterBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"],
"requireSpaceBeforeBinaryOperators": ["?", ":", "+", "-", "/", "*", "%", "==", "===", "!=", "!==", ">", ">=", "<", "<=", "&&", "||"],
"requireSpaceBeforeKeywords": [
"else",
"while",
"catch"
],
"requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch"],
"requireSpaceBeforeObjectValues": true,
"requireSpaceBetweenArguments": true,
"requireSpacesInConditionalExpression": {
"afterTest": true,
"beforeConsequent": true,
"afterConsequent": true,
"beforeAlternate": true
},
"requireSpacesInForStatement": true,
"requireSpacesInFunction": {
"beforeOpeningCurlyBrace": true
},
"requireSpacesInsideObjectBrackets": "all",
"validateParameterSeparator": ", "
}

18
node_modules/express-validator/.jshintrc generated vendored Normal file
View File

@ -0,0 +1,18 @@
{
"regexdash": true,
"browser": true,
"trailing": true,
"sub": true,
"curly": true,
"eqeqeq": true,
"indent": 4,
"latedef": "nofunc",
"newcap": true,
"unused": true,
"eqnull": true,
"bitwise": true,
"noarg": true,
"noempty": true,
"nonew": true,
"node": true
}

3
node_modules/express-validator/.npmignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules
.idea
npm-debug.log

11
node_modules/express-validator/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,11 @@
sudo: false
language: node_js
node_js:
- "0.10"
- "0.12"
- "4.0"
- "4.1"
install:
- npm install
script:
- npm run travis-build

227
node_modules/express-validator/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,227 @@
## Change Log
### upcoming 2015/05/04
- [ea00f9d](https://github.com/ctavan/express-validator/commit/ea00f9d6cfe0859f6f00ceb45d66f4d9270064b0) Update changelog. (@rustybailey)
### v2.10.0 2015/05/04
- [0f48735](https://github.com/ctavan/express-validator/commit/0f48735dc77ec561ad014a721375b561ce3889fe) 2.10.0 (@rustybailey)
- [bc2ef59](https://github.com/ctavan/express-validator/commit/bc2ef59b5a5c45be12f6efb27199a29d8689ac2f) Use the same node versions as node-validator. (@rustybailey)
- [0c3aaec](https://github.com/ctavan/express-validator/commit/0c3aaecb0f7d4a75a1bc20e94290cfe72e98a49c) Bump validator version to 3.39.0 (@rustybailey)
- [dfb757b](https://github.com/ctavan/express-validator/commit/dfb757b8eafe3149c552be4b92eb259fb6bdd5e5) Add changelog to devDependencies and add npm script to generate changelog. (@rustybailey)
- [bf044b5](https://github.com/ctavan/express-validator/commit/bf044b577f6999a7f1e92cb9f74ddf4a44bd78d3) Add node 0.12 to travis.yml, remove dead gist link in README, add license in package.json. (@rustybailey)
- [f42077f](https://github.com/ctavan/express-validator/commit/f42077fabfc9b8ef6100069b17e83f5fab2eb395) Add editorconfig. (@rustybailey)
- [73daa44](https://github.com/ctavan/express-validator/commit/73daa44dee192049da4fff732dec629a6630af73) Add jshint to devDependencies, add .jshintrc, fix semicolon issues. (@rustybailey)
- [fb8d049](https://github.com/ctavan/express-validator/commit/fb8d049dd1f0a0da6c0070cf160316f9b732a732) Add comment to explain before() function busting require's cache in each test file. (@rustybailey)
- [7fc7b1c](https://github.com/ctavan/express-validator/commit/7fc7b1c54c22f19dfc650cba06b47e6e05d0c653) Remove async from devDependencies (@rustybailey)
- [a74de1e](https://github.com/ctavan/express-validator/commit/a74de1eb3ef2bdf67beb5be4fd3a8e51e4d190b5) Remove old tests and change npm test to use Mocha. (@rustybailey)
- [39f1b55](https://github.com/ctavan/express-validator/commit/39f1b55f817a7ca1f0fc802247ba8dd0d24ff21f) Add Mocha tests for validating regex routes (@rustybailey)
- [68adc6e](https://github.com/ctavan/express-validator/commit/68adc6e76b6abb3f0c1946c3c51ca16c1cebe9b6) Add Mocha tests for nested input (@rustybailey)
- [a029176](https://github.com/ctavan/express-validator/commit/a029176a7c7ac0666f0b93adca0d2ea0a57ff98b) Add Mocha tests for mapped output using validationErrors(true) (@rustybailey)
- [5a2f7ef](https://github.com/ctavan/express-validator/commit/5a2f7ef3a5a0f59fb9f6692e2e5d93f81b5e497b) Add Mocha tests for check() (@rustybailey)
- [9cd6f62](https://github.com/ctavan/express-validator/commit/9cd6f626cb287f1a877e0f645690b528938f3dc4) Add Mocha tests for checkQuery() (@rustybailey)
- [c91e022](https://github.com/ctavan/express-validator/commit/c91e0220312097548abaf21d91e076e18726f3ab) Add Mocha tests for checkBody() (@rustybailey)
- [bbcb462](https://github.com/ctavan/express-validator/commit/bbcb4620ada424a2352a148975eba2072d8badf3) Add tests for checkParams() (@rustybailey)
- [d2eb638](https://github.com/ctavan/express-validator/commit/d2eb638611a015dd04d4aa59c4c790ca324bcc66) Add mocha/chai as dependencies, simplify app.js helper, create mocha tests for optional(). (@rustybailey)
### v2.9.1 2015/04/28
- [9c87684](https://github.com/ctavan/express-validator/commit/9c87684a02eff71f40fc98ce3da37992fee464cd) Bump version to 2.9.1. (@rustybailey)
- [37ede78](https://github.com/ctavan/express-validator/commit/37ede786203d5b9aa87acf96bd568c26fcc6de3a) Fix checkHeader so that it works with optional(). (@rustybailey)
- [136307f](https://github.com/ctavan/express-validator/commit/136307f94aebaf4dcc7e83dee62bfd5cae9a1333) Move change log into its own file and expand it using github-changes. Fixes #130 (@rustybailey)
### v2.9.0 2015/03/20
- [c2e5124](https://github.com/ctavan/express-validator/commit/c2e512490667cc1cbc22e2de762c79cbf425354a) Bump version to 2.9.0 (@ctavan)
- [9624cca](https://github.com/ctavan/express-validator/commit/9624cca38836a7299bba570e3addd07913ded174) Update node validator dependency. (@ctavan)
- [9247648](https://github.com/ctavan/express-validator/commit/9247648f7d8fc1c8aa017ad19e1f24e90aff311a) Fix deprecated use of req.param(), closes #117. (@ctavan)
- [d8ba047](https://github.com/ctavan/express-validator/commit/d8ba0470d85e283e38870db5f9a0cde964561171) replaced req.param call to remove deprecation msg (@janza)
- [b2f727b](https://github.com/ctavan/express-validator/commit/b2f727b4d948cd7a94c6c3570fba5de5f626dc34) Add LICENSE (@becausehama)
### v2.8.0 2014/12/23
- [e49ee9d](https://github.com/ctavan/express-validator/commit/e49ee9ddb7cf3ebf804874f1ba5281f890693799) Bump version to 2.8.0 (@ctavan)
- [d48d248](https://github.com/ctavan/express-validator/commit/d48d2480f992ffbe7cac5fe00e3d75f146e5290a) Updating to validator 3.26.0 (@aredo)
### v2.7.0 2014/11/13
- [84937cf](https://github.com/ctavan/express-validator/commit/84937cf4dee304914f763d109a657bf24c61914c) Bump version 2.7.0 (@ctavan)
- [51e39b3](https://github.com/ctavan/express-validator/commit/51e39b3526a0386ab1003b6485a8351567959388) Updating to validator 3.22.1 (@nfrasser)
### v2.6.0 2014/09/24
- [8b67263](https://github.com/ctavan/express-validator/commit/8b67263c1fcf31b920e369fcb1e7a47a0eef07c6) Upgraded to validator 3.19.0 (@fiznool)
### v2.5.0 2014/09/16
- [1dc8679](https://github.com/ctavan/express-validator/commit/1dc8679ef2207e1ac886bf3eeac7f63955c042c5) Bump version to 2.5.0 (@ctavan)
- [2205323](https://github.com/ctavan/express-validator/commit/220532338d20abc57ba2510b1f51c86c31705757) adds tests for optional() method (@BAKFR)
- [7402642](https://github.com/ctavan/express-validator/commit/7402642a9a7917f16bba42c1d06503047821052b) add curly braces to respect the coding style (@BAKFR)
- [b90f482](https://github.com/ctavan/express-validator/commit/b90f482d13d446f4e5d22b9ba038be0740e9d20d) add documentation for customValidators option
### v2.4.0 2014/09/04
- [9d18380](https://github.com/ctavan/express-validator/commit/9d18380884562b9d8e366f1b180f9eee11658f66) Bump version to 2.4.0 (@ctavan)
- [9a167b7](https://github.com/ctavan/express-validator/commit/9a167b7e524113a78ef04e77bf946d9a8832ddc9) whitespace cleanup
- [668e5c5](https://github.com/ctavan/express-validator/commit/668e5c547c22c78e9b10b525d6357cf9b2e8a969) Add support for custom validators
- [58d2142](https://github.com/ctavan/express-validator/commit/58d2142798898cc6b6bec71a1c333324ec6d6a5a) add documentation on README (@BAKFR)
- [e42f650](https://github.com/ctavan/express-validator/commit/e42f650bb165bcaa18d36a2168a6c43968cf9c90) add the method optional() who disables the checks if value is undefined (@BAKFR)
### v2.3.0 2014/06/06
- [a922832](https://github.com/ctavan/express-validator/commit/a9228327c8969b9640646774115012c29e2f13d2) Bump version to 2.3.0 (@ctavan)
- [85348f5](https://github.com/ctavan/express-validator/commit/85348f59ed65fc657bccb9f63a91954b602855b2) Add a check if req.files array is not undefined before accessing it
### v2.2.0 2014/06/03
- [d2ea7b1](https://github.com/ctavan/express-validator/commit/d2ea7b1315cf7403776b7473798f6219ba26ade6) Bump version to 2.2.0 (@ctavan)
### v2.1.2 2014/04/28
- [6dcddc8](https://github.com/ctavan/express-validator/commit/6dcddc83d71e540d20ec2e0da3dbb717c78acd7f) Bump version to 2.1.2 (@ctavan)
- [bffe0d9](https://github.com/ctavan/express-validator/commit/bffe0d9a2ea9a29505eb2264e04badc4d68e221b) Fixed function call order (@killroy42)
- [129be78](https://github.com/ctavan/express-validator/commit/129be780252c9bb88bd281861561077d4bf96241) Fixed arguments usage for strict compliance (@killroy42)
- [defffe1](https://github.com/ctavan/express-validator/commit/defffe1b4493b7e21122fbe4f5ac877543f8a702) Update express_validator.js (@r3mus)
- [01bdbf4](https://github.com/ctavan/express-validator/commit/01bdbf47486136364635edc73725c92f8690a90c) Return sanitized value from req.sanitize() (@dpolivy)
### v2.1.1 2014/03/17
- [151f5a4](https://github.com/ctavan/express-validator/commit/151f5a45775926a07b01366ac4846823d680871b) Bump version to 2.1.1 (@ctavan)
- [75a8359](https://github.com/ctavan/express-validator/commit/75a8359e5703c1e9476c6244bd9a2dcf98b96add) fix: use strict equality/inequality
- [010cb51](https://github.com/ctavan/express-validator/commit/010cb51f75737a347e69d5118b18789e89f28560) fix docs Extending (@bars3s)
- [7388983](https://github.com/ctavan/express-validator/commit/7388983641ac6243ba5cd24d832fad77e884b455) fix sanitaze trim,ltrim... methods (@bars3s)
- [02930ff](https://github.com/ctavan/express-validator/commit/02930ff915e319b57a5a258893aaaa0d38589c7f) add .idea to .gitignore (@bars3s)
### v2.1.0 2014/03/10
- [aaff5d9](https://github.com/ctavan/express-validator/commit/aaff5d92e006ef6ee55ee3758ccfd17fe92c22ac) Update validator to 3.5.0 and bump version to 2.1.0 (@ctavan)
- [7f3b8a9](https://github.com/ctavan/express-validator/commit/7f3b8a9119b2eb17826015cf59a36e0b3925c55a) Update README. (@ctavan)
- [079c6da](https://github.com/ctavan/express-validator/commit/079c6da0bfe14f95a0b94721488e06081e5b89ed) Update package.json (@gkorland)
- [a91664b](https://github.com/ctavan/express-validator/commit/a91664be05bd3ce37811b0c1e24a75aa8d6e5bff) Update node-validator repository url (@marcbachmann)
- [6fe2aa6](https://github.com/ctavan/express-validator/commit/6fe2aa67a7f9fd0110085e67a8066bc46cdbe605) - fixed typo (@theorm)
- [816437a](https://github.com/ctavan/express-validator/commit/816437a7df0299172d9e78ad6c3d0f29e07ebff9) - and quoting node versions to make travis linter happy (@theorm)
- [aa7d749](https://github.com/ctavan/express-validator/commit/aa7d7496b307394a0c55a7dcfbe55c45d2332d62) - removed node 0.6 from .travis.yml. 0.8+ is required now as it is the minimum version for validator.js (@theorm)
- [36e9025](https://github.com/ctavan/express-validator/commit/36e90250ed322b3aefe220dc2afb5bca40de0a5e) - setting node version to >= 0.8 (@theorm)
- [af9abb5](https://github.com/ctavan/express-validator/commit/af9abb54898438092ecba0dfff5c30eb15b32087) - camelCasing variables (@theorm)
### v2.0.0 2014/01/21
- [22fce51](https://github.com/ctavan/express-validator/commit/22fce515cf2fdf9e1064150773be96bcbae37fad) - major version bump & fixing local vars. (@theorm)
### v1.0.2 2014/01/21
- [94a3c13](https://github.com/ctavan/express-validator/commit/94a3c1360a460d6e32d1142ad412a50e4e74eb0c) - version bump and new contributor (@theorm)
- [a219e29](https://github.com/ctavan/express-validator/commit/a219e29db6d01b9c4c5f86ab91b4e23083e958ca) - modified to work with validator 3.1.0 (@theorm)
- [dc0ee77](https://github.com/ctavan/express-validator/commit/dc0ee7783a98c4922121bffe09fc6e40715cc1a0) added documentation for checkParams and checkQuery (@smitp)
- [a8604f8](https://github.com/ctavan/express-validator/commit/a8604f84e09cadceb7ce14d1118b36e11a31235c) As .xss() is removed from node-validator 2.0.0, changed example in comments (@manV)
### v1.0.1 2013/11/25
- [cd65d4c](https://github.com/ctavan/express-validator/commit/cd65d4c71e0f11ded917c20b6e98d9874ee9add6) Bump version to 1.0.1 (@ctavan)
- [63f1248](https://github.com/ctavan/express-validator/commit/63f124886cd693c70d962cdba99e92c38c4dfa18) add information from #21 as I'm not only one who was stuck at this (@kamilbiela)
### v1.0.0 2013/11/11
- [b63f224](https://github.com/ctavan/express-validator/commit/b63f224f6b5a0394e4213dfc5c399b8565ba0bcd) bumped to 1.0.0 (@petecoop)
- [5e5c0a1](https://github.com/ctavan/express-validator/commit/5e5c0a1f571c48e32f196edb461e494fa432ee0b) updated to v2 (@petecoop)
- [406014e](https://github.com/ctavan/express-validator/commit/406014e3a83fa0ead0b2bcdb012f91b93eeded94) Added support for checkQuery and checkParams + tests (@kornifex)
- [7f33f03](https://github.com/ctavan/express-validator/commit/7f33f031617554b3f5386c48de68e7de831d4ab0) Ensure req.body is defined (@cjihrig)
### v0.8.0 2013/08/22
- [57d62fe](https://github.com/ctavan/express-validator/commit/57d62fe815bd8077eac8b7b6d7686c037d9969b5) Bump version to 0.8.0 (@ctavan)
- [feec643](https://github.com/ctavan/express-validator/commit/feec64356e88e4b1cda4e13db503f6389382a469) Bump validator dependency to 1.5.0, closes #47. (@ctavan)
- [7c181e5](https://github.com/ctavan/express-validator/commit/7c181e51cb74bdfef84a4345ddd0c86d80845ebf) Update README.md (@JedWatson)
### v0.7.0 2013/07/10
- [5f59b15](https://github.com/ctavan/express-validator/commit/5f59b15751adf8f2abe615f33afce9f18e83da1a) Bump version to 0.7.0 (@ctavan)
- [69e9203](https://github.com/ctavan/express-validator/commit/69e92030324b194b372ff6dc106b40c167c2f79e) Bump validator dependency to 1.2.1 (@ctavan)
- [f726037](https://github.com/ctavan/express-validator/commit/f72603764e82e9afb7103c4b1e3090a4e4daadce) Fix two typos (@Michael-Stanford)
- [2f52adb](https://github.com/ctavan/express-validator/commit/2f52adbe46ca9f09da58fa98c33dd197bf57cfe3) Check parsed attached Files (@gkorland)
- [9dde887](https://github.com/ctavan/express-validator/commit/9dde8870ba97be360e12bfae50a39751443b22a0) replace 500 code with 400 (@gkorland)
- [09f5c43](https://github.com/ctavan/express-validator/commit/09f5c435e9918270876b53218e8b6c4ab5b91c1c) Also run tests under node v0.10 in travis. (@ctavan)
### v0.6.0 2013/06/14
- [d493673](https://github.com/ctavan/express-validator/commit/d493673956ee0a1c89e2729366dc636fc3c2b1fd) Bump version to 0.6.0. (@ctavan)
- [5aecec5](https://github.com/ctavan/express-validator/commit/5aecec55b476c586332fc4336b2f5997ed6d034c) Bump validator dependency to 1.2.0 (@ctavan)
- [8fe0862](https://github.com/ctavan/express-validator/commit/8fe086282661c10b1765b557423144adb90d2e17) Bumped version to 5 because this is a breaking change. (@arb)
- [066807b](https://github.com/ctavan/express-validator/commit/066807bd25352e06ab6ad9e58088ebd22ab66d3b) Fixed to work with new structure. (@arb)
- [15216ae](https://github.com/ctavan/express-validator/commit/15216ae24ffceff4f04cb28df4ad001d857c2249) Added method to pass options. (@arb)
- [3a341f5](https://github.com/ctavan/express-validator/commit/3a341f5fc03ab75ba2b653ab208f7801422e1665) Added options section (@arb)
### v0.4.1 2013/06/06
- [e739e2b](https://github.com/ctavan/express-validator/commit/e739e2b6877d58707bdad598f9f634d88f417081) Bump version to 0.4.1 (@ctavan)
- [3f03a68](https://github.com/ctavan/express-validator/commit/3f03a683f7732ac39f53324ed6842120e78b8262) Update readme. (@ctavan)
### v0.4.0 2013/06/06
- [1fe9c03](https://github.com/ctavan/express-validator/commit/1fe9c03f1f4416c5c921429ae775c8bfa4773d2d) Bump version to 0.4.0 (@ctavan)
- [0139626](https://github.com/ctavan/express-validator/commit/0139626b09f9072e2f7739fa2a7c7bd10ab74bb0) Upgrade validator dependency. (@ctavan)
- [5ac347c](https://github.com/ctavan/express-validator/commit/5ac347c8aa3b5abfb085bcf740a8ecae6befc51f) Added ignore file to modules stop being marked as changed. (@arb)
- [96e759e](https://github.com/ctavan/express-validator/commit/96e759e0df154352bef835013fb0a71b5416e5ca) Added test for req.checkBody (@arb)
- [a37b8d7](https://github.com/ctavan/express-validator/commit/a37b8d7d1db41673ef76755178be3fa4335aac56) Added myself to the contributers. (@arb)
- [7bf7729](https://github.com/ctavan/express-validator/commit/7bf77296a00469e9d4de7941cb8968e955da13fd) Style change. (@arb)
- [7cb9113](https://github.com/ctavan/express-validator/commit/7cb9113bec43e28c3ec1f78a2a3e20d763da6f3b) Added check body function to validate only the request body. (@arb)
- [69fdeed](https://github.com/ctavan/express-validator/commit/69fdeed8e82681ee03d9ba347a9b180ee17dade5) Sorry, was moving this around without updating. (@Prinzhorn)
- [9ae9e6b](https://github.com/ctavan/express-validator/commit/9ae9e6be816f8550667ed6a4f3e595d1204f4a43) Updated the documentation about extending. (@Prinzhorn)
### v0.3.2 2013/02/27
- [3c1c52c](https://github.com/ctavan/express-validator/commit/3c1c52c7a10fd79b42814c3c6c28ecece9f6dd71) Bump version to 0.3.2 (@ctavan)
- [4ff8a48](https://github.com/ctavan/express-validator/commit/4ff8a4879aa303ea9ef5f98760eb730a48a184f3) Upgrade validator dependency to 0.4.25. Fixes #25. (@ctavan)
### v0.3.1 2013/01/03
- [48f90b7](https://github.com/ctavan/express-validator/commit/48f90b7922a12fbfbef8bc10bcf98a913dd043ad) Bump version to 0.3.1 (@ctavan)
- [c4463f7](https://github.com/ctavan/express-validator/commit/c4463f767ba75ec61f75e8f13455a003b1076c36) Update package.json
### v0.3.0 2012/10/08
- [fa23c0f](https://github.com/ctavan/express-validator/commit/fa23c0f952e781cdf25d2167b870638440cb5eb5) Bump version to 0.3.0 (@ctavan)
- [62bb9dd](https://github.com/ctavan/express-validator/commit/62bb9dd27f1519e3eebaad2647a51cdf7c82675f) Update validator dependency. (@ctavan)
- [e241d9f](https://github.com/ctavan/express-validator/commit/e241d9fa0accab8fc550c5d5aa398c80a0d38b79) Return `null` for validation errors instead of array. (@ctavan)
- [b60e434](https://github.com/ctavan/express-validator/commit/b60e434e03de9e1e37928381beb71031b86cd446) Fix docs. (@ctavan)
### v0.2.4 2012/08/20
- [1fb5b56](https://github.com/ctavan/express-validator/commit/1fb5b560813b3bd1f0d4a9f556b62804b231d94d) Bump version to v0.2.4 (@ctavan)
- [521e50b](https://github.com/ctavan/express-validator/commit/521e50babe0f40c87cc861d835954ce58c3f2ba6) Fix code style / line lengths. (@ctavan)
- [31d51d2](https://github.com/ctavan/express-validator/commit/31d51d245bb9c8f654e62f0ebdd6c9388d80bbf1) Tests for RegExp-defined routes (@cecchi)
- [f73af12](https://github.com/ctavan/express-validator/commit/f73af126290035577cec014630cb478f08d383bb) Using strict comparison (@cecchi)
- [3ba4e3f](https://github.com/ctavan/express-validator/commit/3ba4e3f2340e9e5000b2dd7dd2e83050ecfb236c) Support for routes defined by RegExp (@cecchi)
### v0.2.3 2012/08/03
- [1590b47](https://github.com/ctavan/express-validator/commit/1590b471943e72535be883d3d718b08eeb8034ad) Bump version to 0.2.3 (@ctavan)
- [fda5c03](https://github.com/ctavan/express-validator/commit/fda5c0374298b8d14e6695143db27c6fd3129f2e) Remove node 0.4 from travis and add 0.8 (@ctavan)
### v0.2.2 2012/08/03
- [9537060](https://github.com/ctavan/express-validator/commit/95370604bfde8ff8326c65e64c6a7cb5cc91b386) Update dependencies and bump version to v0.2.2 (@ctavan)
- [c73802c](https://github.com/ctavan/express-validator/commit/c73802c95a5831415c10f8f8de9616f2fa133705) Add documentation (@ctavan)
- [672d48b](https://github.com/ctavan/express-validator/commit/672d48bc3549734edebcbabe9bc6067393f8dd18) Fix coding style (@ctavan)
- [dfccb6d](https://github.com/ctavan/express-validator/commit/dfccb6d68636b53cb7d78d2cdac4433b40f8a014) Restore removed test case (@ctavan)
- [de62248](https://github.com/ctavan/express-validator/commit/de6224811f666f5945267d2439da20b173efb4b5) Updated test for testing nested dot notation (@sharonjl)
- [2ff7983](https://github.com/ctavan/express-validator/commit/2ff7983a7579f303716f4c176277cbd05935481e) Updated method for parsing nested notation (@sharonjl)
- [c54720f](https://github.com/ctavan/express-validator/commit/c54720f74a517f1bd9bcbbb37364ff5107316565) Added validate() alias for check() (@sharonjl)
- [1b94da6](https://github.com/ctavan/express-validator/commit/1b94da675a86921b73450997c10aa52a5e0c0cf2) Update lib/express_validator.js (@pimguilherme)
### v0.2.1 2012/04/25
- [2a5903d](https://github.com/ctavan/express-validator/commit/2a5903dd629f183c278ff0279637ea44ee517eb5) Bump version to 0.2.1 (@ctavan)
- [861806d](https://github.com/ctavan/express-validator/commit/861806d375dce1d8533435219047e742b4d7bf36) Fix chaining validators (@rapee)
- [5436c0f](https://github.com/ctavan/express-validator/commit/5436c0f5020e97f0a74a09a79e40f88fb532ad89) Add travis.ci (@ctavan)
- [65506ba](https://github.com/ctavan/express-validator/commit/65506bac7a62bc7b50c7213e761a81b536fd1578) Code style fixes (@ctavan)
- [94062f0](https://github.com/ctavan/express-validator/commit/94062f051b8ce10cc87cb20079ee7f553f9e449f) Add Makefile (@ctavan)
- [07f4f06](https://github.com/ctavan/express-validator/commit/07f4f060d5cadbfb2465efe93373a8a7d4fc949e) Add @orfaust to contributors (@ctavan)
- [c4b83d0](https://github.com/ctavan/express-validator/commit/c4b83d0db478e22e557de96649a77b7ab264c168) Add more tests, document additions (@ctavan)
- [c3f3a3e](https://github.com/ctavan/express-validator/commit/c3f3a3e704f95ec14f0e8a12375313ff2c177468) Remove unused variable (@ctavan)
- [dc0d92b](https://github.com/ctavan/express-validator/commit/dc0d92b4430547971c9934b663b3c985a30f6bcf) Refactor tests (@ctavan)
- [cae328a](https://github.com/ctavan/express-validator/commit/cae328a6692130df0335582ab26138f09393210e) Add basic test cases and upgrade versions (@ctavan)
- [0c33221](https://github.com/ctavan/express-validator/commit/0c332216cacf70857cbaa7bbb1ce16aeab7bd471) 1: solution for nested inputs. 2: more complete errors response (@orfaust)
- [0d63f04](https://github.com/ctavan/express-validator/commit/0d63f0442e795ec0371e73050076ea3dd60c0725) Fix for undefined req.onErrorCallback (@orfaust)
- [efba5e8](https://github.com/ctavan/express-validator/commit/efba5e82b81cd14b1ec953a56ec531d8169c1fbd) get complete error objects (@orfaust)
### v0.1.3 2012/01/02
- [4e8f245](https://github.com/ctavan/express-validator/commit/4e8f2451266e6a3a7b20180c723e5760fdef89b9) Version bump v0.1.3 (@ctavan)
- [1041b4c](https://github.com/ctavan/express-validator/commit/1041b4c44c7819fc44aa572fcbf2135bc2518b07) Add another example to the readme (@ctavan)
- [cb7d906](https://github.com/ctavan/express-validator/commit/cb7d906718d6023cce485b2b033647928510b8ef) Update readme (@ctavan)
### v0.1.2 2012/01/02
- [3d323c6](https://github.com/ctavan/express-validator/commit/3d323c6daabc6b106a24aca645e527c204370078) Version bump (@ctavan)
- [de0773c](https://github.com/ctavan/express-validator/commit/de0773ce497aed71bee576b0378635e5c51d494c) exposed Validator & Filter to module so that end-users can easily hang their own validations/sanitizers onto them (@troygoode)
- [bed2d78](https://github.com/ctavan/express-validator/commit/bed2d78417ae3e71ef198b48f005da7af98c1710) Also update readme, see #2 (@ctavan)
- [fffa37f](https://github.com/ctavan/express-validator/commit/fffa37f51d9ba769b562ad7170e29ab391b0588c) Return this in error callback to allow for assert-method-chaining, fixes #2 (@ctavan)
### v0.1.1 2011/10/20
- [d8a7658](https://github.com/ctavan/express-validator/commit/d8a7658ddd34e72c445a5827034481a1e91605b4) Add some keywords (@ctavan)
- [9fd2261](https://github.com/ctavan/express-validator/commit/9fd2261817c3fbe32de26670747c020cf6eb0b71) Update version to v0.1.1 (@ctavan)
- [722d9a7](https://github.com/ctavan/express-validator/commit/722d9a7c98fe9e00968eea5b9660f51c073afd1a) Remove now unneeded mixinParams() method, see #1 (@ctavan)
- [fbd6461](https://github.com/ctavan/express-validator/commit/fbd64617e354c06aac5bbd30d338bb4aa303beca) Update example and documentation for changes of #1, fixes #1 (@ctavan)
- [ce69619](https://github.com/ctavan/express-validator/commit/ce69619266357cada2efa3508ae036b9e483a726) Use req.param() instead of req.params + req.mixinParams() for filter() as well. (@ctavan)
- [0e77df0](https://github.com/ctavan/express-validator/commit/0e77df06d688e69d801976264d23d8bc8bd662bb) Use express's req.param() to get params from req.params, req.query and req.body. req.check now no longer relies on req.mixinParams(), see #1 (@ctavan)
- [779660f](https://github.com/ctavan/express-validator/commit/779660f47565bf6cfc66c447f75448d585831821) Typo (@ctavan)
- [7f398b2](https://github.com/ctavan/express-validator/commit/7f398b29404a93c5222ec339f7aaecf4c143f28b) Installation note (@ctavan)
### v0.1.0 2011/10/05
- [764b5dc](https://github.com/ctavan/express-validator/commit/764b5dc4b63df8f1b2ae23602b75e3d4281b793c) Formatting (@ctavan)
- [d0090e7](https://github.com/ctavan/express-validator/commit/d0090e750ad99ce1d1d0bece930da90c1a2c1743) Add me as a contributor + fix some typos (@ctavan)
- [3537462](https://github.com/ctavan/express-validator/commit/3537462d697f520c18e362e0bad3f453dc26847f) Add original author credits to the packag.json (@ctavan)
- [671ad61](https://github.com/ctavan/express-validator/commit/671ad613c85d546328f05e238a8a1ee27ec6ac2c) Add an example server (@ctavan)
- [ae10270](https://github.com/ctavan/express-validator/commit/ae102704accf206ca617a12014a26c03251a365d) Typos (@ctavan)
- [0dfb1ba](https://github.com/ctavan/express-validator/commit/0dfb1ba5d38039a53f139bacff74e1fb920faec8) Improve example in readme, add credits for original author (@ctavan)
- [df36372](https://github.com/ctavan/express-validator/commit/df36372d05928c8f46c69cf056705f977334a167) Initial commit (@ctavan)

21
node_modules/express-validator/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2010 Chris O'Hara <cohara87@gmail.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.

380
node_modules/express-validator/README.md generated vendored Normal file
View File

@ -0,0 +1,380 @@
# express-validator
[![Build Status](https://secure.travis-ci.org/ctavan/express-validator.png)](http://travis-ci.org/ctavan/express-validator)
An [express.js]( https://github.com/visionmedia/express ) middleware for
[node-validator]( https://github.com/chriso/validator.js ).
## Installation
```
npm install express-validator
```
## Usage
```javascript
var util = require('util'),
express = require('express'),
expressValidator = require('express-validator'),
app = express.createServer();
app.use(express.bodyParser());
app.use(expressValidator([options])); // this line must be immediately after express.bodyParser()!
app.post('/:urlparam', function(req, res) {
// VALIDATION
// checkBody only checks req.body; none of the other req parameters
// Similarly checkParams only checks in req.params (URL params) and
// checkQuery only checks req.query (GET params).
req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
req.checkQuery('getparam', 'Invalid getparam').isInt();
// OR assert can be used to check on all 3 types of params.
// req.assert('postparam', 'Invalid postparam').notEmpty().isInt();
// req.assert('urlparam', 'Invalid urlparam').isAlpha();
// req.assert('getparam', 'Invalid getparam').isInt();
// SANITIZATION
// as with validation these will only validate the corresponding
// request object
req.sanitizeBody('postparam').toBoolean();
req.sanitizeParams('urlparam').toBoolean();
req.sanitizeQuery('getparam').toBoolean();
// OR find the relevent param in all areas
req.sanitize('postparam').toBoolean();
var errors = req.validationErrors();
if (errors) {
res.send('There have been validation errors: ' + util.inspect(errors), 400);
return;
}
res.json({
urlparam: req.params.urlparam,
getparam: req.params.getparam,
postparam: req.params.postparam
});
});
app.listen(8888);
```
Which will result in:
```
$ curl -d 'postparam=1' http://localhost:8888/test?getparam=1
{"urlparam":"test","getparam":"1","postparam":true}
$ curl -d 'postparam=1' http://localhost:8888/t1est?getparam=1
There have been validation errors: [
{ param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ]
$ curl -d 'postparam=1' http://localhost:8888/t1est?getparam=1ab
There have been validation errors: [
{ param: 'getparam', msg: 'Invalid getparam', value: '1ab' },
{ param: 'urlparam', msg: 'Invalid urlparam', value: 't1est' } ]
$ curl http://localhost:8888/test?getparam=1&postparam=1
There have been validation errors: [
{ param: 'postparam', msg: 'Invalid postparam', value: undefined} ]
```
### Middleware Options
####`errorFormatter`
_function(param,msg,value)_
The `errorFormatter` option can be used to specify a function that can be used to format the objects that populate the error array that is returned in `req.validationErrors()`. It should return an `Object` that has `param`, `msg`, and `value` keys defined.
```javascript
// In this example, the formParam value is going to get morphed into form body format useful for printing.
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
```
####`customValidators`
_{ "validatorName": function(value, [additional arguments]), ... }_
The `customValidators` option can be used to add additional validation methods as needed. This option should be an `Object` defining the validator names and associated validation functions.
Define your custom validators:
```javascript
app.use(expressValidator({
customValidators: {
isArray: function(value) {
return Array.isArray(value);
},
gte: function(param, num) {
return param >= num;
}
}
}));
```
Use them with their validator name:
```javascript
req.checkBody('users', 'Users must be an array').isArray();
req.checkQuery('time', 'Time must be an integer great than or equal to 5').isInt().gte(5)
```
####`customSanitizers`
_{ "sanitizerName": function(value, [additional arguments]), ... }_
The `customSanitizers` option can be used to add additional sanitizers methods as needed. This option should be an `Object` defining the sanitizer names and associated functions.
Define your custom sanitizers:
```javascript
app.use(expressValidator({
customSanitizers: {
toSanitizeSomehow: function(value) {
var newValue = value;//some operations
return newValue;
},
}
}));
```
Use them with their sanitizer name:
```javascript
req.sanitize('address').toSanitizeSomehow();
```
## Validation
#### req.check();
```javascript
req.check('testparam', 'Error Message').notEmpty().isInt();
req.check('testparam.child', 'Error Message').isInt(); // find nested params
req.check(['testparam', 'child'], 'Error Message').isInt(); // find nested params
```
Starts the validation of the specifed parameter, will look for the parameter in `req` in the order `params`, `query`, `body`, then validate, you can use 'dot-notation' or an array to access nested values.
If a validator takes in params, you would call it like `req.assert('reqParam').contains('thisString');`.
Validators are appended and can be chained. See [chriso/validator.js](https://github.com/chriso/validator.js) for available validators, or [add your own](#customvalidators).
#### req.assert();
Alias for [req.check()](#reqcheck).
#### req.validate();
Alias for [req.check()](#reqcheck).
#### req.checkBody();
Same as [req.check()](#reqcheck), but only looks in `req.body`.
#### req.checkQuery();
Same as [req.check()](#reqcheck), but only looks in `req.query`.
#### req.checkParams();
Same as [req.check()](#reqcheck), but only looks in `req.params`.
#### req.checkHeaders();
Only checks `req.headers`. This method is not covered by the general `req.check()`.
## Asynchronous Validation
If you need to perform asynchronous validation, for example checking a database if a username has been taken already, your custom validator can return a promise.
You **MUST** use `asyncValidationErrors` which returns a promise to check for errors, otherwise the validator promises won't be resolved.
*`asyncValidationErrors` will also return any regular synchronous validation errors.*
```javascript
app.use(expressValidator({
customValidators: {
isUsernameAvailable: function(username) {
return new Promise(function(resolve, reject) {
...
});
}
}
}));
req.check('username', 'Username Taken').isUsernameAvailable();
req.asyncValidationErrors().catch(function(errors) {
res.send(errors);
});
```
## Validation by Schema
Alternatively you can define all your validations at once using a simple schema. This also enables per-validator error messages.
Schema validation will be used if you pass an object to any of the validator methods.
```javascript
req.checkBody({
'email': {
notEmpty: true,
isEmail: {
errorMessage: 'Invalid Email'
}
},
'password': {
notEmpty: true,
isLength: {
options: [2, 10] // pass options to the validator with the options property as an array
},
errorMessage: 'Invalid Password' // Error message for the parameter
},
'name.first': { //
optional: true, // won't validate if field is empty
isLength: {
options: [2, 10],
errorMessage: 'Must be between 2 and 10 chars long' // Error message for the validator, takes precedent over parameter message
},
errorMessage: 'Invalid First Name'
}
});
```
## Validation errors
You have two choices on how to get the validation errors:
```javascript
req.assert('email', 'required').notEmpty();
req.assert('email', 'valid email required').isEmail();
req.assert('password', '6 to 20 characters required').len(6, 20);
var errors = req.validationErrors(); // Or req.asyncValidationErrors();
var mappedErrors = req.validationErrors(true); // Or req.asyncValidationErrors(true);
```
errors:
```javascript
[
{param: "email", msg: "required", value: "<received input>"},
{param: "email", msg: "valid email required", value: "<received input>"},
{param: "password", msg: "6 to 20 characters required", value: "<received input>"}
]
```
mappedErrors:
```javascript
{
email: {
param: "email",
msg: "valid email required",
value: "<received input>"
},
password: {
param: "password",
msg: "6 to 20 characters required",
value: "<received input>"
}
}
```
*Note: Using mappedErrors will only provide the last error per param in the chain of validation errors.*
### Per-validation messages
You can provide an error message for a single validation with `.withMessage()`. This can be chained with the rest of your validation, and if you don't use it for one of the validations then it will fall back to the default.
```javascript
req.assert('email', 'Invalid email')
.notEmpty().withMessage('Email is required')
.isEmail();
var errors = req.validationErrors();
```
errors:
```javascript
[
{param: 'email', msg: 'Email is required', value: '<received input>'}
{param: 'email', msg: 'Invalid Email', value: '<received input>'}
]
```
## Optional input
You can use the `optional()` method to skip validation. By default, it only skips validation if the key does not exist on the request object. If you want to skip validation based on the property being falsy (null, undefined, etc), you can pass in `{ checkFalsy: true }`.
```javascript
req.checkBody('email').optional().isEmail();
//if there is no error, req.body.email is either undefined or a valid mail.
```
## Sanitizer
#### req.sanitize();
```javascript
req.body.comment = 'a <span>comment</span>';
req.body.username = ' a user ';
req.sanitize('comment').escape(); // returns 'a &lt;span&gt;comment&lt;/span&gt;'
req.sanitize('username').trim(); // returns 'a user'
console.log(req.body.comment); // 'a &lt;span&gt;comment&lt;/span&gt;'
console.log(req.body.username); // 'a user'
```
Sanitizes the specified parameter (using 'dot-notation' or array), the parameter will be updated to the sanitized result. Cannot be chained, and will return the result. See [chriso/validator.js](https://github.com/chriso/validator.js) for available sanitizers, or [add your own](#customsanitizers).
If a sanitizer takes in params, you would call it like `req.sanitize('reqParam').whitelist(['a', 'b', 'c']);`.
If the parameter is present in multiple places with the same name e.g. `req.params.comment` & `req.query.comment`, they will all be sanitized.
#### req.filter();
Alias for [req.sanitize()](#reqsanitize).
#### req.sanitizeBody();
Same as [req.sanitize()](#reqsanitize), but only looks in `req.body`.
#### req.sanitizeQuery();
Same as [req.sanitize()](#reqsanitize), but only looks in `req.query`.
#### req.sanitizeParams();
Same as [req.sanitize()](#reqsanitize), but only looks in `req.params`.
#### req.sanitizeHeaders();
Only sanitizes `req.headers`. This method is not covered by the general `req.sanitize()`.
### Regex routes
Express allows you to define regex routes like:
```javascript
app.get(/\/test(\d+)/, function() {});
```
You can validate the extracted matches like this:
```javascript
req.assert(0, 'Not a three-digit integer.').len(3, 3).isInt();
```
## Changelog
See [CHANGELOG.md](CHANGELOG.md)
## Contributors
- Christoph Tavan <dev@tavan.de> - Wrap the gist in an npm package
- @orfaust - Add `validationErrors()` and nested field support
- @zero21xxx - Added `checkBody` function
## License
Copyright (c) 2010 Chris O'Hara <cohara87@gmail.com>, MIT License

1
node_modules/express-validator/index.js generated vendored Normal file
View File

@ -0,0 +1 @@
module.exports = require('./lib/express_validator.js');

408
node_modules/express-validator/lib/express_validator.js generated vendored Normal file
View File

@ -0,0 +1,408 @@
var validator = require('validator');
var _ = require('lodash');
var Promise = require('bluebird');
// validators and sanitizers not prefixed with is/to
var additionalValidators = ['contains', 'equals', 'matches'];
var additionalSanitizers = ['trim', 'ltrim', 'rtrim', 'escape', 'stripLow', 'whitelist', 'blacklist', 'normalizeEmail'];
/**
* Initializes a chain of validators
*
* @class
* @param {(string|string[])} param path to property to validate
* @param {string} failMsg validation failure message
* @param {Request} req request to attach validation errors
* @param {string} location request property to find value (body, params, query, etc.)
* @param {object} options options containing error formatter
*/
function ValidatorChain(param, failMsg, req, location, options) {
this.errorFormatter = options.errorFormatter;
this.param = param;
this.value = location ? _.get(req[location], param) : undefined;
this.validationErrors = [];
this.failMsg = failMsg;
this.req = req;
this.lastError = null; // used by withMessage to get the values of the last error
return this;
}
/**
* Initializes a sanitizer
*
* @class
* @param {(string|string[])} param path to property to sanitize
* @param {[type]} req request to sanitize
* @param {[type]} location request property to find value
*/
function Sanitizer(param, req, locations) {
this.values = locations.map(function(location) {
return _.get(req[location], param);
});
this.req = req;
this.param = param;
this.locations = locations;
return this;
}
/**
* Adds validation methods to request object via express middleware
*
* @method expressValidator
* @param {object} options
* @return {function} middleware
*/
var expressValidator = function(options) {
options = options || {};
var defaults = {
customValidators: {},
customSanitizers: {},
errorFormatter: function(param, msg, value) {
return {
param: param,
msg: msg,
value: value
};
}
};
_.defaults(options, defaults);
// _.set validators and sanitizers as prototype methods on corresponding chains
_.forEach(validator, function(method, methodName) {
if (methodName.match(/^is/) || _.contains(additionalValidators, methodName)) {
ValidatorChain.prototype[methodName] = makeValidator(methodName, validator);
}
if (methodName.match(/^to/) || _.contains(additionalSanitizers, methodName)) {
Sanitizer.prototype[methodName] = makeSanitizer(methodName, validator);
}
});
ValidatorChain.prototype.notEmpty = function() {
return this.isLength(1);
};
ValidatorChain.prototype.len = function() {
return this.isLength.apply(this, arguments);
};
ValidatorChain.prototype.optional = function(opts) {
opts = opts || {};
// By default, optional checks if the key exists, but the user can pass in
// checkFalsy: true to skip validation if the property is falsy
var defaults = {
checkFalsy: false
};
var options = _.assign(defaults, opts);
if (options.checkFalsy) {
if (!this.value) {
this.skipValidating = true;
}
} else {
if (this.value === undefined) {
this.skipValidating = true;
}
}
return this;
};
ValidatorChain.prototype.withMessage = function(message) {
if (this.lastError) {
this.validationErrors.pop();
this.req._validationErrors.pop();
var error = formatErrors.call(this, this.lastError.param, message, this.lastError.value);
this.validationErrors.push(error);
this.req._validationErrors.push(error);
this.lastError = null;
}
return this;
};
_.forEach(options.customValidators, function(method, customValidatorName) {
ValidatorChain.prototype[customValidatorName] = makeValidator(customValidatorName, options.customValidators);
});
_.forEach(options.customSanitizers, function(method, customSanitizerName) {
Sanitizer.prototype[customSanitizerName] = makeSanitizer(customSanitizerName, options.customSanitizers);
});
return function(req, res, next) {
var locations = ['body', 'params', 'query'];
req._validationErrors = [];
req._asyncValidationErrors = [];
req.validationErrors = function(mapped, promisesResolved) {
if (!promisesResolved && req._asyncValidationErrors.length > 0) {
console.warn('WARNING: You have asynchronous validators but you have not used asyncValidateErrors to check for errors.');
}
if (mapped && req._validationErrors.length > 0) {
var errors = {};
req._validationErrors.forEach(function(err) {
errors[err.param] = err;
});
return errors;
}
return req._validationErrors.length > 0 ? req._validationErrors : false;
};
req.asyncValidationErrors = function(mapped) {
return new Promise(function(resolve, reject) {
var promises = req._asyncValidationErrors;
Promise.settle(promises).then(function(results) {
results.forEach(function(result) {
if (result.isRejected()) { req._validationErrors.push(result.reason()); }
});
if (req._validationErrors.length > 0) {
return reject(req.validationErrors(mapped, true));
}
resolve();
});
});
};
locations.forEach(function(location) {
req['sanitize' + _.capitalize(location)] = function(param) {
return new Sanitizer(param, req, [location]);
};
});
req.sanitizeHeaders = function(param) {
if (param === 'referrer') {
param = 'referer';
}
return new Sanitizer(param, req, ['headers']);
};
req.sanitize = function(param) {
return new Sanitizer(param, req, locations);
};
locations.forEach(function(location) {
req['check' + _.capitalize(location)] = function(param, failMsg) {
if (_.isPlainObject(param)) {
return validateSchema(param, req, location, options);
}
return new ValidatorChain(param, failMsg, req, location, options);
};
});
req.checkFiles = function(param, failMsg) {
return new ValidatorChain(param, failMsg, req, 'files', options);
};
req.checkHeaders = function(param, failMsg) {
if (param === 'referrer') {
param = 'referer';
}
return new ValidatorChain(param, failMsg, req, 'headers', options);
};
req.check = function(param, failMsg) {
if (_.isPlainObject(param)) {
return validateSchema(param, req, 'any', options);
}
return new ValidatorChain(param, failMsg, req, locate(req, param), options);
};
req.filter = req.sanitize;
req.assert = req.check;
req.validate = req.check;
next();
};
};
/**
* validate an object using a schema, using following format:
*
* {
* paramName: {
* validatorName: true,
* validator2Name: true
* }
* }
*
* Pass options or a custom error message:
*
* {
* paramName: {
* validatorName: {
* options: ['', ''],
* errorMessage: 'An Error Message'
* }
* }
* }
*
* @method validateSchema
* @param {Object} schema schema of validations
* @param {Request} req request to attach validation errors
* @param {string} location request property to find value (body, params, query, etc.)
* @param {Object} options options containing custom validators & errorFormatter
* @return {object[]} array of errors
*/
function validateSchema(schema, req, loc, options) {
for (var param in schema) {
loc = loc === 'any' ? locate(req, param) : loc;
var validator = new ValidatorChain(param, null, req, loc, options);
var paramErrorMessage = schema[param].errorMessage;
delete schema[param].errorMessage;
for (var methodName in schema[param]) {
validator.failMsg = schema[param][methodName].errorMessage || paramErrorMessage || 'Invalid param';
validator[methodName].apply(validator, schema[param][methodName].options);
}
}
}
/**
* Validates and handles errors, return instance of itself to allow for chaining
*
* @method makeValidator
* @param {string} methodName
* @param {object} container
* @return {function}
*/
function makeValidator(methodName, container) {
return function() {
if (this.skipValidating) {
return this;
}
var args = [];
args.push(this.value);
args = args.concat(Array.prototype.slice.call(arguments));
var isValid = container[methodName].apply(container, args);
var error = formatErrors.call(this, this.param, this.failMsg || 'Invalid value', this.value);
if (isValid.then) {
var promise = isValid.catch(function() {
return Promise.reject(error);
});
this.req._asyncValidationErrors.push(promise);
}
if (!isValid) {
this.validationErrors.push(error);
this.req._validationErrors.push(error);
this.lastError = { param: this.param, value: this.value };
} else {
this.lastError = null;
}
return this;
};
}
/**
* Sanitizes and sets sanitized value on the request, then return instance of itself to allow for chaining
*
* @method makeSanitizer
* @param {string} methodName
* @param {object} container
* @return {function}
*/
function makeSanitizer(methodName, container) {
return function() {
var _arguments = arguments;
var result;
this.values.forEach(function(value, i) {
if (value != null) {
var args = [value];
args = args.concat(Array.prototype.slice.call(_arguments));
result = container[methodName].apply(container, args);
_.set(this.req[this.locations[i]], this.param, result);
this.values[i] = result;
}
}.bind(this));
return result;
};
}
/**
* find location of param
*
* @method param
* @param {Request} req express request object
* @param {(string|string[])} name [description]
* @return {string}
*/
function locate(req, name) {
if (_.get(req.params, name)) {
return 'params';
} else if (_.has(req.query, name)) {
return 'query';
} else if (_.has(req.body, name)) {
return 'body';
}
return undefined;
}
/**
* format param output if passed in as array (for nested)
* before calling errorFormatter
*
* @method param
* @param {(string|string[])} param parameter as a string or array
* @param {string} msg
* @param {string} value
* @return {function}
*/
function formatErrors(param, msg, value) {
var formattedParam = formatParamOutput(param);
return this.errorFormatter(formattedParam, msg, value);
}
// Convert nested params as array into string for output
// Ex: ['users', '0', 'fields', 'email'] to 'users[0].fields.email'
function formatParamOutput(param) {
if (Array.isArray(param)) {
param = param.reduce(function(prev, curr) {
var part = '';
if (validator.isInt(curr)) {
part = '[' + curr + ']';
} else {
if (prev) {
part = '.' + curr;
} else {
part = curr;
}
}
return prev + part;
});
}
return param;
}
module.exports = expressValidator;
module.exports.validator = validator;
module.exports.utils = {
formatParamOutput: formatParamOutput
};

View File

@ -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.

View File

@ -0,0 +1,679 @@
<a href="http://promisesaplus.com/">
<img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo"
title="Promises/A+ 1.1 compliant" align="right" />
</a>
[![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](#what-are-promises-and-why-should-i-use-them) library with focus on innovative features and performance
# Topics
- [Features](#features)
- [Quick start](#quick-start)
- [API Reference and examples](API.md)
- [Support](#support)
- [What are promises and why should I use them?](#what-are-promises-and-why-should-i-use-them)
- [Questions and issues](#questions-and-issues)
- [Error handling](#error-handling)
- [Development](#development)
- [Testing](#testing)
- [Benchmarking](#benchmarks)
- [Custom builds](#custom-builds)
- [For library authors](#for-library-authors)
- [What is the sync build?](#what-is-the-sync-build)
- [License](#license)
- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)
- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)
- [Changelog](changelog.md)
- [Optimization guide](#optimization-guide)
# Features
<img src="http://petkaantonov.github.io/bluebird/logo.png" alt="bluebird logo" align="right" />
- [Promises A+](http://promisesaplus.com)
- [Synchronous inspection](API.md#synchronous-inspection)
- [Concurrency coordination](API.md#collections)
- [Promisification on steroids](API.md#promisification)
- [Resource management through a parallel of python `with`/C# `using`](API.md#resource-management)
- [Cancellation and timeouts](API.md#cancellation)
- [Parallel for C# `async` and `await`](API.md#generators)
- Mind blowing utilities such as
- [`.bind()`](API.md#binddynamic-thisarg---promise)
- [`.call()`](API.md#callstring-propertyname--dynamic-arg---promise)
- [`Promise.join()`](API.md#promisejoinpromisethenablevalue-promises-function-handler---promise)
- [And](API.md#core) [much](API.md#timers) [more](API.md#utility)!
- [Practical debugging solutions and sane defaults](#error-handling)
- [Sick performance](benchmark/)
<hr>
# Quick start
## Node.js
npm install bluebird
Then:
```js
var Promise = require("bluebird");
```
## Browsers
There are many ways to use bluebird in browsers:
- Direct downloads
- Full build [bluebird.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.js)
- Full build minified [bluebird.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.min.js)
- Core build [bluebird.core.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.js)
- Core build minified [bluebird.core.min.js](https://cdn.jsdelivr.net/bluebird/latest/bluebird.core.min.js)
- You may use browserify on the main export
- You may use the [bower](http://bower.io) package.
When using script tags the global variables `Promise` and `P` (alias for `Promise`) become available.
A [minimal bluebird browser build](#custom-builds) is &asymp;38.92KB minified*, 11.65KB gzipped and has no external dependencies.
*Google Closure Compiler using Simple.
#### Browser support
Browsers that [implement ECMA-262, edition 3](http://en.wikipedia.org/wiki/Ecmascript#Implementations) and later are supported.
[![Selenium Test Status](https://saucelabs.com/browser-matrix/petka_antonov.svg)](https://saucelabs.com/u/petka_antonov)
**Note** that in ECMA-262, edition 3 (IE7, IE8 etc.) it is not possible to use methods that have keyword names like `.catch` and `.finally`. The [API documentation](API.md) always lists a compatible alternative name that you can use if you need to support these browsers. For example `.catch` is replaced with `.caught` and `.finally` with `.lastly`.
Also, [long stack trace](API.md#promiselongstacktraces---void) support is only available in Chrome, Firefox and Internet Explorer 10+.
After quick start, see [API Reference and examples](API.md)
<hr>
# Support
- Mailing list: [bluebird-js@googlegroups.com](https://groups.google.com/forum/#!forum/bluebird-js)
- IRC: #promises @freenode
- StackOverflow: [bluebird tag](http://stackoverflow.com/questions/tagged/bluebird)
- Bugs and feature requests: [github issue tracker](https://github.com/petkaantonov/bluebird/issues?state=open)
<hr>
# What are promises and why should I use them?
You should use promises to turn this:
```js
fs.readFile("file.json", function(err, val) {
if( err ) {
console.error("unable to read file");
}
else {
try {
val = JSON.parse(val);
console.log(val.success);
}
catch( e ) {
console.error("invalid json in file");
}
}
});
```
Into this:
```js
fs.readFileAsync("file.json").then(JSON.parse).then(function(val) {
console.log(val.success);
})
.catch(SyntaxError, function(e) {
console.error("invalid json in file");
})
.catch(function(e) {
console.error("unable to read file");
});
```
*If you are wondering "there is no `readFileAsync` method on `fs` that returns a promise", see [promisification](API.md#promisification)*
Actually you might notice the latter has a lot in common with code that would do the same using synchronous I/O:
```js
try {
var val = JSON.parse(fs.readFileSync("file.json"));
console.log(val.success);
}
//Syntax actually not supported in JS but drives the point
catch(SyntaxError e) {
console.error("invalid json in file");
}
catch(Error e) {
console.error("unable to read file");
}
```
And that is the point - being able to have something that is a lot like `return` and `throw` in synchronous code.
You can also use promises to improve code that was written with callback helpers:
```js
//Copyright Plato http://stackoverflow.com/a/19385911/995876
//CC BY-SA 2.5
mapSeries(URLs, function (URL, done) {
var options = {};
needle.get(URL, options, function (error, response, body) {
if (error) {
return done(error);
}
try {
var ret = JSON.parse(body);
return done(null, ret);
}
catch (e) {
done(e);
}
});
}, function (err, results) {
if (err) {
console.log(err);
} else {
console.log('All Needle requests successful');
// results is a 1 to 1 mapping in order of URLs > needle.body
processAndSaveAllInDB(results, function (err) {
if (err) {
return done(err);
}
console.log('All Needle requests saved');
done(null);
});
}
});
```
Is more pleasing to the eye when done with promises:
```js
Promise.promisifyAll(needle);
var options = {};
var current = Promise.resolve();
Promise.map(URLs, function(URL) {
current = current.then(function () {
return needle.getAsync(URL, options);
});
return current;
}).map(function(responseAndBody){
return JSON.parse(responseAndBody[1]);
}).then(function (results) {
return processAndSaveAllInDB(results);
}).then(function(){
console.log('All Needle requests saved');
}).catch(function (e) {
console.log(e);
});
```
Also promises don't just give you correspondences for synchronous features but can also be used as limited event emitters or callback aggregators.
More reading:
- [Promise nuggets](https://promise-nuggets.github.io/)
- [Why I am switching to promises](http://spion.github.io/posts/why-i-am-switching-to-promises.html)
- [What is the the point of promises](http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/#toc_1)
- [Snippets for common problems](https://github.com/petkaantonov/bluebird/wiki/Snippets)
- [Promise anti-patterns](https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns)
# 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`.
# Error handling
This is a problem every promise library needs to handle in some way. Unhandled rejections/exceptions don't really have a good agreed-on asynchronous correspondence. The problem is that it is impossible to predict the future and know if a rejected promise will eventually be handled.
There are two common pragmatic attempts at solving the problem that promise libraries do.
The more popular one is to have the user explicitly communicate that they are done and any unhandled rejections should be thrown, like so:
```js
download().then(...).then(...).done();
```
For handling this problem, in my opinion, this is completely unacceptable and pointless. The user must remember to explicitly call `.done` and that cannot be justified when the problem is forgetting to create an error handler in the first place.
The second approach, which is what bluebird by default takes, is to call a registered handler if a rejection is unhandled by the start of a second turn. The default handler is to write the stack trace to `stderr` or `console.error` in browsers. This is close to what happens with synchronous code - your code doesn't work as expected and you open console and see a stack trace. Nice.
Of course this is not perfect, if your code for some reason needs to swoop in and attach error handler to some promise after the promise has been hanging around a while then you will see annoying messages. In that case you can use the `.done()` method to signal that any hanging exceptions should be thrown.
If you want to override the default handler for these possibly unhandled rejections, you can pass yours like so:
```js
Promise.onPossiblyUnhandledRejection(function(error){
throw error;
});
```
If you want to also enable long stack traces, call:
```js
Promise.longStackTraces();
```
right after the library is loaded.
In node.js use the environment flag `BLUEBIRD_DEBUG`:
```
BLUEBIRD_DEBUG=1 node server.js
```
to enable long stack traces in all instances of bluebird.
Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created. Long stack traces imply a substantial performance penalty, even after using every trick to optimize them.
Long stack traces are enabled by default in the debug build.
#### Expected and unexpected errors
A practical problem with Promises/A+ is that it models Javascript `try-catch` too closely for its own good. Therefore by default promises inherit `try-catch` warts such as the inability to specify the error types that the catch block is eligible for. It is an anti-pattern in every other language to use catch-all handlers because they swallow exceptions that you might not know about.
Now, Javascript does have a perfectly fine and working way of creating error type hierarchies. It is still quite awkward to use them with the built-in `try-catch` however:
```js
try {
//code
}
catch(e) {
if( e instanceof WhatIWantError) {
//handle
}
else {
throw e;
}
}
```
Without such checking, unexpected errors would be silently swallowed. However, with promises, bluebird brings the future (hopefully) here now and extends the `.catch` to [accept potential error type eligibility](API.md#catchfunction-errorclass-function-handler---promise).
For instance here it is expected that some evil or incompetent entity will try to crash our server from `SyntaxError` by providing syntactically invalid JSON:
```js
getJSONFromSomewhere().then(function(jsonString) {
return JSON.parse(jsonString);
}).then(function(object) {
console.log("it was valid json: ", object);
}).catch(SyntaxError, function(e){
console.log("don't be evil");
});
```
Here any kind of unexpected error will be automatically reported on `stderr` along with a stack trace because we only register a handler for the expected `SyntaxError`.
Ok, so, that's pretty neat. But actually not many libraries define error types and it is in fact a complete ghetto out there with ad hoc strings being attached as some arbitrary property name like `.name`, `.type`, `.code`, not having any property at all or even throwing strings as errors and so on. So how can we still listen for expected errors?
Bluebird defines a special error type `OperationalError` (you can get a reference from `Promise.OperationalError`). This type of error is given as rejection reason by promisified methods when
their underlying library gives an untyped, but expected error. Primitives such as strings, and error objects that are directly created like `new Error("database didn't respond")` are considered untyped.
Example of such library is the node core library `fs`. So if we promisify it, we can catch just the errors we want pretty easily and have programmer errors be redirected to unhandled rejection handler so that we notice them:
```js
//Read more about promisification in the API Reference:
//API.md
var fs = Promise.promisifyAll(require("fs"));
fs.readFileAsync("myfile.json").then(JSON.parse).then(function (json) {
console.log("Successful json");
}).catch(SyntaxError, function (e) {
console.error("file contains invalid json");
}).catch(Promise.OperationalError, function (e) {
console.error("unable to read file, because: ", e.message);
});
```
The last `catch` handler is only invoked when the `fs` module explicitly used the `err` argument convention of async callbacks to inform of an expected error. The `OperationalError` instance will contain the original error in its `.cause` property but it does have a direct copy of the `.message` and `.stack` too. In this code any unexpected error - be it in our code or the `fs` module - would not be caught by these handlers and therefore not swallowed.
Since a `catch` handler typed to `Promise.OperationalError` is expected to be used very often, it has a neat shorthand:
```js
.error(function (e) {
console.error("unable to read file, because: ", e.message);
});
```
See [API documentation for `.error()`](API.md#error-rejectedhandler----promise)
Finally, Bluebird also supports predicate-based filters. If you pass a
predicate function instead of an error type, the predicate will receive
the error as an argument. The return result will be used to determine whether
the error handler should be called.
Predicates should allow for very fine grained control over caught errors:
pattern matching, error typesets with set operations and many other techniques
can be implemented on top of them.
Example of using a predicate-based filter:
```js
var Promise = require("bluebird");
var request = Promise.promisify(require("request"));
function clientError(e) {
return e.code >= 400 && e.code < 500;
}
request("http://www.google.com").then(function(contents){
console.log(contents);
}).catch(clientError, function(e){
//A client error like 400 Bad Request happened
});
```
**Danger:** The JavaScript language allows throwing primitive values like strings. Throwing primitives can lead to worse or no stack traces. Primitives [are not exceptions](http://www.devthought.com/2011/12/22/a-string-is-not-an-error/). You should consider always throwing Error objects when handling exceptions.
<hr>
#### How do long stack traces differ from e.g. Q?
Bluebird attempts to have more elaborate traces. Consider:
```js
Error.stackTraceLimit = 25;
Q.longStackSupport = true;
Q().then(function outer() {
return Q().then(function inner() {
return Q().then(function evenMoreInner() {
a.b.c.d();
}).catch(function catcher(e){
console.error(e.stack);
});
})
});
```
You will see
ReferenceError: a is not defined
at evenMoreInner (<anonymous>:7:13)
From previous event:
at inner (<anonymous>:6:20)
Compare to:
```js
Error.stackTraceLimit = 25;
Promise.longStackTraces();
Promise.resolve().then(function outer() {
return Promise.resolve().then(function inner() {
return Promise.resolve().then(function evenMoreInner() {
a.b.c.d();
}).catch(function catcher(e){
console.error(e.stack);
});
});
});
```
ReferenceError: a is not defined
at evenMoreInner (<anonymous>:7:13)
From previous event:
at inner (<anonymous>:6:36)
From previous event:
at outer (<anonymous>:5:32)
From previous event:
at <anonymous>:4:21
at Object.InjectedScript._evaluateOn (<anonymous>:572:39)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:531:52)
at Object.InjectedScript.evaluate (<anonymous>:450:21)
A better and more practical example of the differences can be seen in gorgikosev's [debuggability competition](https://github.com/spion/async-compare#debuggability).
<hr>
# Development
For development tasks such as running benchmarks or testing, you need to clone the repository and install dev-dependencies.
Install [node](http://nodejs.org/) and [npm](https://npmjs.org/)
git clone git@github.com:petkaantonov/bluebird.git
cd bluebird
npm install
## Testing
To run all tests, run
node tools/test
If you need to run generator tests run the `tool/test.js` script with `--harmony` argument and node 0.11+:
node-dev --harmony tools/test
You may specify an individual test file to run with the `--run` script flag:
node tools/test --run=cancel.js
This enables output from the test and may give a better idea where the test is failing. The parameter to `--run` can be any file name located in `test/mocha` folder.
#### Testing in browsers
To run the test in a browser instead of node, pass the flag `--browser` to the test tool
node tools/test --run=cancel.js --browser
This will automatically create a server (default port 9999) and open it in your default browser once the tests have been compiled.
Keep the test tab active because some tests are timing-sensitive and will fail if the browser is throttling timeouts. Chrome will do this for example when the tab is not active.
#### Supported options by the test tool
The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-browser`.
- `--run=String` - Which tests to run (or compile when testing in browser). Default `"all"`. Can also be a glob string (relative to ./test/mocha folder).
- `--cover=String`. Create code coverage using the String as istanbul reporter. Coverage is created in the ./coverage folder. No coverage is created by default, default reporter is `"html"` (use `--cover` to use default reporter).
- `--browser` - Whether to compile tests for browsers. Default `false`.
- `--port=Number` - Port where local server is hosted when testing in browser. Default `9999`
- `--execute-browser-tests` - Whether to execute the compiled tests for browser when using `--browser`. Default `true`.
- `--open-browser` - Whether to open the default browser when executing browser tests. Default `true`.
- `--fake-timers` - Whether to use fake timers (`setTimeout` etc) when running tests in node. Default `true`.
- `--js-hint` - Whether to run JSHint on source files. Default `true`.
- `--saucelabs` - Whether to create a tunnel to sauce labs and run tests in their VMs instead of your browser when compiling tests for browser. Default `false`.
## Benchmarks
To run a benchmark, run the given command for a benchmark while on the project root. Requires bash (on windows the mingw32 that comes with git works fine too).
Node 0.11.2+ is required to run the generator examples.
### 1\. DoxBee sequential
Currently the most relevant benchmark is @gorkikosev's benchmark in the article [Analysis of generators and other async patterns in node](http://spion.github.io/posts/analysis-generators-and-other-async-patterns-node.html). The benchmark emulates a situation where n amount of users are making a request in parallel to execute some mixed async/sync action. The benchmark has been modified to include a warm-up phase to minimize any JITing during timed sections.
Command: `bench doxbee`
### 2\. Made-up parallel
This made-up scenario runs 15 shimmed queries in parallel.
Command: `bench parallel`
## Custom builds
Custom builds for browsers are supported through a command-line utility.
<table>
<caption>The following features can be disabled</caption>
<thead>
<tr>
<th>Feature(s)</th>
<th>Command line identifier</th>
</tr>
</thead>
<tbody>
<tr><td><a href="API.md#any---promise"><code>.any</code></a> and <a href="API.md#promiseanyarraydynamicpromise-values---promise"><code>Promise.any</code></a></td><td><code>any</code></td></tr>
<tr><td><a href="API.md#race---promise"><code>.race</code></a> and <a href="API.md#promiseracearraypromise-promises---promise"><code>Promise.race</code></a></td><td><code>race</code></td></tr>
<tr><td><a href="API.md#callstring-propertyname--dynamic-arg---promise"><code>.call</code></a> and <a href="API.md#getstring-propertyname---promise"><code>.get</code></a></td><td><code>call_get</code></td></tr>
<tr><td><a href="API.md#filterfunction-filterer---promise"><code>.filter</code></a> and <a href="API.md#promisefilterarraydynamicpromise-values-function-filterer---promise"><code>Promise.filter</code></a></td><td><code>filter</code></td></tr>
<tr><td><a href="API.md#mapfunction-mapper---promise"><code>.map</code></a> and <a href="API.md#promisemaparraydynamicpromise-values-function-mapper---promise"><code>Promise.map</code></a></td><td><code>map</code></td></tr>
<tr><td><a href="API.md#reducefunction-reducer--dynamic-initialvalue---promise"><code>.reduce</code></a> and <a href="API.md#promisereducearraydynamicpromise-values-function-reducer--dynamic-initialvalue---promise"><code>Promise.reduce</code></a></td><td><code>reduce</code></td></tr>
<tr><td><a href="API.md#props---promise"><code>.props</code></a> and <a href="API.md#promisepropsobjectpromise-object---promise"><code>Promise.props</code></a></td><td><code>props</code></td></tr>
<tr><td><a href="API.md#settle---promise"><code>.settle</code></a> and <a href="API.md#promisesettlearraydynamicpromise-values---promise"><code>Promise.settle</code></a></td><td><code>settle</code></td></tr>
<tr><td><a href="API.md#someint-count---promise"><code>.some</code></a> and <a href="API.md#promisesomearraydynamicpromise-values-int-count---promise"><code>Promise.some</code></a></td><td><code>some</code></td></tr>
<tr><td><a href="API.md#nodeifyfunction-callback---promise"><code>.nodeify</code></a></td><td><code>nodeify</code></td></tr>
<tr><td><a href="API.md#promisecoroutinegeneratorfunction-generatorfunction---function"><code>Promise.coroutine</code></a> and <a href="API.md#promisespawngeneratorfunction-generatorfunction---promise"><code>Promise.spawn</code></a></td><td><code>generators</code></td></tr>
<tr><td><a href="API.md#progression">Progression</a></td><td><code>progress</code></td></tr>
<tr><td><a href="API.md#promisification">Promisification</a></td><td><code>promisify</code></td></tr>
<tr><td><a href="API.md#cancellation">Cancellation</a></td><td><code>cancel</code></td></tr>
<tr><td><a href="API.md#timers">Timers</a></td><td><code>timers</code></td></tr>
<tr><td><a href="API.md#resource-management">Resource management</a></td><td><code>using</code></td></tr>
</tbody>
</table>
Make sure you have cloned the repo somewhere and did `npm install` successfully.
After that you can run:
node tools/build --features="core"
The above builds the most minimal build you can get. You can add more features separated by spaces from the above list:
node tools/build --features="core filter map reduce"
The custom build file will be found from `/js/browser/bluebird.js`. It will have a comment that lists the disabled and enabled features.
Note that the build leaves the `/js/main` etc folders with same features so if you use the folder for node.js at the same time, don't forget to build
a full version afterwards (after having taken a copy of the bluebird.js somewhere):
node tools/build --debug --main --zalgo --browser --minify
#### Supported options by the build tool
The value of boolean flags is determined by presence, if you want to pass false value for a boolean flag, use the `no-`-prefix e.g. `--no-debug`.
- `--main` - Whether to build the main build. The main build is placed at `js/main` directory. Default `false`.
- `--debug` - Whether to build the debug build. The debug build is placed at `js/debug` directory. Default `false`.
- `--zalgo` - Whether to build the zalgo build. The zalgo build is placed at `js/zalgo` directory. Default `false`.
- `--browser` - Whether to compile the browser build. The browser build file is placed at `js/browser/bluebird.js` Default `false`.
- `--minify` - Whether to minify the compiled browser build. The minified browser build file is placed at `js/browser/bluebird.min.js` Default `true`.
- `--features=String` - See [custom builds](#custom-builds)
<hr>
## For library authors
Building a library that depends on bluebird? You should know about a few features.
If your library needs to do something obtrusive like adding or modifying methods on the `Promise` prototype, uses long stack traces or uses a custom unhandled rejection handler then... that's totally ok as long as you don't use `require("bluebird")`. Instead you should create a file
that creates an isolated copy. For example, creating a file called `bluebird-extended.js` that contains:
```js
//NOTE the function call right after
module.exports = require("bluebird/js/main/promise")();
```
Your library can then use `var Promise = require("bluebird-extended");` and do whatever it wants with it. Then if the application or other library uses their own bluebird promises they will all play well together because of Promises/A+ thenable assimilation magic.
You should also know about [`.nodeify()`](API.md#nodeifyfunction-callback---promise) which makes it easy to provide a dual callback/promise API.
<hr>
## What is the sync build?
You may now use sync build by:
var Promise = require("bluebird/zalgo");
The sync build is provided to see how forced asynchronity affects benchmarks. It should not be used in real code due to the implied hazards.
The normal async build gives Promises/A+ guarantees about asynchronous resolution of promises. Some people think this affects performance or just plain love their code having a possibility
of stack overflow errors and non-deterministic behavior.
The sync build skips the async call trampoline completely, e.g code like:
async.invoke( this.fn, this, val );
Appears as this in the sync build:
this.fn(val);
This should pressure the CPU slightly less and thus the sync build should perform better. Indeed it does, but only marginally. The biggest performance boosts are from writing efficient Javascript, not from compromising determinism.
Note that while some benchmarks are waiting for the next event tick, the CPU is actually not in use during that time. So the resulting benchmark result is not completely accurate because on node.js you only care about how much the CPU is taxed. Any time spent on CPU is time the whole process (or server) is paralyzed. And it is not graceful like it would be with threads.
```js
var cache = new Map(); //ES6 Map or DataStructures/Map or whatever...
function getResult(url) {
var resolver = Promise.pending();
if (cache.has(url)) {
resolver.resolve(cache.get(url));
}
else {
http.get(url, function(err, content) {
if (err) resolver.reject(err);
else {
cache.set(url, content);
resolver.resolve(content);
}
});
}
return resolver.promise;
}
//The result of console.log is truly random without async guarantees
function guessWhatItPrints( url ) {
var i = 3;
getResult(url).then(function(){
i = 4;
});
console.log(i);
}
```
# Optimization guide
Articles about optimization will be periodically posted in [the wiki section](https://github.com/petkaantonov/bluebird/wiki), polishing edits are welcome.
A single cohesive guide compiled from the articles will probably be done eventually.
# License
The MIT License (MIT)
Copyright (c) 2014 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.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -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);
};
};

View File

@ -42,8 +42,6 @@ Async.prototype.throwLater = function(fn, arg) {
arg = fn;
fn = function () { throw arg; };
}
var domain = this._getDomain();
if (domain !== undefined) fn = domain.bind(fn);
if (typeof setTimeout !== "undefined") {
setTimeout(function() {
fn(arg);
@ -57,71 +55,18 @@ Async.prototype.throwLater = function(fn, arg) {
}
};
Async.prototype._getDomain = function() {};
if (util.isNode) {
var EventsModule = require("events");
var domainGetter = function() {
var domain = process.domain;
if (domain === null) return undefined;
return domain;
};
if (EventsModule.usingDomains) {
Async.prototype._getDomain = domainGetter;
} else {
var descriptor =
Object.getOwnPropertyDescriptor(EventsModule, "usingDomains");
if (!descriptor.configurable) {
process.on("domainsActivated", function() {
Async.prototype._getDomain = domainGetter;
});
} else {
var usingDomains = false;
Object.defineProperty(EventsModule, "usingDomains", {
configurable: false,
enumerable: true,
get: function() {
return usingDomains;
},
set: function(value) {
if (usingDomains || !value) return;
usingDomains = true;
Async.prototype._getDomain = domainGetter;
util.toFastProperties(process);
process.emit("domainsActivated");
}
});
}
}
}
function AsyncInvokeLater(fn, receiver, arg) {
var domain = this._getDomain();
if (domain !== undefined) fn = domain.bind(fn);
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
var domain = this._getDomain();
if (domain !== undefined) fn = domain.bind(fn);
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
var domain = this._getDomain();
if (domain !== undefined) {
var fn = domain.bind(promise._settlePromises);
this._normalQueue.push(fn, promise, undefined);
} else {
this._normalQueue._pushOne(promise);
}
this._normalQueue._pushOne(promise);
this._queueTick();
}
@ -130,13 +75,18 @@ if (!util.hasDevTools) {
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
if (schedule.isStatic) {
schedule = function(fn) { setTimeout(fn, 0); };
}
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
@ -144,9 +94,9 @@ if (!util.hasDevTools) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
setTimeout(function() {
this._schedule(function() {
fn.call(receiver, arg);
}, 0);
});
}
};
@ -154,16 +104,14 @@ if (!util.hasDevTools) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
setTimeout(function() {
this._schedule(function() {
promise._settlePromises();
}, 0);
});
}
};
}
Async.prototype.invokeFirst = function (fn, receiver, arg) {
var domain = this._getDomain();
if (domain !== undefined) fn = domain.bind(fn);
this._normalQueue.unshift(fn, receiver, arg);
this._queueTick();
};

View File

@ -10,7 +10,6 @@ var targetRejected = function(e, context) {
};
var bindingResolved = function(thisArg, context) {
this._setBoundTo(thisArg);
if (this._isPending()) {
this._resolveCallback(context.target);
}
@ -25,6 +24,8 @@ Promise.prototype.bind = function (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,
@ -36,7 +37,6 @@ Promise.prototype.bind = function (thisArg) {
maybePromise._then(
bindingResolved, bindingRejected, ret._progress, ret, context);
} else {
ret._setBoundTo(thisArg);
ret._resolveCallback(target);
}
return ret;
@ -59,13 +59,12 @@ Promise.bind = function (thisArg, value) {
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
maybePromise._then(function(thisArg) {
ret._setBoundTo(thisArg);
maybePromise._then(function() {
ret._resolveCallback(value);
}, ret._reject, ret._progress, ret, null);
} else {
ret._setBoundTo(thisArg);
ret._resolveCallback(value);
}
return ret;

View File

@ -382,7 +382,8 @@ var captureStackTrace = (function stackDetection() {
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow) {
if (!("stack" in err) && hasStackAfterThrow &&
typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {

View File

@ -30,7 +30,7 @@ function safePredicate(predicate, e) {
CatchFilter.prototype.doFilter = function (e) {
var cb = this._callback;
var promise = this._promise;
var boundTo = promise._boundTo;
var boundTo = promise._boundValue();
for (var i = 0, len = this._instances.length; i < len; ++i) {
var item = this._instances[i];
var itemIsErrorType = item === Error ||

View File

@ -1,5 +1,6 @@
"use strict";
module.exports = function(Promise, CapturedTrace) {
var getDomain = Promise._getDomain;
var async = require("./async.js");
var Warning = require("./errors.js").Warning;
var util = require("./util.js");
@ -10,11 +11,19 @@ var debugging = false || (util.isNode &&
(!!process.env["BLUEBIRD_DEBUG"] ||
process.env["NODE_ENV"] === "development"));
if (util.isNode && process.env["BLUEBIRD_DEBUG"] == 0) debugging = false;
if (debugging) {
async.disableTrampolineIfNecessary();
}
Promise.prototype._ignoreRejections = function() {
this._unsetRejectionIsUnhandled();
this._bitField = this._bitField | 16777216;
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 16777216) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
@ -113,11 +122,17 @@ Promise.prototype._warn = function(message) {
};
Promise.onPossiblyUnhandledRejection = function (fn) {
possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined;
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
unhandledRejectionHandled = typeof fn === "function" ? fn : undefined;
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
Promise.longStackTraces = function () {

View File

@ -1,7 +1,6 @@
"use strict";
var util = require("./util.js");
var isPrimitive = util.isPrimitive;
var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
module.exports = function(Promise) {
var returner = function () {
@ -10,6 +9,10 @@ var returner = function () {
var thrower = function () {
throw this;
};
var returnUndefined = function() {};
var throwUndefined = function() {
throw undefined;
};
var wrapper = function (value, action) {
if (action === 1) {
@ -26,7 +29,9 @@ var wrapper = function (value, action) {
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (wrapsPrimitiveReceiver && isPrimitive(value)) {
if (value === undefined) return this.then(returnUndefined);
if (isPrimitive(value)) {
return this._then(
wrapper(value, 2),
undefined,
@ -34,13 +39,17 @@ Promise.prototype.thenReturn = function (value) {
undefined,
undefined
);
} else if (value instanceof Promise) {
value._ignoreRejections();
}
return this._then(returner, undefined, undefined, value, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
if (wrapsPrimitiveReceiver && isPrimitive(reason)) {
if (reason === undefined) return this.then(throwUndefined);
if (isPrimitive(reason)) {
return this._then(
wrapper(reason, 1),
undefined,

View File

@ -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;
}
};
}

View File

@ -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);
};
};

View File

@ -1,7 +1,6 @@
"use strict";
module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) {
var util = require("./util.js");
var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver;
var isPrimitive = util.isPrimitive;
var thrower = util.thrower;
@ -23,7 +22,7 @@ function throw$(r) {
}
function promisedFinally(ret, reasonOrValue, isFulfilled) {
var then;
if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) {
if (isPrimitive(reasonOrValue)) {
then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
} else {
then = isFulfilled ? returnThis : throwThis;
@ -36,7 +35,7 @@ function finallyHandler(reasonOrValue) {
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundTo)
? handler.call(promise._boundValue())
: handler();
if (ret !== undefined) {
@ -61,7 +60,7 @@ function tapHandler(value) {
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundTo, value)
? handler.call(promise._boundValue(), value)
: handler(value);
if (ret !== undefined) {

Some files were not shown because too many files have changed in this diff Show More