1/*
2@license
3
4dhtmlxGantt v.6.3.5 Standard
5
6This version of dhtmlxGantt is distributed under GPL 2.0 license and can be legally used in GPL projects.
7
8To use dhtmlxGantt in non-GPL projects (and get Pro version of the product), please obtain Commercial/Enterprise or Ultimate license on our site https://dhtmlx.com/docs/products/dhtmlxGantt/#licensing or contact us at sales@dhtmlx.com
9
10(c) XB Software Ltd.
11
12*/
13(function webpackUniversalModuleDefinition(root, factory) {
14	if(typeof exports === 'object' && typeof module === 'object')
15		module.exports = factory();
16	else if(typeof define === 'function' && define.amd)
17		define("dhtmlxgantt", [], factory);
18	else if(typeof exports === 'object')
19		exports["dhtmlxgantt"] = factory();
20	else
21		root["dhtmlxgantt"] = factory();
22})(window, function() {
23return /******/ (function(modules) { // webpackBootstrap
24/******/ 	// The module cache
25/******/ 	var installedModules = {};
26/******/
27/******/ 	// The require function
28/******/ 	function __webpack_require__(moduleId) {
29/******/
30/******/ 		// Check if module is in cache
31/******/ 		if(installedModules[moduleId]) {
32/******/ 			return installedModules[moduleId].exports;
33/******/ 		}
34/******/ 		// Create a new module (and put it into the cache)
35/******/ 		var module = installedModules[moduleId] = {
36/******/ 			i: moduleId,
37/******/ 			l: false,
38/******/ 			exports: {}
39/******/ 		};
40/******/
41/******/ 		// Execute the module function
42/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
43/******/
44/******/ 		// Flag the module as loaded
45/******/ 		module.l = true;
46/******/
47/******/ 		// Return the exports of the module
48/******/ 		return module.exports;
49/******/ 	}
50/******/
51/******/
52/******/ 	// expose the modules object (__webpack_modules__)
53/******/ 	__webpack_require__.m = modules;
54/******/
55/******/ 	// expose the module cache
56/******/ 	__webpack_require__.c = installedModules;
57/******/
58/******/ 	// define getter function for harmony exports
59/******/ 	__webpack_require__.d = function(exports, name, getter) {
60/******/ 		if(!__webpack_require__.o(exports, name)) {
61/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
62/******/ 		}
63/******/ 	};
64/******/
65/******/ 	// define __esModule on exports
66/******/ 	__webpack_require__.r = function(exports) {
67/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
68/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
69/******/ 		}
70/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
71/******/ 	};
72/******/
73/******/ 	// create a fake namespace object
74/******/ 	// mode & 1: value is a module id, require it
75/******/ 	// mode & 2: merge all properties of value into the ns
76/******/ 	// mode & 4: return value when already ns object
77/******/ 	// mode & 8|1: behave like require
78/******/ 	__webpack_require__.t = function(value, mode) {
79/******/ 		if(mode & 1) value = __webpack_require__(value);
80/******/ 		if(mode & 8) return value;
81/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
82/******/ 		var ns = Object.create(null);
83/******/ 		__webpack_require__.r(ns);
84/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
85/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
86/******/ 		return ns;
87/******/ 	};
88/******/
89/******/ 	// getDefaultExport function for compatibility with non-harmony modules
90/******/ 	__webpack_require__.n = function(module) {
91/******/ 		var getter = module && module.__esModule ?
92/******/ 			function getDefault() { return module['default']; } :
93/******/ 			function getModuleExports() { return module; };
94/******/ 		__webpack_require__.d(getter, 'a', getter);
95/******/ 		return getter;
96/******/ 	};
97/******/
98/******/ 	// Object.prototype.hasOwnProperty.call
99/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
100/******/
101/******/ 	// __webpack_public_path__
102/******/ 	__webpack_require__.p = "/codebase/sources/";
103/******/
104/******/
105/******/ 	// Load entry module and return exports
106/******/ 	return __webpack_require__(__webpack_require__.s = "./sources/dhtmlxgantt.gpl.ts");
107/******/ })
108/************************************************************************/
109/******/ ({
110
111/***/ "./node_modules/bluebird/js/browser/bluebird.js":
112/*!******************************************************!*\
113  !*** ./node_modules/bluebird/js/browser/bluebird.js ***!
114  \******************************************************/
115/*! no static exports found */
116/***/ (function(module, exports, __webpack_require__) {
117
118/* WEBPACK VAR INJECTION */(function(process, global, setImmediate) {/* @preserve
119 * The MIT License (MIT)
120 *
121 * Copyright (c) 2013-2018 Petka Antonov
122 *
123 * Permission is hereby granted, free of charge, to any person obtaining a copy
124 * of this software and associated documentation files (the "Software"), to deal
125 * in the Software without restriction, including without limitation the rights
126 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
127 * copies of the Software, and to permit persons to whom the Software is
128 * furnished to do so, subject to the following conditions:
129 *
130 * The above copyright notice and this permission notice shall be included in
131 * all copies or substantial portions of the Software.
132 *
133 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
134 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
135 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
136 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
137 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
138 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
139 * THE SOFTWARE.
140 *
141 */
142/**
143 * bluebird build version 3.5.4
144 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
145*/
146!function(e){if(true)module.exports=e();else { var f; }}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
147"use strict";
148module.exports = function(Promise) {
149var SomePromiseArray = Promise._SomePromiseArray;
150function any(promises) {
151    var ret = new SomePromiseArray(promises);
152    var promise = ret.promise();
153    ret.setHowMany(1);
154    ret.setUnwrap();
155    ret.init();
156    return promise;
157}
158
159Promise.any = function (promises) {
160    return any(promises);
161};
162
163Promise.prototype.any = function () {
164    return any(this);
165};
166
167};
168
169},{}],2:[function(_dereq_,module,exports){
170"use strict";
171var firstLineError;
172try {throw new Error(); } catch (e) {firstLineError = e;}
173var schedule = _dereq_("./schedule");
174var Queue = _dereq_("./queue");
175var util = _dereq_("./util");
176
177function Async() {
178    this._customScheduler = false;
179    this._isTickUsed = false;
180    this._lateQueue = new Queue(16);
181    this._normalQueue = new Queue(16);
182    this._haveDrainedQueues = false;
183    this._trampolineEnabled = true;
184    var self = this;
185    this.drainQueues = function () {
186        self._drainQueues();
187    };
188    this._schedule = schedule;
189}
190
191Async.prototype.setScheduler = function(fn) {
192    var prev = this._schedule;
193    this._schedule = fn;
194    this._customScheduler = true;
195    return prev;
196};
197
198Async.prototype.hasCustomScheduler = function() {
199    return this._customScheduler;
200};
201
202Async.prototype.enableTrampoline = function() {
203    this._trampolineEnabled = true;
204};
205
206Async.prototype.disableTrampolineIfNecessary = function() {
207    if (util.hasDevTools) {
208        this._trampolineEnabled = false;
209    }
210};
211
212Async.prototype.haveItemsQueued = function () {
213    return this._isTickUsed || this._haveDrainedQueues;
214};
215
216
217Async.prototype.fatalError = function(e, isNode) {
218    if (isNode) {
219        process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
220            "\n");
221        process.exit(2);
222    } else {
223        this.throwLater(e);
224    }
225};
226
227Async.prototype.throwLater = function(fn, arg) {
228    if (arguments.length === 1) {
229        arg = fn;
230        fn = function () { throw arg; };
231    }
232    if (typeof setTimeout !== "undefined") {
233        setTimeout(function() {
234            fn(arg);
235        }, 0);
236    } else try {
237        this._schedule(function() {
238            fn(arg);
239        });
240    } catch (e) {
241        throw new Error("No async scheduler available\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
242    }
243};
244
245function AsyncInvokeLater(fn, receiver, arg) {
246    this._lateQueue.push(fn, receiver, arg);
247    this._queueTick();
248}
249
250function AsyncInvoke(fn, receiver, arg) {
251    this._normalQueue.push(fn, receiver, arg);
252    this._queueTick();
253}
254
255function AsyncSettlePromises(promise) {
256    this._normalQueue._pushOne(promise);
257    this._queueTick();
258}
259
260if (!util.hasDevTools) {
261    Async.prototype.invokeLater = AsyncInvokeLater;
262    Async.prototype.invoke = AsyncInvoke;
263    Async.prototype.settlePromises = AsyncSettlePromises;
264} else {
265    Async.prototype.invokeLater = function (fn, receiver, arg) {
266        if (this._trampolineEnabled) {
267            AsyncInvokeLater.call(this, fn, receiver, arg);
268        } else {
269            this._schedule(function() {
270                setTimeout(function() {
271                    fn.call(receiver, arg);
272                }, 100);
273            });
274        }
275    };
276
277    Async.prototype.invoke = function (fn, receiver, arg) {
278        if (this._trampolineEnabled) {
279            AsyncInvoke.call(this, fn, receiver, arg);
280        } else {
281            this._schedule(function() {
282                fn.call(receiver, arg);
283            });
284        }
285    };
286
287    Async.prototype.settlePromises = function(promise) {
288        if (this._trampolineEnabled) {
289            AsyncSettlePromises.call(this, promise);
290        } else {
291            this._schedule(function() {
292                promise._settlePromises();
293            });
294        }
295    };
296}
297
298function _drainQueue(queue) {
299    while (queue.length() > 0) {
300        _drainQueueStep(queue);
301    }
302}
303
304function _drainQueueStep(queue) {
305    var fn = queue.shift();
306    if (typeof fn !== "function") {
307        fn._settlePromises();
308    } else {
309        var receiver = queue.shift();
310        var arg = queue.shift();
311        fn.call(receiver, arg);
312    }
313}
314
315Async.prototype._drainQueues = function () {
316    _drainQueue(this._normalQueue);
317    this._reset();
318    this._haveDrainedQueues = true;
319    _drainQueue(this._lateQueue);
320};
321
322Async.prototype._queueTick = function () {
323    if (!this._isTickUsed) {
324        this._isTickUsed = true;
325        this._schedule(this.drainQueues);
326    }
327};
328
329Async.prototype._reset = function () {
330    this._isTickUsed = false;
331};
332
333module.exports = Async;
334module.exports.firstLineError = firstLineError;
335
336},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
337"use strict";
338module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
339var calledBind = false;
340var rejectThis = function(_, e) {
341    this._reject(e);
342};
343
344var targetRejected = function(e, context) {
345    context.promiseRejectionQueued = true;
346    context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
347};
348
349var bindingResolved = function(thisArg, context) {
350    if (((this._bitField & 50397184) === 0)) {
351        this._resolveCallback(context.target);
352    }
353};
354
355var bindingRejected = function(e, context) {
356    if (!context.promiseRejectionQueued) this._reject(e);
357};
358
359Promise.prototype.bind = function (thisArg) {
360    if (!calledBind) {
361        calledBind = true;
362        Promise.prototype._propagateFrom = debug.propagateFromFunction();
363        Promise.prototype._boundValue = debug.boundValueFunction();
364    }
365    var maybePromise = tryConvertToPromise(thisArg);
366    var ret = new Promise(INTERNAL);
367    ret._propagateFrom(this, 1);
368    var target = this._target();
369    ret._setBoundTo(maybePromise);
370    if (maybePromise instanceof Promise) {
371        var context = {
372            promiseRejectionQueued: false,
373            promise: ret,
374            target: target,
375            bindingPromise: maybePromise
376        };
377        target._then(INTERNAL, targetRejected, undefined, ret, context);
378        maybePromise._then(
379            bindingResolved, bindingRejected, undefined, ret, context);
380        ret._setOnCancel(maybePromise);
381    } else {
382        ret._resolveCallback(target);
383    }
384    return ret;
385};
386
387Promise.prototype._setBoundTo = function (obj) {
388    if (obj !== undefined) {
389        this._bitField = this._bitField | 2097152;
390        this._boundTo = obj;
391    } else {
392        this._bitField = this._bitField & (~2097152);
393    }
394};
395
396Promise.prototype._isBound = function () {
397    return (this._bitField & 2097152) === 2097152;
398};
399
400Promise.bind = function (thisArg, value) {
401    return Promise.resolve(value).bind(thisArg);
402};
403};
404
405},{}],4:[function(_dereq_,module,exports){
406"use strict";
407var old;
408if (typeof Promise !== "undefined") old = Promise;
409function noConflict() {
410    try { if (Promise === bluebird) Promise = old; }
411    catch (e) {}
412    return bluebird;
413}
414var bluebird = _dereq_("./promise")();
415bluebird.noConflict = noConflict;
416module.exports = bluebird;
417
418},{"./promise":22}],5:[function(_dereq_,module,exports){
419"use strict";
420var cr = Object.create;
421if (cr) {
422    var callerCache = cr(null);
423    var getterCache = cr(null);
424    callerCache[" size"] = getterCache[" size"] = 0;
425}
426
427module.exports = function(Promise) {
428var util = _dereq_("./util");
429var canEvaluate = util.canEvaluate;
430var isIdentifier = util.isIdentifier;
431
432var getMethodCaller;
433var getGetter;
434if (false) { var getCompiled, makeGetter, makeMethodCaller; }
435
436function ensureMethod(obj, methodName) {
437    var fn;
438    if (obj != null) fn = obj[methodName];
439    if (typeof fn !== "function") {
440        var message = "Object " + util.classString(obj) + " has no method '" +
441            util.toString(methodName) + "'";
442        throw new Promise.TypeError(message);
443    }
444    return fn;
445}
446
447function caller(obj) {
448    var methodName = this.pop();
449    var fn = ensureMethod(obj, methodName);
450    return fn.apply(obj, this);
451}
452Promise.prototype.call = function (methodName) {
453    var args = [].slice.call(arguments, 1);;
454    if (false) { var maybeCaller; }
455    args.push(methodName);
456    return this._then(caller, undefined, undefined, args, undefined);
457};
458
459function namedGetter(obj) {
460    return obj[this];
461}
462function indexedGetter(obj) {
463    var index = +this;
464    if (index < 0) index = Math.max(0, index + obj.length);
465    return obj[index];
466}
467Promise.prototype.get = function (propertyName) {
468    var isIndex = (typeof propertyName === "number");
469    var getter;
470    if (!isIndex) {
471        if (canEvaluate) {
472            var maybeGetter = getGetter(propertyName);
473            getter = maybeGetter !== null ? maybeGetter : namedGetter;
474        } else {
475            getter = namedGetter;
476        }
477    } else {
478        getter = indexedGetter;
479    }
480    return this._then(getter, undefined, undefined, propertyName, undefined);
481};
482};
483
484},{"./util":36}],6:[function(_dereq_,module,exports){
485"use strict";
486module.exports = function(Promise, PromiseArray, apiRejection, debug) {
487var util = _dereq_("./util");
488var tryCatch = util.tryCatch;
489var errorObj = util.errorObj;
490var async = Promise._async;
491
492Promise.prototype["break"] = Promise.prototype.cancel = function() {
493    if (!debug.cancellation()) return this._warn("cancellation is disabled");
494
495    var promise = this;
496    var child = promise;
497    while (promise._isCancellable()) {
498        if (!promise._cancelBy(child)) {
499            if (child._isFollowing()) {
500                child._followee().cancel();
501            } else {
502                child._cancelBranched();
503            }
504            break;
505        }
506
507        var parent = promise._cancellationParent;
508        if (parent == null || !parent._isCancellable()) {
509            if (promise._isFollowing()) {
510                promise._followee().cancel();
511            } else {
512                promise._cancelBranched();
513            }
514            break;
515        } else {
516            if (promise._isFollowing()) promise._followee().cancel();
517            promise._setWillBeCancelled();
518            child = promise;
519            promise = parent;
520        }
521    }
522};
523
524Promise.prototype._branchHasCancelled = function() {
525    this._branchesRemainingToCancel--;
526};
527
528Promise.prototype._enoughBranchesHaveCancelled = function() {
529    return this._branchesRemainingToCancel === undefined ||
530           this._branchesRemainingToCancel <= 0;
531};
532
533Promise.prototype._cancelBy = function(canceller) {
534    if (canceller === this) {
535        this._branchesRemainingToCancel = 0;
536        this._invokeOnCancel();
537        return true;
538    } else {
539        this._branchHasCancelled();
540        if (this._enoughBranchesHaveCancelled()) {
541            this._invokeOnCancel();
542            return true;
543        }
544    }
545    return false;
546};
547
548Promise.prototype._cancelBranched = function() {
549    if (this._enoughBranchesHaveCancelled()) {
550        this._cancel();
551    }
552};
553
554Promise.prototype._cancel = function() {
555    if (!this._isCancellable()) return;
556    this._setCancelled();
557    async.invoke(this._cancelPromises, this, undefined);
558};
559
560Promise.prototype._cancelPromises = function() {
561    if (this._length() > 0) this._settlePromises();
562};
563
564Promise.prototype._unsetOnCancel = function() {
565    this._onCancelField = undefined;
566};
567
568Promise.prototype._isCancellable = function() {
569    return this.isPending() && !this._isCancelled();
570};
571
572Promise.prototype.isCancellable = function() {
573    return this.isPending() && !this.isCancelled();
574};
575
576Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
577    if (util.isArray(onCancelCallback)) {
578        for (var i = 0; i < onCancelCallback.length; ++i) {
579            this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
580        }
581    } else if (onCancelCallback !== undefined) {
582        if (typeof onCancelCallback === "function") {
583            if (!internalOnly) {
584                var e = tryCatch(onCancelCallback).call(this._boundValue());
585                if (e === errorObj) {
586                    this._attachExtraTrace(e.e);
587                    async.throwLater(e.e);
588                }
589            }
590        } else {
591            onCancelCallback._resultCancelled(this);
592        }
593    }
594};
595
596Promise.prototype._invokeOnCancel = function() {
597    var onCancelCallback = this._onCancel();
598    this._unsetOnCancel();
599    async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
600};
601
602Promise.prototype._invokeInternalOnCancel = function() {
603    if (this._isCancellable()) {
604        this._doInvokeOnCancel(this._onCancel(), true);
605        this._unsetOnCancel();
606    }
607};
608
609Promise.prototype._resultCancelled = function() {
610    this.cancel();
611};
612
613};
614
615},{"./util":36}],7:[function(_dereq_,module,exports){
616"use strict";
617module.exports = function(NEXT_FILTER) {
618var util = _dereq_("./util");
619var getKeys = _dereq_("./es5").keys;
620var tryCatch = util.tryCatch;
621var errorObj = util.errorObj;
622
623function catchFilter(instances, cb, promise) {
624    return function(e) {
625        var boundTo = promise._boundValue();
626        predicateLoop: for (var i = 0; i < instances.length; ++i) {
627            var item = instances[i];
628
629            if (item === Error ||
630                (item != null && item.prototype instanceof Error)) {
631                if (e instanceof item) {
632                    return tryCatch(cb).call(boundTo, e);
633                }
634            } else if (typeof item === "function") {
635                var matchesPredicate = tryCatch(item).call(boundTo, e);
636                if (matchesPredicate === errorObj) {
637                    return matchesPredicate;
638                } else if (matchesPredicate) {
639                    return tryCatch(cb).call(boundTo, e);
640                }
641            } else if (util.isObject(e)) {
642                var keys = getKeys(item);
643                for (var j = 0; j < keys.length; ++j) {
644                    var key = keys[j];
645                    if (item[key] != e[key]) {
646                        continue predicateLoop;
647                    }
648                }
649                return tryCatch(cb).call(boundTo, e);
650            }
651        }
652        return NEXT_FILTER;
653    };
654}
655
656return catchFilter;
657};
658
659},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
660"use strict";
661module.exports = function(Promise) {
662var longStackTraces = false;
663var contextStack = [];
664
665Promise.prototype._promiseCreated = function() {};
666Promise.prototype._pushContext = function() {};
667Promise.prototype._popContext = function() {return null;};
668Promise._peekContext = Promise.prototype._peekContext = function() {};
669
670function Context() {
671    this._trace = new Context.CapturedTrace(peekContext());
672}
673Context.prototype._pushContext = function () {
674    if (this._trace !== undefined) {
675        this._trace._promiseCreated = null;
676        contextStack.push(this._trace);
677    }
678};
679
680Context.prototype._popContext = function () {
681    if (this._trace !== undefined) {
682        var trace = contextStack.pop();
683        var ret = trace._promiseCreated;
684        trace._promiseCreated = null;
685        return ret;
686    }
687    return null;
688};
689
690function createContext() {
691    if (longStackTraces) return new Context();
692}
693
694function peekContext() {
695    var lastIndex = contextStack.length - 1;
696    if (lastIndex >= 0) {
697        return contextStack[lastIndex];
698    }
699    return undefined;
700}
701Context.CapturedTrace = null;
702Context.create = createContext;
703Context.deactivateLongStackTraces = function() {};
704Context.activateLongStackTraces = function() {
705    var Promise_pushContext = Promise.prototype._pushContext;
706    var Promise_popContext = Promise.prototype._popContext;
707    var Promise_PeekContext = Promise._peekContext;
708    var Promise_peekContext = Promise.prototype._peekContext;
709    var Promise_promiseCreated = Promise.prototype._promiseCreated;
710    Context.deactivateLongStackTraces = function() {
711        Promise.prototype._pushContext = Promise_pushContext;
712        Promise.prototype._popContext = Promise_popContext;
713        Promise._peekContext = Promise_PeekContext;
714        Promise.prototype._peekContext = Promise_peekContext;
715        Promise.prototype._promiseCreated = Promise_promiseCreated;
716        longStackTraces = false;
717    };
718    longStackTraces = true;
719    Promise.prototype._pushContext = Context.prototype._pushContext;
720    Promise.prototype._popContext = Context.prototype._popContext;
721    Promise._peekContext = Promise.prototype._peekContext = peekContext;
722    Promise.prototype._promiseCreated = function() {
723        var ctx = this._peekContext();
724        if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
725    };
726};
727return Context;
728};
729
730},{}],9:[function(_dereq_,module,exports){
731"use strict";
732module.exports = function(Promise, Context) {
733var getDomain = Promise._getDomain;
734var async = Promise._async;
735var Warning = _dereq_("./errors").Warning;
736var util = _dereq_("./util");
737var es5 = _dereq_("./es5");
738var canAttachTrace = util.canAttachTrace;
739var unhandledRejectionHandled;
740var possiblyUnhandledRejection;
741var bluebirdFramePattern =
742    /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
743var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
744var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
745var stackFramePattern = null;
746var formatStack = null;
747var indentStackFrames = false;
748var printWarning;
749var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
750                        (true ||
751                         util.env("BLUEBIRD_DEBUG") ||
752                         util.env("NODE_ENV") === "development"));
753
754var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
755    (debugging || util.env("BLUEBIRD_WARNINGS")));
756
757var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
758    (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
759
760var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
761    (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
762
763Promise.prototype.suppressUnhandledRejections = function() {
764    var target = this._target();
765    target._bitField = ((target._bitField & (~1048576)) |
766                      524288);
767};
768
769Promise.prototype._ensurePossibleRejectionHandled = function () {
770    if ((this._bitField & 524288) !== 0) return;
771    this._setRejectionIsUnhandled();
772    var self = this;
773    setTimeout(function() {
774        self._notifyUnhandledRejection();
775    }, 1);
776};
777
778Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
779    fireRejectionEvent("rejectionHandled",
780                                  unhandledRejectionHandled, undefined, this);
781};
782
783Promise.prototype._setReturnedNonUndefined = function() {
784    this._bitField = this._bitField | 268435456;
785};
786
787Promise.prototype._returnedNonUndefined = function() {
788    return (this._bitField & 268435456) !== 0;
789};
790
791Promise.prototype._notifyUnhandledRejection = function () {
792    if (this._isRejectionUnhandled()) {
793        var reason = this._settledValue();
794        this._setUnhandledRejectionIsNotified();
795        fireRejectionEvent("unhandledRejection",
796                                      possiblyUnhandledRejection, reason, this);
797    }
798};
799
800Promise.prototype._setUnhandledRejectionIsNotified = function () {
801    this._bitField = this._bitField | 262144;
802};
803
804Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
805    this._bitField = this._bitField & (~262144);
806};
807
808Promise.prototype._isUnhandledRejectionNotified = function () {
809    return (this._bitField & 262144) > 0;
810};
811
812Promise.prototype._setRejectionIsUnhandled = function () {
813    this._bitField = this._bitField | 1048576;
814};
815
816Promise.prototype._unsetRejectionIsUnhandled = function () {
817    this._bitField = this._bitField & (~1048576);
818    if (this._isUnhandledRejectionNotified()) {
819        this._unsetUnhandledRejectionIsNotified();
820        this._notifyUnhandledRejectionIsHandled();
821    }
822};
823
824Promise.prototype._isRejectionUnhandled = function () {
825    return (this._bitField & 1048576) > 0;
826};
827
828Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
829    return warn(message, shouldUseOwnTrace, promise || this);
830};
831
832Promise.onPossiblyUnhandledRejection = function (fn) {
833    var domain = getDomain();
834    possiblyUnhandledRejection =
835        typeof fn === "function" ? (domain === null ?
836                                            fn : util.domainBind(domain, fn))
837                                 : undefined;
838};
839
840Promise.onUnhandledRejectionHandled = function (fn) {
841    var domain = getDomain();
842    unhandledRejectionHandled =
843        typeof fn === "function" ? (domain === null ?
844                                            fn : util.domainBind(domain, fn))
845                                 : undefined;
846};
847
848var disableLongStackTraces = function() {};
849Promise.longStackTraces = function () {
850    if (async.haveItemsQueued() && !config.longStackTraces) {
851        throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
852    }
853    if (!config.longStackTraces && longStackTracesIsSupported()) {
854        var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
855        var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
856        var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
857        config.longStackTraces = true;
858        disableLongStackTraces = function() {
859            if (async.haveItemsQueued() && !config.longStackTraces) {
860                throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
861            }
862            Promise.prototype._captureStackTrace = Promise_captureStackTrace;
863            Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
864            Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
865            Context.deactivateLongStackTraces();
866            async.enableTrampoline();
867            config.longStackTraces = false;
868        };
869        Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
870        Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
871        Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
872        Context.activateLongStackTraces();
873        async.disableTrampolineIfNecessary();
874    }
875};
876
877Promise.hasLongStackTraces = function () {
878    return config.longStackTraces && longStackTracesIsSupported();
879};
880
881var fireDomEvent = (function() {
882    try {
883        if (typeof CustomEvent === "function") {
884            var event = new CustomEvent("CustomEvent");
885            util.global.dispatchEvent(event);
886            return function(name, event) {
887                var eventData = {
888                    detail: event,
889                    cancelable: true
890                };
891                es5.defineProperty(
892                    eventData, "promise", {value: event.promise});
893                es5.defineProperty(eventData, "reason", {value: event.reason});
894                var domEvent = new CustomEvent(name.toLowerCase(), eventData);
895                return !util.global.dispatchEvent(domEvent);
896            };
897        } else if (typeof Event === "function") {
898            var event = new Event("CustomEvent");
899            util.global.dispatchEvent(event);
900            return function(name, event) {
901                var domEvent = new Event(name.toLowerCase(), {
902                    cancelable: true
903                });
904                domEvent.detail = event;
905                es5.defineProperty(domEvent, "promise", {value: event.promise});
906                es5.defineProperty(domEvent, "reason", {value: event.reason});
907                return !util.global.dispatchEvent(domEvent);
908            };
909        } else {
910            var event = document.createEvent("CustomEvent");
911            event.initCustomEvent("testingtheevent", false, true, {});
912            util.global.dispatchEvent(event);
913            return function(name, event) {
914                var domEvent = document.createEvent("CustomEvent");
915                domEvent.initCustomEvent(name.toLowerCase(), false, true,
916                    event);
917                return !util.global.dispatchEvent(domEvent);
918            };
919        }
920    } catch (e) {}
921    return function() {
922        return false;
923    };
924})();
925
926var fireGlobalEvent = (function() {
927    if (util.isNode) {
928        return function() {
929            return process.emit.apply(process, arguments);
930        };
931    } else {
932        if (!util.global) {
933            return function() {
934                return false;
935            };
936        }
937        return function(name) {
938            var methodName = "on" + name.toLowerCase();
939            var method = util.global[methodName];
940            if (!method) return false;
941            method.apply(util.global, [].slice.call(arguments, 1));
942            return true;
943        };
944    }
945})();
946
947function generatePromiseLifecycleEventObject(name, promise) {
948    return {promise: promise};
949}
950
951var eventToObjectGenerator = {
952    promiseCreated: generatePromiseLifecycleEventObject,
953    promiseFulfilled: generatePromiseLifecycleEventObject,
954    promiseRejected: generatePromiseLifecycleEventObject,
955    promiseResolved: generatePromiseLifecycleEventObject,
956    promiseCancelled: generatePromiseLifecycleEventObject,
957    promiseChained: function(name, promise, child) {
958        return {promise: promise, child: child};
959    },
960    warning: function(name, warning) {
961        return {warning: warning};
962    },
963    unhandledRejection: function (name, reason, promise) {
964        return {reason: reason, promise: promise};
965    },
966    rejectionHandled: generatePromiseLifecycleEventObject
967};
968
969var activeFireEvent = function (name) {
970    var globalEventFired = false;
971    try {
972        globalEventFired = fireGlobalEvent.apply(null, arguments);
973    } catch (e) {
974        async.throwLater(e);
975        globalEventFired = true;
976    }
977
978    var domEventFired = false;
979    try {
980        domEventFired = fireDomEvent(name,
981                    eventToObjectGenerator[name].apply(null, arguments));
982    } catch (e) {
983        async.throwLater(e);
984        domEventFired = true;
985    }
986
987    return domEventFired || globalEventFired;
988};
989
990Promise.config = function(opts) {
991    opts = Object(opts);
992    if ("longStackTraces" in opts) {
993        if (opts.longStackTraces) {
994            Promise.longStackTraces();
995        } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
996            disableLongStackTraces();
997        }
998    }
999    if ("warnings" in opts) {
1000        var warningsOption = opts.warnings;
1001        config.warnings = !!warningsOption;
1002        wForgottenReturn = config.warnings;
1003
1004        if (util.isObject(warningsOption)) {
1005            if ("wForgottenReturn" in warningsOption) {
1006                wForgottenReturn = !!warningsOption.wForgottenReturn;
1007            }
1008        }
1009    }
1010    if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
1011        if (async.haveItemsQueued()) {
1012            throw new Error(
1013                "cannot enable cancellation after promises are in use");
1014        }
1015        Promise.prototype._clearCancellationData =
1016            cancellationClearCancellationData;
1017        Promise.prototype._propagateFrom = cancellationPropagateFrom;
1018        Promise.prototype._onCancel = cancellationOnCancel;
1019        Promise.prototype._setOnCancel = cancellationSetOnCancel;
1020        Promise.prototype._attachCancellationCallback =
1021            cancellationAttachCancellationCallback;
1022        Promise.prototype._execute = cancellationExecute;
1023        propagateFromFunction = cancellationPropagateFrom;
1024        config.cancellation = true;
1025    }
1026    if ("monitoring" in opts) {
1027        if (opts.monitoring && !config.monitoring) {
1028            config.monitoring = true;
1029            Promise.prototype._fireEvent = activeFireEvent;
1030        } else if (!opts.monitoring && config.monitoring) {
1031            config.monitoring = false;
1032            Promise.prototype._fireEvent = defaultFireEvent;
1033        }
1034    }
1035    return Promise;
1036};
1037
1038function defaultFireEvent() { return false; }
1039
1040Promise.prototype._fireEvent = defaultFireEvent;
1041Promise.prototype._execute = function(executor, resolve, reject) {
1042    try {
1043        executor(resolve, reject);
1044    } catch (e) {
1045        return e;
1046    }
1047};
1048Promise.prototype._onCancel = function () {};
1049Promise.prototype._setOnCancel = function (handler) { ; };
1050Promise.prototype._attachCancellationCallback = function(onCancel) {
1051    ;
1052};
1053Promise.prototype._captureStackTrace = function () {};
1054Promise.prototype._attachExtraTrace = function () {};
1055Promise.prototype._dereferenceTrace = function () {};
1056Promise.prototype._clearCancellationData = function() {};
1057Promise.prototype._propagateFrom = function (parent, flags) {
1058    ;
1059    ;
1060};
1061
1062function cancellationExecute(executor, resolve, reject) {
1063    var promise = this;
1064    try {
1065        executor(resolve, reject, function(onCancel) {
1066            if (typeof onCancel !== "function") {
1067                throw new TypeError("onCancel must be a function, got: " +
1068                                    util.toString(onCancel));
1069            }
1070            promise._attachCancellationCallback(onCancel);
1071        });
1072    } catch (e) {
1073        return e;
1074    }
1075}
1076
1077function cancellationAttachCancellationCallback(onCancel) {
1078    if (!this._isCancellable()) return this;
1079
1080    var previousOnCancel = this._onCancel();
1081    if (previousOnCancel !== undefined) {
1082        if (util.isArray(previousOnCancel)) {
1083            previousOnCancel.push(onCancel);
1084        } else {
1085            this._setOnCancel([previousOnCancel, onCancel]);
1086        }
1087    } else {
1088        this._setOnCancel(onCancel);
1089    }
1090}
1091
1092function cancellationOnCancel() {
1093    return this._onCancelField;
1094}
1095
1096function cancellationSetOnCancel(onCancel) {
1097    this._onCancelField = onCancel;
1098}
1099
1100function cancellationClearCancellationData() {
1101    this._cancellationParent = undefined;
1102    this._onCancelField = undefined;
1103}
1104
1105function cancellationPropagateFrom(parent, flags) {
1106    if ((flags & 1) !== 0) {
1107        this._cancellationParent = parent;
1108        var branchesRemainingToCancel = parent._branchesRemainingToCancel;
1109        if (branchesRemainingToCancel === undefined) {
1110            branchesRemainingToCancel = 0;
1111        }
1112        parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
1113    }
1114    if ((flags & 2) !== 0 && parent._isBound()) {
1115        this._setBoundTo(parent._boundTo);
1116    }
1117}
1118
1119function bindingPropagateFrom(parent, flags) {
1120    if ((flags & 2) !== 0 && parent._isBound()) {
1121        this._setBoundTo(parent._boundTo);
1122    }
1123}
1124var propagateFromFunction = bindingPropagateFrom;
1125
1126function boundValueFunction() {
1127    var ret = this._boundTo;
1128    if (ret !== undefined) {
1129        if (ret instanceof Promise) {
1130            if (ret.isFulfilled()) {
1131                return ret.value();
1132            } else {
1133                return undefined;
1134            }
1135        }
1136    }
1137    return ret;
1138}
1139
1140function longStackTracesCaptureStackTrace() {
1141    this._trace = new CapturedTrace(this._peekContext());
1142}
1143
1144function longStackTracesAttachExtraTrace(error, ignoreSelf) {
1145    if (canAttachTrace(error)) {
1146        var trace = this._trace;
1147        if (trace !== undefined) {
1148            if (ignoreSelf) trace = trace._parent;
1149        }
1150        if (trace !== undefined) {
1151            trace.attachExtraTrace(error);
1152        } else if (!error.__stackCleaned__) {
1153            var parsed = parseStackAndMessage(error);
1154            util.notEnumerableProp(error, "stack",
1155                parsed.message + "\n" + parsed.stack.join("\n"));
1156            util.notEnumerableProp(error, "__stackCleaned__", true);
1157        }
1158    }
1159}
1160
1161function longStackTracesDereferenceTrace() {
1162    this._trace = undefined;
1163}
1164
1165function checkForgottenReturns(returnValue, promiseCreated, name, promise,
1166                               parent) {
1167    if (returnValue === undefined && promiseCreated !== null &&
1168        wForgottenReturn) {
1169        if (parent !== undefined && parent._returnedNonUndefined()) return;
1170        if ((promise._bitField & 65535) === 0) return;
1171
1172        if (name) name = name + " ";
1173        var handlerLine = "";
1174        var creatorLine = "";
1175        if (promiseCreated._trace) {
1176            var traceLines = promiseCreated._trace.stack.split("\n");
1177            var stack = cleanStack(traceLines);
1178            for (var i = stack.length - 1; i >= 0; --i) {
1179                var line = stack[i];
1180                if (!nodeFramePattern.test(line)) {
1181                    var lineMatches = line.match(parseLinePattern);
1182                    if (lineMatches) {
1183                        handlerLine  = "at " + lineMatches[1] +
1184                            ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
1185                    }
1186                    break;
1187                }
1188            }
1189
1190            if (stack.length > 0) {
1191                var firstUserLine = stack[0];
1192                for (var i = 0; i < traceLines.length; ++i) {
1193
1194                    if (traceLines[i] === firstUserLine) {
1195                        if (i > 0) {
1196                            creatorLine = "\n" + traceLines[i - 1];
1197                        }
1198                        break;
1199                    }
1200                }
1201
1202            }
1203        }
1204        var msg = "a promise was created in a " + name +
1205            "handler " + handlerLine + "but was not returned from it, " +
1206            "see http://goo.gl/rRqMUw" +
1207            creatorLine;
1208        promise._warn(msg, true, promiseCreated);
1209    }
1210}
1211
1212function deprecated(name, replacement) {
1213    var message = name +
1214        " is deprecated and will be removed in a future version.";
1215    if (replacement) message += " Use " + replacement + " instead.";
1216    return warn(message);
1217}
1218
1219function warn(message, shouldUseOwnTrace, promise) {
1220    if (!config.warnings) return;
1221    var warning = new Warning(message);
1222    var ctx;
1223    if (shouldUseOwnTrace) {
1224        promise._attachExtraTrace(warning);
1225    } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
1226        ctx.attachExtraTrace(warning);
1227    } else {
1228        var parsed = parseStackAndMessage(warning);
1229        warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
1230    }
1231
1232    if (!activeFireEvent("warning", warning)) {
1233        formatAndLogError(warning, "", true);
1234    }
1235}
1236
1237function reconstructStack(message, stacks) {
1238    for (var i = 0; i < stacks.length - 1; ++i) {
1239        stacks[i].push("From previous event:");
1240        stacks[i] = stacks[i].join("\n");
1241    }
1242    if (i < stacks.length) {
1243        stacks[i] = stacks[i].join("\n");
1244    }
1245    return message + "\n" + stacks.join("\n");
1246}
1247
1248function removeDuplicateOrEmptyJumps(stacks) {
1249    for (var i = 0; i < stacks.length; ++i) {
1250        if (stacks[i].length === 0 ||
1251            ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
1252            stacks.splice(i, 1);
1253            i--;
1254        }
1255    }
1256}
1257
1258function removeCommonRoots(stacks) {
1259    var current = stacks[0];
1260    for (var i = 1; i < stacks.length; ++i) {
1261        var prev = stacks[i];
1262        var currentLastIndex = current.length - 1;
1263        var currentLastLine = current[currentLastIndex];
1264        var commonRootMeetPoint = -1;
1265
1266        for (var j = prev.length - 1; j >= 0; --j) {
1267            if (prev[j] === currentLastLine) {
1268                commonRootMeetPoint = j;
1269                break;
1270            }
1271        }
1272
1273        for (var j = commonRootMeetPoint; j >= 0; --j) {
1274            var line = prev[j];
1275            if (current[currentLastIndex] === line) {
1276                current.pop();
1277                currentLastIndex--;
1278            } else {
1279                break;
1280            }
1281        }
1282        current = prev;
1283    }
1284}
1285
1286function cleanStack(stack) {
1287    var ret = [];
1288    for (var i = 0; i < stack.length; ++i) {
1289        var line = stack[i];
1290        var isTraceLine = "    (No stack trace)" === line ||
1291            stackFramePattern.test(line);
1292        var isInternalFrame = isTraceLine && shouldIgnore(line);
1293        if (isTraceLine && !isInternalFrame) {
1294            if (indentStackFrames && line.charAt(0) !== " ") {
1295                line = "    " + line;
1296            }
1297            ret.push(line);
1298        }
1299    }
1300    return ret;
1301}
1302
1303function stackFramesAsArray(error) {
1304    var stack = error.stack.replace(/\s+$/g, "").split("\n");
1305    for (var i = 0; i < stack.length; ++i) {
1306        var line = stack[i];
1307        if ("    (No stack trace)" === line || stackFramePattern.test(line)) {
1308            break;
1309        }
1310    }
1311    if (i > 0 && error.name != "SyntaxError") {
1312        stack = stack.slice(i);
1313    }
1314    return stack;
1315}
1316
1317function parseStackAndMessage(error) {
1318    var stack = error.stack;
1319    var message = error.toString();
1320    stack = typeof stack === "string" && stack.length > 0
1321                ? stackFramesAsArray(error) : ["    (No stack trace)"];
1322    return {
1323        message: message,
1324        stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
1325    };
1326}
1327
1328function formatAndLogError(error, title, isSoft) {
1329    if (typeof console !== "undefined") {
1330        var message;
1331        if (util.isObject(error)) {
1332            var stack = error.stack;
1333            message = title + formatStack(stack, error);
1334        } else {
1335            message = title + String(error);
1336        }
1337        if (typeof printWarning === "function") {
1338            printWarning(message, isSoft);
1339        } else if (typeof console.log === "function" ||
1340            typeof console.log === "object") {
1341            console.log(message);
1342        }
1343    }
1344}
1345
1346function fireRejectionEvent(name, localHandler, reason, promise) {
1347    var localEventFired = false;
1348    try {
1349        if (typeof localHandler === "function") {
1350            localEventFired = true;
1351            if (name === "rejectionHandled") {
1352                localHandler(promise);
1353            } else {
1354                localHandler(reason, promise);
1355            }
1356        }
1357    } catch (e) {
1358        async.throwLater(e);
1359    }
1360
1361    if (name === "unhandledRejection") {
1362        if (!activeFireEvent(name, reason, promise) && !localEventFired) {
1363            formatAndLogError(reason, "Unhandled rejection ");
1364        }
1365    } else {
1366        activeFireEvent(name, promise);
1367    }
1368}
1369
1370function formatNonError(obj) {
1371    var str;
1372    if (typeof obj === "function") {
1373        str = "[function " +
1374            (obj.name || "anonymous") +
1375            "]";
1376    } else {
1377        str = obj && typeof obj.toString === "function"
1378            ? obj.toString() : util.toString(obj);
1379        var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
1380        if (ruselessToString.test(str)) {
1381            try {
1382                var newStr = JSON.stringify(obj);
1383                str = newStr;
1384            }
1385            catch(e) {
1386
1387            }
1388        }
1389        if (str.length === 0) {
1390            str = "(empty array)";
1391        }
1392    }
1393    return ("(<" + snip(str) + ">, no stack trace)");
1394}
1395
1396function snip(str) {
1397    var maxChars = 41;
1398    if (str.length < maxChars) {
1399        return str;
1400    }
1401    return str.substr(0, maxChars - 3) + "...";
1402}
1403
1404function longStackTracesIsSupported() {
1405    return typeof captureStackTrace === "function";
1406}
1407
1408var shouldIgnore = function() { return false; };
1409var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
1410function parseLineInfo(line) {
1411    var matches = line.match(parseLineInfoRegex);
1412    if (matches) {
1413        return {
1414            fileName: matches[1],
1415            line: parseInt(matches[2], 10)
1416        };
1417    }
1418}
1419
1420function setBounds(firstLineError, lastLineError) {
1421    if (!longStackTracesIsSupported()) return;
1422    var firstStackLines = firstLineError.stack.split("\n");
1423    var lastStackLines = lastLineError.stack.split("\n");
1424    var firstIndex = -1;
1425    var lastIndex = -1;
1426    var firstFileName;
1427    var lastFileName;
1428    for (var i = 0; i < firstStackLines.length; ++i) {
1429        var result = parseLineInfo(firstStackLines[i]);
1430        if (result) {
1431            firstFileName = result.fileName;
1432            firstIndex = result.line;
1433            break;
1434        }
1435    }
1436    for (var i = 0; i < lastStackLines.length; ++i) {
1437        var result = parseLineInfo(lastStackLines[i]);
1438        if (result) {
1439            lastFileName = result.fileName;
1440            lastIndex = result.line;
1441            break;
1442        }
1443    }
1444    if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
1445        firstFileName !== lastFileName || firstIndex >= lastIndex) {
1446        return;
1447    }
1448
1449    shouldIgnore = function(line) {
1450        if (bluebirdFramePattern.test(line)) return true;
1451        var info = parseLineInfo(line);
1452        if (info) {
1453            if (info.fileName === firstFileName &&
1454                (firstIndex <= info.line && info.line <= lastIndex)) {
1455                return true;
1456            }
1457        }
1458        return false;
1459    };
1460}
1461
1462function CapturedTrace(parent) {
1463    this._parent = parent;
1464    this._promisesCreated = 0;
1465    var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
1466    captureStackTrace(this, CapturedTrace);
1467    if (length > 32) this.uncycle();
1468}
1469util.inherits(CapturedTrace, Error);
1470Context.CapturedTrace = CapturedTrace;
1471
1472CapturedTrace.prototype.uncycle = function() {
1473    var length = this._length;
1474    if (length < 2) return;
1475    var nodes = [];
1476    var stackToIndex = {};
1477
1478    for (var i = 0, node = this; node !== undefined; ++i) {
1479        nodes.push(node);
1480        node = node._parent;
1481    }
1482    length = this._length = i;
1483    for (var i = length - 1; i >= 0; --i) {
1484        var stack = nodes[i].stack;
1485        if (stackToIndex[stack] === undefined) {
1486            stackToIndex[stack] = i;
1487        }
1488    }
1489    for (var i = 0; i < length; ++i) {
1490        var currentStack = nodes[i].stack;
1491        var index = stackToIndex[currentStack];
1492        if (index !== undefined && index !== i) {
1493            if (index > 0) {
1494                nodes[index - 1]._parent = undefined;
1495                nodes[index - 1]._length = 1;
1496            }
1497            nodes[i]._parent = undefined;
1498            nodes[i]._length = 1;
1499            var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
1500
1501            if (index < length - 1) {
1502                cycleEdgeNode._parent = nodes[index + 1];
1503                cycleEdgeNode._parent.uncycle();
1504                cycleEdgeNode._length =
1505                    cycleEdgeNode._parent._length + 1;
1506            } else {
1507                cycleEdgeNode._parent = undefined;
1508                cycleEdgeNode._length = 1;
1509            }
1510            var currentChildLength = cycleEdgeNode._length + 1;
1511            for (var j = i - 2; j >= 0; --j) {
1512                nodes[j]._length = currentChildLength;
1513                currentChildLength++;
1514            }
1515            return;
1516        }
1517    }
1518};
1519
1520CapturedTrace.prototype.attachExtraTrace = function(error) {
1521    if (error.__stackCleaned__) return;
1522    this.uncycle();
1523    var parsed = parseStackAndMessage(error);
1524    var message = parsed.message;
1525    var stacks = [parsed.stack];
1526
1527    var trace = this;
1528    while (trace !== undefined) {
1529        stacks.push(cleanStack(trace.stack.split("\n")));
1530        trace = trace._parent;
1531    }
1532    removeCommonRoots(stacks);
1533    removeDuplicateOrEmptyJumps(stacks);
1534    util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
1535    util.notEnumerableProp(error, "__stackCleaned__", true);
1536};
1537
1538var captureStackTrace = (function stackDetection() {
1539    var v8stackFramePattern = /^\s*at\s*/;
1540    var v8stackFormatter = function(stack, error) {
1541        if (typeof stack === "string") return stack;
1542
1543        if (error.name !== undefined &&
1544            error.message !== undefined) {
1545            return error.toString();
1546        }
1547        return formatNonError(error);
1548    };
1549
1550    if (typeof Error.stackTraceLimit === "number" &&
1551        typeof Error.captureStackTrace === "function") {
1552        Error.stackTraceLimit += 6;
1553        stackFramePattern = v8stackFramePattern;
1554        formatStack = v8stackFormatter;
1555        var captureStackTrace = Error.captureStackTrace;
1556
1557        shouldIgnore = function(line) {
1558            return bluebirdFramePattern.test(line);
1559        };
1560        return function(receiver, ignoreUntil) {
1561            Error.stackTraceLimit += 6;
1562            captureStackTrace(receiver, ignoreUntil);
1563            Error.stackTraceLimit -= 6;
1564        };
1565    }
1566    var err = new Error();
1567
1568    if (typeof err.stack === "string" &&
1569        err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
1570        stackFramePattern = /@/;
1571        formatStack = v8stackFormatter;
1572        indentStackFrames = true;
1573        return function captureStackTrace(o) {
1574            o.stack = new Error().stack;
1575        };
1576    }
1577
1578    var hasStackAfterThrow;
1579    try { throw new Error(); }
1580    catch(e) {
1581        hasStackAfterThrow = ("stack" in e);
1582    }
1583    if (!("stack" in err) && hasStackAfterThrow &&
1584        typeof Error.stackTraceLimit === "number") {
1585        stackFramePattern = v8stackFramePattern;
1586        formatStack = v8stackFormatter;
1587        return function captureStackTrace(o) {
1588            Error.stackTraceLimit += 6;
1589            try { throw new Error(); }
1590            catch(e) { o.stack = e.stack; }
1591            Error.stackTraceLimit -= 6;
1592        };
1593    }
1594
1595    formatStack = function(stack, error) {
1596        if (typeof stack === "string") return stack;
1597
1598        if ((typeof error === "object" ||
1599            typeof error === "function") &&
1600            error.name !== undefined &&
1601            error.message !== undefined) {
1602            return error.toString();
1603        }
1604        return formatNonError(error);
1605    };
1606
1607    return null;
1608
1609})([]);
1610
1611if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
1612    printWarning = function (message) {
1613        console.warn(message);
1614    };
1615    if (util.isNode && process.stderr.isTTY) {
1616        printWarning = function(message, isSoft) {
1617            var color = isSoft ? "\u001b[33m" : "\u001b[31m";
1618            console.warn(color + message + "\u001b[0m\n");
1619        };
1620    } else if (!util.isNode && typeof (new Error().stack) === "string") {
1621        printWarning = function(message, isSoft) {
1622            console.warn("%c" + message,
1623                        isSoft ? "color: darkorange" : "color: red");
1624        };
1625    }
1626}
1627
1628var config = {
1629    warnings: warnings,
1630    longStackTraces: false,
1631    cancellation: false,
1632    monitoring: false
1633};
1634
1635if (longStackTraces) Promise.longStackTraces();
1636
1637return {
1638    longStackTraces: function() {
1639        return config.longStackTraces;
1640    },
1641    warnings: function() {
1642        return config.warnings;
1643    },
1644    cancellation: function() {
1645        return config.cancellation;
1646    },
1647    monitoring: function() {
1648        return config.monitoring;
1649    },
1650    propagateFromFunction: function() {
1651        return propagateFromFunction;
1652    },
1653    boundValueFunction: function() {
1654        return boundValueFunction;
1655    },
1656    checkForgottenReturns: checkForgottenReturns,
1657    setBounds: setBounds,
1658    warn: warn,
1659    deprecated: deprecated,
1660    CapturedTrace: CapturedTrace,
1661    fireDomEvent: fireDomEvent,
1662    fireGlobalEvent: fireGlobalEvent
1663};
1664};
1665
1666},{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){
1667"use strict";
1668module.exports = function(Promise) {
1669function returner() {
1670    return this.value;
1671}
1672function thrower() {
1673    throw this.reason;
1674}
1675
1676Promise.prototype["return"] =
1677Promise.prototype.thenReturn = function (value) {
1678    if (value instanceof Promise) value.suppressUnhandledRejections();
1679    return this._then(
1680        returner, undefined, undefined, {value: value}, undefined);
1681};
1682
1683Promise.prototype["throw"] =
1684Promise.prototype.thenThrow = function (reason) {
1685    return this._then(
1686        thrower, undefined, undefined, {reason: reason}, undefined);
1687};
1688
1689Promise.prototype.catchThrow = function (reason) {
1690    if (arguments.length <= 1) {
1691        return this._then(
1692            undefined, thrower, undefined, {reason: reason}, undefined);
1693    } else {
1694        var _reason = arguments[1];
1695        var handler = function() {throw _reason;};
1696        return this.caught(reason, handler);
1697    }
1698};
1699
1700Promise.prototype.catchReturn = function (value) {
1701    if (arguments.length <= 1) {
1702        if (value instanceof Promise) value.suppressUnhandledRejections();
1703        return this._then(
1704            undefined, returner, undefined, {value: value}, undefined);
1705    } else {
1706        var _value = arguments[1];
1707        if (_value instanceof Promise) _value.suppressUnhandledRejections();
1708        var handler = function() {return _value;};
1709        return this.caught(value, handler);
1710    }
1711};
1712};
1713
1714},{}],11:[function(_dereq_,module,exports){
1715"use strict";
1716module.exports = function(Promise, INTERNAL) {
1717var PromiseReduce = Promise.reduce;
1718var PromiseAll = Promise.all;
1719
1720function promiseAllThis() {
1721    return PromiseAll(this);
1722}
1723
1724function PromiseMapSeries(promises, fn) {
1725    return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
1726}
1727
1728Promise.prototype.each = function (fn) {
1729    return PromiseReduce(this, fn, INTERNAL, 0)
1730              ._then(promiseAllThis, undefined, undefined, this, undefined);
1731};
1732
1733Promise.prototype.mapSeries = function (fn) {
1734    return PromiseReduce(this, fn, INTERNAL, INTERNAL);
1735};
1736
1737Promise.each = function (promises, fn) {
1738    return PromiseReduce(promises, fn, INTERNAL, 0)
1739              ._then(promiseAllThis, undefined, undefined, promises, undefined);
1740};
1741
1742Promise.mapSeries = PromiseMapSeries;
1743};
1744
1745
1746},{}],12:[function(_dereq_,module,exports){
1747"use strict";
1748var es5 = _dereq_("./es5");
1749var Objectfreeze = es5.freeze;
1750var util = _dereq_("./util");
1751var inherits = util.inherits;
1752var notEnumerableProp = util.notEnumerableProp;
1753
1754function subError(nameProperty, defaultMessage) {
1755    function SubError(message) {
1756        if (!(this instanceof SubError)) return new SubError(message);
1757        notEnumerableProp(this, "message",
1758            typeof message === "string" ? message : defaultMessage);
1759        notEnumerableProp(this, "name", nameProperty);
1760        if (Error.captureStackTrace) {
1761            Error.captureStackTrace(this, this.constructor);
1762        } else {
1763            Error.call(this);
1764        }
1765    }
1766    inherits(SubError, Error);
1767    return SubError;
1768}
1769
1770var _TypeError, _RangeError;
1771var Warning = subError("Warning", "warning");
1772var CancellationError = subError("CancellationError", "cancellation error");
1773var TimeoutError = subError("TimeoutError", "timeout error");
1774var AggregateError = subError("AggregateError", "aggregate error");
1775try {
1776    _TypeError = TypeError;
1777    _RangeError = RangeError;
1778} catch(e) {
1779    _TypeError = subError("TypeError", "type error");
1780    _RangeError = subError("RangeError", "range error");
1781}
1782
1783var methods = ("join pop push shift unshift slice filter forEach some " +
1784    "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
1785
1786for (var i = 0; i < methods.length; ++i) {
1787    if (typeof Array.prototype[methods[i]] === "function") {
1788        AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
1789    }
1790}
1791
1792es5.defineProperty(AggregateError.prototype, "length", {
1793    value: 0,
1794    configurable: false,
1795    writable: true,
1796    enumerable: true
1797});
1798AggregateError.prototype["isOperational"] = true;
1799var level = 0;
1800AggregateError.prototype.toString = function() {
1801    var indent = Array(level * 4 + 1).join(" ");
1802    var ret = "\n" + indent + "AggregateError of:" + "\n";
1803    level++;
1804    indent = Array(level * 4 + 1).join(" ");
1805    for (var i = 0; i < this.length; ++i) {
1806        var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
1807        var lines = str.split("\n");
1808        for (var j = 0; j < lines.length; ++j) {
1809            lines[j] = indent + lines[j];
1810        }
1811        str = lines.join("\n");
1812        ret += str + "\n";
1813    }
1814    level--;
1815    return ret;
1816};
1817
1818function OperationalError(message) {
1819    if (!(this instanceof OperationalError))
1820        return new OperationalError(message);
1821    notEnumerableProp(this, "name", "OperationalError");
1822    notEnumerableProp(this, "message", message);
1823    this.cause = message;
1824    this["isOperational"] = true;
1825
1826    if (message instanceof Error) {
1827        notEnumerableProp(this, "message", message.message);
1828        notEnumerableProp(this, "stack", message.stack);
1829    } else if (Error.captureStackTrace) {
1830        Error.captureStackTrace(this, this.constructor);
1831    }
1832
1833}
1834inherits(OperationalError, Error);
1835
1836var errorTypes = Error["__BluebirdErrorTypes__"];
1837if (!errorTypes) {
1838    errorTypes = Objectfreeze({
1839        CancellationError: CancellationError,
1840        TimeoutError: TimeoutError,
1841        OperationalError: OperationalError,
1842        RejectionError: OperationalError,
1843        AggregateError: AggregateError
1844    });
1845    es5.defineProperty(Error, "__BluebirdErrorTypes__", {
1846        value: errorTypes,
1847        writable: false,
1848        enumerable: false,
1849        configurable: false
1850    });
1851}
1852
1853module.exports = {
1854    Error: Error,
1855    TypeError: _TypeError,
1856    RangeError: _RangeError,
1857    CancellationError: errorTypes.CancellationError,
1858    OperationalError: errorTypes.OperationalError,
1859    TimeoutError: errorTypes.TimeoutError,
1860    AggregateError: errorTypes.AggregateError,
1861    Warning: Warning
1862};
1863
1864},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
1865var isES5 = (function(){
1866    "use strict";
1867    return this === undefined;
1868})();
1869
1870if (isES5) {
1871    module.exports = {
1872        freeze: Object.freeze,
1873        defineProperty: Object.defineProperty,
1874        getDescriptor: Object.getOwnPropertyDescriptor,
1875        keys: Object.keys,
1876        names: Object.getOwnPropertyNames,
1877        getPrototypeOf: Object.getPrototypeOf,
1878        isArray: Array.isArray,
1879        isES5: isES5,
1880        propertyIsWritable: function(obj, prop) {
1881            var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
1882            return !!(!descriptor || descriptor.writable || descriptor.set);
1883        }
1884    };
1885} else {
1886    var has = {}.hasOwnProperty;
1887    var str = {}.toString;
1888    var proto = {}.constructor.prototype;
1889
1890    var ObjectKeys = function (o) {
1891        var ret = [];
1892        for (var key in o) {
1893            if (has.call(o, key)) {
1894                ret.push(key);
1895            }
1896        }
1897        return ret;
1898    };
1899
1900    var ObjectGetDescriptor = function(o, key) {
1901        return {value: o[key]};
1902    };
1903
1904    var ObjectDefineProperty = function (o, key, desc) {
1905        o[key] = desc.value;
1906        return o;
1907    };
1908
1909    var ObjectFreeze = function (obj) {
1910        return obj;
1911    };
1912
1913    var ObjectGetPrototypeOf = function (obj) {
1914        try {
1915            return Object(obj).constructor.prototype;
1916        }
1917        catch (e) {
1918            return proto;
1919        }
1920    };
1921
1922    var ArrayIsArray = function (obj) {
1923        try {
1924            return str.call(obj) === "[object Array]";
1925        }
1926        catch(e) {
1927            return false;
1928        }
1929    };
1930
1931    module.exports = {
1932        isArray: ArrayIsArray,
1933        keys: ObjectKeys,
1934        names: ObjectKeys,
1935        defineProperty: ObjectDefineProperty,
1936        getDescriptor: ObjectGetDescriptor,
1937        freeze: ObjectFreeze,
1938        getPrototypeOf: ObjectGetPrototypeOf,
1939        isES5: isES5,
1940        propertyIsWritable: function() {
1941            return true;
1942        }
1943    };
1944}
1945
1946},{}],14:[function(_dereq_,module,exports){
1947"use strict";
1948module.exports = function(Promise, INTERNAL) {
1949var PromiseMap = Promise.map;
1950
1951Promise.prototype.filter = function (fn, options) {
1952    return PromiseMap(this, fn, options, INTERNAL);
1953};
1954
1955Promise.filter = function (promises, fn, options) {
1956    return PromiseMap(promises, fn, options, INTERNAL);
1957};
1958};
1959
1960},{}],15:[function(_dereq_,module,exports){
1961"use strict";
1962module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
1963var util = _dereq_("./util");
1964var CancellationError = Promise.CancellationError;
1965var errorObj = util.errorObj;
1966var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
1967
1968function PassThroughHandlerContext(promise, type, handler) {
1969    this.promise = promise;
1970    this.type = type;
1971    this.handler = handler;
1972    this.called = false;
1973    this.cancelPromise = null;
1974}
1975
1976PassThroughHandlerContext.prototype.isFinallyHandler = function() {
1977    return this.type === 0;
1978};
1979
1980function FinallyHandlerCancelReaction(finallyHandler) {
1981    this.finallyHandler = finallyHandler;
1982}
1983
1984FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
1985    checkCancel(this.finallyHandler);
1986};
1987
1988function checkCancel(ctx, reason) {
1989    if (ctx.cancelPromise != null) {
1990        if (arguments.length > 1) {
1991            ctx.cancelPromise._reject(reason);
1992        } else {
1993            ctx.cancelPromise._cancel();
1994        }
1995        ctx.cancelPromise = null;
1996        return true;
1997    }
1998    return false;
1999}
2000
2001function succeed() {
2002    return finallyHandler.call(this, this.promise._target()._settledValue());
2003}
2004function fail(reason) {
2005    if (checkCancel(this, reason)) return;
2006    errorObj.e = reason;
2007    return errorObj;
2008}
2009function finallyHandler(reasonOrValue) {
2010    var promise = this.promise;
2011    var handler = this.handler;
2012
2013    if (!this.called) {
2014        this.called = true;
2015        var ret = this.isFinallyHandler()
2016            ? handler.call(promise._boundValue())
2017            : handler.call(promise._boundValue(), reasonOrValue);
2018        if (ret === NEXT_FILTER) {
2019            return ret;
2020        } else if (ret !== undefined) {
2021            promise._setReturnedNonUndefined();
2022            var maybePromise = tryConvertToPromise(ret, promise);
2023            if (maybePromise instanceof Promise) {
2024                if (this.cancelPromise != null) {
2025                    if (maybePromise._isCancelled()) {
2026                        var reason =
2027                            new CancellationError("late cancellation observer");
2028                        promise._attachExtraTrace(reason);
2029                        errorObj.e = reason;
2030                        return errorObj;
2031                    } else if (maybePromise.isPending()) {
2032                        maybePromise._attachCancellationCallback(
2033                            new FinallyHandlerCancelReaction(this));
2034                    }
2035                }
2036                return maybePromise._then(
2037                    succeed, fail, undefined, this, undefined);
2038            }
2039        }
2040    }
2041
2042    if (promise.isRejected()) {
2043        checkCancel(this);
2044        errorObj.e = reasonOrValue;
2045        return errorObj;
2046    } else {
2047        checkCancel(this);
2048        return reasonOrValue;
2049    }
2050}
2051
2052Promise.prototype._passThrough = function(handler, type, success, fail) {
2053    if (typeof handler !== "function") return this.then();
2054    return this._then(success,
2055                      fail,
2056                      undefined,
2057                      new PassThroughHandlerContext(this, type, handler),
2058                      undefined);
2059};
2060
2061Promise.prototype.lastly =
2062Promise.prototype["finally"] = function (handler) {
2063    return this._passThrough(handler,
2064                             0,
2065                             finallyHandler,
2066                             finallyHandler);
2067};
2068
2069
2070Promise.prototype.tap = function (handler) {
2071    return this._passThrough(handler, 1, finallyHandler);
2072};
2073
2074Promise.prototype.tapCatch = function (handlerOrPredicate) {
2075    var len = arguments.length;
2076    if(len === 1) {
2077        return this._passThrough(handlerOrPredicate,
2078                                 1,
2079                                 undefined,
2080                                 finallyHandler);
2081    } else {
2082         var catchInstances = new Array(len - 1),
2083            j = 0, i;
2084        for (i = 0; i < len - 1; ++i) {
2085            var item = arguments[i];
2086            if (util.isObject(item)) {
2087                catchInstances[j++] = item;
2088            } else {
2089                return Promise.reject(new TypeError(
2090                    "tapCatch statement predicate: "
2091                    + "expecting an object but got " + util.classString(item)
2092                ));
2093            }
2094        }
2095        catchInstances.length = j;
2096        var handler = arguments[i];
2097        return this._passThrough(catchFilter(catchInstances, handler, this),
2098                                 1,
2099                                 undefined,
2100                                 finallyHandler);
2101    }
2102
2103};
2104
2105return PassThroughHandlerContext;
2106};
2107
2108},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){
2109"use strict";
2110module.exports = function(Promise,
2111                          apiRejection,
2112                          INTERNAL,
2113                          tryConvertToPromise,
2114                          Proxyable,
2115                          debug) {
2116var errors = _dereq_("./errors");
2117var TypeError = errors.TypeError;
2118var util = _dereq_("./util");
2119var errorObj = util.errorObj;
2120var tryCatch = util.tryCatch;
2121var yieldHandlers = [];
2122
2123function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
2124    for (var i = 0; i < yieldHandlers.length; ++i) {
2125        traceParent._pushContext();
2126        var result = tryCatch(yieldHandlers[i])(value);
2127        traceParent._popContext();
2128        if (result === errorObj) {
2129            traceParent._pushContext();
2130            var ret = Promise.reject(errorObj.e);
2131            traceParent._popContext();
2132            return ret;
2133        }
2134        var maybePromise = tryConvertToPromise(result, traceParent);
2135        if (maybePromise instanceof Promise) return maybePromise;
2136    }
2137    return null;
2138}
2139
2140function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
2141    if (debug.cancellation()) {
2142        var internal = new Promise(INTERNAL);
2143        var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
2144        this._promise = internal.lastly(function() {
2145            return _finallyPromise;
2146        });
2147        internal._captureStackTrace();
2148        internal._setOnCancel(this);
2149    } else {
2150        var promise = this._promise = new Promise(INTERNAL);
2151        promise._captureStackTrace();
2152    }
2153    this._stack = stack;
2154    this._generatorFunction = generatorFunction;
2155    this._receiver = receiver;
2156    this._generator = undefined;
2157    this._yieldHandlers = typeof yieldHandler === "function"
2158        ? [yieldHandler].concat(yieldHandlers)
2159        : yieldHandlers;
2160    this._yieldedPromise = null;
2161    this._cancellationPhase = false;
2162}
2163util.inherits(PromiseSpawn, Proxyable);
2164
2165PromiseSpawn.prototype._isResolved = function() {
2166    return this._promise === null;
2167};
2168
2169PromiseSpawn.prototype._cleanup = function() {
2170    this._promise = this._generator = null;
2171    if (debug.cancellation() && this._finallyPromise !== null) {
2172        this._finallyPromise._fulfill();
2173        this._finallyPromise = null;
2174    }
2175};
2176
2177PromiseSpawn.prototype._promiseCancelled = function() {
2178    if (this._isResolved()) return;
2179    var implementsReturn = typeof this._generator["return"] !== "undefined";
2180
2181    var result;
2182    if (!implementsReturn) {
2183        var reason = new Promise.CancellationError(
2184            "generator .return() sentinel");
2185        Promise.coroutine.returnSentinel = reason;
2186        this._promise._attachExtraTrace(reason);
2187        this._promise._pushContext();
2188        result = tryCatch(this._generator["throw"]).call(this._generator,
2189                                                         reason);
2190        this._promise._popContext();
2191    } else {
2192        this._promise._pushContext();
2193        result = tryCatch(this._generator["return"]).call(this._generator,
2194                                                          undefined);
2195        this._promise._popContext();
2196    }
2197    this._cancellationPhase = true;
2198    this._yieldedPromise = null;
2199    this._continue(result);
2200};
2201
2202PromiseSpawn.prototype._promiseFulfilled = function(value) {
2203    this._yieldedPromise = null;
2204    this._promise._pushContext();
2205    var result = tryCatch(this._generator.next).call(this._generator, value);
2206    this._promise._popContext();
2207    this._continue(result);
2208};
2209
2210PromiseSpawn.prototype._promiseRejected = function(reason) {
2211    this._yieldedPromise = null;
2212    this._promise._attachExtraTrace(reason);
2213    this._promise._pushContext();
2214    var result = tryCatch(this._generator["throw"])
2215        .call(this._generator, reason);
2216    this._promise._popContext();
2217    this._continue(result);
2218};
2219
2220PromiseSpawn.prototype._resultCancelled = function() {
2221    if (this._yieldedPromise instanceof Promise) {
2222        var promise = this._yieldedPromise;
2223        this._yieldedPromise = null;
2224        promise.cancel();
2225    }
2226};
2227
2228PromiseSpawn.prototype.promise = function () {
2229    return this._promise;
2230};
2231
2232PromiseSpawn.prototype._run = function () {
2233    this._generator = this._generatorFunction.call(this._receiver);
2234    this._receiver =
2235        this._generatorFunction = undefined;
2236    this._promiseFulfilled(undefined);
2237};
2238
2239PromiseSpawn.prototype._continue = function (result) {
2240    var promise = this._promise;
2241    if (result === errorObj) {
2242        this._cleanup();
2243        if (this._cancellationPhase) {
2244            return promise.cancel();
2245        } else {
2246            return promise._rejectCallback(result.e, false);
2247        }
2248    }
2249
2250    var value = result.value;
2251    if (result.done === true) {
2252        this._cleanup();
2253        if (this._cancellationPhase) {
2254            return promise.cancel();
2255        } else {
2256            return promise._resolveCallback(value);
2257        }
2258    } else {
2259        var maybePromise = tryConvertToPromise(value, this._promise);
2260        if (!(maybePromise instanceof Promise)) {
2261            maybePromise =
2262                promiseFromYieldHandler(maybePromise,
2263                                        this._yieldHandlers,
2264                                        this._promise);
2265            if (maybePromise === null) {
2266                this._promiseRejected(
2267                    new TypeError(
2268                        "A value %s was yielded that could not be treated as a promise\u000a\u000a    See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) +
2269                        "From coroutine:\u000a" +
2270                        this._stack.split("\n").slice(1, -7).join("\n")
2271                    )
2272                );
2273                return;
2274            }
2275        }
2276        maybePromise = maybePromise._target();
2277        var bitField = maybePromise._bitField;
2278        ;
2279        if (((bitField & 50397184) === 0)) {
2280            this._yieldedPromise = maybePromise;
2281            maybePromise._proxy(this, null);
2282        } else if (((bitField & 33554432) !== 0)) {
2283            Promise._async.invoke(
2284                this._promiseFulfilled, this, maybePromise._value()
2285            );
2286        } else if (((bitField & 16777216) !== 0)) {
2287            Promise._async.invoke(
2288                this._promiseRejected, this, maybePromise._reason()
2289            );
2290        } else {
2291            this._promiseCancelled();
2292        }
2293    }
2294};
2295
2296Promise.coroutine = function (generatorFunction, options) {
2297    if (typeof generatorFunction !== "function") {
2298        throw new TypeError("generatorFunction must be a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
2299    }
2300    var yieldHandler = Object(options).yieldHandler;
2301    var PromiseSpawn$ = PromiseSpawn;
2302    var stack = new Error().stack;
2303    return function () {
2304        var generator = generatorFunction.apply(this, arguments);
2305        var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
2306                                      stack);
2307        var ret = spawn.promise();
2308        spawn._generator = generator;
2309        spawn._promiseFulfilled(undefined);
2310        return ret;
2311    };
2312};
2313
2314Promise.coroutine.addYieldHandler = function(fn) {
2315    if (typeof fn !== "function") {
2316        throw new TypeError("expecting a function but got " + util.classString(fn));
2317    }
2318    yieldHandlers.push(fn);
2319};
2320
2321Promise.spawn = function (generatorFunction) {
2322    debug.deprecated("Promise.spawn()", "Promise.coroutine()");
2323    if (typeof generatorFunction !== "function") {
2324        return apiRejection("generatorFunction must be a function\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
2325    }
2326    var spawn = new PromiseSpawn(generatorFunction, this);
2327    var ret = spawn.promise();
2328    spawn._run(Promise.spawn);
2329    return ret;
2330};
2331};
2332
2333},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
2334"use strict";
2335module.exports =
2336function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
2337         getDomain) {
2338var util = _dereq_("./util");
2339var canEvaluate = util.canEvaluate;
2340var tryCatch = util.tryCatch;
2341var errorObj = util.errorObj;
2342var reject;
2343
2344if (false) { var i, promiseSetters, thenCallbacks, holderClasses, generateHolderClass, promiseSetter, thenCallback; }
2345
2346Promise.join = function () {
2347    var last = arguments.length - 1;
2348    var fn;
2349    if (last > 0 && typeof arguments[last] === "function") {
2350        fn = arguments[last];
2351        if (false) { var domain, bitField, maybePromise, i, callbacks, holder, HolderClass, ret; }
2352    }
2353    var args = [].slice.call(arguments);;
2354    if (fn) args.pop();
2355    var ret = new PromiseArray(args).promise();
2356    return fn !== undefined ? ret.spread(fn) : ret;
2357};
2358
2359};
2360
2361},{"./util":36}],18:[function(_dereq_,module,exports){
2362"use strict";
2363module.exports = function(Promise,
2364                          PromiseArray,
2365                          apiRejection,
2366                          tryConvertToPromise,
2367                          INTERNAL,
2368                          debug) {
2369var getDomain = Promise._getDomain;
2370var util = _dereq_("./util");
2371var tryCatch = util.tryCatch;
2372var errorObj = util.errorObj;
2373var async = Promise._async;
2374
2375function MappingPromiseArray(promises, fn, limit, _filter) {
2376    this.constructor$(promises);
2377    this._promise._captureStackTrace();
2378    var domain = getDomain();
2379    this._callback = domain === null ? fn : util.domainBind(domain, fn);
2380    this._preservedValues = _filter === INTERNAL
2381        ? new Array(this.length())
2382        : null;
2383    this._limit = limit;
2384    this._inFlight = 0;
2385    this._queue = [];
2386    async.invoke(this._asyncInit, this, undefined);
2387}
2388util.inherits(MappingPromiseArray, PromiseArray);
2389
2390MappingPromiseArray.prototype._asyncInit = function() {
2391    this._init$(undefined, -2);
2392};
2393
2394MappingPromiseArray.prototype._init = function () {};
2395
2396MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
2397    var values = this._values;
2398    var length = this.length();
2399    var preservedValues = this._preservedValues;
2400    var limit = this._limit;
2401
2402    if (index < 0) {
2403        index = (index * -1) - 1;
2404        values[index] = value;
2405        if (limit >= 1) {
2406            this._inFlight--;
2407            this._drainQueue();
2408            if (this._isResolved()) return true;
2409        }
2410    } else {
2411        if (limit >= 1 && this._inFlight >= limit) {
2412            values[index] = value;
2413            this._queue.push(index);
2414            return false;
2415        }
2416        if (preservedValues !== null) preservedValues[index] = value;
2417
2418        var promise = this._promise;
2419        var callback = this._callback;
2420        var receiver = promise._boundValue();
2421        promise._pushContext();
2422        var ret = tryCatch(callback).call(receiver, value, index, length);
2423        var promiseCreated = promise._popContext();
2424        debug.checkForgottenReturns(
2425            ret,
2426            promiseCreated,
2427            preservedValues !== null ? "Promise.filter" : "Promise.map",
2428            promise
2429        );
2430        if (ret === errorObj) {
2431            this._reject(ret.e);
2432            return true;
2433        }
2434
2435        var maybePromise = tryConvertToPromise(ret, this._promise);
2436        if (maybePromise instanceof Promise) {
2437            maybePromise = maybePromise._target();
2438            var bitField = maybePromise._bitField;
2439            ;
2440            if (((bitField & 50397184) === 0)) {
2441                if (limit >= 1) this._inFlight++;
2442                values[index] = maybePromise;
2443                maybePromise._proxy(this, (index + 1) * -1);
2444                return false;
2445            } else if (((bitField & 33554432) !== 0)) {
2446                ret = maybePromise._value();
2447            } else if (((bitField & 16777216) !== 0)) {
2448                this._reject(maybePromise._reason());
2449                return true;
2450            } else {
2451                this._cancel();
2452                return true;
2453            }
2454        }
2455        values[index] = ret;
2456    }
2457    var totalResolved = ++this._totalResolved;
2458    if (totalResolved >= length) {
2459        if (preservedValues !== null) {
2460            this._filter(values, preservedValues);
2461        } else {
2462            this._resolve(values);
2463        }
2464        return true;
2465    }
2466    return false;
2467};
2468
2469MappingPromiseArray.prototype._drainQueue = function () {
2470    var queue = this._queue;
2471    var limit = this._limit;
2472    var values = this._values;
2473    while (queue.length > 0 && this._inFlight < limit) {
2474        if (this._isResolved()) return;
2475        var index = queue.pop();
2476        this._promiseFulfilled(values[index], index);
2477    }
2478};
2479
2480MappingPromiseArray.prototype._filter = function (booleans, values) {
2481    var len = values.length;
2482    var ret = new Array(len);
2483    var j = 0;
2484    for (var i = 0; i < len; ++i) {
2485        if (booleans[i]) ret[j++] = values[i];
2486    }
2487    ret.length = j;
2488    this._resolve(ret);
2489};
2490
2491MappingPromiseArray.prototype.preservedValues = function () {
2492    return this._preservedValues;
2493};
2494
2495function map(promises, fn, options, _filter) {
2496    if (typeof fn !== "function") {
2497        return apiRejection("expecting a function but got " + util.classString(fn));
2498    }
2499
2500    var limit = 0;
2501    if (options !== undefined) {
2502        if (typeof options === "object" && options !== null) {
2503            if (typeof options.concurrency !== "number") {
2504                return Promise.reject(
2505                    new TypeError("'concurrency' must be a number but it is " +
2506                                    util.classString(options.concurrency)));
2507            }
2508            limit = options.concurrency;
2509        } else {
2510            return Promise.reject(new TypeError(
2511                            "options argument must be an object but it is " +
2512                             util.classString(options)));
2513        }
2514    }
2515    limit = typeof limit === "number" &&
2516        isFinite(limit) && limit >= 1 ? limit : 0;
2517    return new MappingPromiseArray(promises, fn, limit, _filter).promise();
2518}
2519
2520Promise.prototype.map = function (fn, options) {
2521    return map(this, fn, options, null);
2522};
2523
2524Promise.map = function (promises, fn, options, _filter) {
2525    return map(promises, fn, options, _filter);
2526};
2527
2528
2529};
2530
2531},{"./util":36}],19:[function(_dereq_,module,exports){
2532"use strict";
2533module.exports =
2534function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
2535var util = _dereq_("./util");
2536var tryCatch = util.tryCatch;
2537
2538Promise.method = function (fn) {
2539    if (typeof fn !== "function") {
2540        throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
2541    }
2542    return function () {
2543        var ret = new Promise(INTERNAL);
2544        ret._captureStackTrace();
2545        ret._pushContext();
2546        var value = tryCatch(fn).apply(this, arguments);
2547        var promiseCreated = ret._popContext();
2548        debug.checkForgottenReturns(
2549            value, promiseCreated, "Promise.method", ret);
2550        ret._resolveFromSyncValue(value);
2551        return ret;
2552    };
2553};
2554
2555Promise.attempt = Promise["try"] = function (fn) {
2556    if (typeof fn !== "function") {
2557        return apiRejection("expecting a function but got " + util.classString(fn));
2558    }
2559    var ret = new Promise(INTERNAL);
2560    ret._captureStackTrace();
2561    ret._pushContext();
2562    var value;
2563    if (arguments.length > 1) {
2564        debug.deprecated("calling Promise.try with more than 1 argument");
2565        var arg = arguments[1];
2566        var ctx = arguments[2];
2567        value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
2568                                  : tryCatch(fn).call(ctx, arg);
2569    } else {
2570        value = tryCatch(fn)();
2571    }
2572    var promiseCreated = ret._popContext();
2573    debug.checkForgottenReturns(
2574        value, promiseCreated, "Promise.try", ret);
2575    ret._resolveFromSyncValue(value);
2576    return ret;
2577};
2578
2579Promise.prototype._resolveFromSyncValue = function (value) {
2580    if (value === util.errorObj) {
2581        this._rejectCallback(value.e, false);
2582    } else {
2583        this._resolveCallback(value, true);
2584    }
2585};
2586};
2587
2588},{"./util":36}],20:[function(_dereq_,module,exports){
2589"use strict";
2590var util = _dereq_("./util");
2591var maybeWrapAsError = util.maybeWrapAsError;
2592var errors = _dereq_("./errors");
2593var OperationalError = errors.OperationalError;
2594var es5 = _dereq_("./es5");
2595
2596function isUntypedError(obj) {
2597    return obj instanceof Error &&
2598        es5.getPrototypeOf(obj) === Error.prototype;
2599}
2600
2601var rErrorKey = /^(?:name|message|stack|cause)$/;
2602function wrapAsOperationalError(obj) {
2603    var ret;
2604    if (isUntypedError(obj)) {
2605        ret = new OperationalError(obj);
2606        ret.name = obj.name;
2607        ret.message = obj.message;
2608        ret.stack = obj.stack;
2609        var keys = es5.keys(obj);
2610        for (var i = 0; i < keys.length; ++i) {
2611            var key = keys[i];
2612            if (!rErrorKey.test(key)) {
2613                ret[key] = obj[key];
2614            }
2615        }
2616        return ret;
2617    }
2618    util.markAsOriginatingFromRejection(obj);
2619    return obj;
2620}
2621
2622function nodebackForPromise(promise, multiArgs) {
2623    return function(err, value) {
2624        if (promise === null) return;
2625        if (err) {
2626            var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
2627            promise._attachExtraTrace(wrapped);
2628            promise._reject(wrapped);
2629        } else if (!multiArgs) {
2630            promise._fulfill(value);
2631        } else {
2632            var args = [].slice.call(arguments, 1);;
2633            promise._fulfill(args);
2634        }
2635        promise = null;
2636    };
2637}
2638
2639module.exports = nodebackForPromise;
2640
2641},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
2642"use strict";
2643module.exports = function(Promise) {
2644var util = _dereq_("./util");
2645var async = Promise._async;
2646var tryCatch = util.tryCatch;
2647var errorObj = util.errorObj;
2648
2649function spreadAdapter(val, nodeback) {
2650    var promise = this;
2651    if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
2652    var ret =
2653        tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
2654    if (ret === errorObj) {
2655        async.throwLater(ret.e);
2656    }
2657}
2658
2659function successAdapter(val, nodeback) {
2660    var promise = this;
2661    var receiver = promise._boundValue();
2662    var ret = val === undefined
2663        ? tryCatch(nodeback).call(receiver, null)
2664        : tryCatch(nodeback).call(receiver, null, val);
2665    if (ret === errorObj) {
2666        async.throwLater(ret.e);
2667    }
2668}
2669function errorAdapter(reason, nodeback) {
2670    var promise = this;
2671    if (!reason) {
2672        var newReason = new Error(reason + "");
2673        newReason.cause = reason;
2674        reason = newReason;
2675    }
2676    var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
2677    if (ret === errorObj) {
2678        async.throwLater(ret.e);
2679    }
2680}
2681
2682Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
2683                                                                     options) {
2684    if (typeof nodeback == "function") {
2685        var adapter = successAdapter;
2686        if (options !== undefined && Object(options).spread) {
2687            adapter = spreadAdapter;
2688        }
2689        this._then(
2690            adapter,
2691            errorAdapter,
2692            undefined,
2693            this,
2694            nodeback
2695        );
2696    }
2697    return this;
2698};
2699};
2700
2701},{"./util":36}],22:[function(_dereq_,module,exports){
2702"use strict";
2703module.exports = function() {
2704var makeSelfResolutionError = function () {
2705    return new TypeError("circular promise resolution chain\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
2706};
2707var reflectHandler = function() {
2708    return new Promise.PromiseInspection(this._target());
2709};
2710var apiRejection = function(msg) {
2711    return Promise.reject(new TypeError(msg));
2712};
2713function Proxyable() {}
2714var UNDEFINED_BINDING = {};
2715var util = _dereq_("./util");
2716
2717var getDomain;
2718if (util.isNode) {
2719    getDomain = function() {
2720        var ret = process.domain;
2721        if (ret === undefined) ret = null;
2722        return ret;
2723    };
2724} else {
2725    getDomain = function() {
2726        return null;
2727    };
2728}
2729util.notEnumerableProp(Promise, "_getDomain", getDomain);
2730
2731var es5 = _dereq_("./es5");
2732var Async = _dereq_("./async");
2733var async = new Async();
2734es5.defineProperty(Promise, "_async", {value: async});
2735var errors = _dereq_("./errors");
2736var TypeError = Promise.TypeError = errors.TypeError;
2737Promise.RangeError = errors.RangeError;
2738var CancellationError = Promise.CancellationError = errors.CancellationError;
2739Promise.TimeoutError = errors.TimeoutError;
2740Promise.OperationalError = errors.OperationalError;
2741Promise.RejectionError = errors.OperationalError;
2742Promise.AggregateError = errors.AggregateError;
2743var INTERNAL = function(){};
2744var APPLY = {};
2745var NEXT_FILTER = {};
2746var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
2747var PromiseArray =
2748    _dereq_("./promise_array")(Promise, INTERNAL,
2749                               tryConvertToPromise, apiRejection, Proxyable);
2750var Context = _dereq_("./context")(Promise);
2751 /*jshint unused:false*/
2752var createContext = Context.create;
2753var debug = _dereq_("./debuggability")(Promise, Context);
2754var CapturedTrace = debug.CapturedTrace;
2755var PassThroughHandlerContext =
2756    _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
2757var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
2758var nodebackForPromise = _dereq_("./nodeback");
2759var errorObj = util.errorObj;
2760var tryCatch = util.tryCatch;
2761function check(self, executor) {
2762    if (self == null || self.constructor !== Promise) {
2763        throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a    See http://goo.gl/MqrFmX\u000a");
2764    }
2765    if (typeof executor !== "function") {
2766        throw new TypeError("expecting a function but got " + util.classString(executor));
2767    }
2768
2769}
2770
2771function Promise(executor) {
2772    if (executor !== INTERNAL) {
2773        check(this, executor);
2774    }
2775    this._bitField = 0;
2776    this._fulfillmentHandler0 = undefined;
2777    this._rejectionHandler0 = undefined;
2778    this._promise0 = undefined;
2779    this._receiver0 = undefined;
2780    this._resolveFromExecutor(executor);
2781    this._promiseCreated();
2782    this._fireEvent("promiseCreated", this);
2783}
2784
2785Promise.prototype.toString = function () {
2786    return "[object Promise]";
2787};
2788
2789Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
2790    var len = arguments.length;
2791    if (len > 1) {
2792        var catchInstances = new Array(len - 1),
2793            j = 0, i;
2794        for (i = 0; i < len - 1; ++i) {
2795            var item = arguments[i];
2796            if (util.isObject(item)) {
2797                catchInstances[j++] = item;
2798            } else {
2799                return apiRejection("Catch statement predicate: " +
2800                    "expecting an object but got " + util.classString(item));
2801            }
2802        }
2803        catchInstances.length = j;
2804        fn = arguments[i];
2805        return this.then(undefined, catchFilter(catchInstances, fn, this));
2806    }
2807    return this.then(undefined, fn);
2808};
2809
2810Promise.prototype.reflect = function () {
2811    return this._then(reflectHandler,
2812        reflectHandler, undefined, this, undefined);
2813};
2814
2815Promise.prototype.then = function (didFulfill, didReject) {
2816    if (debug.warnings() && arguments.length > 0 &&
2817        typeof didFulfill !== "function" &&
2818        typeof didReject !== "function") {
2819        var msg = ".then() only accepts functions but was passed: " +
2820                util.classString(didFulfill);
2821        if (arguments.length > 1) {
2822            msg += ", " + util.classString(didReject);
2823        }
2824        this._warn(msg);
2825    }
2826    return this._then(didFulfill, didReject, undefined, undefined, undefined);
2827};
2828
2829Promise.prototype.done = function (didFulfill, didReject) {
2830    var promise =
2831        this._then(didFulfill, didReject, undefined, undefined, undefined);
2832    promise._setIsFinal();
2833};
2834
2835Promise.prototype.spread = function (fn) {
2836    if (typeof fn !== "function") {
2837        return apiRejection("expecting a function but got " + util.classString(fn));
2838    }
2839    return this.all()._then(fn, undefined, undefined, APPLY, undefined);
2840};
2841
2842Promise.prototype.toJSON = function () {
2843    var ret = {
2844        isFulfilled: false,
2845        isRejected: false,
2846        fulfillmentValue: undefined,
2847        rejectionReason: undefined
2848    };
2849    if (this.isFulfilled()) {
2850        ret.fulfillmentValue = this.value();
2851        ret.isFulfilled = true;
2852    } else if (this.isRejected()) {
2853        ret.rejectionReason = this.reason();
2854        ret.isRejected = true;
2855    }
2856    return ret;
2857};
2858
2859Promise.prototype.all = function () {
2860    if (arguments.length > 0) {
2861        this._warn(".all() was passed arguments but it does not take any");
2862    }
2863    return new PromiseArray(this).promise();
2864};
2865
2866Promise.prototype.error = function (fn) {
2867    return this.caught(util.originatesFromRejection, fn);
2868};
2869
2870Promise.getNewLibraryCopy = module.exports;
2871
2872Promise.is = function (val) {
2873    return val instanceof Promise;
2874};
2875
2876Promise.fromNode = Promise.fromCallback = function(fn) {
2877    var ret = new Promise(INTERNAL);
2878    ret._captureStackTrace();
2879    var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
2880                                         : false;
2881    var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
2882    if (result === errorObj) {
2883        ret._rejectCallback(result.e, true);
2884    }
2885    if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
2886    return ret;
2887};
2888
2889Promise.all = function (promises) {
2890    return new PromiseArray(promises).promise();
2891};
2892
2893Promise.cast = function (obj) {
2894    var ret = tryConvertToPromise(obj);
2895    if (!(ret instanceof Promise)) {
2896        ret = new Promise(INTERNAL);
2897        ret._captureStackTrace();
2898        ret._setFulfilled();
2899        ret._rejectionHandler0 = obj;
2900    }
2901    return ret;
2902};
2903
2904Promise.resolve = Promise.fulfilled = Promise.cast;
2905
2906Promise.reject = Promise.rejected = function (reason) {
2907    var ret = new Promise(INTERNAL);
2908    ret._captureStackTrace();
2909    ret._rejectCallback(reason, true);
2910    return ret;
2911};
2912
2913Promise.setScheduler = function(fn) {
2914    if (typeof fn !== "function") {
2915        throw new TypeError("expecting a function but got " + util.classString(fn));
2916    }
2917    return async.setScheduler(fn);
2918};
2919
2920Promise.prototype._then = function (
2921    didFulfill,
2922    didReject,
2923    _,    receiver,
2924    internalData
2925) {
2926    var haveInternalData = internalData !== undefined;
2927    var promise = haveInternalData ? internalData : new Promise(INTERNAL);
2928    var target = this._target();
2929    var bitField = target._bitField;
2930
2931    if (!haveInternalData) {
2932        promise._propagateFrom(this, 3);
2933        promise._captureStackTrace();
2934        if (receiver === undefined &&
2935            ((this._bitField & 2097152) !== 0)) {
2936            if (!((bitField & 50397184) === 0)) {
2937                receiver = this._boundValue();
2938            } else {
2939                receiver = target === this ? undefined : this._boundTo;
2940            }
2941        }
2942        this._fireEvent("promiseChained", this, promise);
2943    }
2944
2945    var domain = getDomain();
2946    if (!((bitField & 50397184) === 0)) {
2947        var handler, value, settler = target._settlePromiseCtx;
2948        if (((bitField & 33554432) !== 0)) {
2949            value = target._rejectionHandler0;
2950            handler = didFulfill;
2951        } else if (((bitField & 16777216) !== 0)) {
2952            value = target._fulfillmentHandler0;
2953            handler = didReject;
2954            target._unsetRejectionIsUnhandled();
2955        } else {
2956            settler = target._settlePromiseLateCancellationObserver;
2957            value = new CancellationError("late cancellation observer");
2958            target._attachExtraTrace(value);
2959            handler = didReject;
2960        }
2961
2962        async.invoke(settler, target, {
2963            handler: domain === null ? handler
2964                : (typeof handler === "function" &&
2965                    util.domainBind(domain, handler)),
2966            promise: promise,
2967            receiver: receiver,
2968            value: value
2969        });
2970    } else {
2971        target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
2972    }
2973
2974    return promise;
2975};
2976
2977Promise.prototype._length = function () {
2978    return this._bitField & 65535;
2979};
2980
2981Promise.prototype._isFateSealed = function () {
2982    return (this._bitField & 117506048) !== 0;
2983};
2984
2985Promise.prototype._isFollowing = function () {
2986    return (this._bitField & 67108864) === 67108864;
2987};
2988
2989Promise.prototype._setLength = function (len) {
2990    this._bitField = (this._bitField & -65536) |
2991        (len & 65535);
2992};
2993
2994Promise.prototype._setFulfilled = function () {
2995    this._bitField = this._bitField | 33554432;
2996    this._fireEvent("promiseFulfilled", this);
2997};
2998
2999Promise.prototype._setRejected = function () {
3000    this._bitField = this._bitField | 16777216;
3001    this._fireEvent("promiseRejected", this);
3002};
3003
3004Promise.prototype._setFollowing = function () {
3005    this._bitField = this._bitField | 67108864;
3006    this._fireEvent("promiseResolved", this);
3007};
3008
3009Promise.prototype._setIsFinal = function () {
3010    this._bitField = this._bitField | 4194304;
3011};
3012
3013Promise.prototype._isFinal = function () {
3014    return (this._bitField & 4194304) > 0;
3015};
3016
3017Promise.prototype._unsetCancelled = function() {
3018    this._bitField = this._bitField & (~65536);
3019};
3020
3021Promise.prototype._setCancelled = function() {
3022    this._bitField = this._bitField | 65536;
3023    this._fireEvent("promiseCancelled", this);
3024};
3025
3026Promise.prototype._setWillBeCancelled = function() {
3027    this._bitField = this._bitField | 8388608;
3028};
3029
3030Promise.prototype._setAsyncGuaranteed = function() {
3031    if (async.hasCustomScheduler()) return;
3032    this._bitField = this._bitField | 134217728;
3033};
3034
3035Promise.prototype._receiverAt = function (index) {
3036    var ret = index === 0 ? this._receiver0 : this[
3037            index * 4 - 4 + 3];
3038    if (ret === UNDEFINED_BINDING) {
3039        return undefined;
3040    } else if (ret === undefined && this._isBound()) {
3041        return this._boundValue();
3042    }
3043    return ret;
3044};
3045
3046Promise.prototype._promiseAt = function (index) {
3047    return this[
3048            index * 4 - 4 + 2];
3049};
3050
3051Promise.prototype._fulfillmentHandlerAt = function (index) {
3052    return this[
3053            index * 4 - 4 + 0];
3054};
3055
3056Promise.prototype._rejectionHandlerAt = function (index) {
3057    return this[
3058            index * 4 - 4 + 1];
3059};
3060
3061Promise.prototype._boundValue = function() {};
3062
3063Promise.prototype._migrateCallback0 = function (follower) {
3064    var bitField = follower._bitField;
3065    var fulfill = follower._fulfillmentHandler0;
3066    var reject = follower._rejectionHandler0;
3067    var promise = follower._promise0;
3068    var receiver = follower._receiverAt(0);
3069    if (receiver === undefined) receiver = UNDEFINED_BINDING;
3070    this._addCallbacks(fulfill, reject, promise, receiver, null);
3071};
3072
3073Promise.prototype._migrateCallbackAt = function (follower, index) {
3074    var fulfill = follower._fulfillmentHandlerAt(index);
3075    var reject = follower._rejectionHandlerAt(index);
3076    var promise = follower._promiseAt(index);
3077    var receiver = follower._receiverAt(index);
3078    if (receiver === undefined) receiver = UNDEFINED_BINDING;
3079    this._addCallbacks(fulfill, reject, promise, receiver, null);
3080};
3081
3082Promise.prototype._addCallbacks = function (
3083    fulfill,
3084    reject,
3085    promise,
3086    receiver,
3087    domain
3088) {
3089    var index = this._length();
3090
3091    if (index >= 65535 - 4) {
3092        index = 0;
3093        this._setLength(0);
3094    }
3095
3096    if (index === 0) {
3097        this._promise0 = promise;
3098        this._receiver0 = receiver;
3099        if (typeof fulfill === "function") {
3100            this._fulfillmentHandler0 =
3101                domain === null ? fulfill : util.domainBind(domain, fulfill);
3102        }
3103        if (typeof reject === "function") {
3104            this._rejectionHandler0 =
3105                domain === null ? reject : util.domainBind(domain, reject);
3106        }
3107    } else {
3108        var base = index * 4 - 4;
3109        this[base + 2] = promise;
3110        this[base + 3] = receiver;
3111        if (typeof fulfill === "function") {
3112            this[base + 0] =
3113                domain === null ? fulfill : util.domainBind(domain, fulfill);
3114        }
3115        if (typeof reject === "function") {
3116            this[base + 1] =
3117                domain === null ? reject : util.domainBind(domain, reject);
3118        }
3119    }
3120    this._setLength(index + 1);
3121    return index;
3122};
3123
3124Promise.prototype._proxy = function (proxyable, arg) {
3125    this._addCallbacks(undefined, undefined, arg, proxyable, null);
3126};
3127
3128Promise.prototype._resolveCallback = function(value, shouldBind) {
3129    if (((this._bitField & 117506048) !== 0)) return;
3130    if (value === this)
3131        return this._rejectCallback(makeSelfResolutionError(), false);
3132    var maybePromise = tryConvertToPromise(value, this);
3133    if (!(maybePromise instanceof Promise)) return this._fulfill(value);
3134
3135    if (shouldBind) this._propagateFrom(maybePromise, 2);
3136
3137    var promise = maybePromise._target();
3138
3139    if (promise === this) {
3140        this._reject(makeSelfResolutionError());
3141        return;
3142    }
3143
3144    var bitField = promise._bitField;
3145    if (((bitField & 50397184) === 0)) {
3146        var len = this._length();
3147        if (len > 0) promise._migrateCallback0(this);
3148        for (var i = 1; i < len; ++i) {
3149            promise._migrateCallbackAt(this, i);
3150        }
3151        this._setFollowing();
3152        this._setLength(0);
3153        this._setFollowee(promise);
3154    } else if (((bitField & 33554432) !== 0)) {
3155        this._fulfill(promise._value());
3156    } else if (((bitField & 16777216) !== 0)) {
3157        this._reject(promise._reason());
3158    } else {
3159        var reason = new CancellationError("late cancellation observer");
3160        promise._attachExtraTrace(reason);
3161        this._reject(reason);
3162    }
3163};
3164
3165Promise.prototype._rejectCallback =
3166function(reason, synchronous, ignoreNonErrorWarnings) {
3167    var trace = util.ensureErrorObject(reason);
3168    var hasStack = trace === reason;
3169    if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
3170        var message = "a promise was rejected with a non-error: " +
3171            util.classString(reason);
3172        this._warn(message, true);
3173    }
3174    this._attachExtraTrace(trace, synchronous ? hasStack : false);
3175    this._reject(reason);
3176};
3177
3178Promise.prototype._resolveFromExecutor = function (executor) {
3179    if (executor === INTERNAL) return;
3180    var promise = this;
3181    this._captureStackTrace();
3182    this._pushContext();
3183    var synchronous = true;
3184    var r = this._execute(executor, function(value) {
3185        promise._resolveCallback(value);
3186    }, function (reason) {
3187        promise._rejectCallback(reason, synchronous);
3188    });
3189    synchronous = false;
3190    this._popContext();
3191
3192    if (r !== undefined) {
3193        promise._rejectCallback(r, true);
3194    }
3195};
3196
3197Promise.prototype._settlePromiseFromHandler = function (
3198    handler, receiver, value, promise
3199) {
3200    var bitField = promise._bitField;
3201    if (((bitField & 65536) !== 0)) return;
3202    promise._pushContext();
3203    var x;
3204    if (receiver === APPLY) {
3205        if (!value || typeof value.length !== "number") {
3206            x = errorObj;
3207            x.e = new TypeError("cannot .spread() a non-array: " +
3208                                    util.classString(value));
3209        } else {
3210            x = tryCatch(handler).apply(this._boundValue(), value);
3211        }
3212    } else {
3213        x = tryCatch(handler).call(receiver, value);
3214    }
3215    var promiseCreated = promise._popContext();
3216    bitField = promise._bitField;
3217    if (((bitField & 65536) !== 0)) return;
3218
3219    if (x === NEXT_FILTER) {
3220        promise._reject(value);
3221    } else if (x === errorObj) {
3222        promise._rejectCallback(x.e, false);
3223    } else {
3224        debug.checkForgottenReturns(x, promiseCreated, "",  promise, this);
3225        promise._resolveCallback(x);
3226    }
3227};
3228
3229Promise.prototype._target = function() {
3230    var ret = this;
3231    while (ret._isFollowing()) ret = ret._followee();
3232    return ret;
3233};
3234
3235Promise.prototype._followee = function() {
3236    return this._rejectionHandler0;
3237};
3238
3239Promise.prototype._setFollowee = function(promise) {
3240    this._rejectionHandler0 = promise;
3241};
3242
3243Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
3244    var isPromise = promise instanceof Promise;
3245    var bitField = this._bitField;
3246    var asyncGuaranteed = ((bitField & 134217728) !== 0);
3247    if (((bitField & 65536) !== 0)) {
3248        if (isPromise) promise._invokeInternalOnCancel();
3249
3250        if (receiver instanceof PassThroughHandlerContext &&
3251            receiver.isFinallyHandler()) {
3252            receiver.cancelPromise = promise;
3253            if (tryCatch(handler).call(receiver, value) === errorObj) {
3254                promise._reject(errorObj.e);
3255            }
3256        } else if (handler === reflectHandler) {
3257            promise._fulfill(reflectHandler.call(receiver));
3258        } else if (receiver instanceof Proxyable) {
3259            receiver._promiseCancelled(promise);
3260        } else if (isPromise || promise instanceof PromiseArray) {
3261            promise._cancel();
3262        } else {
3263            receiver.cancel();
3264        }
3265    } else if (typeof handler === "function") {
3266        if (!isPromise) {
3267            handler.call(receiver, value, promise);
3268        } else {
3269            if (asyncGuaranteed) promise._setAsyncGuaranteed();
3270            this._settlePromiseFromHandler(handler, receiver, value, promise);
3271        }
3272    } else if (receiver instanceof Proxyable) {
3273        if (!receiver._isResolved()) {
3274            if (((bitField & 33554432) !== 0)) {
3275                receiver._promiseFulfilled(value, promise);
3276            } else {
3277                receiver._promiseRejected(value, promise);
3278            }
3279        }
3280    } else if (isPromise) {
3281        if (asyncGuaranteed) promise._setAsyncGuaranteed();
3282        if (((bitField & 33554432) !== 0)) {
3283            promise._fulfill(value);
3284        } else {
3285            promise._reject(value);
3286        }
3287    }
3288};
3289
3290Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
3291    var handler = ctx.handler;
3292    var promise = ctx.promise;
3293    var receiver = ctx.receiver;
3294    var value = ctx.value;
3295    if (typeof handler === "function") {
3296        if (!(promise instanceof Promise)) {
3297            handler.call(receiver, value, promise);
3298        } else {
3299            this._settlePromiseFromHandler(handler, receiver, value, promise);
3300        }
3301    } else if (promise instanceof Promise) {
3302        promise._reject(value);
3303    }
3304};
3305
3306Promise.prototype._settlePromiseCtx = function(ctx) {
3307    this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
3308};
3309
3310Promise.prototype._settlePromise0 = function(handler, value, bitField) {
3311    var promise = this._promise0;
3312    var receiver = this._receiverAt(0);
3313    this._promise0 = undefined;
3314    this._receiver0 = undefined;
3315    this._settlePromise(promise, handler, receiver, value);
3316};
3317
3318Promise.prototype._clearCallbackDataAtIndex = function(index) {
3319    var base = index * 4 - 4;
3320    this[base + 2] =
3321    this[base + 3] =
3322    this[base + 0] =
3323    this[base + 1] = undefined;
3324};
3325
3326Promise.prototype._fulfill = function (value) {
3327    var bitField = this._bitField;
3328    if (((bitField & 117506048) >>> 16)) return;
3329    if (value === this) {
3330        var err = makeSelfResolutionError();
3331        this._attachExtraTrace(err);
3332        return this._reject(err);
3333    }
3334    this._setFulfilled();
3335    this._rejectionHandler0 = value;
3336
3337    if ((bitField & 65535) > 0) {
3338        if (((bitField & 134217728) !== 0)) {
3339            this._settlePromises();
3340        } else {
3341            async.settlePromises(this);
3342        }
3343        this._dereferenceTrace();
3344    }
3345};
3346
3347Promise.prototype._reject = function (reason) {
3348    var bitField = this._bitField;
3349    if (((bitField & 117506048) >>> 16)) return;
3350    this._setRejected();
3351    this._fulfillmentHandler0 = reason;
3352
3353    if (this._isFinal()) {
3354        return async.fatalError(reason, util.isNode);
3355    }
3356
3357    if ((bitField & 65535) > 0) {
3358        async.settlePromises(this);
3359    } else {
3360        this._ensurePossibleRejectionHandled();
3361    }
3362};
3363
3364Promise.prototype._fulfillPromises = function (len, value) {
3365    for (var i = 1; i < len; i++) {
3366        var handler = this._ful