diff options
| author | Kumar Priyansh <[email protected]> | 2019-01-19 12:37:14 +0530 |
|---|---|---|
| committer | Kumar Priyansh <[email protected]> | 2019-01-19 12:37:14 +0530 |
| commit | dcdfc94cb39dfe2c39925a0145ffa45e2d061c30 (patch) | |
| tree | 4f6379d955555b298c0e7b83a67e264240ee5614 /cordova/node_modules/q | |
| parent | 76f7b3678d3f1ff99c3935a774d420453b0c3cb9 (diff) | |
| download | WeatherApp-dcdfc94cb39dfe2c39925a0145ffa45e2d061c30.tar.xz WeatherApp-dcdfc94cb39dfe2c39925a0145ffa45e2d061c30.zip | |
Initial Upload via GIT
Diffstat (limited to 'cordova/node_modules/q')
| -rwxr-xr-x | cordova/node_modules/q/CHANGES.md | 800 | ||||
| -rwxr-xr-x | cordova/node_modules/q/LICENSE | 18 | ||||
| -rwxr-xr-x | cordova/node_modules/q/README.md | 874 | ||||
| -rwxr-xr-x | cordova/node_modules/q/package.json | 117 | ||||
| -rwxr-xr-x | cordova/node_modules/q/q.js | 2076 | ||||
| -rwxr-xr-x | cordova/node_modules/q/queue.js | 35 |
6 files changed, 3920 insertions, 0 deletions
diff --git a/cordova/node_modules/q/CHANGES.md b/cordova/node_modules/q/CHANGES.md new file mode 100755 index 0000000..766fcdc --- /dev/null +++ b/cordova/node_modules/q/CHANGES.md @@ -0,0 +1,800 @@ + +## 1.5.1 + + - Q.any now annotates its error message to clarify that Q.any was involved and + includes only the last error emitted. (Ivan Etchart) + - Avoid domain.dispose during tests in preparation for Node.js 9. (Anna + Henningsen) + +## 1.5.0 + + - Q.any gives an error message from the last rejected promise + - Throw if callback supplied to "finally" is invalid (@grahamrhay) + - Long stack trace improvements, can now construct long stack traces + across rethrows. + +## 1.4.1 + + - Address an issue that prevented Q from being used as a `<script>` for + Firefox add-ons. Q can now be used in any environment that provides `window` + or `self` globals, favoring `window` since add-ons have an an immutable + `self` that is distinct from `window`. + +## 1.4.0 + + - Add `noConflict` support for use in `<script>` (@jahnjw). + +## 1.3.0 + + - Add tracking for unhandled and handled rejections in Node.js (@benjamingr). + +## 1.2.1 + + - Fix Node.js environment detection for modern Browserify (@kahnjw). + +## 1.2.0 + + - Added Q.any(promisesArray) method (@vergara). + Returns a promise fulfilled with the value of the first resolved promise in + promisesArray. If all promises in promisesArray are rejected, it returns + a rejected promise. + +## 1.1.2 + + - Removed extraneous files from the npm package by using the "files" + whitelist in package.json instead of the .npmignore blacklist. + (@anton-rudeshko) + +## 1.1.1 + + - Fix a pair of regressions in bootstrapping, one which precluded + WebWorker support, and another that precluded support in + ``<script>`` usage outright. #607 + +## 1.1.0 + + - Adds support for enabling long stack traces in node.js by setting + environment variable `Q_DEBUG=1`. + - Introduces the `tap` method to promises, which will see a value + pass through without alteration. + - Use instanceof to recognize own promise instances as opposed to + thenables. + - Construct timeout errors with `code === ETIMEDOUT` (Kornel Lesiński) + - More descriminant CommonJS module environment detection. + - Dropped continuous integration for Node.js 0.6 and 0.8 because of + changes to npm that preclude the use of new `^` version predicate + operator in any transitive dependency. + - Users can now override `Q.nextTick`. + +## 1.0.1 + + - Adds support for `Q.Promise`, which implements common usage of the + ES6 `Promise` constructor and its methods. `Promise` does not have + a valid promise constructor and a proper implementation awaits + version 2 of Q. + - Removes the console stopgap for a promise inspector. This no longer + works with any degree of reliability. + - Fixes support for content security policies that forbid eval. Now + using the `StopIteration` global to distinguish SpiderMonkey + generators from ES6 generators, assuming that they will never + coexist. + +## 1.0.0 + +:cake: This is all but a re-release of version 0.9, which has settled +into a gentle maintenance mode and rightly deserves an official 1.0. +An ambitious 2.0 release is already around the corner, but 0.9/1.0 +have been distributed far and wide and demand long term support. + + - Q will now attempt to post a debug message in browsers regardless + of whether window.Touch is defined. Chrome at least now has this + property regardless of whether touch is supported by the underlying + hardware. + - Remove deprecation warning from `promise.valueOf`. The function is + called by the browser in various ways so there is no way to + distinguish usage that should be migrated from usage that cannot be + altered. + +## 0.9.7 + + - :warning: `q.min.js` is no longer checked-in. It is however still + created by Grunt and NPM. + - Fixes a bug that inhibited `Q.async` with implementations of the new + ES6 generators. + - Fixes a bug with `nextTick` affecting Safari 6.0.5 the first time a + page loads when an `iframe` is involved. + - Introduces `passByCopy`, `join`, and `race`. + - Shows stack traces or error messages on the console, instead of + `Error` objects. + - Elimintates wrapper methods for improved performance. + - `Q.all` now propagates progress notifications of the form you might + expect of ES6 iterations, `{value, index}` where the `value` is the + progress notification from the promise at `index`. + +## 0.9.6 + + - Fixes a bug in recognizing the difference between compatible Q + promises, and Q promises from before the implementation of "inspect". + The latter are now coerced. + - Fixes an infinite asynchronous coercion cycle introduced by former + solution, in two independently sufficient ways. 1.) All promises + returned by makePromise now implement "inspect", albeit a default + that reports that the promise has an "unknown" state. 2.) The + implementation of "then/when" is now in "then" instead of "when", so + that the responsibility to "coerce" the given promise rests solely in + the "when" method and the "then" method may assume that "this" is a + promise of the right type. + - Refactors `nextTick` to use an unrolled microtask within Q regardless + of how new ticks a requested. #316 @rkatic + +## 0.9.5 + + - Introduces `inspect` for getting the state of a promise as + `{state: "fulfilled" | "rejected" | "pending", value | reason}`. + - Introduces `allSettled` which produces an array of promises states + for the input promises once they have all "settled". This is in + accordance with a discussion on Promises/A+ that "settled" refers to + a promise that is "fulfilled" or "rejected". "resolved" refers to a + deferred promise that has been "resolved" to another promise, + "sealing its fate" to the fate of the successor promise. + - Long stack traces are now off by default. Set `Q.longStackSupport` + to true to enable long stack traces. + - Long stack traces can now follow the entire asynchronous history of a + promise, not just a single jump. + - Introduces `spawn` for an immediately invoked asychronous generator. + @jlongster + - Support for *experimental* synonyms `mapply`, `mcall`, `nmapply`, + `nmcall` for method invocation. + +## 0.9.4 + + - `isPromise` and `isPromiseAlike` now always returns a boolean + (even for falsy values). #284 @lfac-pt + - Support for ES6 Generators in `async` #288 @andywingo + - Clear duplicate promise rejections from dispatch methods #238 @SLaks + - Unhandled rejection API #296 @domenic + `stopUnhandledRejectionTracking`, `getUnhandledReasons`, + `resetUnhandledRejections`. + +## 0.9.3 + + - Add the ability to give `Q.timeout`'s errors a custom error message. #270 + @jgrenon + - Fix Q's call-stack busting behavior in Node.js 0.10, by switching from + `process.nextTick` to `setImmediate`. #254 #259 + - Fix Q's behavior when used with the Mocha test runner in the browser, since + Mocha introduces a fake `process` global without a `nextTick` property. #267 + - Fix some, but not all, cases wherein Q would give false positives in its + unhandled rejection detection (#252). A fix for other cases (#238) is + hopefully coming soon. + - Made `Q.promise` throw early if given a non-function. + +## 0.9.2 + + - Pass through progress notifications when using `timeout`. #229 @omares + - Pass through progress notifications when using `delay`. + - Fix `nbind` to actually bind the `thisArg`. #232 @davidpadbury + +## 0.9.1 + + - Made the AMD detection compatible with the RequireJS optimizer's `namespace` + option. #225 @terinjokes + - Fix side effects from `valueOf`, and thus from `isFulfilled`, `isRejected`, + and `isPending`. #226 @benjamn + +## 0.9.0 + +This release removes many layers of deprecated methods and brings Q closer to +alignment with Mark Miller’s TC39 [strawman][] for concurrency. At the same +time, it fixes many bugs and adds a few features around error handling. Finally, +it comes with an updated and comprehensive [API Reference][]. + +[strawman]: http://wiki.ecmascript.org/doku.php?id=strawman:concurrency +[API Reference]: https://github.com/kriskowal/q/wiki/API-Reference + +### API Cleanup + +The following deprecated or undocumented methods have been removed. +Their replacements are listed here: + +<table> + <thead> + <tr> + <th>0.8.x method</th> + <th>0.9 replacement</th> + </tr> + </thead> + <tbody> + <tr> + <td><code>Q.ref</code></td> + <td><code>Q</code></td> + </tr> + <tr> + <td><code>call</code>, <code>apply</code>, <code>bind</code> (*)</td> + <td><code>fcall</code>/<code>invoke</code>, <code>fapply</code>/<code>post</code>, <code>fbind</code></td> + </tr> + <tr> + <td><code>ncall</code>, <code>napply</code> (*)</td> + <td><code>nfcall</code>/<code>ninvoke</code>, <code>nfapply</code>/<code>npost</code></td> + </tr> + <tr> + <td><code>end</code></td> + <td><code>done</code></td> + </tr> + <tr> + <td><code>put</code></td> + <td><code>set</code></td> + </tr> + <tr> + <td><code>node</code></td> + <td><code>nbind</code></td> + </tr> + <tr> + <td><code>nend</code></td> + <td><code>nodeify</code></td> + </tr> + <tr> + <td><code>isResolved</code></td> + <td><code>isPending</code></td> + </tr> + <tr> + <td><code>deferred.node</code></td> + <td><code>deferred.makeNodeResolver</code></td> + </tr> + <tr> + <td><code>Method</code>, <code>sender</code></td> + <td><code>dispatcher</code></td> + </tr> + <tr> + <td><code>send</code></td> + <td><code>dispatch</code></td> + </tr> + <tr> + <td><code>view</code>, <code>viewInfo</code></td> + <td>(none)</td> + </tr> + </tbody> +</table> + + +(*) Use of ``thisp`` is discouraged. For calling methods, use ``post`` or +``invoke``. + +### Alignment with the Concurrency Strawman + +- Q now exports a `Q(value)` function, an alias for `resolve`. + `Q.call`, `Q.apply`, and `Q.bind` were removed to make room for the + same methods on the function prototype. +- `invoke` has been aliased to `send` in all its forms. +- `post` with no method name acts like `fapply`. + +### Error Handling + +- Long stack traces can be turned off by setting `Q.stackJumpLimit` to zero. + In the future, this property will be used to fine tune how many stack jumps + are retained in long stack traces; for now, anything nonzero is treated as + one (since Q only tracks one stack jump at the moment, see #144). #168 +- In Node.js, if there are unhandled rejections when the process exits, they + are output to the console. #115 + +### Other + +- `delete` and `set` (née `put`) no longer have a fulfillment value. +- Q promises are no longer frozen, which + [helps with performance](http://code.google.com/p/v8/issues/detail?id=1858). +- `thenReject` is now included, as a counterpart to `thenResolve`. +- The included browser `nextTick` shim is now faster. #195 @rkatic. + +### Bug Fixes + +- Q now works in Internet Explorer 10. #186 @ForbesLindesay +- `fbind` no longer hard-binds the returned function's `this` to `undefined`. + #202 +- `Q.reject` no longer leaks memory. #148 +- `npost` with no arguments now works. #207 +- `allResolved` now works with non-Q promises ("thenables"). #179 +- `keys` behavior is now correct even in browsers without native + `Object.keys`. #192 @rkatic +- `isRejected` and the `exception` property now work correctly if the + rejection reason is falsy. #198 + +### Internals and Advanced + +- The internal interface for a promise now uses + `dispatchPromise(resolve, op, operands)` instead of `sendPromise(op, + resolve, ...operands)`, which reduces the cases where Q needs to do + argument slicing. +- The internal protocol uses different operands. "put" is now "set". + "del" is now "delete". "view" and "viewInfo" have been removed. +- `Q.fulfill` has been added. It is distinct from `Q.resolve` in that + it does not pass promises through, nor coerces promises from other + systems. The promise becomes the fulfillment value. This is only + recommended for use when trying to fulfill a promise with an object that has + a `then` function that is at the same time not a promise. + +## 0.8.12 +- Treat foreign promises as unresolved in `Q.isFulfilled`; this lets `Q.all` + work on arrays containing foreign promises. #154 +- Fix minor incompliances with the [Promises/A+ spec][] and [test suite][]. #157 + #158 + +[Promises/A+ spec]: http://promises-aplus.github.com/promises-spec/ +[test suite]: https://github.com/promises-aplus/promises-tests + +## 0.8.11 + + - Added ``nfcall``, ``nfapply``, and ``nfbind`` as ``thisp``-less versions of + ``ncall``, ``napply``, and ``nbind``. The latter are now deprecated. #142 + - Long stack traces no longer cause linearly-growing memory usage when chaining + promises together. #111 + - Inspecting ``error.stack`` in a rejection handler will now give a long stack + trace. #103 + - Fixed ``Q.timeout`` to clear its timeout handle when the promise is rejected; + previously, it kept the event loop alive until the timeout period expired. + #145 @dfilatov + - Added `q/queue` module, which exports an infinite promise queue + constructor. + +## 0.8.10 + + - Added ``done`` as a replacement for ``end``, taking the usual fulfillment, + rejection, and progress handlers. It's essentially equivalent to + ``then(f, r, p).end()``. + - Added ``Q.onerror``, a settable error trap that you can use to get full stack + traces for uncaught errors. #94 + - Added ``thenResolve`` as a shortcut for returning a constant value once a + promise is fulfilled. #108 @ForbesLindesay + - Various tweaks to progress notification, including propagation and + transformation of progress values and only forwarding a single progress + object. + - Renamed ``nend`` to ``nodeify``. It no longer returns an always-fulfilled + promise when a Node callback is passed. + - ``deferred.resolve`` and ``deferred.reject`` no longer (sometimes) return + ``deferred.promise``. + - Fixed stack traces getting mangled if they hit ``end`` twice. #116 #121 @ef4 + - Fixed ``ninvoke`` and ``npost`` to work on promises for objects with Node + methods. #134 + - Fixed accidental coercion of objects with nontrivial ``valueOf`` methods, + like ``Date``s, by the promise's ``valueOf`` method. #135 + - Fixed ``spread`` not calling the passed rejection handler if given a rejected + promise. + +## 0.8.9 + + - Added ``nend`` + - Added preliminary progress notification support, via + ``promise.then(onFulfilled, onRejected, onProgress)``, + ``promise.progress(onProgress)``, and ``deferred.notify(...progressData)``. + - Made ``put`` and ``del`` return the object acted upon for easier chaining. + #84 + - Fixed coercion cycles with cooperating promises. #106 + +## 0.8.7 + + - Support [Montage Require](http://github.com/kriskowal/mr) + +## 0.8.6 + + - Fixed ``npost`` and ``ninvoke`` to pass the correct ``thisp``. #74 + - Fixed various cases involving unorthodox rejection reasons. #73 #90 + @ef4 + - Fixed double-resolving of misbehaved custom promises. #75 + - Sped up ``Q.all`` for arrays contain already-resolved promises or scalar + values. @ForbesLindesay + - Made stack trace filtering work when concatenating assets. #93 @ef4 + - Added warnings for deprecated methods. @ForbesLindesay + - Added ``.npmignore`` file so that dependent packages get a slimmer + ``node_modules`` directory. + +## 0.8.5 + + - Added preliminary support for long traces (@domenic) + - Added ``fapply``, ``fcall``, ``fbind`` for non-thisp + promised function calls. + - Added ``return`` for async generators, where generators + are implemented. + - Rejected promises now have an "exception" property. If an object + isRejected(object), then object.valueOf().exception will + be the wrapped error. + - Added Jasmine specifications + - Support Internet Explorers 7–9 (with multiple bug fixes @domenic) + - Support Firefox 12 + - Support Safari 5.1.5 + - Support Chrome 18 + +## 0.8.4 + + - WARNING: ``promise.timeout`` is now rejected with an ``Error`` object + and the message now includes the duration of the timeout in + miliseconds. This doesn't constitute (in my opinion) a + backward-incompatibility since it is a change of an undocumented and + unspecified public behavior, but if you happened to depend on the + exception being a string, you will need to revise your code. + - Added ``deferred.makeNodeResolver()`` to replace the more cryptic + ``deferred.node()`` method. + - Added experimental ``Q.promise(maker(resolve, reject))`` to make a + promise inside a callback, such that thrown exceptions in the + callback are converted and the resolver and rejecter are arguments. + This is a shorthand for making a deferred directly and inspired by + @gozala’s stream constructor pattern and the Microsoft Windows Metro + Promise constructor interface. + - Added experimental ``Q.begin()`` that is intended to kick off chains + of ``.then`` so that each of these can be reordered without having to + edit the new and former first step. + +## 0.8.3 + + - Added ``isFulfilled``, ``isRejected``, and ``isResolved`` + to the promise prototype. + - Added ``allResolved`` for waiting for every promise to either be + fulfilled or rejected, without propagating an error. @utvara #53 + - Added ``Q.bind`` as a method to transform functions that + return and throw into promise-returning functions. See + [an example](https://gist.github.com/1782808). @domenic + - Renamed ``node`` export to ``nbind``, and added ``napply`` to + complete the set. ``node`` remains as deprecated. @domenic #58 + - Renamed ``Method`` export to ``sender``. ``Method`` + remains as deprecated and will be removed in the next + major version since I expect it has very little usage. + - Added browser console message indicating a live list of + unhandled errors. + - Added support for ``msSetImmediate`` (IE10) or ``setImmediate`` + (available via [polyfill](https://github.com/NobleJS/setImmediate)) + as a browser-side ``nextTick`` implementation. #44 #50 #59 + - Stopped using the event-queue dependency, which was in place for + Narwhal support: now directly using ``process.nextTick``. + - WARNING: EXPERIMENTAL: added ``finally`` alias for ``fin``, ``catch`` + alias for ``fail``, ``try`` alias for ``call``, and ``delete`` alias + for ``del``. These properties are enquoted in the library for + cross-browser compatibility, but may be used as property names in + modern engines. + +## 0.8.2 + + - Deprecated ``ref`` in favor of ``resolve`` as recommended by + @domenic. + - Update event-queue dependency. + +## 0.8.1 + + - Fixed Opera bug. #35 @cadorn + - Fixed ``Q.all([])`` #32 @domenic + +## 0.8.0 + + - WARNING: ``enqueue`` removed. Use ``nextTick`` instead. + This is more consistent with NodeJS and (subjectively) + more explicit and intuitive. + - WARNING: ``def`` removed. Use ``master`` instead. The + term ``def`` was too confusing to new users. + - WARNING: ``spy`` removed in favor of ``fin``. + - WARNING: ``wait`` removed. Do ``all(args).get(0)`` instead. + - WARNING: ``join`` removed. Do ``all(args).spread(callback)`` instead. + - WARNING: Removed the ``Q`` function module.exports alias + for ``Q.ref``. It conflicts with ``Q.apply`` in weird + ways, making it uncallable. + - Revised ``delay`` so that it accepts both ``(value, + timeout)`` and ``(timeout)`` variations based on + arguments length. + - Added ``ref().spread(cb(...args))``, a variant of + ``then`` that spreads an array across multiple arguments. + Useful with ``all()``. + - Added ``defer().node()`` Node callback generator. The + callback accepts ``(error, value)`` or ``(error, + ...values)``. For multiple value arguments, the + fulfillment value is an array, useful in conjunction with + ``spread``. + - Added ``node`` and ``ncall``, both with the signature + ``(fun, thisp_opt, ...args)``. The former is a decorator + and the latter calls immediately. ``node`` optional + binds and partially applies. ``ncall`` can bind and pass + arguments. + +## 0.7.2 + + - Fixed thenable promise assimilation. + +## 0.7.1 + + - Stopped shimming ``Array.prototype.reduce``. The + enumerable property has bad side-effects. Libraries that + depend on this (for example, QQ) will need to be revised. + +## 0.7.0 - BACKWARD INCOMPATIBILITY + + - WARNING: Removed ``report`` and ``asap`` + - WARNING: The ``callback`` argument of the ``fin`` + function no longer receives any arguments. Thus, it can + be used to call functions that should not receive + arguments on resolution. Use ``when``, ``then``, or + ``fail`` if you need a value. + - IMPORTANT: Fixed a bug in the use of ``MessageChannel`` + for ``nextTick``. + - Renamed ``enqueue`` to ``nextTick``. + - Added experimental ``view`` and ``viewInfo`` for creating + views of promises either when or before they're + fulfilled. + - Shims are now externally applied so subsequent scripts or + dependees can use them. + - Improved minification results. + - Improved readability. + +## 0.6.0 - BACKWARD INCOMPATIBILITY + + - WARNING: In practice, the implementation of ``spy`` and + the name ``fin`` were useful. I've removed the old + ``fin`` implementation and renamed/aliased ``spy``. + - The "q" module now exports its ``ref`` function as a "Q" + constructor, with module systems that support exports + assignment including NodeJS, RequireJS, and when used as + a ``<script>`` tag. Notably, strictly compliant CommonJS + does not support this, but UncommonJS does. + - Added ``async`` decorator for generators that use yield + to "trampoline" promises. In engines that support + generators (SpiderMonkey), this will greatly reduce the + need for nested callbacks. + - Made ``when`` chainable. + - Made ``all`` chainable. + +## 0.5.3 + + - Added ``all`` and refactored ``join`` and ``wait`` to use + it. All of these will now reject at the earliest + rejection. + +## 0.5.2 + + - Minor improvement to ``spy``; now waits for resolution of + callback promise. + +## 0.5.1 + + - Made most Q API methods chainable on promise objects, and + turned the previous promise-methods of ``join``, + ``wait``, and ``report`` into Q API methods. + - Added ``apply`` and ``call`` to the Q API, and ``apply`` + as a promise handler. + - Added ``fail``, ``fin``, and ``spy`` to Q and the promise + prototype for convenience when observing rejection, + fulfillment and rejection, or just observing without + affecting the resolution. + - Renamed ``def`` (although ``def`` remains shimmed until + the next major release) to ``master``. + - Switched to using ``MessageChannel`` for next tick task + enqueue in browsers that support it. + +## 0.5.0 - MINOR BACKWARD INCOMPATIBILITY + + - Exceptions are no longer reported when consumed. + - Removed ``error`` from the API. Since exceptions are + getting consumed, throwing them in an errback causes the + exception to silently disappear. Use ``end``. + - Added ``end`` as both an API method and a promise-chain + ending method. It causes propagated rejections to be + thrown, which allows Node to write stack traces and + emit ``uncaughtException`` events, and browsers to + likewise emit ``onerror`` and log to the console. + - Added ``join`` and ``wait`` as promise chain functions, + so you can wait for variadic promises, returning your own + promise back, or join variadic promises, resolving with a + callback that receives variadic fulfillment values. + +## 0.4.4 + + - ``end`` no longer returns a promise. It is the end of the + promise chain. + - Stopped reporting thrown exceptions in ``when`` callbacks + and errbacks. These must be explicitly reported through + ``.end()``, ``.then(null, Q.error)``, or some other + mechanism. + - Added ``report`` as an API method, which can be used as + an errback to report and propagate an error. + - Added ``report`` as a promise-chain method, so an error + can be reported if it passes such a gate. + +## 0.4.3 + + - Fixed ``<script>`` support that regressed with 0.4.2 + because of "use strict" in the module system + multi-plexer. + +## 0.4.2 + + - Added support for RequireJS (jburke) + +## 0.4.1 + + - Added an "end" method to the promise prototype, + as a shorthand for waiting for the promise to + be resolved gracefully, and failing to do so, + to dump an error message. + +## 0.4.0 - BACKWARD INCOMPATIBLE* + + - *Removed the utility modules. NPM and Node no longer + expose any module except the main module. These have + been moved and merged into the "qq" package. + - *In a non-CommonJS browser, q.js can be used as a script. + It now creates a Q global variable. + - Fixed thenable assimilation. + - Fixed some issues with asap, when it resolves to + undefined, or throws an exception. + +## 0.3.0 - BACKWARD-INCOMPATIBLE + + - The `post` method has been reverted to its original + signature, as provided in Tyler Close's `ref_send` API. + That is, `post` accepts two arguments, the second of + which is an arbitrary object, but usually invocation + arguments as an `Array`. To provide variadic arguments + to `post`, there is a new `invoke` function that posts + the variadic arguments to the value given in the first + argument. + - The `defined` method has been moved from `q` to `q/util` + since it gets no use in practice but is still + theoretically useful. + - The `Promise` constructor has been renamed to + `makePromise` to be consistent with the convention that + functions that do not require the `new` keyword to be + used as constructors have camelCase names. + - The `isResolved` function has been renamed to + `isFulfilled`. There is a new `isResolved` function that + indicates whether a value is not a promise or, if it is a + promise, whether it has been either fulfilled or + rejected. The code has been revised to reflect this + nuance in terminology. + +## 0.2.10 + + - Added `join` to `"q/util"` for variadically joining + multiple promises. + +## 0.2.9 + + - The future-compatible `invoke` method has been added, + to replace `post`, since `post` will become backward- + incompatible in the next major release. + - Exceptions thrown in the callbacks of a `when` call are + now emitted to Node's `"uncaughtException"` `process` + event in addition to being returned as a rejection reason. + +## 0.2.8 + + - Exceptions thrown in the callbacks of a `when` call + are now consumed, warned, and transformed into + rejections of the promise returned by `when`. + +## 0.2.7 + + - Fixed a minor bug in thenable assimilation, regressed + because of the change in the forwarding protocol. + - Fixed behavior of "q/util" `deep` method on dates and + other primitives. Github issue #11. + +## 0.2.6 + + - Thenables (objects with a "then" method) are accepted + and provided, bringing this implementation of Q + into conformance with Promises/A, B, and D. + - Added `makePromise`, to replace the `Promise` function + eventually. + - Rejections are now also duck-typed. A rejection is a + promise with a valueOf method that returns a rejection + descriptor. A rejection descriptor has a + "promiseRejected" property equal to "true" and a + "reason" property corresponding to the rejection reason. + - Altered the `makePromise` API such that the `fallback` + method no longer receives a superfluous `resolved` method + after the `operator`. The fallback method is responsible + only for returning a resolution. This breaks an + undocumented API, so third-party API's depending on the + previous undocumented behavior may break. + +## 0.2.5 + + - Changed promises into a duck-type such that multiple + instances of the Q module can exchange promise objects. + A promise is now defined as "an object that implements the + `promiseSend(op, resolved, ...)` method and `valueOf`". + - Exceptions in promises are now captured and returned + as rejections. + +## 0.2.4 + + - Fixed bug in `ref` that prevented `del` messages from + being received (gozala) + - Fixed a conflict with FireFox 4; constructor property + is now read-only. + +## 0.2.3 + + - Added `keys` message to promises and to the promise API. + +## 0.2.2 + + - Added boilerplate to `q/queue` and `q/util`. + - Fixed missing dependency to `q/queue`. + +## 0.2.1 + + - The `resolve` and `reject` methods of `defer` objects now + return the resolution promise for convenience. + - Added `q/util`, which provides `step`, `delay`, `shallow`, + `deep`, and three reduction orders. + - Added `q/queue` module for a promise `Queue`. + - Added `q-comm` to the list of compatible libraries. + - Deprecated `defined` from `q`, with intent to move it to + `q/util`. + +## 0.2.0 - BACKWARD INCOMPATIBLE + + - Changed post(ref, name, args) to variadic + post(ref, name, ...args). BACKWARD INCOMPATIBLE + - Added a def(value) method to annotate an object as being + necessarily a local value that cannot be serialized, such + that inter-process/worker/vat promise communication + libraries will send messages to it, but never send it + back. + - Added a send(value, op, ...args) method to the public API, for + forwarding messages to a value or promise in a future turn. + +## 0.1.9 + + - Added isRejected() for testing whether a value is a rejected + promise. isResolved() retains the behavior of stating + that rejected promises are not resolved. + +## 0.1.8 + + - Fixed isResolved(null) and isResolved(undefined) [issue #9] + - Fixed a problem with the Object.create shim + +## 0.1.7 + + - shimmed ES5 Object.create in addition to Object.freeze + for compatibility on non-ES5 engines (gozala) + +## 0.1.6 + + - Q.isResolved added + - promise.valueOf() now returns the value of resolved + and near values + - asap retried + - promises are frozen when possible + +## 0.1.5 + + - fixed dependency list for Teleport (gozala) + - all unit tests now pass (gozala) + +## 0.1.4 + + - added support for Teleport as an engine (gozala) + - simplified and updated methods for getting internal + print and enqueue functions universally (gozala) + +## 0.1.3 + + - fixed erroneous link to the q module in package.json + +## 0.1.2 + + - restructured for overlay style package compatibility + +## 0.1.0 + + - removed asap because it was broken, probably down to the + philosophy. + +## 0.0.3 + + - removed q-util + - fixed asap so it returns a value if completed + +## 0.0.2 + + - added q-util + +## 0.0.1 + + - initial version diff --git a/cordova/node_modules/q/LICENSE b/cordova/node_modules/q/LICENSE new file mode 100755 index 0000000..9ce1ea5 --- /dev/null +++ b/cordova/node_modules/q/LICENSE @@ -0,0 +1,18 @@ +Copyright 2009–2017 Kristopher Michael Kowal. All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/cordova/node_modules/q/README.md b/cordova/node_modules/q/README.md new file mode 100755 index 0000000..d2f57a6 --- /dev/null +++ b/cordova/node_modules/q/README.md @@ -0,0 +1,874 @@ +[](http://travis-ci.org/kriskowal/q) +[](https://cdnjs.com/libraries/q.js) + +<a href="http://promises-aplus.github.com/promises-spec"> + <img src="http://kriskowal.github.io/q/q.png" align="right" alt="Q logo" /> +</a> + +If a function cannot return a value or throw an exception without +blocking, it can return a promise instead. A promise is an object +that represents the return value or the thrown exception that the +function may eventually provide. A promise can also be used as a +proxy for a [remote object][Q-Connection] to overcome latency. + +[Q-Connection]: https://github.com/kriskowal/q-connection + +On the first pass, promises can mitigate the “[Pyramid of +Doom][POD]”: the situation where code marches to the right faster +than it marches forward. + +[POD]: http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/ + +```javascript +step1(function (value1) { + step2(value1, function(value2) { + step3(value2, function(value3) { + step4(value3, function(value4) { + // Do something with value4 + }); + }); + }); +}); +``` + +With a promise library, you can flatten the pyramid. + +```javascript +Q.fcall(promisedStep1) +.then(promisedStep2) +.then(promisedStep3) +.then(promisedStep4) +.then(function (value4) { + // Do something with value4 +}) +.catch(function (error) { + // Handle any error from all above steps +}) +.done(); +``` + +With this approach, you also get implicit error propagation, just like `try`, +`catch`, and `finally`. An error in `promisedStep1` will flow all the way to +the `catch` function, where it’s caught and handled. (Here `promisedStepN` is +a version of `stepN` that returns a promise.) + +The callback approach is called an “inversion of control”. +A function that accepts a callback instead of a return value +is saying, “Don’t call me, I’ll call you.”. Promises +[un-invert][IOC] the inversion, cleanly separating the input +arguments from control flow arguments. This simplifies the +use and creation of API’s, particularly variadic, +rest and spread arguments. + +[IOC]: http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript + + +## Getting Started + +The Q module can be loaded as: + +- A ``<script>`` tag (creating a ``Q`` global variable): ~2.5 KB minified and + gzipped. +- A Node.js and CommonJS module, available in [npm](https://npmjs.org/) as + the [q](https://npmjs.org/package/q) package +- An AMD module +- A [component](https://github.com/component/component) as ``microjs/q`` +- Using [bower](http://bower.io/) as `q#^1.4.1` +- Using [NuGet](http://nuget.org/) as [Q](https://nuget.org/packages/q) + +Q can exchange promises with jQuery, Dojo, When.js, WinJS, and more. + +## Resources + +Our [wiki][] contains a number of useful resources, including: + +- A method-by-method [Q API reference][reference]. +- A growing [examples gallery][examples], showing how Q can be used to make + everything better. From XHR to database access to accessing the Flickr API, + Q is there for you. +- There are many libraries that produce and consume Q promises for everything + from file system/database access or RPC to templating. For a list of some of + the more popular ones, see [Libraries][]. +- If you want materials that introduce the promise concept generally, and the + below tutorial isn't doing it for you, check out our collection of + [presentations, blog posts, and podcasts][resources]. +- A guide for those [coming from jQuery's `$.Deferred`][jquery]. + +We'd also love to have you join the Q-Continuum [mailing list][]. + +[wiki]: https://github.com/kriskowal/q/wiki +[reference]: https://github.com/kriskowal/q/wiki/API-Reference +[examples]: https://github.com/kriskowal/q/wiki/Examples-Gallery +[Libraries]: https://github.com/kriskowal/q/wiki/Libraries +[resources]: https://github.com/kriskowal/q/wiki/General-Promise-Resources +[jquery]: https://github.com/kriskowal/q/wiki/Coming-from-jQuery +[mailing list]: https://groups.google.com/forum/#!forum/q-continuum + + +## Tutorial + +Promises have a ``then`` method, which you can use to get the eventual +return value (fulfillment) or thrown exception (rejection). + +```javascript +promiseMeSomething() +.then(function (value) { +}, function (reason) { +}); +``` + +If ``promiseMeSomething`` returns a promise that gets fulfilled later +with a return value, the first function (the fulfillment handler) will be +called with the value. However, if the ``promiseMeSomething`` function +gets rejected later by a thrown exception, the second function (the +rejection handler) will be called with the exception. + +Note that resolution of a promise is always asynchronous: that is, the +fulfillment or rejection handler will always be called in the next turn of the +event loop (i.e. `process.nextTick` in Node). This gives you a nice +guarantee when mentally tracing the flow of your code, namely that +``then`` will always return before either handler is executed. + +In this tutorial, we begin with how to consume and work with promises. We'll +talk about how to create them, and thus create functions like +`promiseMeSomething` that return promises, [below](#the-beginning). + + +### Propagation + +The ``then`` method returns a promise, which in this example, I’m +assigning to ``outputPromise``. + +```javascript +var outputPromise = getInputPromise() +.then(function (input) { +}, function (reason) { +}); +``` + +The ``outputPromise`` variable becomes a new promise for the return +value of either handler. Since a function can only either return a +value or throw an exception, only one handler will ever be called and it +will be responsible for resolving ``outputPromise``. + +- If you return a value in a handler, ``outputPromise`` will get + fulfilled. + +- If you throw an exception in a handler, ``outputPromise`` will get + rejected. + +- If you return a **promise** in a handler, ``outputPromise`` will + “become” that promise. Being able to become a new promise is useful + for managing delays, combining results, or recovering from errors. + +If the ``getInputPromise()`` promise gets rejected and you omit the +rejection handler, the **error** will go to ``outputPromise``: + +```javascript +var outputPromise = getInputPromise() +.then(function (value) { +}); +``` + +If the input promise gets fulfilled and you omit the fulfillment handler, the +**value** will go to ``outputPromise``: + +```javascript +var outputPromise = getInputPromise() +.then(null, function (error) { +}); +``` + +Q promises provide a ``fail`` shorthand for ``then`` when you are only +interested in handling the error: + +```javascript +var outputPromise = getInputPromise() +.fail(function (error) { +}); +``` + +If you are writing JavaScript for modern engines only or using +CoffeeScript, you may use `catch` instead of `fail`. + +Promises also have a ``fin`` function that is like a ``finally`` clause. +The final handler gets called, with no arguments, when the promise +returned by ``getInputPromise()`` either returns a value or throws an +error. The value returned or error thrown by ``getInputPromise()`` +passes directly to ``outputPromise`` unless the final handler fails, and +may be delayed if the final handler returns a promise. + +```javascript +var outputPromise = getInputPromise() +.fin(function () { + // close files, database connections, stop servers, conclude tests +}); +``` + +- If the handler returns a value, the value is ignored +- If the handler throws an error, the error passes to ``outputPromise`` +- If the handler returns a promise, ``outputPromise`` gets postponed. The + eventual value or error has the same effect as an immediate return + value or thrown error: a value would be ignored, an error would be + forwarded. + +If you are writing JavaScript for modern engines only or using +CoffeeScript, you may use `finally` instead of `fin`. + +### Chaining + +There are two ways to chain promises. You can chain promises either +inside or outside handlers. The next two examples are equivalent. + +```javascript +return getUsername() +.then(function (username) { + return getUser(username) + .then(function (user) { + // if we get here without an error, + // the value returned here + // or the exception thrown here + // resolves the promise returned + // by the first line + }) +}); +``` + +```javascript +return getUsername() +.then(function (username) { + return getUser(username); +}) +.then(function (user) { + // if we get here without an error, + // the value returned here + // or the exception thrown here + // resolves the promise returned + // by the first line +}); +``` + +The only difference is nesting. It’s useful to nest handlers if you +need to capture multiple input values in your closure. + +```javascript +function authenticate() { + return getUsername() + .then(function (username) { + return getUser(username); + }) + // chained because we will not need the user name in the next event + .then(function (user) { + return getPassword() + // nested because we need both user and password next + .then(function (password) { + if (user.passwordHash !== hash(password)) { + throw new Error("Can't authenticate"); + } + }); + }); +} +``` + + +### Combination + +You can turn an array of promises into a promise for the whole, +fulfilled array using ``all``. + +```javascript +return Q.all([ + eventualAdd(2, 2), + eventualAdd(10, 20) +]); +``` + +If you have a promise for an array, you can use ``spread`` as a +replacement for ``then``. The ``spread`` function “spreads” the +values over the arguments of the fulfillment handler. The rejection handler +will get called at the first sign of failure. That is, whichever of +the received promises fails first gets handled by the rejection handler. + +```javascript +function eventualAdd(a, b) { + return Q.spread([a, b], function (a, b) { + return a + b; + }) +} +``` + +But ``spread`` calls ``all`` initially, so you can skip it in chains. + +```javascript +return getUsername() +.then(function (username) { + return [username, getUser(username)]; +}) +.spread(function (username, user) { +}); +``` + +The ``all`` function returns a promise for an array of values. When this +promise is fulfilled, the array contains the fulfillment values of the original +promises, in the same order as those promises. If one of the given promises +is rejected, the returned promise is immediately rejected, not waiting for the +rest of the batch. If you want to wait for all of the promises to either be +fulfilled or rejected, you can use ``allSettled``. + +```javascript +Q.allSettled(promises) +.then(function (results) { + results.forEach(function (result) { + if (result.state === "fulfilled") { + var value = result.value; + } else { + var reason = result.reason; + } + }); +}); +``` + +The ``any`` function accepts an array of promises and returns a promise that is +fulfilled by the first given promise to be fulfilled, or rejected if all of the +given promises are rejected. + +```javascript +Q.any(promises) +.then(function (first) { + // Any of the promises was fulfilled. +}, function (error) { + // All of the promises were rejected. +}); +``` + +### Sequences + +If you have a number of promise-producing functions that need +to be run sequentially, you can of course do so manually: + +```javascript +return foo(initialVal).then(bar).then(baz).then(qux); +``` + +However, if you want to run a dynamically constructed sequence of +functions, you'll want something like this: + +```javascript +var funcs = [foo, bar, baz, qux]; + +var result = Q(initialVal); +funcs.forEach(function (f) { + result = result.then(f); +}); +return result; +``` + +You can make this slightly more compact using `reduce`: + +```javascript +return funcs.reduce(function (soFar, f) { + return soFar.then(f); +}, Q(initialVal)); +``` + +Or, you could use the ultra-compact version: + +```javascript +return funcs.reduce(Q.when, Q(initialVal)); +``` + +### Handling Errors + +One sometimes-unintuitive aspect of promises is that if you throw an +exception in the fulfillment handler, it will not be caught by the error +handler. + +```javascript +return foo() +.then(function (value) { + throw new Error("Can't bar."); +}, function (error) { + // We only get here if "foo" fails +}); +``` + +To see why this is, consider the parallel between promises and +``try``/``catch``. We are ``try``-ing to execute ``foo()``: the error +handler represents a ``catch`` for ``foo()``, while the fulfillment handler +represents code that happens *after* the ``try``/``catch`` block. +That code then needs its own ``try``/``catch`` block. + +In terms of promises, this means chaining your rejection handler: + +```javascript +return foo() +.then(function (value) { + throw new Error("Can't bar."); +}) +.fail(function (error) { + // We get here with either foo's error or bar's error +}); +``` + +### Progress Notification + +It's possible for promises to report their progress, e.g. for tasks that take a +long time like a file upload. Not all promises will implement progress +notifications, but for those that do, you can consume the progress values using +a third parameter to ``then``: + +```javascript +return uploadFile() +.then(function () { + // Success uploading the file +}, function (err) { + // There was an error, and we get the reason for error +}, function (progress) { + // We get notified of the upload's progress as it is executed +}); +``` + +Like `fail`, Q also provides a shorthand for progress callbacks +called `progress`: + +```javascript +return uploadFile().progress(function (progress) { + // We get notified of the upload's progress +}); +``` + +### The End + +When you get to the end of a chain of promises, you should either +return the last promise or end the chain. Since handlers catch +errors, it’s an unfortunate pattern that the exceptions can go +unobserved. + +So, either return it, + +```javascript +return foo() +.then(function () { + return "bar"; +}); +``` + +Or, end it. + +```javascript +foo() +.then(function () { + return "bar"; +}) +.done(); +``` + +Ending a promise chain makes sure that, if an error doesn’t get +handled before the end, it will get rethrown and reported. + +This is a stopgap. We are exploring ways to make unhandled errors +visible without any explicit handling. + + +### The Beginning + +Everything above assumes you get a promise from somewhere else. This +is the common case. Every once in a while, you will need to create a +promise from scratch. + +#### Using ``Q.fcall`` + +You can create a promise from a value using ``Q.fcall``. This returns a +promise for 10. + +```javascript +return Q.fcall(function () { + return 10; +}); +``` + +You can also use ``fcall`` to get a promise for an exception. + +```javascript +return Q.fcall(function () { + throw new Error("Can't do it"); +}); +``` + +As the name implies, ``fcall`` can call functions, or even promised +functions. This uses the ``eventualAdd`` function above to add two +numbers. + +```javascript +return Q.fcall(eventualAdd, 2, 2); +``` + + +#### Using Deferreds + +If you have to interface with asynchronous functions that are callback-based +instead of promise-based, Q provides a few shortcuts (like ``Q.nfcall`` and +friends). But much of the time, the solution will be to use *deferreds*. + +```javascript +var deferred = Q.defer(); +FS.readFile("foo.txt", "utf-8", function (error, text) { + if (error) { + deferred.reject(new Error(error)); + } else { + deferred.resolve(text); + } +}); +return deferred.promise; +``` + +Note that a deferred can be resolved with a value or a promise. The +``reject`` function is a shorthand for resolving with a rejected +promise. + +```javascript +// this: +deferred.reject(new Error("Can't do it")); + +// is shorthand for: +var rejection = Q.fcall(function () { + throw new Error("Can't do it"); +}); +deferred.resolve(rejection); +``` + +This is a simplified implementation of ``Q.delay``. + +```javascript +function delay(ms) { + var deferred = Q.defer(); + setTimeout(deferred.resolve, ms); + return deferred.promise; +} +``` + +This is a simplified implementation of ``Q.timeout`` + +```javascript +function timeout(promise, ms) { + var deferred = Q.defer(); + Q.when(promise, deferred.resolve); + delay(ms).then(function () { + deferred.reject(new Error("Timed out")); + }); + return deferred.promise; +} +``` + +Finally, you can send a progress notification to the promise with +``deferred.notify``. + +For illustration, this is a wrapper for XML HTTP requests in the browser. Note +that a more [thorough][XHR] implementation would be in order in practice. + +[XHR]: https://github.com/montagejs/mr/blob/71e8df99bb4f0584985accd6f2801ef3015b9763/browser.js#L29-L73 + +```javascript +function requestOkText(url) { + var request = new XMLHttpRequest(); + var deferred = Q.defer(); + + request.open("GET", url, true); + request.onload = onload; + request.onerror = onerror; + request.onprogress = onprogress; + request.send(); + + function onload() { + if (request.status === 200) { + deferred.resolve(request.responseText); + } else { + deferred.reject(new Error("Status code was " + request.status)); + } + } + + function onerror() { + deferred.reject(new Error("Can't XHR " + JSON.stringify(url))); + } + + function onprogress(event) { + deferred.notify(event.loaded / event.total); + } + + return deferred.promise; +} +``` + +Below is an example of how to use this ``requestOkText`` function: + +```javascript +requestOkText("http://localhost:3000") +.then(function (responseText) { + // If the HTTP response returns 200 OK, log the response text. + console.log(responseText); +}, function (error) { + // If there's an error or a non-200 status code, log the error. + console.error(error); +}, function (progress) { + // Log the progress as it comes in. + console.log("Request progress: " + Math.round(progress * 100) + "%"); +}); +``` + +#### Using `Q.Promise` + +This is an alternative promise-creation API that has the same power as +the deferred concept, but without introducing another conceptual entity. + +Rewriting the `requestOkText` example above using `Q.Promise`: + +```javascript +function requestOkText(url) { + return Q.Promise(function(resolve, reject, notify) { + var request = new XMLHttpRequest(); + + request.open("GET", url, true); + request.onload = onload; + request.onerror = onerror; + request.onprogress = onprogress; + request.send(); + + function onload() { + if (request.status === 200) { + resolve(request.responseText); + } else { + reject(new Error("Status code was " + request.status)); + } + } + + function onerror() { + reject(new Error("Can't XHR " + JSON.stringify(url))); + } + + function onprogress(event) { + notify(event.loaded / event.total); + } + }); +} +``` + +If `requestOkText` were to throw an exception, the returned promise would be +rejected with that thrown exception as the rejection reason. + +### The Middle + +If you are using a function that may return a promise, but just might +return a value if it doesn’t need to defer, you can use the “static” +methods of the Q library. + +The ``when`` function is the static equivalent for ``then``. + +```javascript +return Q.when(valueOrPromise, function (value) { +}, function (error) { +}); +``` + +All of the other methods on a promise have static analogs with the +same name. + +The following are equivalent: + +```javascript +return Q.all([a, b]); +``` + +```javascript +return Q.fcall(function () { + return [a, b]; +}) +.all(); +``` + +When working with promises provided by other libraries, you should +convert it to a Q promise. Not all promise libraries make the same +guarantees as Q and certainly don’t provide all of the same methods. +Most libraries only provide a partially functional ``then`` method. +This thankfully is all we need to turn them into vibrant Q promises. + +```javascript +return Q($.ajax(...)) +.then(function () { +}); +``` + +If there is any chance that the promise you receive is not a Q promise +as provided by your library, you should wrap it using a Q function. +You can even use ``Q.invoke`` as a shorthand. + +```javascript +return Q.invoke($, 'ajax', ...) +.then(function () { +}); +``` + + +### Over the Wire + +A promise can serve as a proxy for another object, even a remote +object. There are methods that allow you to optimistically manipulate +properties or call functions. All of these interactions return +promises, so they can be chained. + +``` +direct manipulation using a promise as a proxy +-------------------------- ------------------------------- +value.foo promise.get("foo") +value.foo = value promise.put("foo", value) +delete value.foo promise.del("foo") +value.foo(...args) promise.post("foo", [args]) +value.foo(...args) promise.invoke("foo", ...args) +value(...args) promise.fapply([args]) +value(...args) promise.fcall(...args) +``` + +If the promise is a proxy for a remote object, you can shave +round-trips by using these functions instead of ``then``. To take +advantage of promises for remote objects, check out [Q-Connection][]. + +[Q-Connection]: https://github.com/kriskowal/q-connection + +Even in the case of non-remote objects, these methods can be used as +shorthand for particularly-simple fulfillment handlers. For example, you +can replace + +```javascript +return Q.fcall(function () { + return [{ foo: "bar" }, { foo: "baz" }]; +}) +.then(function (value) { + return value[0].foo; +}); +``` + +with + +```javascript +return Q.fcall(function () { + return [{ foo: "bar" }, { foo: "baz" }]; +}) +.get(0) +.get("foo"); +``` + + +### Adapting Node + +If you're working with functions that make use of the Node.js callback pattern, +where callbacks are in the form of `function(err, result)`, Q provides a few +useful utility functions for converting between them. The most straightforward +are probably `Q.nfcall` and `Q.nfapply` ("Node function call/apply") for calling +Node.js-style functions and getting back a promise: + +```javascript +return Q.nfcall(FS.readFile, "foo.txt", "utf-8"); +return Q.nfapply(FS.readFile, ["foo.txt", "utf-8"]); +``` + +If you are working with methods, instead of simple functions, you can easily +run in to the usual problems where passing a method to another function—like +`Q.nfcall`—"un-binds" the method from its owner. To avoid this, you can either +use `Function.prototype.bind` or some nice shortcut methods we provide: + +```javascript +return Q.ninvoke(redisClient, "get", "user:1:id"); +return Q.npost(redisClient, "get", ["user:1:id"]); +``` + +You can also create reusable wrappers with `Q.denodeify` or `Q.nbind`: + +```javascript +var readFile = Q.denodeify(FS.readFile); +return readFile("foo.txt", "utf-8"); + +var redisClientGet = Q.nbind(redisClient.get, redisClient); +return redisClientGet("user:1:id"); +``` + +Finally, if you're working with raw deferred objects, there is a +`makeNodeResolver` method on deferreds that can be handy: + +```javascript +var deferred = Q.defer(); +FS.readFile("foo.txt", "utf-8", deferred.makeNodeResolver()); +return deferred.promise; +``` + +### Long Stack Traces + +Q comes with optional support for “long stack traces,” wherein the `stack` +property of `Error` rejection reasons is rewritten to be traced along +asynchronous jumps instead of stopping at the most recent one. As an example: + +```js +function theDepthsOfMyProgram() { + Q.delay(100).done(function explode() { + throw new Error("boo!"); + }); +} + +theDepthsOfMyProgram(); +``` + +usually would give a rather unhelpful stack trace looking something like + +``` +Error: boo! + at explode (/path/to/test.js:3:11) + at _fulfilled (/path/to/test.js:q:54) + at resolvedValue.promiseDispatch.done (/path/to/q.js:823:30) + at makePromise.promise.promiseDispatch (/path/to/q.js:496:13) + at pending (/path/to/q.js:397:39) + at process.startup.processNextTick.process._tickCallback (node.js:244:9) +``` + +But, if you turn this feature on by setting + +```js +Q.longStackSupport = true; +``` + +then the above code gives a nice stack trace to the tune of + +``` +Error: boo! + at explode (/path/to/test.js:3:11) +From previous event: + at theDepthsOfMyProgram (/path/to/test.js:2:16) + at Object.<anonymous> (/path/to/test.js:7:1) +``` + +Note how you can see the function that triggered the async operation in the +stack trace! This is very helpful for debugging, as otherwise you end up getting +only the first line, plus a bunch of Q internals, with no sign of where the +operation started. + +In node.js, this feature can also be enabled through the Q_DEBUG environment +variable: + +``` +Q_DEBUG=1 node server.js +``` + +This will enable long stack support in every instance of Q. + +This feature does come with somewhat-serious performance and memory overhead, +however. If you're working with lots of promises, or trying to scale a server +to many users, you should probably keep it off. But in development, go for it! + +## Tests + +You can view the results of the Q test suite [in your browser][tests]! + +[tests]: https://rawgithub.com/kriskowal/q/v1/spec/q-spec.html + +## License + +Copyright 2009–2017 Kristopher Michael Kowal and contributors +MIT License (enclosed) + diff --git a/cordova/node_modules/q/package.json b/cordova/node_modules/q/package.json new file mode 100755 index 0000000..31cc440 --- /dev/null +++ b/cordova/node_modules/q/package.json @@ -0,0 +1,117 @@ +{ + "_from": "[email protected]", + "_id": "[email protected]", + "_inBundle": true, + "_integrity": "sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc=", + "_location": "/cordova-ios/q", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "[email protected]", + "name": "q", + "escapedName": "q", + "rawSpec": "1.5.1", + "saveSpec": null, + "fetchSpec": "1.5.1" + }, + "_requiredBy": [ + "/cordova-ios", + "/cordova-ios/cordova-common" + ], + "_resolved": "https://registry.npmjs.org/q/-/q-1.5.1.tgz", + "_shasum": "7e32f75b41381291d04611f1bf14109ac00651d7", + "_spec": "[email protected]", + "_where": "/Users/brodybits/Documents/cordova/cordova-ios", + "author": { + "name": "Kris Kowal", + "email": "[email protected]", + "url": "https://github.com/kriskowal" + }, + "bugs": { + "url": "http://github.com/kriskowal/q/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Kris Kowal", + "email": "[email protected]", + "url": "https://github.com/kriskowal" + }, + { + "name": "Irakli Gozalishvili", + "email": "[email protected]", + "url": "http://jeditoolkit.com" + }, + { + "name": "Domenic Denicola", + "email": "[email protected]", + "url": "http://domenicdenicola.com" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "A library for promises (CommonJS/Promises/A,B,D)", + "devDependencies": { + "cover": "*", + "grunt": "~0.4.1", + "grunt-cli": "~0.1.9", + "grunt-contrib-uglify": "~0.9.1", + "jasmine-node": "1.11.0", + "jshint": "~2.1.9", + "matcha": "~0.2.0", + "opener": "*", + "promises-aplus-tests": "1.x" + }, + "directories": { + "test": "./spec" + }, + "engines": { + "node": ">=0.6.0", + "teleport": ">=0.2.0" + }, + "files": [ + "LICENSE", + "q.js", + "queue.js" + ], + "homepage": "https://github.com/kriskowal/q", + "keywords": [ + "q", + "promise", + "promises", + "promises-a", + "promises-aplus", + "deferred", + "future", + "async", + "flow control", + "fluent", + "browser", + "node" + ], + "license": "MIT", + "main": "q.js", + "name": "q", + "overlay": { + "teleport": { + "dependencies": { + "system": ">=0.0.4" + } + } + }, + "repository": { + "type": "git", + "url": "git://github.com/kriskowal/q.git" + }, + "scripts": { + "benchmark": "matcha", + "cover": "cover run jasmine-node spec && cover report html && opener cover_html/index.html", + "lint": "jshint q.js", + "minify": "grunt", + "prepublish": "grunt", + "test": "npm ls -s && jasmine-node spec && promises-aplus-tests spec/aplus-adapter && npm run -s lint", + "test-browser": "opener spec/q-spec.html" + }, + "version": "1.5.1" +} diff --git a/cordova/node_modules/q/q.js b/cordova/node_modules/q/q.js new file mode 100755 index 0000000..6e46795 --- /dev/null +++ b/cordova/node_modules/q/q.js @@ -0,0 +1,2076 @@ +// vim:ts=4:sts=4:sw=4: +/*! + * + * Copyright 2009-2017 Kris Kowal under the terms of the MIT + * license found at https://github.com/kriskowal/q/blob/v1/LICENSE + * + * With parts by Tyler Close + * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found + * at http://www.opensource.org/licenses/mit-license.html + * Forked at ref_send.js version: 2009-05-11 + * + * With parts by Mark Miller + * Copyright (C) 2011 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +(function (definition) { + "use strict"; + + // This file will function properly as a <script> tag, or a module + // using CommonJS and NodeJS or RequireJS module formats. In + // Common/Node/RequireJS, the module exports the Q API and when + // executed as a simple <script>, it creates a Q global instead. + + // Montage Require + if (typeof bootstrap === "function") { + bootstrap("promise", definition); + + // CommonJS + } else if (typeof exports === "object" && typeof module === "object") { + module.exports = definition(); + + // RequireJS + } else if (typeof define === "function" && define.amd) { + define(definition); + + // SES (Secure EcmaScript) + } else if (typeof ses !== "undefined") { + if (!ses.ok()) { + return; + } else { + ses.makeQ = definition; + } + + // <script> + } else if (typeof window !== "undefined" || typeof self !== "undefined") { + // Prefer window over self for add-on scripts. Use self for + // non-windowed contexts. + var global = typeof window !== "undefined" ? window : self; + + // Get the `window` object, save the previous Q global + // and initialize Q as a global. + var previousQ = global.Q; + global.Q = definition(); + + // Add a noConflict function so Q can be removed from the + // global namespace. + global.Q.noConflict = function () { + global.Q = previousQ; + return this; + }; + + } else { + throw new Error("This environment was not anticipated by Q. Please file a bug."); + } + +})(function () { +"use strict"; + +var hasStacks = false; +try { + throw new Error(); +} catch (e) { + hasStacks = !!e.stack; +} + +// All code after this point will be filtered from stack traces reported +// by Q. +var qStartingLine = captureLine(); +var qFileName; + +// shims + +// used for fallback in "allResolved" +var noop = function () {}; + +// Use the fastest possible means to execute a task in a future turn +// of the event loop. +var nextTick =(function () { + // linked list of tasks (single, with head node) + var head = {task: void 0, next: null}; + var tail = head; + var flushing = false; + var requestTick = void 0; + var isNodeJS = false; + // queue for late tasks, used by unhandled rejection tracking + var laterQueue = []; + + function flush() { + /* jshint loopfunc: true */ + var task, domain; + + while (head.next) { + head = head.next; + task = head.task; + head.task = void 0; + domain = head.domain; + + if (domain) { + head.domain = void 0; + domain.enter(); + } + runSingle(task, domain); + + } + while (laterQueue.length) { + task = laterQueue.pop(); + runSingle(task); + } + flushing = false; + } + // runs a single function in the async queue + function runSingle(task, domain) { + try { + task(); + + } catch (e) { + if (isNodeJS) { + // In node, uncaught exceptions are considered fatal errors. + // Re-throw them synchronously to interrupt flushing! + + // Ensure continuation if the uncaught exception is suppressed + // listening "uncaughtException" events (as domains does). + // Continue in next event to avoid tick recursion. + if (domain) { + domain.exit(); + } + setTimeout(flush, 0); + if (domain) { + domain.enter(); + } + + throw e; + + } else { + // In browsers, uncaught exceptions are not fatal. + // Re-throw them asynchronously to avoid slow-downs. + setTimeout(function () { + throw e; + }, 0); + } + } + + if (domain) { + domain.exit(); + } + } + + nextTick = function (task) { + tail = tail.next = { + task: task, + domain: isNodeJS && process.domain, + next: null + }; + + if (!flushing) { + flushing = true; + requestTick(); + } + }; + + if (typeof process === "object" && + process.toString() === "[object process]" && process.nextTick) { + // Ensure Q is in a real Node environment, with a `process.nextTick`. + // To see through fake Node environments: + // * Mocha test runner - exposes a `process` global without a `nextTick` + // * Browserify - exposes a `process.nexTick` function that uses + // `setTimeout`. In this case `setImmediate` is preferred because + // it is faster. Browserify's `process.toString()` yields + // "[object Object]", while in a real Node environment + // `process.toString()` yields "[object process]". + isNodeJS = true; + + requestTick = function () { + process.nextTick(flush); + }; + + } else if (typeof setImmediate === "function") { + // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate + if (typeof window !== "undefined") { + requestTick = setImmediate.bind(window, flush); + } else { + requestTick = function () { + setImmediate(flush); + }; + } + + } else if (typeof MessageChannel !== "undefined") { + // modern browsers + // http://www.nonblocking.io/2011/06/windownexttick.html + var channel = new MessageChannel(); + // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create + // working message ports the first time a page loads. + channel.port1.onmessage = function () { + requestTick = requestPortTick; + channel.port1.onmessage = flush; + flush(); + }; + var requestPortTick = function () { + // Opera requires us to provide a message payload, regardless of + // whether we use it. + channel.port2.postMessage(0); + }; + requestTick = function () { + setTimeout(flush, 0); + requestPortTick(); + }; + + } else { + // old browsers + requestTick = function () { + setTimeout(flush, 0); + }; + } + // runs a task after all other tasks have been run + // this is useful for unhandled rejection tracking that needs to happen + // after all `then`d tasks have been run. + nextTick.runAfter = function (task) { + laterQueue.push(task); + if (!flushing) { + flushing = true; + requestTick(); + } + }; + return nextTick; +})(); + +// Attempt to make generics safe in the face of downstream +// modifications. +// There is no situation where this is necessary. +// If you need a security guarantee, these primordials need to be +// deeply frozen anyway, and if you don’t need a security guarantee, +// this is just plain paranoid. +// However, this **might** have the nice side-effect of reducing the size of +// the minified code by reducing x.call() to merely x() +// See Mark Miller’s explanation of what this does. +// http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming +var call = Function.call; +function uncurryThis(f) { + return function () { + return call.apply(f, arguments); + }; +} +// This is equivalent, but slower: +// uncurryThis = Function_bind.bind(Function_bind.call); +// http://jsperf.com/uncurrythis + +var array_slice = uncurryThis(Array.prototype.slice); + +var array_reduce = uncurryThis( + Array.prototype.reduce || function (callback, basis) { + var index = 0, + length = this.length; + // concerning the initial value, if one is not provided + if (arguments.length === 1) { + // seek to the first value in the array, accounting + // for the possibility that is is a sparse array + do { + if (index in this) { + basis = this[index++]; + break; + } + if (++index >= length) { + throw new TypeError(); + } + } while (1); + } + // reduce + for (; index < length; index++) { + // account for the possibility that the array is sparse + if (index in this) { + basis = callback(basis, this[index], index); + } + } + return basis; + } +); + +var array_indexOf = uncurryThis( + Array.prototype.indexOf || function (value) { + // not a very good shim, but good enough for our one use of it + for (var i = 0; i < this.length; i++) { + if (this[i] === value) { + return i; + } + } + return -1; + } +); + +var array_map = uncurryThis( + Array.prototype.map || function (callback, thisp) { + var self = this; + var collect = []; + array_reduce(self, function (undefined, value, index) { + collect.push(callback.call(thisp, value, index, self)); + }, void 0); + return collect; + } +); + +var object_create = Object.create || function (prototype) { + function Type() { } + Type.prototype = prototype; + return new Type(); +}; + +var object_defineProperty = Object.defineProperty || function (obj, prop, descriptor) { + obj[prop] = descriptor.value; + return obj; +}; + +var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); + +var object_keys = Object.keys || function (object) { + var keys = []; + for (var key in object) { + if (object_hasOwnProperty(object, key)) { + keys.push(key); + } + } + return keys; +}; + +var object_toString = uncurryThis(Object.prototype.toString); + +function isObject(value) { + return value === Object(value); +} + +// generator related shims + +// FIXME: Remove this function once ES6 generators are in SpiderMonkey. +function isStopIteration(exception) { + return ( + object_toString(exception) === "[object StopIteration]" || + exception instanceof QReturnValue + ); +} + +// FIXME: Remove this helper and Q.return once ES6 generators are in +// SpiderMonkey. +var QReturnValue; +if (typeof ReturnValue !== "undefined") { + QReturnValue = ReturnValue; +} else { + QReturnValue = function (value) { + this.value = value; + }; +} + +// long stack traces + +var STACK_JUMP_SEPARATOR = "From previous event:"; + +function makeStackTraceLong(error, promise) { + // If possible, transform the error stack trace by removing Node and Q + // cruft, then concatenating with the stack trace of `promise`. See #57. + if (hasStacks && + promise.stack && + typeof error === "object" && + error !== null && + error.stack + ) { + var stacks = []; + for (var p = promise; !!p; p = p.source) { + if (p.stack && (!error.__minimumStackCounter__ || error.__minimumStackCounter__ > p.stackCounter)) { + object_defineProperty(error, "__minimumStackCounter__", {value: p.stackCounter, configurable: true}); + stacks.unshift(p.stack); + } + } + stacks.unshift(error.stack); + + var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); + var stack = filterStackString(concatedStacks); + object_defineProperty(error, "stack", {value: stack, configurable: true}); + } +} + +function filterStackString(stackString) { + var lines = stackString.split("\n"); + var desiredLines = []; + for (var i = 0; i < lines.length; ++i) { + var line = lines[i]; + + if (!isInternalFrame(line) && !isNodeFrame(line) && line) { + desiredLines.push(line); + } + } + return desiredLines.join("\n"); +} + +function isNodeFrame(stackLine) { + return stackLine.indexOf("(module.js:") !== -1 || + stackLine.indexOf("(node.js:") !== -1; +} + +function getFileNameAndLineNumber(stackLine) { + // Named functions: "at functionName (filename:lineNumber:columnNumber)" + // In IE10 function name can have spaces ("Anonymous function") O_o + var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); + if (attempt1) { + return [attempt1[1], Number(attempt1[2])]; + } + + // Anonymous functions: "at filename:lineNumber:columnNumber" + var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); + if (attempt2) { + return [attempt2[1], Number(attempt2[2])]; + } + + // Firefox style: "function@filename:lineNumber or @filename:lineNumber" + var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); + if (attempt3) { + return [attempt3[1], Number(attempt3[2])]; + } +} + +function isInternalFrame(stackLine) { + var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); + + if (!fileNameAndLineNumber) { + return false; + } + + var fileName = fileNameAndLineNumber[0]; + var lineNumber = fileNameAndLineNumber[1]; + + return fileName === qFileName && + lineNumber >= qStartingLine && + lineNumber <= qEndingLine; +} + +// discover own file name and line number range for filtering stack +// traces +function captureLine() { + if (!hasStacks) { + return; + } + + try { + throw new Error(); + } catch (e) { + var lines = e.stack.split("\n"); + var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; + var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); + if (!fileNameAndLineNumber) { + return; + } + + qFileName = fileNameAndLineNumber[0]; + return fileNameAndLineNumber[1]; + } +} + +function deprecate(callback, name, alternative) { + return function () { + if (typeof console !== "undefined" && + typeof console.warn === "function") { + console.warn(name + " is deprecated, use " + alternative + + " instead.", new Error("").stack); + } + return callback.apply(callback, arguments); + }; +} + +// end of shims +// beginning of real work + +/** + * Constructs a promise for an immediate reference, passes promises through, or + * coerces promises from different systems. + * @param value immediate reference or promise + */ +function Q(value) { + // If the object is already a Promise, return it directly. This enables + // the resolve function to both be used to created references from objects, + // but to tolerably coerce non-promises to promises. + if (value instanceof Promise) { + return value; + } + + // assimilate thenables + if (isPromiseAlike(value)) { + return coerce(value); + } else { + return fulfill(value); + } +} +Q.resolve = Q; + +/** + * Performs a task in a future turn of the event loop. + * @param {Function} task + */ +Q.nextTick = nextTick; + +/** + * Controls whether or not long stack traces will be on + */ +Q.longStackSupport = false; + +/** + * The counter is used to determine the stopping point for building + * long stack traces. In makeStackTraceLong we walk backwards through + * the linked list of promises, only stacks which were created before + * the rejection are concatenated. + */ +var longStackCounter = 1; + +// enable long stacks if Q_DEBUG is set +if (typeof process === "object" && process && process.env && process.env.Q_DEBUG) { + Q.longStackSupport = true; +} + +/** + * Constructs a {promise, resolve, reject} object. + * + * `resolve` is a callback to invoke with a more resolved value for the + * promise. To fulfill the promise, invoke `resolve` with any value that is + * not a thenable. To reject the promise, invoke `resolve` with a rejected + * thenable, or invoke `reject` with the reason directly. To resolve the + * promise to another thenable, thus putting it in the same state, invoke + * `resolve` with that other thenable. + */ +Q.defer = defer; +function defer() { + // if "messages" is an "Array", that indicates that the promise has not yet + // been resolved. If it is "undefined", it has been resolved. Each + // element of the messages array is itself an array of complete arguments to + // forward to the resolved promise. We coerce the resolution value to a + // promise using the `resolve` function because it handles both fully + // non-thenable values and other thenables gracefully. + var messages = [], progressListeners = [], resolvedPromise; + + var deferred = object_create(defer.prototype); + var promise = object_create(Promise.prototype); + + promise.promiseDispatch = function (resolve, op, operands) { + var args = array_slice(arguments); + if (messages) { + messages.push(args); + if (op === "when" && operands[1]) { // progress operand + progressListeners.push(operands[1]); + } + } else { + Q.nextTick(function () { + resolvedPromise.promiseDispatch.apply(resolvedPromise, args); + }); + } + }; + + // XXX deprecated + promise.valueOf = function () { + if (messages) { + return promise; + } + var nearerValue = nearer(resolvedPromise); + if (isPromise(nearerValue)) { + resolvedPromise = nearerValue; // shorten chain + } + return nearerValue; + }; + + promise.inspect = function () { + if (!resolvedPromise) { + return { state: "pending" }; + } + return resolvedPromise.inspect(); + }; + + if (Q.longStackSupport && hasStacks) { + try { + throw new Error(); + } catch (e) { + // NOTE: don't try to use `Error.captureStackTrace` or transfer the + // accessor around; that causes memory leaks as per GH-111. Just + // reify the stack trace as a string ASAP. + // + // At the same time, cut off the first line; it's always just + // "[object Promise]\n", as per the `toString`. + promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1); + promise.stackCounter = longStackCounter++; + } + } + + // NOTE: we do the checks for `resolvedPromise` in each method, instead of + // consolidating them into `become`, since otherwise we'd create new + // promises with the lines `become(whatever(value))`. See e.g. GH-252. + + function become(newPromise) { + resolvedPromise = newPromise; + + if (Q.longStackSupport && hasStacks) { + // Only hold a reference to the new promise if long stacks + // are enabled to reduce memory usage + promise.source = newPromise; + } + + array_reduce(messages, function (undefined, message) { + Q.nextTick(function () { + newPromise.promiseDispatch.apply(newPromise, message); + }); + }, void 0); + + messages = void 0; + progressListeners = void 0; + } + + deferred.promise = promise; + deferred.resolve = function (value) { + if (resolvedPromise) { + return; + } + + become(Q(value)); + }; + + deferred.fulfill = function (value) { + if (resolvedPromise) { + return; + } + + become(fulfill(value)); + }; + deferred.reject = function (reason) { + if (resolvedPromise) { + return; + } + + become(reject(reason)); + }; + deferred.notify = function (progress) { + if (resolvedPromise) { + return; + } + + array_reduce(progressListeners, function (undefined, progressListener) { + Q.nextTick(function () { + progressListener(progress); + }); + }, void 0); + }; + + return deferred; +} + +/** + * Creates a Node-style callback that will resolve or reject the deferred + * promise. + * @returns a nodeback + */ +defer.prototype.makeNodeResolver = function () { + var self = this; + return function (error, value) { + if (error) { + self.reject(error); + } else if (arguments.length > 2) { + self.resolve(array_slice(arguments, 1)); + } else { + self.resolve(value); + } + }; +}; + +/** + * @param resolver {Function} a function that returns nothing and accepts + * the resolve, reject, and notify functions for a deferred. + * @returns a promise that may be resolved with the given resolve and reject + * functions, or rejected by a thrown exception in resolver + */ +Q.Promise = promise; // ES6 +Q.promise = promise; +function promise(resolver) { + if (typeof resolver !== "function") { + throw new TypeError("resolver must be a function."); + } + var deferred = defer(); + try { + resolver(deferred.resolve, deferred.reject, deferred.notify); + } catch (reason) { + deferred.reject(reason); + } + return deferred.promise; +} + +promise.race = race; // ES6 +promise.all = all; // ES6 +promise.reject = reject; // ES6 +promise.resolve = Q; // ES6 + +// XXX experimental. This method is a way to denote that a local value is +// serializable and should be immediately dispatched to a remote upon request, +// instead of passing a reference. +Q.passByCopy = function (object) { + //freeze(object); + //passByCopies.set(object, true); + return object; +}; + +Promise.prototype.passByCopy = function () { + //freeze(object); + //passByCopies.set(object, true); + return this; +}; + +/** + * If two promises eventually fulfill to the same value, promises that value, + * but otherwise rejects. + * @param x {Any*} + * @param y {Any*} + * @returns {Any*} a promise for x and y if they are the same, but a rejection + * otherwise. + * + */ +Q.join = function (x, y) { + return Q(x).join(y); +}; + +Promise.prototype.join = function (that) { + return Q([this, that]).spread(function (x, y) { + if (x === y) { + // TODO: "===" should be Object.is or equiv + return x; + } else { + throw new Error("Q can't join: not the same: " + x + " " + y); + } + }); +}; + +/** + * Returns a promise for the first of an array of promises to become settled. + * @param answers {Array[Any*]} promises to race + * @returns {Any*} the first promise to be settled + */ +Q.race = race; +function race(answerPs) { + return promise(function (resolve, reject) { + // Switch to this once we can assume at least ES5 + // answerPs.forEach(function (answerP) { + // Q(answerP).then(resolve, reject); + // }); + // Use this in the meantime + for (var i = 0, len = answerPs.length; i < len; i++) { + Q(answerPs[i]).then(resolve, reject); + } + }); +} + +Promise.prototype.race = function () { + return this.then(Q.race); +}; + +/** + * Constructs a Promise with a promise descriptor object and optional fallback + * function. The descriptor contains methods like when(rejected), get(name), + * set(name, value), post(name, args), and delete(name), which all + * return either a value, a promise for a value, or a rejection. The fallback + * accepts the operation name, a resolver, and any further arguments that would + * have been forwarded to the appropriate method above had a method been + * provided with the proper name. The API makes no guarantees about the nature + * of the returned object, apart from that it is usable whereever promises are + * bought and sold. + */ +Q.makePromise = Promise; +function Promise(descriptor, fallback, inspect) { + if (fallback === void 0) { + fallback = function (op) { + return reject(new Error( + "Promise does not support operation: " + op + )); + }; + } + if (inspect === void 0) { + inspect = function () { + return {state: "unknown"}; + }; + } + + var promise = object_create(Promise.prototype); + + promise.promiseDispatch = function (resolve, op, args) { + var result; + try { + if (descriptor[op]) { + result = descriptor[op].apply(promise, args); + } else { + result = fallback.call(promise, op, args); + } + } catch (exception) { + result = reject(exception); + } + if (resolve) { + resolve(result); + } + }; + + promise.inspect = inspect; + + // XXX deprecated `valueOf` and `exception` support + if (inspect) { + var inspected = inspect(); + if (inspected.state === "rejected") { + promise.exception = inspected.reason; + } + + promise.valueOf = function () { + var inspected = inspect(); + if (inspected.state === "pending" || + inspected.state === "rejected") { + return promise; + } + return inspected.value; + }; + } + + return promise; +} + +Promise.prototype.toString = function () { + return "[object Promise]"; +}; + +Promise.prototype.then = function (fulfilled, rejected, progressed) { + var self = this; + var deferred = defer(); + var done = false; // ensure the untrusted promise makes at most a + // single call to one of the callbacks + + function _fulfilled(value) { + try { + return typeof fulfilled === "function" ? fulfilled(value) : value; + } catch (exception) { + return reject(exception); + } + } + + function _rejected(exception) { + if (typeof rejected === "function") { + makeStackTraceLong(exception, self); + try { + return rejected(exception); + } catch (newException) { + return reject(newException); + } + } + return reject(exception); + } + + function _progressed(value) { + return typeof progressed === "function" ? progressed(value) : value; + } + + Q.nextTick(function () { + self.promiseDispatch(function (value) { + if (done) { + return; + } + done = true; + + deferred.resolve(_fulfilled(value)); + }, "when", [function (exception) { + if (done) { + return; + } + done = true; + + deferred.resolve(_rejected(exception)); + }]); + }); + + // Progress propagator need to be attached in the current tick. + self.promiseDispatch(void 0, "when", [void 0, function (value) { + var newValue; + var threw = false; + try { + newValue = _progressed(value); + } catch (e) { + threw = true; + if (Q.onerror) { + Q.onerror(e); + } else { + throw e; + } + } + + if (!threw) { + deferred.notify(newValue); + } + }]); + + return deferred.promise; +}; + +Q.tap = function (promise, callback) { + return Q(promise).tap(callback); +}; + +/** + * Works almost like "finally", but not called for rejections. + * Original resolution value is passed through callback unaffected. + * Callback may return a promise that will be awaited for. + * @param {Function} callback + * @returns {Q.Promise} + * @example + * doSomething() + * .then(...) + * .tap(console.log) + * .then(...); + */ +Promise.prototype.tap = function (callback) { + callback = Q(callback); + + return this.then(function (value) { + return callback.fcall(value).thenResolve(value); + }); +}; + +/** + * Registers an observer on a promise. + * + * Guarantees: + * + * 1. that fulfilled and rejected will be called only once. + * 2. that either the fulfilled callback or the rejected callback will be + * called, but not both. + * 3. that fulfilled and rejected will not be called in this turn. + * + * @param value promise or immediate reference to observe + * @param fulfilled function to be called with the fulfilled value + * @param rejected function to be called with the rejection exception + * @param progressed function to be called on any progress notifications + * @return promise for the return value from the invoked callback + */ +Q.when = when; +function when(value, fulfilled, rejected, progressed) { + return Q(value).then(fulfilled, rejected, progressed); +} + +Promise.prototype.thenResolve = function (value) { + return this.then(function () { return value; }); +}; + +Q.thenResolve = function (promise, value) { + return Q(promise).thenResolve(value); +}; + +Promise.prototype.thenReject = function (reason) { + return this.then(function () { throw reason; }); +}; + +Q.thenReject = function (promise, reason) { + return Q(promise).thenReject(reason); +}; + +/** + * If an object is not a promise, it is as "near" as possible. + * If a promise is rejected, it is as "near" as possible too. + * If it’s a fulfilled promise, the fulfillment value is nearer. + * If it’s a deferred promise and the deferred has been resolved, the + * resolution is "nearer". + * @param object + * @returns most resolved (nearest) form of the object + */ + +// XXX should we re-do this? +Q.nearer = nearer; +function nearer(value) { + if (isPromise(value)) { + var inspected = value.inspect(); + if (inspected.state === "fulfilled") { + return inspected.value; + } + } + return value; +} + +/** + * @returns whether the given object is a promise. + * Otherwise it is a fulfilled value. + */ +Q.isPromise = isPromise; +function isPromise(object) { + return object instanceof Promise; +} + +Q.isPromiseAlike = isPromiseAlike; +function isPromiseAlike(object) { + return isObject(object) && typeof object.then === "function"; +} + +/** + * @returns whether the given object is a pending promise, meaning not + * fulfilled or rejected. + */ +Q.isPending = isPending; +function isPending(object) { + return isPromise(object) && object.inspect().state === "pending"; +} + +Promise.prototype.isPending = function () { + return this.inspect().state === "pending"; +}; + +/** + * @returns whether the given object is a value or fulfilled + * promise. + */ +Q.isFulfilled = isFulfilled; +function isFulfilled(object) { + return !isPromise(object) || object.inspect().state === "fulfilled"; +} + +Promise.prototype.isFulfilled = function () { + return this.inspect().state === "fulfilled"; +}; + +/** + * @returns whether the given object is a rejected promise. + */ +Q.isRejected = isRejected; +function isRejected(object) { + return isPromise(object) && object.inspect().state === "rejected"; +} + +Promise.prototype.isRejected = function () { + return this.inspect().state === "rejected"; +}; + +//// BEGIN UNHANDLED REJECTION TRACKING + +// This promise library consumes exceptions thrown in handlers so they can be +// handled by a subsequent promise. The exceptions get added to this array when +// they are created, and removed when they are handled. Note that in ES6 or +// shimmed environments, this would naturally be a `Set`. +var unhandledReasons = []; +var unhandledRejections = []; +var reportedUnhandledRejections = []; +var trackUnhandledRejections = true; + +function resetUnhandledRejections() { + unhandledReasons.length = 0; + unhandledRejections.length = 0; + + if (!trackUnhandledRejections) { + trackUnhandledRejections = true; + } +} + +function trackRejection(promise, reason) { + if (!trackUnhandledRejections) { + return; + } + if (typeof process === "object" && typeof process.emit === "function") { + Q.nextTick.runAfter(function () { + if (array_indexOf(unhandledRejections, promise) !== -1) { + process.emit("unhandledRejection", reason, promise); + reportedUnhandledRejections.push(promise); + } + }); + } + + unhandledRejections.push(promise); + if (reason && typeof reason.stack !== "undefined") { + unhandledReasons.push(reason.stack); + } else { + unhandledReasons.push("(no stack) " + reason); + } +} + +function untrackRejection(promise) { + if (!trackUnhandledRejections) { + return; + } + + var at = array_indexOf(unhandledRejections, promise); + if (at !== -1) { + if (typeof process === "object" && typeof process.emit === "function") { + Q.nextTick.runAfter(function () { + var atReport = array_indexOf(reportedUnhandledRejections, promise); + if (atReport !== -1) { + process.emit("rejectionHandled", unhandledReasons[at], promise); + reportedUnhandledRejections.splice(atReport, 1); + } + }); + } + unhandledRejections.splice(at, 1); + unhandledReasons.splice(at, 1); + } +} + +Q.resetUnhandledRejections = resetUnhandledRejections; + +Q.getUnhandledReasons = function () { + // Make a copy so that consumers can't interfere with our internal state. + return unhandledReasons.slice(); +}; + +Q.stopUnhandledRejectionTracking = function () { + resetUnhandledRejections(); + trackUnhandledRejections = false; +}; + +resetUnhandledRejections(); + +//// END UNHANDLED REJECTION TRACKING + +/** + * Constructs a rejected promise. + * @param reason value describing the failure + */ +Q.reject = reject; +function reject(reason) { + var rejection = Promise({ + "when": function (rejected) { + // note that the error has been handled + if (rejected) { + untrackRejection(this); + } + return rejected ? rejected(reason) : this; + } + }, function fallback() { + return this; + }, function inspect() { + return { state: "rejected", reason: reason }; + }); + + // Note that the reason has not been handled. + trackRejection(rejection, reason); + + return rejection; +} + +/** + * Constructs a fulfilled promise for an immediate reference. + * @param value immediate reference + */ +Q.fulfill = fulfill; +function fulfill(value) { + return Promise({ + "when": function () { + return value; + }, + "get": function (name) { + return value[name]; + }, + "set": function (name, rhs) { + value[name] = rhs; + }, + "delete": function (name) { + delete value[name]; + }, + "post": function (name, args) { + // Mark Miller proposes that post with no name should apply a + // promised function. + if (name === null || name === void 0) { + return value.apply(void 0, args); + } else { + return value[name].apply(value, args); + } + }, + "apply": function (thisp, args) { + return value.apply(thisp, args); + }, + "keys": function () { + return object_keys(value); + } + }, void 0, function inspect() { + return { state: "fulfilled", value: value }; + }); +} + +/** + * Converts thenables to Q promises. + * @param promise thenable promise + * @returns a Q promise + */ +function coerce(promise) { + var deferred = defer(); + Q.nextTick(function () { + try { + promise.then(deferred.resolve, deferred.reject, deferred.notify); + } catch (exception) { + deferred.reject(exception); + } + }); + return deferred.promise; +} + +/** + * Annotates an object such that it will never be + * transferred away from this process over any promise + * communication channel. + * @param object + * @returns promise a wrapping of that object that + * additionally responds to the "isDef" message + * without a rejection. + */ +Q.master = master; +function master(object) { + return Promise({ + "isDef": function () {} + }, function fallback(op, args) { + return dispatch(object, op, args); + }, function () { + return Q(object).inspect(); + }); +} + +/** + * Spreads the values of a promised array of arguments into the + * fulfillment callback. + * @param fulfilled callback that receives variadic arguments from the + * promised array + * @param rejected callback that receives the exception if the promise + * is rejected. + * @returns a promise for the return value or thrown exception of + * either callback. + */ +Q.spread = spread; +function spread(value, fulfilled, rejected) { + return Q(value).spread(fulfilled, rejected); +} + +Promise.prototype.spread = function (fulfilled, rejected) { + return this.all().then(function (array) { + return fulfilled.apply(void 0, array); + }, rejected); +}; + +/** + * The async function is a decorator for generator functions, turning + * them into asynchronous generators. Although generators are only part + * of the newest ECMAScript 6 drafts, this code does not cause syntax + * errors in older engines. This code should continue to work and will + * in fact improve over time as the language improves. + * + * ES6 generators are currently part of V8 version 3.19 with the + * --harmony-generators runtime flag enabled. SpiderMonkey has had them + * for longer, but under an older Python-inspired form. This function + * works on both kinds of generators. + * + * Decorates a generator function such that: + * - it may yield promises + * - execution will continue when that promise is fulfilled + * - the value of the yield expression will be the fulfilled value + * - it returns a promise for the return value (when the generator + * stops iterating) + * - the decorated function returns a promise for the return value + * of the generator or the first rejected promise among those + * yielded. + * - if an error is thrown in the generator, it propagates through + * every following yield until it is caught, or until it escapes + * the generator function altogether, and is translated into a + * rejection for the promise returned by the decorated generator. + */ +Q.async = async; +function async(makeGenerator) { + return function () { + // when verb is "send", arg is a value + // when verb is "throw", arg is an exception + function continuer(verb, arg) { + var result; + + // Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only + // engine that has a deployed base of browsers that support generators. + // However, SM's generators use the Python-inspired semantics of + // outdated ES6 drafts. We would like to support ES6, but we'd also + // like to make it possible to use generators in deployed browsers, so + // we also support Python-style generators. At some point we can remove + // this block. + + if (typeof StopIteration === "undefined") { + // ES6 Generators + try { + result = generator[verb](arg); + } catch (exception) { + return reject(exception); + } + if (result.done) { + return Q(result.value); + } else { + return when(result.value, callback, errback); + } + } else { + // SpiderMonkey Generators + // FIXME: Remove this case when SM does ES6 generators. + try { + result = generator[verb](arg); + } catch (exception) { + if (isStopIteration(exception)) { + return Q(exception.value); + } else { + return reject(exception); + } + } + return when(result, callback, errback); + } + } + var generator = makeGenerator.apply(this, arguments); + var callback = continuer.bind(continuer, "next"); + var errback = continuer.bind(continuer, "throw"); + return callback(); + }; +} + +/** + * The spawn function is a small wrapper around async that immediately + * calls the generator and also ends the promise chain, so that any + * unhandled errors are thrown instead of forwarded to the error + * handler. This is useful because it's extremely common to run + * generators at the top-level to work with libraries. + */ +Q.spawn = spawn; +function spawn(makeGenerator) { + Q.done(Q.async(makeGenerator)()); +} + +// FIXME: Remove this interface once ES6 generators are in SpiderMonkey. +/** + * Throws a ReturnValue exception to stop an asynchronous generator. + * + * This interface is a stop-gap measure to support generator return + * values in older Firefox/SpiderMonkey. In browsers that support ES6 + * generators like Chromium 29, just use "return" in your generator + * functions. + * + * @param value the return value for the surrounding generator + * @throws ReturnValue exception with the value. + * @example + * // ES6 style + * Q.async(function* () { + * var foo = yield getFooPromise(); + * var bar = yield getBarPromise(); + * return foo + bar; + * }) + * // Older SpiderMonkey style + * Q.async(function () { + * var foo = yield getFooPromise(); + * var bar = yield getBarPromise(); + * Q.return(foo + bar); + * }) + */ +Q["return"] = _return; +function _return(value) { + throw new QReturnValue(value); +} + +/** + * The promised function decorator ensures that any promise arguments + * are settled and passed as values (`this` is also settled and passed + * as a value). It will also ensure that the result of a function is + * always a promise. + * + * @example + * var add = Q.promised(function (a, b) { + * return a + b; + * }); + * add(Q(a), Q(B)); + * + * @param {function} callback The function to decorate + * @returns {function} a function that has been decorated. + */ +Q.promised = promised; +function promised(callback) { + return function () { + return spread([this, all(arguments)], function (self, args) { + return callback.apply(self, args); + }); + }; +} + +/** + * sends a message to a value in a future turn + * @param object* the recipient + * @param op the name of the message operation, e.g., "when", + * @param args further arguments to be forwarded to the operation + * @returns result {Promise} a promise for the result of the operation + */ +Q.dispatch = dispatch; +function dispatch(object, op, args) { + return Q(object).dispatch(op, args); +} + +Promise.prototype.dispatch = function (op, args) { + var self = this; + var deferred = defer(); + Q.nextTick(function () { + self.promiseDispatch(deferred.resolve, op, args); + }); + return deferred.promise; +}; + +/** + * Gets the value of a property in a future turn. + * @param object promise or immediate reference for target object + * @param name name of property to get + * @return promise for the property value + */ +Q.get = function (object, key) { + return Q(object).dispatch("get", [key]); +}; + +Promise.prototype.get = function (key) { + return this.dispatch("get", [key]); +}; + +/** + * Sets the value of a property in a future turn. + * @param object promise or immediate reference for object object + * @param name name of property to set + * @param value new value of property + * @return promise for the return value + */ +Q.set = function (object, key, value) { + return Q(object).dispatch("set", [key, value]); +}; + +Promise.prototype.set = function (key, value) { + return this.dispatch("set", [key, value]); +}; + +/** + * Deletes a property in a future turn. + * @param object promise or immediate reference for target object + * @param name name of property to delete + * @return promise for the return value + */ +Q.del = // XXX legacy +Q["delete"] = function (object, key) { + return Q(object).dispatch("delete", [key]); +}; + +Promise.prototype.del = // XXX legacy +Promise.prototype["delete"] = function (key) { + return this.dispatch("delete", [key]); +}; + +/** + * Invokes a method in a future turn. + * @param object promise or immediate reference for target object + * @param name name of method to invoke + * @param value a value to post, typically an array of + * invocation arguments for promises that + * are ultimately backed with `resolve` values, + * as opposed to those backed with URLs + * wherein the posted value can be any + * JSON serializable object. + * @return promise for the return value + */ +// bound locally because it is used by other methods +Q.mapply = // XXX As proposed by "Redsandro" +Q.post = function (object, name, args) { + return Q(object).dispatch("post", [name, args]); +}; + +Promise.prototype.mapply = // XXX As proposed by "Redsandro" +Promise.prototype.post = function (name, args) { + return this.dispatch("post", [name, args]); +}; + +/** + * Invokes a method in a future turn. + * @param object promise or immediate reference for target object + * @param name name of method to invoke + * @param ...args array of invocation arguments + * @return promise for the return value + */ +Q.send = // XXX Mark Miller's proposed parlance +Q.mcall = // XXX As proposed by "Redsandro" +Q.invoke = function (object, name /*...args*/) { + return Q(object).dispatch("post", [name, array_slice(arguments, 2)]); +}; + +Promise.prototype.send = // XXX Mark Miller's proposed parlance +Promise.prototype.mcall = // XXX As proposed by "Redsandro" +Promise.prototype.invoke = function (name /*...args*/) { + return this.dispatch("post", [name, array_slice(arguments, 1)]); +}; + +/** + * Applies the promised function in a future turn. + * @param object promise or immediate reference for target function + * @param args array of application arguments + */ +Q.fapply = function (object, args) { + return Q(object).dispatch("apply", [void 0, args]); +}; + +Promise.prototype.fapply = function (args) { + return this.dispatch("apply", [void 0, args]); +}; + +/** + * Calls the promised function in a future turn. + * @param object promise or immediate reference for target function + * @param ...args array of application arguments + */ +Q["try"] = +Q.fcall = function (object /* ...args*/) { + return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]); +}; + +Promise.prototype.fcall = function (/*...args*/) { + return this.dispatch("apply", [void 0, array_slice(arguments)]); +}; + +/** + * Binds the promised function, transforming return values into a fulfilled + * promise and thrown errors into a rejected one. + * @param object promise or immediate reference for target function + * @param ...args array of application arguments + */ +Q.fbind = function (object /*...args*/) { + var promise = Q(object); + var args = array_slice(arguments, 1); + return function fbound() { + return promise.dispatch("apply", [ + this, + args.concat(array_slice(arguments)) + ]); + }; +}; +Promise.prototype.fbind = function (/*...args*/) { + var promise = this; + var args = array_slice(arguments); + return function fbound() { + return promise.dispatch("apply", [ + this, + args.concat(array_slice(arguments)) + ]); + }; +}; + +/** + * Requests the names of the owned properties of a promised + * object in a future turn. + * @param object promise or immediate reference for target object + * @return promise for the keys of the eventually settled object + */ +Q.keys = function (object) { + return Q(object).dispatch("keys", []); +}; + +Promise.prototype.keys = function () { + return this.dispatch("keys", []); +}; + +/** + * Turns an array of promises into a promise for an array. If any of + * the promises gets rejected, the whole array is rejected immediately. + * @param {Array*} an array (or promise for an array) of values (or + * promises for values) + * @returns a promise for an array of the corresponding values + */ +// By Mark Miller +// http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled +Q.all = all; +function all(promises) { + return when(promises, function (promises) { + var pendingCount = 0; + var deferred = defer(); + array_reduce(promises, function (undefined, promise, index) { + var snapshot; + if ( + isPromise(promise) && + (snapshot = promise.inspect()).state === "fulfilled" + ) { + promises[index] = snapshot.value; + } else { + ++pendingCount; + when( + promise, + function (value) { + promises[index] = value; + if (--pendingCount === 0) { + deferred.resolve(promises); + } + }, + deferred.reject, + function (progress) { + deferred.notify({ index: index, value: progress }); + } + ); + } + }, void 0); + if (pendingCount === 0) { + deferred.resolve(promises); + } + return deferred.promise; + }); +} + +Promise.prototype.all = function () { + return all(this); +}; + +/** + * Returns the first resolved promise of an array. Prior rejected promises are + * ignored. Rejects only if all promises are rejected. + * @param {Array*} an array containing values or promises for values + * @returns a promise fulfilled with the value of the first resolved promise, + * or a rejected promise if all promises are rejected. + */ +Q.any = any; + +function any(promises) { + if (promises.length === 0) { + return Q.resolve(); + } + + var deferred = Q.defer(); + var pendingCount = 0; + array_reduce(promises, function (prev, current, index) { + var promise = promises[index]; + + pendingCount++; + + when(promise, onFulfilled, onRejected, onProgress); + function onFulfilled(result) { + deferred.resolve(result); + } + function onRejected(err) { + pendingCount--; + if (pendingCount === 0) { + var rejection = err || new Error("" + err); + + rejection.message = ("Q can't get fulfillment value from any promise, all " + + "promises were rejected. Last error message: " + rejection.message); + + deferred.reject(rejection); + } + } + function onProgress(progress) { + deferred.notify({ + index: index, + value: progress + }); + } + }, undefined); + + return deferred.promise; +} + +Promise.prototype.any = function () { + return any(this); +}; + +/** + * Waits for all promises to be settled, either fulfilled or + * rejected. This is distinct from `all` since that would stop + * waiting at the first rejection. The promise returned by + * `allResolved` will never be rejected. + * @param promises a promise for an array (or an array) of promises + * (or values) + * @return a promise for an array of promises + */ +Q.allResolved = deprecate(allResolved, "allResolved", "allSettled"); +function allResolved(promises) { + return when(promises, function (promises) { + promises = array_map(promises, Q); + return when(all(array_map(promises, function (promise) { + return when(promise, noop, noop); + })), function () { + return promises; + }); + }); +} + +Promise.prototype.allResolved = function () { + return allResolved(this); +}; + +/** + * @see Promise#allSettled + */ +Q.allSettled = allSettled; +function allSettled(promises) { + return Q(promises).allSettled(); +} + +/** + * Turns an array of promises into a promise for an array of their states (as + * returned by `inspect`) when they have all settled. + * @param {Array[Any*]} values an array (or promise for an array) of values (or + * promises for values) + * @returns {Array[State]} an array of states for the respective values. + */ +Promise.prototype.allSettled = function () { + return this.then(function (promises) { + return all(array_map(promises, function (promise) { + promise = Q(promise); + function regardless() { + return promise.inspect(); + } + return promise.then(regardless, regardless); + })); + }); +}; + +/** + * Captures the failure of a promise, giving an oportunity to recover + * with a callback. If the given promise is fulfilled, the returned + * promise is fulfilled. + * @param {Any*} promise for something + * @param {Function} callback to fulfill the returned promise if the + * given promise is rejected + * @returns a promise for the return value of the callback + */ +Q.fail = // XXX legacy +Q["catch"] = function (object, rejected) { + return Q(object).then(void 0, rejected); +}; + +Promise.prototype.fail = // XXX legacy +Promise.prototype["catch"] = function (rejected) { + return this.then(void 0, rejected); +}; + +/** + * Attaches a listener that can respond to progress notifications from a + * promise's originating deferred. This listener receives the exact arguments + * passed to ``deferred.notify``. + * @param {Any*} promise for something + * @param {Function} callback to receive any progress notifications + * @returns the given promise, unchanged + */ +Q.progress = progress; +function progress(object, progressed) { + return Q(object).then(void 0, void 0, progressed); +} + +Promise.prototype.progress = function (progressed) { + return this.then(void 0, void 0, progressed); +}; + +/** + * Provides an opportunity to observe the settling of a promise, + * regardless of whether the promise is fulfilled or rejected. Forwards + * the resolution to the returned promise when the callback is done. + * The callback can return a promise to defer completion. + * @param {Any*} promise + * @param {Function} callback to observe the resolution of the given + * promise, takes no arguments. + * @returns a promise for the resolution of the given promise when + * ``fin`` is done. + */ +Q.fin = // XXX legacy +Q["finally"] = function (object, callback) { + return Q(object)["finally"](callback); +}; + +Promise.prototype.fin = // XXX legacy +Promise.prototype["finally"] = function (callback) { + if (!callback || typeof callback.apply !== "function") { + throw new Error("Q can't apply finally callback"); + } + callback = Q(callback); + return this.then(function (value) { + return callback.fcall().then(function () { + return value; + }); + }, function (reason) { + // TODO attempt to recycle the rejection with "this". + return callback.fcall().then(function () { + throw reason; + }); + }); +}; + +/** + * Terminates a chain of promises, forcing rejections to be + * thrown as exceptions. + * @param {Any*} promise at the end of a chain of promises + * @returns nothing + */ +Q.done = function (object, fulfilled, rejected, progress) { + return Q(object).done(fulfilled, rejected, progress); +}; + +Promise.prototype.done = function (fulfilled, rejected, progress) { + var onUnhandledError = function (error) { + // forward to a future turn so that ``when`` + // does not catch it and turn it into a rejection. + Q.nextTick(function () { + makeStackTraceLong(error, promise); + if (Q.onerror) { + Q.onerror(error); + } else { + throw error; + } + }); + }; + + // Avoid unnecessary `nextTick`ing via an unnecessary `when`. + var promise = fulfilled || rejected || progress ? + this.then(fulfilled, rejected, progress) : + this; + + if (typeof process === "object" && process && process.domain) { + onUnhandledError = process.domain.bind(onUnhandledError); + } + + promise.then(void 0, onUnhandledError); +}; + +/** + * Causes a promise to be rejected if it does not get fulfilled before + * some milliseconds time out. + * @param {Any*} promise + * @param {Number} milliseconds timeout + * @param {Any*} custom error message or Error object (optional) + * @returns a promise for the resolution of the given promise if it is + * fulfilled before the timeout, otherwise rejected. + */ +Q.timeout = function (object, ms, error) { + return Q(object).timeout(ms, error); +}; + +Promise.prototype.timeout = function (ms, error) { + var deferred = defer(); + var timeoutId = setTimeout(function () { + if (!error || "string" === typeof error) { + error = new Error(error || "Timed out after " + ms + " ms"); + error.code = "ETIMEDOUT"; + } + deferred.reject(error); + }, ms); + + this.then(function (value) { + clearTimeout(timeoutId); + deferred.resolve(value); + }, function (exception) { + clearTimeout(timeoutId); + deferred.reject(exception); + }, deferred.notify); + + return deferred.promise; +}; + +/** + * Returns a promise for the given value (or promised value), some + * milliseconds after it resolved. Passes rejections immediately. + * @param {Any*} promise + * @param {Number} milliseconds + * @returns a promise for the resolution of the given promise after milliseconds + * time has elapsed since the resolution of the given promise. + * If the given promise rejects, that is passed immediately. + */ +Q.delay = function (object, timeout) { + if (timeout === void 0) { + timeout = object; + object = void 0; + } + return Q(object).delay(timeout); +}; + +Promise.prototype.delay = function (timeout) { + return this.then(function (value) { + var deferred = defer(); + setTimeout(function () { + deferred.resolve(value); + }, timeout); + return deferred.promise; + }); +}; + +/** + * Passes a continuation to a Node function, which is called with the given + * arguments provided as an array, and returns a promise. + * + * Q.nfapply(FS.readFile, [__filename]) + * .then(function (content) { + * }) + * + */ +Q.nfapply = function (callback, args) { + return Q(callback).nfapply(args); +}; + +Promise.prototype.nfapply = function (args) { + var deferred = defer(); + var nodeArgs = array_slice(args); + nodeArgs.push(deferred.makeNodeResolver()); + this.fapply(nodeArgs).fail(deferred.reject); + return deferred.promise; +}; + +/** + * Passes a continuation to a Node function, which is called with the given + * arguments provided individually, and returns a promise. + * @example + * Q.nfcall(FS.readFile, __filename) + * .then(function (content) { + * }) + * + */ +Q.nfcall = function (callback /*...args*/) { + var args = array_slice(arguments, 1); + return Q(callback).nfapply(args); +}; + +Promise.prototype.nfcall = function (/*...args*/) { + var nodeArgs = array_slice(arguments); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + this.fapply(nodeArgs).fail(deferred.reject); + return deferred.promise; +}; + +/** + * Wraps a NodeJS continuation passing function and returns an equivalent + * version that returns a promise. + * @example + * Q.nfbind(FS.readFile, __filename)("utf-8") + * .then(console.log) + * .done() + */ +Q.nfbind = +Q.denodeify = function (callback /*...args*/) { + if (callback === undefined) { + throw new Error("Q can't wrap an undefined function"); + } + var baseArgs = array_slice(arguments, 1); + return function () { + var nodeArgs = baseArgs.concat(array_slice(arguments)); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + Q(callback).fapply(nodeArgs).fail(deferred.reject); + return deferred.promise; + }; +}; + +Promise.prototype.nfbind = +Promise.prototype.denodeify = function (/*...args*/) { + var args = array_slice(arguments); + args.unshift(this); + return Q.denodeify.apply(void 0, args); +}; + +Q.nbind = function (callback, thisp /*...args*/) { + var baseArgs = array_slice(arguments, 2); + return function () { + var nodeArgs = baseArgs.concat(array_slice(arguments)); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + function bound() { + return callback.apply(thisp, arguments); + } + Q(bound).fapply(nodeArgs).fail(deferred.reject); + return deferred.promise; + }; +}; + +Promise.prototype.nbind = function (/*thisp, ...args*/) { + var args = array_slice(arguments, 0); + args.unshift(this); + return Q.nbind.apply(void 0, args); +}; + +/** + * Calls a method of a Node-style object that accepts a Node-style + * callback with a given array of arguments, plus a provided callback. + * @param object an object that has the named method + * @param {String} name name of the method of object + * @param {Array} args arguments to pass to the method; the callback + * will be provided by Q and appended to these arguments. + * @returns a promise for the value or error + */ +Q.nmapply = // XXX As proposed by "Redsandro" +Q.npost = function (object, name, args) { + return Q(object).npost(name, args); +}; + +Promise.prototype.nmapply = // XXX As proposed by "Redsandro" +Promise.prototype.npost = function (name, args) { + var nodeArgs = array_slice(args || []); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); + return deferred.promise; +}; + +/** + * Calls a method of a Node-style object that accepts a Node-style + * callback, forwarding the given variadic arguments, plus a provided + * callback argument. + * @param object an object that has the named method + * @param {String} name name of the method of object + * @param ...args arguments to pass to the method; the callback will + * be provided by Q and appended to these arguments. + * @returns a promise for the value or error + */ +Q.nsend = // XXX Based on Mark Miller's proposed "send" +Q.nmcall = // XXX Based on "Redsandro's" proposal +Q.ninvoke = function (object, name /*...args*/) { + var nodeArgs = array_slice(arguments, 2); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject); + return deferred.promise; +}; + +Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send" +Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal +Promise.prototype.ninvoke = function (name /*...args*/) { + var nodeArgs = array_slice(arguments, 1); + var deferred = defer(); + nodeArgs.push(deferred.makeNodeResolver()); + this.dispatch("post", [name, nodeArgs]).fail(deferred.reject); + return deferred.promise; +}; + +/** + * If a function would like to support both Node continuation-passing-style and + * promise-returning-style, it can end its internal promise chain with + * `nodeify(nodeback)`, forwarding the optional nodeback argument. If the user + * elects to use a nodeback, the result will be sent there. If they do not + * pass a nodeback, they will receive the result promise. + * @param object a result (or a promise for a result) + * @param {Function} nodeback a Node.js-style callback + * @returns either the promise or nothing + */ +Q.nodeify = nodeify; +function nodeify(object, nodeback) { + return Q(object).nodeify(nodeback); +} + +Promise.prototype.nodeify = function (nodeback) { + if (nodeback) { + this.then(function (value) { + Q.nextTick(function () { + nodeback(null, value); + }); + }, function (error) { + Q.nextTick(function () { + nodeback(error); + }); + }); + } else { + return this; + } +}; + +Q.noConflict = function() { + throw new Error("Q.noConflict only works when Q is used as a global"); +}; + +// All code before this point will be filtered from stack traces. +var qEndingLine = captureLine(); + +return Q; + +}); diff --git a/cordova/node_modules/q/queue.js b/cordova/node_modules/q/queue.js new file mode 100755 index 0000000..1505fd0 --- /dev/null +++ b/cordova/node_modules/q/queue.js @@ -0,0 +1,35 @@ + +var Q = require("./q"); + +module.exports = Queue; +function Queue() { + var ends = Q.defer(); + var closed = Q.defer(); + return { + put: function (value) { + var next = Q.defer(); + ends.resolve({ + head: value, + tail: next.promise + }); + ends.resolve = next.resolve; + }, + get: function () { + var result = ends.promise.get("head"); + ends.promise = ends.promise.get("tail"); + return result.fail(function (error) { + closed.resolve(error); + throw error; + }); + }, + closed: closed.promise, + close: function (error) { + error = error || new Error("Can't get value from closed queue"); + var end = {head: Q.reject(error)}; + end.tail = end; + ends.resolve(end); + return closed.promise; + } + }; +} + |
