1/* @preserve 2 * The MIT License (MIT) 3 * 4 * Copyright (c) 2013-2018 Petka Antonov 5 * 6 * Permission is hereby granted, free of charge, to any person obtaining a copy 7 * of this software and associated documentation files (the "Software"), to deal 8 * in the Software without restriction, including without limitation the rights 9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 * copies of the Software, and to permit persons to whom the Software is 11 * furnished to do so, subject to the following conditions: 12 * 13 * The above copyright notice and this permission notice shall be included in 14 * all copies or substantial portions of the Software. 15 * 16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 * THE SOFTWARE. 23 * 24 */ 25/** 26 * bluebird build version 3.5.5 27 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each 28*/ 29!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ 30"use strict"; 31module.exports = function(Promise) { 32var SomePromiseArray = Promise._SomePromiseArray; 33function any(promises) { 34 var ret = new SomePromiseArray(promises); 35 var promise = ret.promise(); 36 ret.setHowMany(1); 37 ret.setUnwrap(); 38 ret.init(); 39 return promise; 40} 41 42Promise.any = function (promises) { 43 return any(promises); 44}; 45 46Promise.prototype.any = function () { 47 return any(this); 48}; 49 50}; 51 52},{}],2:[function(_dereq_,module,exports){ 53"use strict"; 54var firstLineError; 55try {throw new Error(); } catch (e) {firstLineError = e;} 56var schedule = _dereq_("./schedule"); 57var Queue = _dereq_("./queue"); 58var util = _dereq_("./util"); 59 60function Async() { 61 this._customScheduler = false; 62 this._isTickUsed = false; 63 this._lateQueue = new Queue(16); 64 this._normalQueue = new Queue(16); 65 this._haveDrainedQueues = false; 66 this._trampolineEnabled = true; 67 var self = this; 68 this.drainQueues = function () { 69 self._drainQueues(); 70 }; 71 this._schedule = schedule; 72} 73 74Async.prototype.setScheduler = function(fn) { 75 var prev = this._schedule; 76 this._schedule = fn; 77 this._customScheduler = true; 78 return prev; 79}; 80 81Async.prototype.hasCustomScheduler = function() { 82 return this._customScheduler; 83}; 84 85Async.prototype.enableTrampoline = function() { 86 this._trampolineEnabled = true; 87}; 88 89Async.prototype.disableTrampolineIfNecessary = function() { 90 if (util.hasDevTools) { 91 this._trampolineEnabled = false; 92 } 93}; 94 95Async.prototype.haveItemsQueued = function () { 96 return this._isTickUsed || this._haveDrainedQueues; 97}; 98 99 100Async.prototype.fatalError = function(e, isNode) { 101 if (isNode) { 102 process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + 103 "\n"); 104 process.exit(2); 105 } else { 106 this.throwLater(e); 107 } 108}; 109 110Async.prototype.throwLater = function(fn, arg) { 111 if (arguments.length === 1) { 112 arg = fn; 113 fn = function () { throw arg; }; 114 } 115 if (typeof setTimeout !== "undefined") { 116 setTimeout(function() { 117 fn(arg); 118 }, 0); 119 } else try { 120 this._schedule(function() { 121 fn(arg); 122 }); 123 } catch (e) { 124 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 125 } 126}; 127 128function AsyncInvokeLater(fn, receiver, arg) { 129 this._lateQueue.push(fn, receiver, arg); 130 this._queueTick(); 131} 132 133function AsyncInvoke(fn, receiver, arg) { 134 this._normalQueue.push(fn, receiver, arg); 135 this._queueTick(); 136} 137 138function AsyncSettlePromises(promise) { 139 this._normalQueue._pushOne(promise); 140 this._queueTick(); 141} 142 143if (!util.hasDevTools) { 144 Async.prototype.invokeLater = AsyncInvokeLater; 145 Async.prototype.invoke = AsyncInvoke; 146 Async.prototype.settlePromises = AsyncSettlePromises; 147} else { 148 Async.prototype.invokeLater = function (fn, receiver, arg) { 149 if (this._trampolineEnabled) { 150 AsyncInvokeLater.call(this, fn, receiver, arg); 151 } else { 152 this._schedule(function() { 153 setTimeout(function() { 154 fn.call(receiver, arg); 155 }, 100); 156 }); 157 } 158 }; 159 160 Async.prototype.invoke = function (fn, receiver, arg) { 161 if (this._trampolineEnabled) { 162 AsyncInvoke.call(this, fn, receiver, arg); 163 } else { 164 this._schedule(function() { 165 fn.call(receiver, arg); 166 }); 167 } 168 }; 169 170 Async.prototype.settlePromises = function(promise) { 171 if (this._trampolineEnabled) { 172 AsyncSettlePromises.call(this, promise); 173 } else { 174 this._schedule(function() { 175 promise._settlePromises(); 176 }); 177 } 178 }; 179} 180 181function _drainQueue(queue) { 182 while (queue.length() > 0) { 183 _drainQueueStep(queue); 184 } 185} 186 187function _drainQueueStep(queue) { 188 var fn = queue.shift(); 189 if (typeof fn !== "function") { 190 fn._settlePromises(); 191 } else { 192 var receiver = queue.shift(); 193 var arg = queue.shift(); 194 fn.call(receiver, arg); 195 } 196} 197 198Async.prototype._drainQueues = function () { 199 _drainQueue(this._normalQueue); 200 this._reset(); 201 this._haveDrainedQueues = true; 202 _drainQueue(this._lateQueue); 203}; 204 205Async.prototype._queueTick = function () { 206 if (!this._isTickUsed) { 207 this._isTickUsed = true; 208 this._schedule(this.drainQueues); 209 } 210}; 211 212Async.prototype._reset = function () { 213 this._isTickUsed = false; 214}; 215 216module.exports = Async; 217module.exports.firstLineError = firstLineError; 218 219},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ 220"use strict"; 221module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { 222var calledBind = false; 223var rejectThis = function(_, e) { 224 this._reject(e); 225}; 226 227var targetRejected = function(e, context) { 228 context.promiseRejectionQueued = true; 229 context.bindingPromise._then(rejectThis, rejectThis, null, this, e); 230}; 231 232var bindingResolved = function(thisArg, context) { 233 if (((this._bitField & 50397184) === 0)) { 234 this._resolveCallback(context.target); 235 } 236}; 237 238var bindingRejected = function(e, context) { 239 if (!context.promiseRejectionQueued) this._reject(e); 240}; 241 242Promise.prototype.bind = function (thisArg) { 243 if (!calledBind) { 244 calledBind = true; 245 Promise.prototype._propagateFrom = debug.propagateFromFunction(); 246 Promise.prototype._boundValue = debug.boundValueFunction(); 247 } 248 var maybePromise = tryConvertToPromise(thisArg); 249 var ret = new Promise(INTERNAL); 250 ret._propagateFrom(this, 1); 251 var target = this._target(); 252 ret._setBoundTo(maybePromise); 253 if (maybePromise instanceof Promise) { 254 var context = { 255 promiseRejectionQueued: false, 256 promise: ret, 257 target: target, 258 bindingPromise: maybePromise 259 }; 260 target._then(INTERNAL, targetRejected, undefined, ret, context); 261 maybePromise._then( 262 bindingResolved, bindingRejected, undefined, ret, context); 263 ret._setOnCancel(maybePromise); 264 } else { 265 ret._resolveCallback(target); 266 } 267 return ret; 268}; 269 270Promise.prototype._setBoundTo = function (obj) { 271 if (obj !== undefined) { 272 this._bitField = this._bitField | 2097152; 273 this._boundTo = obj; 274 } else { 275 this._bitField = this._bitField & (~2097152); 276 } 277}; 278 279Promise.prototype._isBound = function () { 280 return (this._bitField & 2097152) === 2097152; 281}; 282 283Promise.bind = function (thisArg, value) { 284 return Promise.resolve(value).bind(thisArg); 285}; 286}; 287 288},{}],4:[function(_dereq_,module,exports){ 289"use strict"; 290var old; 291if (typeof Promise !== "undefined") old = Promise; 292function noConflict() { 293 try { if (Promise === bluebird) Promise = old; } 294 catch (e) {} 295 return bluebird; 296} 297var bluebird = _dereq_("./promise")(); 298bluebird.noConflict = noConflict; 299module.exports = bluebird; 300 301},{"./promise":22}],5:[function(_dereq_,module,exports){ 302"use strict"; 303var cr = Object.create; 304if (cr) { 305 var callerCache = cr(null); 306 var getterCache = cr(null); 307 callerCache[" size"] = getterCache[" size"] = 0; 308} 309 310module.exports = function(Promise) { 311var util = _dereq_("./util"); 312var canEvaluate = util.canEvaluate; 313var isIdentifier = util.isIdentifier; 314 315var getMethodCaller; 316var getGetter; 317if (!true) { 318var makeMethodCaller = function (methodName) { 319 return new Function("ensureMethod", " \n\ 320 return function(obj) { \n\ 321 'use strict' \n\ 322 var len = this.length; \n\ 323 ensureMethod(obj, 'methodName'); \n\ 324 switch(len) { \n\ 325 case 1: return obj.methodName(this[0]); \n\ 326 case 2: return obj.methodName(this[0], this[1]); \n\ 327 case 3: return obj.methodName(this[0], this[1], this[2]); \n\ 328 case 0: return obj.methodName(); \n\ 329 default: \n\ 330 return obj.methodName.apply(obj, this); \n\ 331 } \n\ 332 }; \n\ 333 ".replace(/methodName/g, methodName))(ensureMethod); 334}; 335 336var makeGetter = function (propertyName) { 337 return new Function("obj", " \n\ 338 'use strict'; \n\ 339 return obj.propertyName; \n\ 340 ".replace("propertyName", propertyName)); 341}; 342 343var getCompiled = function(name, compiler, cache) { 344 var ret = cache[name]; 345 if (typeof ret !== "function") { 346 if (!isIdentifier(name)) { 347 return null; 348 } 349 ret = compiler(name); 350 cache[name] = ret; 351 cache[" size"]++; 352 if (cache[" size"] > 512) { 353 var keys = Object.keys(cache); 354 for (var i = 0; i < 256; ++i) delete cache[keys[i]]; 355 cache[" size"] = keys.length - 256; 356 } 357 } 358 return ret; 359}; 360 361getMethodCaller = function(name) { 362 return getCompiled(name, makeMethodCaller, callerCache); 363}; 364 365getGetter = function(name) { 366 return getCompiled(name, makeGetter, getterCache); 367}; 368} 369 370function ensureMethod(obj, methodName) { 371 var fn; 372 if (obj != null) fn = obj[methodName]; 373 if (typeof fn !== "function") { 374 var message = "Object " + util.classString(obj) + " has no method '" + 375 util.toString(methodName) + "'"; 376 throw new Promise.TypeError(message); 377 } 378 return fn; 379} 380 381function caller(obj) { 382 var methodName = this.pop(); 383 var fn = ensureMethod(obj, methodName); 384 return fn.apply(obj, this); 385} 386Promise.prototype.call = function (methodName) { 387 var args = [].slice.call(arguments, 1);; 388 if (!true) { 389 if (canEvaluate) { 390 var maybeCaller = getMethodCaller(methodName); 391 if (maybeCaller !== null) { 392 return this._then( 393 maybeCaller, undefined, undefined, args, undefined); 394 } 395 } 396 } 397 args.push(methodName); 398 return this._then(caller, undefined, undefined, args, undefined); 399}; 400 401function namedGetter(obj) { 402 return obj[this]; 403} 404function indexedGetter(obj) { 405 var index = +this; 406 if (index < 0) index = Math.max(0, index + obj.length); 407 return obj[index]; 408} 409Promise.prototype.get = function (propertyName) { 410 var isIndex = (typeof propertyName === "number"); 411 var getter; 412 if (!isIndex) { 413 if (canEvaluate) { 414 var maybeGetter = getGetter(propertyName); 415 getter = maybeGetter !== null ? maybeGetter : namedGetter; 416 } else { 417 getter = namedGetter; 418 } 419 } else { 420 getter = indexedGetter; 421 } 422 return this._then(getter, undefined, undefined, propertyName, undefined); 423}; 424}; 425 426},{"./util":36}],6:[function(_dereq_,module,exports){ 427"use strict"; 428module.exports = function(Promise, PromiseArray, apiRejection, debug) { 429var util = _dereq_("./util"); 430var tryCatch = util.tryCatch; 431var errorObj = util.errorObj; 432var async = Promise._async; 433 434Promise.prototype["break"] = Promise.prototype.cancel = function() { 435 if (!debug.cancellation()) return this._warn("cancellation is disabled"); 436 437 var promise = this; 438 var child = promise; 439 while (promise._isCancellable()) { 440 if (!promise._cancelBy(child)) { 441 if (child._isFollowing()) { 442 child._followee().cancel(); 443 } else { 444 child._cancelBranched(); 445 } 446 break; 447 } 448 449 var parent = promise._cancellationParent; 450 if (parent == null || !parent._isCancellable()) { 451 if (promise._isFollowing()) { 452 promise._followee().cancel(); 453 } else { 454 promise._cancelBranched(); 455 } 456 break; 457 } else { 458 if (promise._isFollowing()) promise._followee().cancel(); 459 promise._setWillBeCancelled(); 460 child = promise; 461 promise = parent; 462 } 463 } 464}; 465 466Promise.prototype._branchHasCancelled = function() { 467 this._branchesRemainingToCancel--; 468}; 469 470Promise.prototype._enoughBranchesHaveCancelled = function() { 471 return this._branchesRemainingToCancel === undefined || 472 this._branchesRemainingToCancel <= 0; 473}; 474 475Promise.prototype._cancelBy = function(canceller) { 476 if (canceller === this) { 477 this._branchesRemainingToCancel = 0; 478 this._invokeOnCancel(); 479 return true; 480 } else { 481 this._branchHasCancelled(); 482 if (this._enoughBranchesHaveCancelled()) { 483 this._invokeOnCancel(); 484 return true; 485 } 486 } 487 return false; 488}; 489 490Promise.prototype._cancelBranched = function() { 491 if (this._enoughBranchesHaveCancelled()) { 492 this._cancel(); 493 } 494}; 495 496Promise.prototype._cancel = function() { 497 if (!this._isCancellable()) return; 498 this._setCancelled(); 499 async.invoke(this._cancelPromises, this, undefined); 500}; 501 502Promise.prototype._cancelPromises = function() { 503 if (this._length() > 0) this._settlePromises(); 504}; 505 506Promise.prototype._unsetOnCancel = function() { 507 this._onCancelField = undefined; 508}; 509 510Promise.prototype._isCancellable = function() { 511 return this.isPending() && !this._isCancelled(); 512}; 513 514Promise.prototype.isCancellable = function() { 515 return this.isPending() && !this.isCancelled(); 516}; 517 518Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { 519 if (util.isArray(onCancelCallback)) { 520 for (var i = 0; i < onCancelCallback.length; ++i) { 521 this._doInvokeOnCancel(onCancelCallback[i], internalOnly); 522 } 523 } else if (onCancelCallback !== undefined) { 524 if (typeof onCancelCallback === "function") { 525 if (!internalOnly) { 526 var e = tryCatch(onCancelCallback).call(this._boundValue()); 527 if (e === errorObj) { 528 this._attachExtraTrace(e.e); 529 async.throwLater(e.e); 530 } 531 } 532 } else { 533 onCancelCallback._resultCancelled(this); 534 } 535 } 536}; 537 538Promise.prototype._invokeOnCancel = function() { 539 var onCancelCallback = this._onCancel(); 540 this._unsetOnCancel(); 541 async.invoke(this._doInvokeOnCancel, this, onCancelCallback); 542}; 543 544Promise.prototype._invokeInternalOnCancel = function() { 545 if (this._isCancellable()) { 546 this._doInvokeOnCancel(this._onCancel(), true); 547 this._unsetOnCancel(); 548 } 549}; 550 551Promise.prototype._resultCancelled = function() { 552 this.cancel(); 553}; 554 555}; 556 557},{"./util":36}],7:[function(_dereq_,module,exports){ 558"use strict"; 559module.exports = function(NEXT_FILTER) { 560var util = _dereq_("./util"); 561var getKeys = _dereq_("./es5").keys; 562var tryCatch = util.tryCatch; 563var errorObj = util.errorObj; 564 565function catchFilter(instances, cb, promise) { 566 return function(e) { 567 var boundTo = promise._boundValue(); 568 predicateLoop: for (var i = 0; i < instances.length; ++i) { 569 var item = instances[i]; 570 571 if (item === Error || 572 (item != null && item.prototype instanceof Error)) { 573 if (e instanceof item) { 574 return tryCatch(cb).call(boundTo, e); 575 } 576 } else if (typeof item === "function") { 577 var matchesPredicate = tryCatch(item).call(boundTo, e); 578 if (matchesPredicate === errorObj) { 579 return matchesPredicate; 580 } else if (matchesPredicate) { 581 return tryCatch(cb).call(boundTo, e); 582 } 583 } else if (util.isObject(e)) { 584 var keys = getKeys(item); 585 for (var j = 0; j < keys.length; ++j) { 586 var key = keys[j]; 587 if (item[key] != e[key]) { 588 continue predicateLoop; 589 } 590 } 591 return tryCatch(cb).call(boundTo, e); 592 } 593 } 594 return NEXT_FILTER; 595 }; 596} 597 598return catchFilter; 599}; 600 601},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ 602"use strict"; 603module.exports = function(Promise) { 604var longStackTraces = false; 605var contextStack = []; 606 607Promise.prototype._promiseCreated = function() {}; 608Promise.prototype._pushContext = function() {}; 609Promise.prototype._popContext = function() {return null;}; 610Promise._peekContext = Promise.prototype._peekContext = function() {}; 611 612function Context() { 613 this._trace = new Context.CapturedTrace(peekContext()); 614} 615Context.prototype._pushContext = function () { 616 if (this._trace !== undefined) { 617 this._trace._promiseCreated = null; 618 contextStack.push(this._trace); 619 } 620}; 621 622Context.prototype._popContext = function () { 623 if (this._trace !== undefined) { 624 var trace = contextStack.pop(); 625 var ret = trace._promiseCreated; 626 trace._promiseCreated = null; 627 return ret; 628 } 629 return null; 630}; 631 632function createContext() { 633 if (longStackTraces) return new Context(); 634} 635 636function peekContext() { 637 var lastIndex = contextStack.length - 1; 638 if (lastIndex >= 0) { 639 return contextStack[lastIndex]; 640 } 641 return undefined; 642} 643Context.CapturedTrace = null; 644Context.create = createContext; 645Context.deactivateLongStackTraces = function() {}; 646Context.activateLongStackTraces = function() { 647 var Promise_pushContext = Promise.prototype._pushContext; 648 var Promise_popContext = Promise.prototype._popContext; 649 var Promise_PeekContext = Promise._peekContext; 650 var Promise_peekContext = Promise.prototype._peekContext; 651 var Promise_promiseCreated = Promise.prototype._promiseCreated; 652 Context.deactivateLongStackTraces = function() { 653 Promise.prototype._pushContext = Promise_pushContext; 654 Promise.prototype._popContext = Promise_popContext; 655 Promise._peekContext = Promise_PeekContext; 656 Promise.prototype._peekContext = Promise_peekContext; 657 Promise.prototype._promiseCreated = Promise_promiseCreated; 658 longStackTraces = false; 659 }; 660 longStackTraces = true; 661 Promise.prototype._pushContext = Context.prototype._pushContext; 662 Promise.prototype._popContext = Context.prototype._popContext; 663 Promise._peekContext = Promise.prototype._peekContext = peekContext; 664 Promise.prototype._promiseCreated = function() { 665 var ctx = this._peekContext(); 666 if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; 667 }; 668}; 669return Context; 670}; 671 672},{}],9:[function(_dereq_,module,exports){ 673"use strict"; 674module.exports = function(Promise, Context) { 675var getDomain = Promise._getDomain; 676var async = Promise._async; 677var Warning = _dereq_("./errors").Warning; 678var util = _dereq_("./util"); 679var es5 = _dereq_("./es5"); 680var canAttachTrace = util.canAttachTrace; 681var unhandledRejectionHandled; 682var possiblyUnhandledRejection; 683var bluebirdFramePattern = 684 /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; 685var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; 686var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; 687var stackFramePattern = null; 688var formatStack = null; 689var indentStackFrames = false; 690var printWarning; 691var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && 692 (true || 693 util.env("BLUEBIRD_DEBUG") || 694 util.env("NODE_ENV") === "development")); 695 696var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && 697 (debugging || util.env("BLUEBIRD_WARNINGS"))); 698 699var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && 700 (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); 701 702var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && 703 (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); 704 705Promise.prototype.suppressUnhandledRejections = function() { 706 var target = this._target(); 707 target._bitField = ((target._bitField & (~1048576)) | 708 524288); 709}; 710 711Promise.prototype._ensurePossibleRejectionHandled = function () { 712 if ((this._bitField & 524288) !== 0) return; 713 this._setRejectionIsUnhandled(); 714 var self = this; 715 setTimeout(function() { 716 self._notifyUnhandledRejection(); 717 }, 1); 718}; 719 720Promise.prototype._notifyUnhandledRejectionIsHandled = function () { 721 fireRejectionEvent("rejectionHandled", 722 unhandledRejectionHandled, undefined, this); 723}; 724 725Promise.prototype._setReturnedNonUndefined = function() { 726 this._bitField = this._bitField | 268435456; 727}; 728 729Promise.prototype._returnedNonUndefined = function() { 730 return (this._bitField & 268435456) !== 0; 731}; 732 733Promise.prototype._notifyUnhandledRejection = function () { 734 if (this._isRejectionUnhandled()) { 735 var reason = this._settledValue(); 736 this._setUnhandledRejectionIsNotified(); 737 fireRejectionEvent("unhandledRejection", 738 possiblyUnhandledRejection, reason, this); 739 } 740}; 741 742Promise.prototype._setUnhandledRejectionIsNotified = function () { 743 this._bitField = this._bitField | 262144; 744}; 745 746Promise.prototype._unsetUnhandledRejectionIsNotified = function () { 747 this._bitField = this._bitField & (~262144); 748}; 749 750Promise.prototype._isUnhandledRejectionNotified = function () { 751 return (this._bitField & 262144) > 0; 752}; 753 754Promise.prototype._setRejectionIsUnhandled = function () { 755 this._bitField = this._bitField | 1048576; 756}; 757 758Promise.prototype._unsetRejectionIsUnhandled = function () { 759 this._bitField = this._bitField & (~1048576); 760 if (this._isUnhandledRejectionNotified()) { 761 this._unsetUnhandledRejectionIsNotified(); 762 this._notifyUnhandledRejectionIsHandled(); 763 } 764}; 765 766Promise.prototype._isRejectionUnhandled = function () { 767 return (this._bitField & 1048576) > 0; 768}; 769 770Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { 771 return warn(message, shouldUseOwnTrace, promise || this); 772}; 773 774Promise.onPossiblyUnhandledRejection = function (fn) { 775 var domain = getDomain(); 776 possiblyUnhandledRejection = 777 typeof fn === "function" ? (domain === null ? 778 fn : util.domainBind(domain, fn)) 779 : undefined; 780}; 781 782Promise.onUnhandledRejectionHandled = function (fn) { 783 var domain = getDomain(); 784 unhandledRejectionHandled = 785 typeof fn === "function" ? (domain === null ? 786 fn : util.domainBind(domain, fn)) 787 : undefined; 788}; 789 790var disableLongStackTraces = function() {}; 791Promise.longStackTraces = function () { 792 if (async.haveItemsQueued() && !config.longStackTraces) { 793 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 794 } 795 if (!config.longStackTraces && longStackTracesIsSupported()) { 796 var Promise_captureStackTrace = Promise.prototype._captureStackTrace; 797 var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; 798 var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace; 799 config.longStackTraces = true; 800 disableLongStackTraces = function() { 801 if (async.haveItemsQueued() && !config.longStackTraces) { 802 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 803 } 804 Promise.prototype._captureStackTrace = Promise_captureStackTrace; 805 Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; 806 Promise.prototype._dereferenceTrace = Promise_dereferenceTrace; 807 Context.deactivateLongStackTraces(); 808 async.enableTrampoline(); 809 config.longStackTraces = false; 810 }; 811 Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; 812 Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; 813 Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace; 814 Context.activateLongStackTraces(); 815 async.disableTrampolineIfNecessary(); 816 } 817}; 818 819Promise.hasLongStackTraces = function () { 820 return config.longStackTraces && longStackTracesIsSupported(); 821}; 822 823var fireDomEvent = (function() { 824 try { 825 if (typeof CustomEvent === "function") { 826 var event = new CustomEvent("CustomEvent"); 827 util.global.dispatchEvent(event); 828 return function(name, event) { 829 var eventData = { 830 detail: event, 831 cancelable: true 832 }; 833 es5.defineProperty( 834 eventData, "promise", {value: event.promise}); 835 es5.defineProperty(eventData, "reason", {value: event.reason}); 836 var domEvent = new CustomEvent(name.toLowerCase(), eventData); 837 return !util.global.dispatchEvent(domEvent); 838 }; 839 } else if (typeof Event === "function") { 840 var event = new Event("CustomEvent"); 841 util.global.dispatchEvent(event); 842 return function(name, event) { 843 var domEvent = new Event(name.toLowerCase(), { 844 cancelable: true 845 }); 846 domEvent.detail = event; 847 es5.defineProperty(domEvent, "promise", {value: event.promise}); 848 es5.defineProperty(domEvent, "reason", {value: event.reason}); 849 return !util.global.dispatchEvent(domEvent); 850 }; 851 } else { 852 var event = document.createEvent("CustomEvent"); 853 event.initCustomEvent("testingtheevent", false, true, {}); 854 util.global.dispatchEvent(event); 855 return function(name, event) { 856 var domEvent = document.createEvent("CustomEvent"); 857 domEvent.initCustomEvent(name.toLowerCase(), false, true, 858 event); 859 return !util.global.dispatchEvent(domEvent); 860 }; 861 } 862 } catch (e) {} 863 return function() { 864 return false; 865 }; 866})(); 867 868var fireGlobalEvent = (function() { 869 if (util.isNode) { 870 return function() { 871 return process.emit.apply(process, arguments); 872 }; 873 } else { 874 if (!util.global) { 875 return function() { 876 return false; 877 }; 878 } 879 return function(name) { 880 var methodName = "on" + name.toLowerCase(); 881 var method = util.global[methodName]; 882 if (!method) return false; 883 method.apply(util.global, [].slice.call(arguments, 1)); 884 return true; 885 }; 886 } 887})(); 888 889function generatePromiseLifecycleEventObject(name, promise) { 890 return {promise: promise}; 891} 892 893var eventToObjectGenerator = { 894 promiseCreated: generatePromiseLifecycleEventObject, 895 promiseFulfilled: generatePromiseLifecycleEventObject, 896 promiseRejected: generatePromiseLifecycleEventObject, 897 promiseResolved: generatePromiseLifecycleEventObject, 898 promiseCancelled: generatePromiseLifecycleEventObject, 899 promiseChained: function(name, promise, child) { 900 return {promise: promise, child: child}; 901 }, 902 warning: function(name, warning) { 903 return {warning: warning}; 904 }, 905 unhandledRejection: function (name, reason, promise) { 906 return {reason: reason, promise: promise}; 907 }, 908 rejectionHandled: generatePromiseLifecycleEventObject 909}; 910 911var activeFireEvent = function (name) { 912 var globalEventFired = false; 913 try { 914 globalEventFired = fireGlobalEvent.apply(null, arguments); 915 } catch (e) { 916 async.throwLater(e); 917 globalEventFired = true; 918 } 919 920 var domEventFired = false; 921 try { 922 domEventFired = fireDomEvent(name, 923 eventToObjectGenerator[name].apply(null, arguments)); 924 } catch (e) { 925 async.throwLater(e); 926 domEventFired = true; 927 } 928 929 return domEventFired || globalEventFired; 930}; 931 932Promise.config = function(opts) { 933 opts = Object(opts); 934 if ("longStackTraces" in opts) { 935 if (opts.longStackTraces) { 936 Promise.longStackTraces(); 937 } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { 938 disableLongStackTraces(); 939 } 940 } 941 if ("warnings" in opts) { 942 var warningsOption = opts.warnings; 943 config.warnings = !!warningsOption; 944 wForgottenReturn = config.warnings; 945 946 if (util.isObject(warningsOption)) { 947 if ("wForgottenReturn" in warningsOption) { 948 wForgottenReturn = !!warningsOption.wForgottenReturn; 949 } 950 } 951 } 952 if ("cancellation" in opts && opts.cancellation && !config.cancellation) { 953 if (async.haveItemsQueued()) { 954 throw new Error( 955 "cannot enable cancellation after promises are in use"); 956 } 957 Promise.prototype._clearCancellationData = 958 cancellationClearCancellationData; 959 Promise.prototype._propagateFrom = cancellationPropagateFrom; 960 Promise.prototype._onCancel = cancellationOnCancel; 961 Promise.prototype._setOnCancel = cancellationSetOnCancel; 962 Promise.prototype._attachCancellationCallback = 963 cancellationAttachCancellationCallback; 964 Promise.prototype._execute = cancellationExecute; 965 propagateFromFunction = cancellationPropagateFrom; 966 config.cancellation = true; 967 } 968 if ("monitoring" in opts) { 969 if (opts.monitoring && !config.monitoring) { 970 config.monitoring = true; 971 Promise.prototype._fireEvent = activeFireEvent; 972 } else if (!opts.monitoring && config.monitoring) { 973 config.monitoring = false; 974 Promise.prototype._fireEvent = defaultFireEvent; 975 } 976 } 977 return Promise; 978}; 979 980function defaultFireEvent() { return false; } 981 982Promise.prototype._fireEvent = defaultFireEvent; 983Promise.prototype._execute = function(executor, resolve, reject) { 984 try { 985 executor(resolve, reject); 986 } catch (e) { 987 return e; 988 } 989}; 990Promise.prototype._onCancel = function () {}; 991Promise.prototype._setOnCancel = function (handler) { ; }; 992Promise.prototype._attachCancellationCallback = function(onCancel) { 993 ; 994}; 995Promise.prototype._captureStackTrace = function () {}; 996Promise.prototype._attachExtraTrace = function () {}; 997Promise.prototype._dereferenceTrace = function () {}; 998Promise.prototype._clearCancellationData = function() {}; 999Promise.prototype._propagateFrom = function (parent, flags) { 1000 ; 1001 ; 1002}; 1003 1004function cancellationExecute(executor, resolve, reject) { 1005 var promise = this; 1006 try { 1007 executor(resolve, reject, function(onCancel) { 1008 if (typeof onCancel !== "function") { 1009 throw new TypeError("onCancel must be a function, got: " + 1010 util.toString(onCancel)); 1011 } 1012 promise._attachCancellationCallback(onCancel); 1013 }); 1014 } catch (e) { 1015 return e; 1016 } 1017} 1018 1019function cancellationAttachCancellationCallback(onCancel) { 1020 if (!this._isCancellable()) return this; 1021 1022 var previousOnCancel = this._onCancel(); 1023 if (previousOnCancel !== undefined) { 1024 if (util.isArray(previousOnCancel)) { 1025 previousOnCancel.push(onCancel); 1026 } else { 1027 this._setOnCancel([previousOnCancel, onCancel]); 1028 } 1029 } else { 1030 this._setOnCancel(onCancel); 1031 } 1032} 1033 1034function cancellationOnCancel() { 1035 return this._onCancelField; 1036} 1037 1038function cancellationSetOnCancel(onCancel) { 1039 this._onCancelField = onCancel; 1040} 1041 1042function cancellationClearCancellationData() { 1043 this._cancellationParent = undefined; 1044 this._onCancelField = undefined; 1045} 1046 1047function cancellationPropagateFrom(parent, flags) { 1048 if ((flags & 1) !== 0) { 1049 this._cancellationParent = parent; 1050 var branchesRemainingToCancel = parent._branchesRemainingToCancel; 1051 if (branchesRemainingToCancel === undefined) { 1052 branchesRemainingToCancel = 0; 1053 } 1054 parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; 1055 } 1056 if ((flags & 2) !== 0 && parent._isBound()) { 1057 this._setBoundTo(parent._boundTo); 1058 } 1059} 1060 1061function bindingPropagateFrom(parent, flags) { 1062 if ((flags & 2) !== 0 && parent._isBound()) { 1063 this._setBoundTo(parent._boundTo); 1064 } 1065} 1066var propagateFromFunction = bindingPropagateFrom; 1067 1068function boundValueFunction() { 1069 var ret = this._boundTo; 1070 if (ret !== undefined) { 1071 if (ret instanceof Promise) { 1072 if (ret.isFulfilled()) { 1073 return ret.value(); 1074 } else { 1075 return undefined; 1076 } 1077 } 1078 } 1079 return ret; 1080} 1081 1082function longStackTracesCaptureStackTrace() { 1083 this._trace = new CapturedTrace(this._peekContext()); 1084} 1085 1086function longStackTracesAttachExtraTrace(error, ignoreSelf) { 1087 if (canAttachTrace(error)) { 1088 var trace = this._trace; 1089 if (trace !== undefined) { 1090 if (ignoreSelf) trace = trace._parent; 1091 } 1092 if (trace !== undefined) { 1093 trace.attachExtraTrace(error); 1094 } else if (!error.__stackCleaned__) { 1095 var parsed = parseStackAndMessage(error); 1096 util.notEnumerableProp(error, "stack", 1097 parsed.message + "\n" + parsed.stack.join("\n")); 1098 util.notEnumerableProp(error, "__stackCleaned__", true); 1099 } 1100 } 1101} 1102 1103function longStackTracesDereferenceTrace() { 1104 this._trace = undefined; 1105} 1106 1107function checkForgottenReturns(returnValue, promiseCreated, name, promise, 1108 parent) { 1109 if (returnValue === undefined && promiseCreated !== null && 1110 wForgottenReturn) { 1111 if (parent !== undefined && parent._returnedNonUndefined()) return; 1112 if ((promise._bitField & 65535) === 0) return; 1113 1114 if (name) name = name + " "; 1115 var handlerLine = ""; 1116 var creatorLine = ""; 1117 if (promiseCreated._trace) { 1118 var traceLines = promiseCreated._trace.stack.split("\n"); 1119 var stack = cleanStack(traceLines); 1120 for (var i = stack.length - 1; i >= 0; --i) { 1121 var line = stack[i]; 1122 if (!nodeFramePattern.test(line)) { 1123 var lineMatches = line.match(parseLinePattern); 1124 if (lineMatches) { 1125 handlerLine = "at " + lineMatches[1] + 1126 ":" + lineMatches[2] + ":" + lineMatches[3] + " "; 1127 } 1128 break; 1129 } 1130 } 1131 1132 if (stack.length > 0) { 1133 var firstUserLine = stack[0]; 1134 for (var i = 0; i < traceLines.length; ++i) { 1135 1136 if (traceLines[i] === firstUserLine) { 1137 if (i > 0) { 1138 creatorLine = "\n" + traceLines[i - 1]; 1139 } 1140 break; 1141 } 1142 } 1143 1144 } 1145 } 1146 var msg = "a promise was created in a " + name + 1147 "handler " + handlerLine + "but was not returned from it, " + 1148 "see http://goo.gl/rRqMUw" + 1149 creatorLine; 1150 promise._warn(msg, true, promiseCreated); 1151 } 1152} 1153 1154function deprecated(name, replacement) { 1155 var message = name + 1156 " is deprecated and will be removed in a future version."; 1157 if (replacement) message += " Use " + replacement + " instead."; 1158 return warn(message); 1159} 1160 1161function warn(message, shouldUseOwnTrace, promise) { 1162 if (!config.warnings) return; 1163 var warning = new Warning(message); 1164 var ctx; 1165 if (shouldUseOwnTrace) { 1166 promise._attachExtraTrace(warning); 1167 } else if (config.longStackTraces && (ctx = Promise._peekContext())) { 1168 ctx.attachExtraTrace(warning); 1169 } else { 1170 var parsed = parseStackAndMessage(warning); 1171 warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); 1172 } 1173 1174 if (!activeFireEvent("warning", warning)) { 1175 formatAndLogError(warning, "", true); 1176 } 1177} 1178 1179function reconstructStack(message, stacks) { 1180 for (var i = 0; i < stacks.length - 1; ++i) { 1181 stacks[i].push("From previous event:"); 1182 stacks[i] = stacks[i].join("\n"); 1183 } 1184 if (i < stacks.length) { 1185 stacks[i] = stacks[i].join("\n"); 1186 } 1187 return message + "\n" + stacks.join("\n"); 1188} 1189 1190function removeDuplicateOrEmptyJumps(stacks) { 1191 for (var i = 0; i < stacks.length; ++i) { 1192 if (stacks[i].length === 0 || 1193 ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { 1194 stacks.splice(i, 1); 1195 i--; 1196 } 1197 } 1198} 1199 1200function removeCommonRoots(stacks) { 1201 var current = stacks[0]; 1202 for (var i = 1; i < stacks.length; ++i) { 1203 var prev = stacks[i]; 1204 var currentLastIndex = current.length - 1; 1205 var currentLastLine = current[currentLastIndex]; 1206 var commonRootMeetPoint = -1; 1207 1208 for (var j = prev.length - 1; j >= 0; --j) { 1209 if (prev[j] === currentLastLine) { 1210 commonRootMeetPoint = j; 1211 break; 1212 } 1213 } 1214 1215 for (var j = commonRootMeetPoint; j >= 0; --j) { 1216 var line = prev[j]; 1217 if (current[currentLastIndex] === line) { 1218 current.pop(); 1219 currentLastIndex--; 1220 } else { 1221 break; 1222 } 1223 } 1224 current = prev; 1225 } 1226} 1227 1228function cleanStack(stack) { 1229 var ret = []; 1230 for (var i = 0; i < stack.length; ++i) { 1231 var line = stack[i]; 1232 var isTraceLine = " (No stack trace)" === line || 1233 stackFramePattern.test(line); 1234 var isInternalFrame = isTraceLine && shouldIgnore(line); 1235 if (isTraceLine && !isInternalFrame) { 1236 if (indentStackFrames && line.charAt(0) !== " ") { 1237 line = " " + line; 1238 } 1239 ret.push(line); 1240 } 1241 } 1242 return ret; 1243} 1244 1245function stackFramesAsArray(error) { 1246 var stack = error.stack.replace(/\s+$/g, "").split("\n"); 1247 for (var i = 0; i < stack.length; ++i) { 1248 var line = stack[i]; 1249 if (" (No stack trace)" === line || stackFramePattern.test(line)) { 1250 break; 1251 } 1252 } 1253 if (i > 0 && error.name != "SyntaxError") { 1254 stack = stack.slice(i); 1255 } 1256 return stack; 1257} 1258 1259function parseStackAndMessage(error) { 1260 var stack = error.stack; 1261 var message = error.toString(); 1262 stack = typeof stack === "string" && stack.length > 0 1263 ? stackFramesAsArray(error) : [" (No stack trace)"]; 1264 return { 1265 message: message, 1266 stack: error.name == "SyntaxError" ? stack : cleanStack(stack) 1267 }; 1268} 1269 1270function formatAndLogError(error, title, isSoft) { 1271 if (typeof console !== "undefined") { 1272 var message; 1273 if (util.isObject(error)) { 1274 var stack = error.stack; 1275 message = title + formatStack(stack, error); 1276 } else { 1277 message = title + String(error); 1278 } 1279 if (typeof printWarning === "function") { 1280 printWarning(message, isSoft); 1281 } else if (typeof console.log === "function" || 1282 typeof console.log === "object") { 1283 console.log(message); 1284 } 1285 } 1286} 1287 1288function fireRejectionEvent(name, localHandler, reason, promise) { 1289 var localEventFired = false; 1290 try { 1291 if (typeof localHandler === "function") { 1292 localEventFired = true; 1293 if (name === "rejectionHandled") { 1294 localHandler(promise); 1295 } else { 1296 localHandler(reason, promise); 1297 } 1298 } 1299 } catch (e) { 1300 async.throwLater(e); 1301 } 1302 1303 if (name === "unhandledRejection") { 1304 if (!activeFireEvent(name, reason, promise) && !localEventFired) { 1305 formatAndLogError(reason, "Unhandled rejection "); 1306 } 1307 } else { 1308 activeFireEvent(name, promise); 1309 } 1310} 1311 1312function formatNonError(obj) { 1313 var str; 1314 if (typeof obj === "function") { 1315 str = "[function " + 1316 (obj.name || "anonymous") + 1317 "]"; 1318 } else { 1319 str = obj && typeof obj.toString === "function" 1320 ? obj.toString() : util.toString(obj); 1321 var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; 1322 if (ruselessToString.test(str)) { 1323 try { 1324 var newStr = JSON.stringify(obj); 1325 str = newStr; 1326 } 1327 catch(e) { 1328 1329 } 1330 } 1331 if (str.length === 0) { 1332 str = "(empty array)"; 1333 } 1334 } 1335 return ("(<" + snip(str) + ">, no stack trace)"); 1336} 1337 1338function snip(str) { 1339 var maxChars = 41; 1340 if (str.length < maxChars) { 1341 return str; 1342 } 1343 return str.substr(0, maxChars - 3) + "..."; 1344} 1345 1346function longStackTracesIsSupported() { 1347 return typeof captureStackTrace === "function"; 1348} 1349 1350var shouldIgnore = function() { return false; }; 1351var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; 1352function parseLineInfo(line) { 1353 var matches = line.match(parseLineInfoRegex); 1354 if (matches) { 1355 return { 1356 fileName: matches[1], 1357 line: parseInt(matches[2], 10) 1358 }; 1359 } 1360} 1361 1362function setBounds(firstLineError, lastLineError) { 1363 if (!longStackTracesIsSupported()) return; 1364 var firstStackLines = (firstLineError.stack || "").split("\n"); 1365 var lastStackLines = (lastLineError.stack || "").split("\n"); 1366 var firstIndex = -1; 1367 var lastIndex = -1; 1368 var firstFileName; 1369 var lastFileName; 1370 for (var i = 0; i < firstStackLines.length; ++i) { 1371 var result = parseLineInfo(firstStackLines[i]); 1372 if (result) { 1373 firstFileName = result.fileName; 1374 firstIndex = result.line; 1375 break; 1376 } 1377 } 1378 for (var i = 0; i < lastStackLines.length; ++i) { 1379 var result = parseLineInfo(lastStackLines[i]); 1380 if (result) { 1381 lastFileName = result.fileName; 1382 lastIndex = result.line; 1383 break; 1384 } 1385 } 1386 if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || 1387 firstFileName !== lastFileName || firstIndex >= lastIndex) { 1388 return; 1389 } 1390 1391 shouldIgnore = function(line) { 1392 if (bluebirdFramePattern.test(line)) return true; 1393 var info = parseLineInfo(line); 1394 if (info) { 1395 if (info.fileName === firstFileName && 1396 (firstIndex <= info.line && info.line <= lastIndex)) { 1397 return true; 1398 } 1399 } 1400 return false; 1401 }; 1402} 1403 1404function CapturedTrace(parent) { 1405 this._parent = parent; 1406 this._promisesCreated = 0; 1407 var length = this._length = 1 + (parent === undefined ? 0 : parent._length); 1408 captureStackTrace(this, CapturedTrace); 1409 if (length > 32) this.uncycle(); 1410} 1411util.inherits(CapturedTrace, Error); 1412Context.CapturedTrace = CapturedTrace; 1413 1414CapturedTrace.prototype.uncycle = function() { 1415 var length = this._length; 1416 if (length < 2) return; 1417 var nodes = []; 1418 var stackToIndex = {}; 1419 1420 for (var i = 0, node = this; node !== undefined; ++i) { 1421 nodes.push(node); 1422 node = node._parent; 1423 } 1424 length = this._length = i; 1425 for (var i = length - 1; i >= 0; --i) { 1426 var stack = nodes[i].stack; 1427 if (stackToIndex[stack] === undefined) { 1428 stackToIndex[stack] = i; 1429 } 1430 } 1431 for (var i = 0; i < length; ++i) { 1432 var currentStack = nodes[i].stack; 1433 var index = stackToIndex[currentStack]; 1434 if (index !== undefined && index !== i) { 1435 if (index > 0) { 1436 nodes[index - 1]._parent = undefined; 1437 nodes[index - 1]._length = 1; 1438 } 1439 nodes[i]._parent = undefined; 1440 nodes[i]._length = 1; 1441 var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; 1442 1443 if (index < length - 1) { 1444 cycleEdgeNode._parent = nodes[index + 1]; 1445 cycleEdgeNode._parent.uncycle(); 1446 cycleEdgeNode._length = 1447 cycleEdgeNode._parent._length + 1; 1448 } else { 1449 cycleEdgeNode._parent = undefined; 1450 cycleEdgeNode._length = 1; 1451 } 1452 var currentChildLength = cycleEdgeNode._length + 1; 1453 for (var j = i - 2; j >= 0; --j) { 1454 nodes[j]._length = currentChildLength; 1455 currentChildLength++; 1456 } 1457 return; 1458 } 1459 } 1460}; 1461 1462CapturedTrace.prototype.attachExtraTrace = function(error) { 1463 if (error.__stackCleaned__) return; 1464 this.uncycle(); 1465 var parsed = parseStackAndMessage(error); 1466 var message = parsed.message; 1467 var stacks = [parsed.stack]; 1468 1469 var trace = this; 1470 while (trace !== undefined) { 1471 stacks.push(cleanStack(trace.stack.split("\n"))); 1472 trace = trace._parent; 1473 } 1474 removeCommonRoots(stacks); 1475 removeDuplicateOrEmptyJumps(stacks); 1476 util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); 1477 util.notEnumerableProp(error, "__stackCleaned__", true); 1478}; 1479 1480var captureStackTrace = (function stackDetection() { 1481 var v8stackFramePattern = /^\s*at\s*/; 1482 var v8stackFormatter = function(stack, error) { 1483 if (typeof stack === "string") return stack; 1484 1485 if (error.name !== undefined && 1486 error.message !== undefined) { 1487 return error.toString(); 1488 } 1489 return formatNonError(error); 1490 }; 1491 1492 if (typeof Error.stackTraceLimit === "number" && 1493 typeof Error.captureStackTrace === "function") { 1494 Error.stackTraceLimit += 6; 1495 stackFramePattern = v8stackFramePattern; 1496 formatStack = v8stackFormatter; 1497 var captureStackTrace = Error.captureStackTrace; 1498 1499 shouldIgnore = function(line) { 1500 return bluebirdFramePattern.test(line); 1501 }; 1502 return function(receiver, ignoreUntil) { 1503 Error.stackTraceLimit += 6; 1504 captureStackTrace(receiver, ignoreUntil); 1505 Error.stackTraceLimit -= 6; 1506 }; 1507 } 1508 var err = new Error(); 1509 1510 if (typeof err.stack === "string" && 1511 err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { 1512 stackFramePattern = /@/; 1513 formatStack = v8stackFormatter; 1514 indentStackFrames = true; 1515 return function captureStackTrace(o) { 1516 o.stack = new Error().stack; 1517 }; 1518 } 1519 1520 var hasStackAfterThrow; 1521 try { throw new Error(); } 1522 catch(e) { 1523 hasStackAfterThrow = ("stack" in e); 1524 } 1525 if (!("stack" in err) && hasStackAfterThrow && 1526 typeof Error.stackTraceLimit === "number") { 1527 stackFramePattern = v8stackFramePattern; 1528 formatStack = v8stackFormatter; 1529 return function captureStackTrace(o) { 1530 Error.stackTraceLimit += 6; 1531 try { throw new Error(); } 1532 catch(e) { o.stack = e.stack; } 1533 Error.stackTraceLimit -= 6; 1534 }; 1535 } 1536 1537 formatStack = function(stack, error) { 1538 if (typeof stack === "string") return stack; 1539 1540 if ((typeof error === "object" || 1541 typeof error === "function") && 1542 error.name !== undefined && 1543 error.message !== undefined) { 1544 return error.toString(); 1545 } 1546 return formatNonError(error); 1547 }; 1548 1549 return null; 1550 1551})([]); 1552 1553if (typeof console !== "undefined" && typeof console.warn !== "undefined") { 1554 printWarning = function (message) { 1555 console.warn(message); 1556 }; 1557 if (util.isNode && process.stderr.isTTY) { 1558 printWarning = function(message, isSoft) { 1559 var color = isSoft ? "\u001b[33m" : "\u001b[31m"; 1560 console.warn(color + message + "\u001b[0m\n"); 1561 }; 1562 } else if (!util.isNode && typeof (new Error().stack) === "string") { 1563 printWarning = function(message, isSoft) { 1564 console.warn("%c" + message, 1565 isSoft ? "color: darkorange" : "color: red"); 1566 }; 1567 } 1568} 1569 1570var config = { 1571 warnings: warnings, 1572 longStackTraces: false, 1573 cancellation: false, 1574 monitoring: false 1575}; 1576 1577if (longStackTraces) Promise.longStackTraces(); 1578 1579return { 1580 longStackTraces: function() { 1581 return config.longStackTraces; 1582 }, 1583 warnings: function() { 1584 return config.warnings; 1585 }, 1586 cancellation: function() { 1587 return config.cancellation; 1588 }, 1589 monitoring: function() { 1590 return config.monitoring; 1591 }, 1592 propagateFromFunction: function() { 1593 return propagateFromFunction; 1594 }, 1595 boundValueFunction: function() { 1596 return boundValueFunction; 1597 }, 1598 checkForgottenReturns: checkForgottenReturns, 1599 setBounds: setBounds, 1600 warn: warn, 1601 deprecated: deprecated, 1602 CapturedTrace: CapturedTrace, 1603 fireDomEvent: fireDomEvent, 1604 fireGlobalEvent: fireGlobalEvent 1605}; 1606}; 1607 1608},{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){ 1609"use strict"; 1610module.exports = function(Promise) { 1611function returner() { 1612 return this.value; 1613} 1614function thrower() { 1615 throw this.reason; 1616} 1617 1618Promise.prototype["return"] = 1619Promise.prototype.thenReturn = function (value) { 1620 if (value instanceof Promise) value.suppressUnhandledRejections(); 1621 return this._then( 1622 returner, undefined, undefined, {value: value}, undefined); 1623}; 1624 1625Promise.prototype["throw"] = 1626Promise.prototype.thenThrow = function (reason) { 1627 return this._then( 1628 thrower, undefined, undefined, {reason: reason}, undefined); 1629}; 1630 1631Promise.prototype.catchThrow = function (reason) { 1632 if (arguments.length <= 1) { 1633 return this._then( 1634 undefined, thrower, undefined, {reason: reason}, undefined); 1635 } else { 1636 var _reason = arguments[1]; 1637 var handler = function() {throw _reason;}; 1638 return this.caught(reason, handler); 1639 } 1640}; 1641 1642Promise.prototype.catchReturn = function (value) { 1643 if (arguments.length <= 1) { 1644 if (value instanceof Promise) value.suppressUnhandledRejections(); 1645 return this._then( 1646 undefined, returner, undefined, {value: value}, undefined); 1647 } else { 1648 var _value = arguments[1]; 1649 if (_value instanceof Promise) _value.suppressUnhandledRejections(); 1650 var handler = function() {return _value;}; 1651 return this.caught(value, handler); 1652 } 1653}; 1654}; 1655 1656},{}],11:[function(_dereq_,module,exports){ 1657"use strict"; 1658module.exports = function(Promise, INTERNAL) { 1659var PromiseReduce = Promise.reduce; 1660var PromiseAll = Promise.all; 1661 1662function promiseAllThis() { 1663 return PromiseAll(this); 1664} 1665 1666function PromiseMapSeries(promises, fn) { 1667 return PromiseReduce(promises, fn, INTERNAL, INTERNAL); 1668} 1669 1670Promise.prototype.each = function (fn) { 1671 return PromiseReduce(this, fn, INTERNAL, 0) 1672 ._then(promiseAllThis, undefined, undefined, this, undefined); 1673}; 1674 1675Promise.prototype.mapSeries = function (fn) { 1676 return PromiseReduce(this, fn, INTERNAL, INTERNAL); 1677}; 1678 1679Promise.each = function (promises, fn) { 1680 return PromiseReduce(promises, fn, INTERNAL, 0) 1681 ._then(promiseAllThis, undefined, undefined, promises, undefined); 1682}; 1683 1684Promise.mapSeries = PromiseMapSeries; 1685}; 1686 1687 1688},{}],12:[function(_dereq_,module,exports){ 1689"use strict"; 1690var es5 = _dereq_("./es5"); 1691var Objectfreeze = es5.freeze; 1692var util = _dereq_("./util"); 1693var inherits = util.inherits; 1694var notEnumerableProp = util.notEnumerableProp; 1695 1696function subError(nameProperty, defaultMessage) { 1697 function SubError(message) { 1698 if (!(this instanceof SubError)) return new SubError(message); 1699 notEnumerableProp(this, "message", 1700 typeof message === "string" ? message : defaultMessage); 1701 notEnumerableProp(this, "name", nameProperty); 1702 if (Error.captureStackTrace) { 1703 Error.captureStackTrace(this, this.constructor); 1704 } else { 1705 Error.call(this); 1706 } 1707 } 1708 inherits(SubError, Error); 1709 return SubError; 1710} 1711 1712var _TypeError, _RangeError; 1713var Warning = subError("Warning", "warning"); 1714var CancellationError = subError("CancellationError", "cancellation error"); 1715var TimeoutError = subError("TimeoutError", "timeout error"); 1716var AggregateError = subError("AggregateError", "aggregate error"); 1717try { 1718 _TypeError = TypeError; 1719 _RangeError = RangeError; 1720} catch(e) { 1721 _TypeError = subError("TypeError", "type error"); 1722 _RangeError = subError("RangeError", "range error"); 1723} 1724 1725var methods = ("join pop push shift unshift slice filter forEach some " + 1726 "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); 1727 1728for (var i = 0; i < methods.length; ++i) { 1729 if (typeof Array.prototype[methods[i]] === "function") { 1730 AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; 1731 } 1732} 1733 1734es5.defineProperty(AggregateError.prototype, "length", { 1735 value: 0, 1736 configurable: false, 1737 writable: true, 1738 enumerable: true 1739}); 1740AggregateError.prototype["isOperational"] = true; 1741var level = 0; 1742AggregateError.prototype.toString = function() { 1743 var indent = Array(level * 4 + 1).join(" "); 1744 var ret = "\n" + indent + "AggregateError of:" + "\n"; 1745 level++; 1746 indent = Array(level * 4 + 1).join(" "); 1747 for (var i = 0; i < this.length; ++i) { 1748 var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; 1749 var lines = str.split("\n"); 1750 for (var j = 0; j < lines.length; ++j) { 1751 lines[j] = indent + lines[j]; 1752 } 1753 str = lines.join("\n"); 1754 ret += str + "\n"; 1755 } 1756 level--; 1757 return ret; 1758}; 1759 1760function OperationalError(message) { 1761 if (!(this instanceof OperationalError)) 1762 return new OperationalError(message); 1763 notEnumerableProp(this, "name", "OperationalError"); 1764 notEnumerableProp(this, "message", message); 1765 this.cause = message; 1766 this["isOperational"] = true; 1767 1768 if (message instanceof Error) { 1769 notEnumerableProp(this, "message", message.message); 1770 notEnumerableProp(this, "stack", message.stack); 1771 } else if (Error.captureStackTrace) { 1772 Error.captureStackTrace(this, this.constructor); 1773 } 1774 1775} 1776inherits(OperationalError, Error); 1777 1778var errorTypes = Error["__BluebirdErrorTypes__"]; 1779if (!errorTypes) { 1780 errorTypes = Objectfreeze({ 1781 CancellationError: CancellationError, 1782 TimeoutError: TimeoutError, 1783 OperationalError: OperationalError, 1784 RejectionError: OperationalError, 1785 AggregateError: AggregateError 1786 }); 1787 es5.defineProperty(Error, "__BluebirdErrorTypes__", { 1788 value: errorTypes, 1789 writable: false, 1790 enumerable: false, 1791 configurable: false 1792 }); 1793} 1794 1795module.exports = { 1796 Error: Error, 1797 TypeError: _TypeError, 1798 RangeError: _RangeError, 1799 CancellationError: errorTypes.CancellationError, 1800 OperationalError: errorTypes.OperationalError, 1801 TimeoutError: errorTypes.TimeoutError, 1802 AggregateError: errorTypes.AggregateError, 1803 Warning: Warning 1804}; 1805 1806},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ 1807var isES5 = (function(){ 1808 "use strict"; 1809 return this === undefined; 1810})(); 1811 1812if (isES5) { 1813 module.exports = { 1814 freeze: Object.freeze, 1815 defineProperty: Object.defineProperty, 1816 getDescriptor: Object.getOwnPropertyDescriptor, 1817 keys: Object.keys, 1818 names: Object.getOwnPropertyNames, 1819 getPrototypeOf: Object.getPrototypeOf, 1820 isArray: Array.isArray, 1821 isES5: isES5, 1822 propertyIsWritable: function(obj, prop) { 1823 var descriptor = Object.getOwnPropertyDescriptor(obj, prop); 1824 return !!(!descriptor || descriptor.writable || descriptor.set); 1825 } 1826 }; 1827} else { 1828 var has = {}.hasOwnProperty; 1829 var str = {}.toString; 1830 var proto = {}.constructor.prototype; 1831 1832 var ObjectKeys = function (o) { 1833 var ret = []; 1834 for (var key in o) { 1835 if (has.call(o, key)) { 1836 ret.push(key); 1837 } 1838 } 1839 return ret; 1840 }; 1841 1842 var ObjectGetDescriptor = function(o, key) { 1843 return {value: o[key]}; 1844 }; 1845 1846 var ObjectDefineProperty = function (o, key, desc) { 1847 o[key] = desc.value; 1848 return o; 1849 }; 1850 1851 var ObjectFreeze = function (obj) { 1852 return obj; 1853 }; 1854 1855 var ObjectGetPrototypeOf = function (obj) { 1856 try { 1857 return Object(obj).constructor.prototype; 1858 } 1859 catch (e) { 1860 return proto; 1861 } 1862 }; 1863 1864 var ArrayIsArray = function (obj) { 1865 try { 1866 return str.call(obj) === "[object Array]"; 1867 } 1868 catch(e) { 1869 return false; 1870 } 1871 }; 1872 1873 module.exports = { 1874 isArray: ArrayIsArray, 1875 keys: ObjectKeys, 1876 names: ObjectKeys, 1877 defineProperty: ObjectDefineProperty, 1878 getDescriptor: ObjectGetDescriptor, 1879 freeze: ObjectFreeze, 1880 getPrototypeOf: ObjectGetPrototypeOf, 1881 isES5: isES5, 1882 propertyIsWritable: function() { 1883 return true; 1884 } 1885 }; 1886} 1887 1888},{}],14:[function(_dereq_,module,exports){ 1889"use strict"; 1890module.exports = function(Promise, INTERNAL) { 1891var PromiseMap = Promise.map; 1892 1893Promise.prototype.filter = function (fn, options) { 1894 return PromiseMap(this, fn, options, INTERNAL); 1895}; 1896 1897Promise.filter = function (promises, fn, options) { 1898 return PromiseMap(promises, fn, options, INTERNAL); 1899}; 1900}; 1901 1902},{}],15:[function(_dereq_,module,exports){ 1903"use strict"; 1904module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { 1905var util = _dereq_("./util"); 1906var CancellationError = Promise.CancellationError; 1907var errorObj = util.errorObj; 1908var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); 1909 1910function PassThroughHandlerContext(promise, type, handler) { 1911 this.promise = promise; 1912 this.type = type; 1913 this.handler = handler; 1914 this.called = false; 1915 this.cancelPromise = null; 1916} 1917 1918PassThroughHandlerContext.prototype.isFinallyHandler = function() { 1919 return this.type === 0; 1920}; 1921 1922function FinallyHandlerCancelReaction(finallyHandler) { 1923 this.finallyHandler = finallyHandler; 1924} 1925 1926FinallyHandlerCancelReaction.prototype._resultCancelled = function() { 1927 checkCancel(this.finallyHandler); 1928}; 1929 1930function checkCancel(ctx, reason) { 1931 if (ctx.cancelPromise != null) { 1932 if (arguments.length > 1) { 1933 ctx.cancelPromise._reject(reason); 1934 } else { 1935 ctx.cancelPromise._cancel(); 1936 } 1937 ctx.cancelPromise = null; 1938 return true; 1939 } 1940 return false; 1941} 1942 1943function succeed() { 1944 return finallyHandler.call(this, this.promise._target()._settledValue()); 1945} 1946function fail(reason) { 1947 if (checkCancel(this, reason)) return; 1948 errorObj.e = reason; 1949 return errorObj; 1950} 1951function finallyHandler(reasonOrValue) { 1952 var promise = this.promise; 1953 var handler = this.handler; 1954 1955 if (!this.called) { 1956 this.called = true; 1957 var ret = this.isFinallyHandler() 1958 ? handler.call(promise._boundValue()) 1959 : handler.call(promise._boundValue(), reasonOrValue); 1960 if (ret === NEXT_FILTER) { 1961 return ret; 1962 } else if (ret !== undefined) { 1963 promise._setReturnedNonUndefined(); 1964 var maybePromise = tryConvertToPromise(ret, promise); 1965 if (maybePromise instanceof Promise) { 1966 if (this.cancelPromise != null) { 1967 if (maybePromise._isCancelled()) { 1968 var reason = 1969 new CancellationError("late cancellation observer"); 1970 promise._attachExtraTrace(reason); 1971 errorObj.e = reason; 1972 return errorObj; 1973 } else if (maybePromise.isPending()) { 1974 maybePromise._attachCancellationCallback( 1975 new FinallyHandlerCancelReaction(this)); 1976 } 1977 } 1978 return maybePromise._then( 1979 succeed, fail, undefined, this, undefined); 1980 } 1981 } 1982 } 1983 1984 if (promise.isRejected()) { 1985 checkCancel(this); 1986 errorObj.e = reasonOrValue; 1987 return errorObj; 1988 } else { 1989 checkCancel(this); 1990 return reasonOrValue; 1991 } 1992} 1993 1994Promise.prototype._passThrough = function(handler, type, success, fail) { 1995 if (typeof handler !== "function") return this.then(); 1996 return this._then(success, 1997 fail, 1998 undefined, 1999 new PassThroughHandlerContext(this, type, handler), 2000 undefined); 2001}; 2002 2003Promise.prototype.lastly = 2004Promise.prototype["finally"] = function (handler) { 2005 return this._passThrough(handler, 2006 0, 2007 finallyHandler, 2008 finallyHandler); 2009}; 2010 2011 2012Promise.prototype.tap = function (handler) { 2013 return this._passThrough(handler, 1, finallyHandler); 2014}; 2015 2016Promise.prototype.tapCatch = function (handlerOrPredicate) { 2017 var len = arguments.length; 2018 if(len === 1) { 2019 return this._passThrough(handlerOrPredicate, 2020 1, 2021 undefined, 2022 finallyHandler); 2023 } else { 2024 var catchInstances = new Array(len - 1), 2025 j = 0, i; 2026 for (i = 0; i < len - 1; ++i) { 2027 var item = arguments[i]; 2028 if (util.isObject(item)) { 2029 catchInstances[j++] = item; 2030 } else { 2031 return Promise.reject(new TypeError( 2032 "tapCatch statement predicate: " 2033 + "expecting an object but got " + util.classString(item) 2034 )); 2035 } 2036 } 2037 catchInstances.length = j; 2038 var handler = arguments[i]; 2039 return this._passThrough(catchFilter(catchInstances, handler, this), 2040 1, 2041 undefined, 2042 finallyHandler); 2043 } 2044 2045}; 2046 2047return PassThroughHandlerContext; 2048}; 2049 2050},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){ 2051"use strict"; 2052module.exports = function(Promise, 2053 apiRejection, 2054 INTERNAL, 2055 tryConvertToPromise, 2056 Proxyable, 2057 debug) { 2058var errors = _dereq_("./errors"); 2059var TypeError = errors.TypeError; 2060var util = _dereq_("./util"); 2061var errorObj = util.errorObj; 2062var tryCatch = util.tryCatch; 2063var yieldHandlers = []; 2064 2065function promiseFromYieldHandler(value, yieldHandlers, traceParent) { 2066 for (var i = 0; i < yieldHandlers.length; ++i) { 2067 traceParent._pushContext(); 2068 var result = tryCatch(yieldHandlers[i])(value); 2069 traceParent._popContext(); 2070 if (result === errorObj) { 2071 traceParent._pushContext(); 2072 var ret = Promise.reject(errorObj.e); 2073 traceParent._popContext(); 2074 return ret; 2075 } 2076 var maybePromise = tryConvertToPromise(result, traceParent); 2077 if (maybePromise instanceof Promise) return maybePromise; 2078 } 2079 return null; 2080} 2081 2082function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { 2083 if (debug.cancellation()) { 2084 var internal = new Promise(INTERNAL); 2085 var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); 2086 this._promise = internal.lastly(function() { 2087 return _finallyPromise; 2088 }); 2089 internal._captureStackTrace(); 2090 internal._setOnCancel(this); 2091 } else { 2092 var promise = this._promise = new Promise(INTERNAL); 2093 promise._captureStackTrace(); 2094 } 2095 this._stack = stack; 2096 this._generatorFunction = generatorFunction; 2097 this._receiver = receiver; 2098 this._generator = undefined; 2099 this._yieldHandlers = typeof yieldHandler === "function" 2100 ? [yieldHandler].concat(yieldHandlers) 2101 : yieldHandlers; 2102 this._yieldedPromise = null; 2103 this._cancellationPhase = false; 2104} 2105util.inherits(PromiseSpawn, Proxyable); 2106 2107PromiseSpawn.prototype._isResolved = function() { 2108 return this._promise === null; 2109}; 2110 2111PromiseSpawn.prototype._cleanup = function() { 2112 this._promise = this._generator = null; 2113 if (debug.cancellation() && this._finallyPromise !== null) { 2114 this._finallyPromise._fulfill(); 2115 this._finallyPromise = null; 2116 } 2117}; 2118 2119PromiseSpawn.prototype._promiseCancelled = function() { 2120 if (this._isResolved()) return; 2121 var implementsReturn = typeof this._generator["return"] !== "undefined"; 2122 2123 var result; 2124 if (!implementsReturn) { 2125 var reason = new Promise.CancellationError( 2126 "generator .return() sentinel"); 2127 Promise.coroutine.returnSentinel = reason; 2128 this._promise._attachExtraTrace(reason); 2129 this._promise._pushContext(); 2130 result = tryCatch(this._generator["throw"]).call(this._generator, 2131 reason); 2132 this._promise._popContext(); 2133 } else { 2134 this._promise._pushContext(); 2135 result = tryCatch(this._generator["return"]).call(this._generator, 2136 undefined); 2137 this._promise._popContext(); 2138 } 2139 this._cancellationPhase = true; 2140 this._yieldedPromise = null; 2141 this._continue(result); 2142}; 2143 2144PromiseSpawn.prototype._promiseFulfilled = function(value) { 2145 this._yieldedPromise = null; 2146 this._promise._pushContext(); 2147 var result = tryCatch(this._generator.next).call(this._generator, value); 2148 this._promise._popContext(); 2149 this._continue(result); 2150}; 2151 2152PromiseSpawn.prototype._promiseRejected = function(reason) { 2153 this._yieldedPromise = null; 2154 this._promise._attachExtraTrace(reason); 2155 this._promise._pushContext(); 2156 var result = tryCatch(this._generator["throw"]) 2157 .call(this._generator, reason); 2158 this._promise._popContext(); 2159 this._continue(result); 2160}; 2161 2162PromiseSpawn.prototype._resultCancelled = function() { 2163 if (this._yieldedPromise instanceof Promise) { 2164 var promise = this._yieldedPromise; 2165 this._yieldedPromise = null; 2166 promise.cancel(); 2167 } 2168}; 2169 2170PromiseSpawn.prototype.promise = function () { 2171 return this._promise; 2172}; 2173 2174PromiseSpawn.prototype._run = function () { 2175 this._generator = this._generatorFunction.call(this._receiver); 2176 this._receiver = 2177 this._generatorFunction = undefined; 2178 this._promiseFulfilled(undefined); 2179}; 2180 2181PromiseSpawn.prototype._continue = function (result) { 2182 var promise = this._promise; 2183 if (result === errorObj) { 2184 this._cleanup(); 2185 if (this._cancellationPhase) { 2186 return promise.cancel(); 2187 } else { 2188 return promise._rejectCallback(result.e, false); 2189 } 2190 } 2191 2192 var value = result.value; 2193 if (result.done === true) { 2194 this._cleanup(); 2195 if (this._cancellationPhase) { 2196 return promise.cancel(); 2197 } else { 2198 return promise._resolveCallback(value); 2199 } 2200 } else { 2201 var maybePromise = tryConvertToPromise(value, this._promise); 2202 if (!(maybePromise instanceof Promise)) { 2203 maybePromise = 2204 promiseFromYieldHandler(maybePromise, 2205 this._yieldHandlers, 2206 this._promise); 2207 if (maybePromise === null) { 2208 this._promiseRejected( 2209 new TypeError( 2210 "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)) + 2211 "From coroutine:\u000a" + 2212 this._stack.split("\n").slice(1, -7).join("\n") 2213 ) 2214 ); 2215 return; 2216 } 2217 } 2218 maybePromise = maybePromise._target(); 2219 var bitField = maybePromise._bitField; 2220 ; 2221 if (((bitField & 50397184) === 0)) { 2222 this._yieldedPromise = maybePromise; 2223 maybePromise._proxy(this, null); 2224 } else if (((bitField & 33554432) !== 0)) { 2225 Promise._async.invoke( 2226 this._promiseFulfilled, this, maybePromise._value() 2227 ); 2228 } else if (((bitField & 16777216) !== 0)) { 2229 Promise._async.invoke( 2230 this._promiseRejected, this, maybePromise._reason() 2231 ); 2232 } else { 2233 this._promiseCancelled(); 2234 } 2235 } 2236}; 2237 2238Promise.coroutine = function (generatorFunction, options) { 2239 if (typeof generatorFunction !== "function") { 2240 throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 2241 } 2242 var yieldHandler = Object(options).yieldHandler; 2243 var PromiseSpawn$ = PromiseSpawn; 2244 var stack = new Error().stack; 2245 return function () { 2246 var generator = generatorFunction.apply(this, arguments); 2247 var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, 2248 stack); 2249 var ret = spawn.promise(); 2250 spawn._generator = generator; 2251 spawn._promiseFulfilled(undefined); 2252 return ret; 2253 }; 2254}; 2255 2256Promise.coroutine.addYieldHandler = function(fn) { 2257 if (typeof fn !== "function") { 2258 throw new TypeError("expecting a function but got " + util.classString(fn)); 2259 } 2260 yieldHandlers.push(fn); 2261}; 2262 2263Promise.spawn = function (generatorFunction) { 2264 debug.deprecated("Promise.spawn()", "Promise.coroutine()"); 2265 if (typeof generatorFunction !== "function") { 2266 return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 2267 } 2268 var spawn = new PromiseSpawn(generatorFunction, this); 2269 var ret = spawn.promise(); 2270 spawn._run(Promise.spawn); 2271 return ret; 2272}; 2273}; 2274 2275},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ 2276"use strict"; 2277module.exports = 2278function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, 2279 getDomain) { 2280var util = _dereq_("./util"); 2281var canEvaluate = util.canEvaluate; 2282var tryCatch = util.tryCatch; 2283var errorObj = util.errorObj; 2284var reject; 2285 2286if (!true) { 2287if (canEvaluate) { 2288 var thenCallback = function(i) { 2289 return new Function("value", "holder", " \n\ 2290 'use strict'; \n\ 2291 holder.pIndex = value; \n\ 2292 holder.checkFulfillment(this); \n\ 2293 ".replace(/Index/g, i)); 2294 }; 2295 2296 var promiseSetter = function(i) { 2297 return new Function("promise", "holder", " \n\ 2298 'use strict'; \n\ 2299 holder.pIndex = promise; \n\ 2300 ".replace(/Index/g, i)); 2301 }; 2302 2303 var generateHolderClass = function(total) { 2304 var props = new Array(total); 2305 for (var i = 0; i < props.length; ++i) { 2306 props[i] = "this.p" + (i+1); 2307 } 2308 var assignment = props.join(" = ") + " = null;"; 2309 var cancellationCode= "var promise;\n" + props.map(function(prop) { 2310 return " \n\ 2311 promise = " + prop + "; \n\ 2312 if (promise instanceof Promise) { \n\ 2313 promise.cancel(); \n\ 2314 } \n\ 2315 "; 2316 }).join("\n"); 2317 var passedArguments = props.join(", "); 2318 var name = "Holder$" + total; 2319 2320 2321 var code = "return function(tryCatch, errorObj, Promise, async) { \n\ 2322 'use strict'; \n\ 2323 function [TheName](fn) { \n\ 2324 [TheProperties] \n\ 2325 this.fn = fn; \n\ 2326 this.asyncNeeded = true; \n\ 2327 this.now = 0; \n\ 2328 } \n\ 2329 \n\ 2330 [TheName].prototype._callFunction = function(promise) { \n\ 2331 promise._pushContext(); \n\ 2332 var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ 2333 promise._popContext(); \n\ 2334 if (ret === errorObj) { \n\ 2335 promise._rejectCallback(ret.e, false); \n\ 2336 } else { \n\ 2337 promise._resolveCallback(ret); \n\ 2338 } \n\ 2339 }; \n\ 2340 \n\ 2341 [TheName].prototype.checkFulfillment = function(promise) { \n\ 2342 var now = ++this.now; \n\ 2343 if (now === [TheTotal]) { \n\ 2344 if (this.asyncNeeded) { \n\ 2345 async.invoke(this._callFunction, this, promise); \n\ 2346 } else { \n\ 2347 this._callFunction(promise); \n\ 2348 } \n\ 2349 \n\ 2350 } \n\ 2351 }; \n\ 2352 \n\ 2353 [TheName].prototype._resultCancelled = function() { \n\ 2354 [CancellationCode] \n\ 2355 }; \n\ 2356 \n\ 2357 return [TheName]; \n\ 2358 }(tryCatch, errorObj, Promise, async); \n\ 2359 "; 2360 2361 code = code.replace(/\[TheName\]/g, name) 2362 .replace(/\[TheTotal\]/g, total) 2363 .replace(/\[ThePassedArguments\]/g, passedArguments) 2364 .replace(/\[TheProperties\]/g, assignment) 2365 .replace(/\[CancellationCode\]/g, cancellationCode); 2366 2367 return new Function("tryCatch", "errorObj", "Promise", "async", code) 2368 (tryCatch, errorObj, Promise, async); 2369 }; 2370 2371 var holderClasses = []; 2372 var thenCallbacks = []; 2373 var promiseSetters = []; 2374 2375 for (var i = 0; i < 8; ++i) { 2376 holderClasses.push(generateHolderClass(i + 1)); 2377 thenCallbacks.push(thenCallback(i + 1)); 2378 promiseSetters.push(promiseSetter(i + 1)); 2379 } 2380 2381 reject = function (reason) { 2382 this._reject(reason); 2383 }; 2384}} 2385 2386Promise.join = function () { 2387 var last = arguments.length - 1; 2388 var fn; 2389 if (last > 0 && typeof arguments[last] === "function") { 2390 fn = arguments[last]; 2391 if (!true) { 2392 if (last <= 8 && canEvaluate) { 2393 var ret = new Promise(INTERNAL); 2394 ret._captureStackTrace(); 2395 var HolderClass = holderClasses[last - 1]; 2396 var holder = new HolderClass(fn); 2397 var callbacks = thenCallbacks; 2398 2399 for (var i = 0; i < last; ++i) { 2400 var maybePromise = tryConvertToPromise(arguments[i], ret); 2401 if (maybePromise instanceof Promise) { 2402 maybePromise = maybePromise._target(); 2403 var bitField = maybePromise._bitField; 2404 ; 2405 if (((bitField & 50397184) === 0)) { 2406 maybePromise._then(callbacks[i], reject, 2407 undefined, ret, holder); 2408 promiseSetters[i](maybePromise, holder); 2409 holder.asyncNeeded = false; 2410 } else if (((bitField & 33554432) !== 0)) { 2411 callbacks[i].call(ret, 2412 maybePromise._value(), holder); 2413 } else if (((bitField & 16777216) !== 0)) { 2414 ret._reject(maybePromise._reason()); 2415 } else { 2416 ret._cancel(); 2417 } 2418 } else { 2419 callbacks[i].call(ret, maybePromise, holder); 2420 } 2421 } 2422 2423 if (!ret._isFateSealed()) { 2424 if (holder.asyncNeeded) { 2425 var domain = getDomain(); 2426 if (domain !== null) { 2427 holder.fn = util.domainBind(domain, holder.fn); 2428 } 2429 } 2430 ret._setAsyncGuaranteed(); 2431 ret._setOnCancel(holder); 2432 } 2433 return ret; 2434 } 2435 } 2436 } 2437 var args = [].slice.call(arguments);; 2438 if (fn) args.pop(); 2439 var ret = new PromiseArray(args).promise(); 2440 return fn !== undefined ? ret.spread(fn) : ret; 2441}; 2442 2443}; 2444 2445},{"./util":36}],18:[function(_dereq_,module,exports){ 2446"use strict"; 2447module.exports = function(Promise, 2448 PromiseArray, 2449 apiRejection, 2450 tryConvertToPromise, 2451 INTERNAL, 2452 debug) { 2453var getDomain = Promise._getDomain; 2454var util = _dereq_("./util"); 2455var tryCatch = util.tryCatch; 2456var errorObj = util.errorObj; 2457var async = Promise._async; 2458 2459function MappingPromiseArray(promises, fn, limit, _filter) { 2460 this.constructor$(promises); 2461 this._promise._captureStackTrace(); 2462 var domain = getDomain(); 2463 this._callback = domain === null ? fn : util.domainBind(domain, fn); 2464 this._preservedValues = _filter === INTERNAL 2465 ? new Array(this.length()) 2466 : null; 2467 this._limit = limit; 2468 this._inFlight = 0; 2469 this._queue = []; 2470 async.invoke(this._asyncInit, this, undefined); 2471} 2472util.inherits(MappingPromiseArray, PromiseArray); 2473 2474MappingPromiseArray.prototype._asyncInit = function() { 2475 this._init$(undefined, -2); 2476}; 2477 2478MappingPromiseArray.prototype._init = function () {}; 2479 2480MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { 2481 var values = this._values; 2482 var length = this.length(); 2483 var preservedValues = this._preservedValues; 2484 var limit = this._limit; 2485 2486 if (index < 0) { 2487 index = (index * -1) - 1; 2488 values[index] = value; 2489 if (limit >= 1) { 2490 this._inFlight--; 2491 this._drainQueue(); 2492 if (this._isResolved()) return true; 2493 } 2494 } else { 2495 if (limit >= 1 && this._inFlight >= limit) { 2496 values[index] = value; 2497 this._queue.push(index); 2498 return false; 2499 } 2500 if (preservedValues !== null) preservedValues[index] = value; 2501 2502 var promise = this._promise; 2503 var callback = this._callback; 2504 var receiver = promise._boundValue(); 2505 promise._pushContext(); 2506 var ret = tryCatch(callback).call(receiver, value, index, length); 2507 var promiseCreated = promise._popContext(); 2508 debug.checkForgottenReturns( 2509 ret, 2510 promiseCreated, 2511 preservedValues !== null ? "Promise.filter" : "Promise.map", 2512 promise 2513 ); 2514 if (ret === errorObj) { 2515 this._reject(ret.e); 2516 return true; 2517 } 2518 2519 var maybePromise = tryConvertToPromise(ret, this._promise); 2520 if (maybePromise instanceof Promise) { 2521 maybePromise = maybePromise._target(); 2522 var bitField = maybePromise._bitField; 2523 ; 2524 if (((bitField & 50397184) === 0)) { 2525 if (limit >= 1) this._inFlight++; 2526 values[index] = maybePromise; 2527 maybePromise._proxy(this, (index + 1) * -1); 2528 return false; 2529 } else if (((bitField & 33554432) !== 0)) { 2530 ret = maybePromise._value(); 2531 } else if (((bitField & 16777216) !== 0)) { 2532 this._reject(maybePromise._reason()); 2533 return true; 2534 } else { 2535 this._cancel(); 2536 return true; 2537 } 2538 } 2539 values[index] = ret; 2540 } 2541 var totalResolved = ++this._totalResolved; 2542 if (totalResolved >= length) { 2543 if (preservedValues !== null) { 2544 this._filter(values, preservedValues); 2545 } else { 2546 this._resolve(values); 2547 } 2548 return true; 2549 } 2550 return false; 2551}; 2552 2553MappingPromiseArray.prototype._drainQueue = function () { 2554 var queue = this._queue; 2555 var limit = this._limit; 2556 var values = this._values; 2557 while (queue.length > 0 && this._inFlight < limit) { 2558 if (this._isResolved()) return; 2559 var index = queue.pop(); 2560 this._promiseFulfilled(values[index], index); 2561 } 2562}; 2563 2564MappingPromiseArray.prototype._filter = function (booleans, values) { 2565 var len = values.length; 2566 var ret = new Array(len); 2567 var j = 0; 2568 for (var i = 0; i < len; ++i) { 2569 if (booleans[i]) ret[j++] = values[i]; 2570 } 2571 ret.length = j; 2572 this._resolve(ret); 2573}; 2574 2575MappingPromiseArray.prototype.preservedValues = function () { 2576 return this._preservedValues; 2577}; 2578 2579function map(promises, fn, options, _filter) { 2580 if (typeof fn !== "function") { 2581 return apiRejection("expecting a function but got " + util.classString(fn)); 2582 } 2583 2584 var limit = 0; 2585 if (options !== undefined) { 2586 if (typeof options === "object" && options !== null) { 2587 if (typeof options.concurrency !== "number") { 2588 return Promise.reject( 2589 new TypeError("'concurrency' must be a number but it is " + 2590 util.classString(options.concurrency))); 2591 } 2592 limit = options.concurrency; 2593 } else { 2594 return Promise.reject(new TypeError( 2595 "options argument must be an object but it is " + 2596 util.classString(options))); 2597 } 2598 } 2599 limit = typeof limit === "number" && 2600 isFinite(limit) && limit >= 1 ? limit : 0; 2601 return new MappingPromiseArray(promises, fn, limit, _filter).promise(); 2602} 2603 2604Promise.prototype.map = function (fn, options) { 2605 return map(this, fn, options, null); 2606}; 2607 2608Promise.map = function (promises, fn, options, _filter) { 2609 return map(promises, fn, options, _filter); 2610}; 2611 2612 2613}; 2614 2615},{"./util":36}],19:[function(_dereq_,module,exports){ 2616"use strict"; 2617module.exports = 2618function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { 2619var util = _dereq_("./util"); 2620var tryCatch = util.tryCatch; 2621 2622Promise.method = function (fn) { 2623 if (typeof fn !== "function") { 2624 throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); 2625 } 2626 return function () { 2627 var ret = new Promise(INTERNAL); 2628 ret._captureStackTrace(); 2629 ret._pushContext(); 2630 var value = tryCatch(fn).apply(this, arguments); 2631 var promiseCreated = ret._popContext(); 2632 debug.checkForgottenReturns( 2633 value, promiseCreated, "Promise.method", ret); 2634 ret._resolveFromSyncValue(value); 2635 return ret; 2636 }; 2637}; 2638 2639Promise.attempt = Promise["try"] = function (fn) { 2640 if (typeof fn !== "function") { 2641 return apiRejection("expecting a function but got " + util.classString(fn)); 2642 } 2643 var ret = new Promise(INTERNAL); 2644 ret._captureStackTrace(); 2645 ret._pushContext(); 2646 var value; 2647 if (arguments.length > 1) { 2648 debug.deprecated("calling Promise.try with more than 1 argument"); 2649 var arg = arguments[1]; 2650 var ctx = arguments[2]; 2651 value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) 2652 : tryCatch(fn).call(ctx, arg); 2653 } else { 2654 value = tryCatch(fn)(); 2655 } 2656 var promiseCreated = ret._popContext(); 2657 debug.checkForgottenReturns( 2658 value, promiseCreated, "Promise.try", ret); 2659 ret._resolveFromSyncValue(value); 2660 return ret; 2661}; 2662 2663Promise.prototype._resolveFromSyncValue = function (value) { 2664 if (value === util.errorObj) { 2665 this._rejectCallback(value.e, false); 2666 } else { 2667 this._resolveCallback(value, true); 2668 } 2669}; 2670}; 2671 2672},{"./util":36}],20:[function(_dereq_,module,exports){ 2673"use strict"; 2674var util = _dereq_("./util"); 2675var maybeWrapAsError = util.maybeWrapAsError; 2676var errors = _dereq_("./errors"); 2677var OperationalError = errors.OperationalError; 2678var es5 = _dereq_("./es5"); 2679 2680function isUntypedError(obj) { 2681 return obj instanceof Error && 2682 es5.getPrototypeOf(obj) === Error.prototype; 2683} 2684 2685var rErrorKey = /^(?:name|message|stack|cause)$/; 2686function wrapAsOperationalError(obj) { 2687 var ret; 2688 if (isUntypedError(obj)) { 2689 ret = new OperationalError(obj); 2690 ret.name = obj.name; 2691 ret.message = obj.message; 2692 ret.stack = obj.stack; 2693 var keys = es5.keys(obj); 2694 for (var i = 0; i < keys.length; ++i) { 2695 var key = keys[i]; 2696 if (!rErrorKey.test(key)) { 2697 ret[key] = obj[key]; 2698 } 2699 } 2700 return ret; 2701 } 2702 util.markAsOriginatingFromRejection(obj); 2703 return obj; 2704} 2705 2706function nodebackForPromise(promise, multiArgs) { 2707 return function(err, value) { 2708 if (promise === null) return; 2709 if (err) { 2710 var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); 2711 promise._attachExtraTrace(wrapped); 2712 promise._reject(wrapped); 2713 } else if (!multiArgs) { 2714 promise._fulfill(value); 2715 } else { 2716 var args = [].slice.call(arguments, 1);; 2717 promise._fulfill(args); 2718 } 2719 promise = null; 2720 }; 2721} 2722 2723module.exports = nodebackForPromise; 2724 2725},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ 2726"use strict"; 2727module.exports = function(Promise) { 2728var util = _dereq_("./util"); 2729var async = Promise._async; 2730var tryCatch = util.tryCatch; 2731var errorObj = util.errorObj; 2732 2733function spreadAdapter(val, nodeback) { 2734 var promise = this; 2735 if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); 2736 var ret = 2737 tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); 2738 if (ret === errorObj) { 2739 async.throwLater(ret.e); 2740 } 2741} 2742 2743function successAdapter(val, nodeback) { 2744 var promise = this; 2745 var receiver = promise._boundValue(); 2746 var ret = val === undefined 2747 ? tryCatch(nodeback).call(receiver, null) 2748 : tryCatch(nodeback).call(receiver, null, val); 2749 if (ret === errorObj) { 2750 async.throwLater(ret.e); 2751 } 2752} 2753function errorAdapter(reason, nodeback) { 2754 var promise = this; 2755 if (!reason) { 2756 var newReason = new Error(reason + ""); 2757 newReason.cause = reason; 2758 reason = newReason; 2759 } 2760 var ret = tryCatch(nodeback).call(promise._boundValue(), reason); 2761 if (ret === errorObj) { 2762 async.throwLater(ret.e); 2763 } 2764} 2765 2766Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, 2767 options) { 2768 if (typeof nodeback == "function") { 2769 var adapter = successAdapter; 2770 if (options !== undefined && Object(options).spread) { 2771 adapter = spreadAdapter; 2772 } 2773 this._then( 2774 adapter, 2775 errorAdapter, 2776 undefined, 2777 this, 2778 nodeback 2779 ); 2780 } 2781 return this; 2782}; 2783}; 2784 2785},{"./util":36}],22:[function(_dereq_,module,exports){ 2786"use strict"; 2787module.exports = function() { 2788var makeSelfResolutionError = function () { 2789 return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 2790}; 2791var reflectHandler = function() { 2792 return new Promise.PromiseInspection(this._target()); 2793}; 2794var apiRejection = function(msg) { 2795 return Promise.reject(new TypeError(msg)); 2796}; 2797function Proxyable() {} 2798var UNDEFINED_BINDING = {}; 2799var util = _dereq_("./util"); 2800 2801var getDomain; 2802if (util.isNode) { 2803 getDomain = function() { 2804 var ret = process.domain; 2805 if (ret === undefined) ret = null; 2806 return ret; 2807 }; 2808} else { 2809 getDomain = function() { 2810 return null; 2811 }; 2812} 2813util.notEnumerableProp(Promise, "_getDomain", getDomain); 2814 2815var es5 = _dereq_("./es5"); 2816var Async = _dereq_("./async"); 2817var async = new Async(); 2818es5.defineProperty(Promise, "_async", {value: async}); 2819var errors = _dereq_("./errors"); 2820var TypeError = Promise.TypeError = errors.TypeError; 2821Promise.RangeError = errors.RangeError; 2822var CancellationError = Promise.CancellationError = errors.CancellationError; 2823Promise.TimeoutError = errors.TimeoutError; 2824Promise.OperationalError = errors.OperationalError; 2825Promise.RejectionError = errors.OperationalError; 2826Promise.AggregateError = errors.AggregateError; 2827var INTERNAL = function(){}; 2828var APPLY = {}; 2829var NEXT_FILTER = {}; 2830var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); 2831var PromiseArray = 2832 _dereq_("./promise_array")(Promise, INTERNAL, 2833 tryConvertToPromise, apiRejection, Proxyable); 2834var Context = _dereq_("./context")(Promise); 2835 /*jshint unused:false*/ 2836var createContext = Context.create; 2837var debug = _dereq_("./debuggability")(Promise, Context); 2838var CapturedTrace = debug.CapturedTrace; 2839var PassThroughHandlerContext = 2840 _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); 2841var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); 2842var nodebackForPromise = _dereq_("./nodeback"); 2843var errorObj = util.errorObj; 2844var tryCatch = util.tryCatch; 2845function check(self, executor) { 2846 if (self == null || self.constructor !== Promise) { 2847 throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 2848 } 2849 if (typeof executor !== "function") { 2850 throw new TypeError("expecting a function but got " + util.classString(executor)); 2851 } 2852 2853} 2854 2855function Promise(executor) { 2856 if (executor !== INTERNAL) { 2857 check(this, executor); 2858 } 2859 this._bitField = 0; 2860 this._fulfillmentHandler0 = undefined; 2861 this._rejectionHandler0 = undefined; 2862 this._promise0 = undefined; 2863 this._receiver0 = undefined; 2864 this._resolveFromExecutor(executor); 2865 this._promiseCreated(); 2866 this._fireEvent("promiseCreated", this); 2867} 2868 2869Promise.prototype.toString = function () { 2870 return "[object Promise]"; 2871}; 2872 2873Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { 2874 var len = arguments.length; 2875 if (len > 1) { 2876 var catchInstances = new Array(len - 1), 2877 j = 0, i; 2878 for (i = 0; i < len - 1; ++i) { 2879 var item = arguments[i]; 2880 if (util.isObject(item)) { 2881 catchInstances[j++] = item; 2882 } else { 2883 return apiRejection("Catch statement predicate: " + 2884 "expecting an object but got " + util.classString(item)); 2885 } 2886 } 2887 catchInstances.length = j; 2888 fn = arguments[i]; 2889 2890 if (typeof fn !== "function") { 2891 throw new TypeError("The last argument to .catch() " + 2892 "must be a function, got " + util.toString(fn)); 2893 } 2894 return this.then(undefined, catchFilter(catchInstances, fn, this)); 2895 } 2896 return this.then(undefined, fn); 2897}; 2898 2899Promise.prototype.reflect = function () { 2900 return this._then(reflectHandler, 2901 reflectHandler, undefined, this, undefined); 2902}; 2903 2904Promise.prototype.then = function (didFulfill, didReject) { 2905 if (debug.warnings() && arguments.length > 0 && 2906 typeof didFulfill !== "function" && 2907 typeof didReject !== "function") { 2908 var msg = ".then() only accepts functions but was passed: " + 2909 util.classString(didFulfill); 2910 if (arguments.length > 1) { 2911 msg += ", " + util.classString(didReject); 2912 } 2913 this._warn(msg); 2914 } 2915 return this._then(didFulfill, didReject, undefined, undefined, undefined); 2916}; 2917 2918Promise.prototype.done = function (didFulfill, didReject) { 2919 var promise = 2920 this._then(didFulfill, didReject, undefined, undefined, undefined); 2921 promise._setIsFinal(); 2922}; 2923 2924Promise.prototype.spread = function (fn) { 2925 if (typeof fn !== "function") { 2926 return apiRejection("expecting a function but got " + util.classString(fn)); 2927 } 2928 return this.all()._then(fn, undefined, undefined, APPLY, undefined); 2929}; 2930 2931Promise.prototype.toJSON = function () { 2932 var ret = { 2933 isFulfilled: false, 2934 isRejected: false, 2935 fulfillmentValue: undefined, 2936 rejectionReason: undefined 2937 }; 2938 if (this.isFulfilled()) { 2939 ret.fulfillmentValue = this.value(); 2940 ret.isFulfilled = true; 2941 } else if (this.isRejected()) { 2942 ret.rejectionReason = this.reason(); 2943 ret.isRejected = true; 2944 } 2945 return ret; 2946}; 2947 2948Promise.prototype.all = function () { 2949 if (arguments.length > 0) { 2950 this._warn(".all() was passed arguments but it does not take any"); 2951 } 2952 return new PromiseArray(this).promise(); 2953}; 2954 2955Promise.prototype.error = function (fn) { 2956 return this.caught(util.originatesFromRejection, fn); 2957}; 2958 2959Promise.getNewLibraryCopy = module.exports; 2960 2961Promise.is = function (val) { 2962 return val instanceof Promise; 2963}; 2964 2965Promise.fromNode = Promise.fromCallback = function(fn) { 2966 var ret = new Promise(INTERNAL); 2967 ret._captureStackTrace(); 2968 var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs 2969 : false; 2970 var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); 2971 if (result === errorObj) { 2972 ret._rejectCallback(result.e, true); 2973 } 2974 if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); 2975 return ret; 2976}; 2977 2978Promise.all = function (promises) { 2979 return new PromiseArray(promises).promise(); 2980}; 2981 2982Promise.cast = function (obj) { 2983 var ret = tryConvertToPromise(obj); 2984 if (!(ret instanceof Promise)) { 2985 ret = new Promise(INTERNAL); 2986 ret._captureStackTrace(); 2987 ret._setFulfilled(); 2988 ret._rejectionHandler0 = obj; 2989 } 2990 return ret; 2991}; 2992 2993Promise.resolve = Promise.fulfilled = Promise.cast; 2994 2995Promise.reject = Promise.rejected = function (reason) { 2996 var ret = new Promise(INTERNAL); 2997 ret._captureStackTrace(); 2998 ret._rejectCallback(reason, true); 2999 return ret; 3000}; 3001 3002Promise.setScheduler = function(fn) { 3003 if (typeof fn !== "function") { 3004 throw new TypeError("expecting a function but got " + util.classString(fn)); 3005 } 3006 return async.setScheduler(fn); 3007}; 3008 3009Promise.prototype._then = function ( 3010 didFulfill, 3011 didReject, 3012 _, receiver, 3013 internalData 3014) { 3015 var haveInternalData = internalData !== undefined; 3016 var promise = haveInternalData ? internalData : new Promise(INTERNAL); 3017 var target = this._target(); 3018 var bitField = target._bitField; 3019 3020 if (!haveInternalData) { 3021 promise._propagateFrom(this, 3); 3022 promise._captureStackTrace(); 3023 if (receiver === undefined && 3024 ((this._bitField & 2097152) !== 0)) { 3025 if (!((bitField & 50397184) === 0)) { 3026 receiver = this._boundValue(); 3027 } else { 3028 receiver = target === this ? undefined : this._boundTo; 3029 } 3030 } 3031 this._fireEvent("promiseChained", this, promise); 3032 } 3033 3034 var domain = getDomain(); 3035 if (!((bitField & 50397184) === 0)) { 3036 var handler, value, settler = target._settlePromiseCtx; 3037 if (((bitField & 33554432) !== 0)) { 3038 value = target._rejectionHandler0; 3039 handler = didFulfill; 3040 } else if (((bitField & 16777216) !== 0)) { 3041 value = target._fulfillmentHandler0; 3042 handler = didReject; 3043 target._unsetRejectionIsUnhandled(); 3044 } else { 3045 settler = target._settlePromiseLateCancellationObserver; 3046 value = new CancellationError("late cancellation observer"); 3047 target._attachExtraTrace(value); 3048 handler = didReject; 3049 } 3050 3051 async.invoke(settler, target, { 3052 handler: domain === null ? handler 3053 : (typeof handler === "function" && 3054 util.domainBind(domain, handler)), 3055 promise: promise, 3056 receiver: receiver, 3057 value: value 3058 }); 3059 } else { 3060 target._addCallbacks(didFulfill, didReject, promise, receiver, domain); 3061 } 3062 3063 return promise; 3064}; 3065 3066Promise.prototype._length = function () { 3067 return this._bitField & 65535; 3068}; 3069 3070Promise.prototype._isFateSealed = function () { 3071 return (this._bitField & 117506048) !== 0; 3072}; 3073 3074Promise.prototype._isFollowing = function () { 3075 return (this._bitField & 67108864) === 67108864; 3076}; 3077 3078Promise.prototype._setLength = function (len) { 3079 this._bitField = (this._bitField & -65536) | 3080 (len & 65535); 3081}; 3082 3083Promise.prototype._setFulfilled = function () { 3084 this._bitField = this._bitField | 33554432; 3085 this._fireEvent("promiseFulfilled", this); 3086}; 3087 3088Promise.prototype._setRejected = function () { 3089 this._bitField = this._bitField | 16777216; 3090 this._fireEvent("promiseRejected", this); 3091}; 3092 3093Promise.prototype._setFollowing = function () { 3094 this._bitField = this._bitField | 67108864; 3095 this._fireEvent("promiseResolved", this); 3096}; 3097 3098Promise.prototype._setIsFinal = function () { 3099 this._bitField = this._bitField | 4194304; 3100}; 3101 3102Promise.prototype._isFinal = function () { 3103 return (this._bitField & 4194304) > 0; 3104}; 3105 3106Promise.prototype._unsetCancelled = function() { 3107 this._bitField = this._bitField & (~65536); 3108}; 3109 3110Promise.prototype._setCancelled = function() { 3111 this._bitField = this._bitField | 65536; 3112 this._fireEvent("promiseCancelled", this); 3113}; 3114 3115Promise.prototype._setWillBeCancelled = function() { 3116 this._bitField = this._bitField | 8388608; 3117}; 3118 3119Promise.prototype._setAsyncGuaranteed = function() { 3120 if (async.hasCustomScheduler()) return; 3121 this._bitField = this._bitField | 134217728; 3122}; 3123 3124Promise.prototype._receiverAt = function (index) { 3125 var ret = index === 0 ? this._receiver0 : this[ 3126 index * 4 - 4 + 3]; 3127 if (ret === UNDEFINED_BINDING) { 3128 return undefined; 3129 } else if (ret === undefined && this._isBound()) { 3130 return this._boundValue(); 3131 } 3132 return ret; 3133}; 3134 3135Promise.prototype._promiseAt = function (index) { 3136 return this[ 3137 index * 4 - 4 + 2]; 3138}; 3139 3140Promise.prototype._fulfillmentHandlerAt = function (index) { 3141 return this[ 3142 index * 4 - 4 + 0]; 3143}; 3144 3145Promise.prototype._rejectionHandlerAt = function (index) { 3146 return this[ 3147 index * 4 - 4 + 1]; 3148}; 3149 3150Promise.prototype._boundValue = function() {}; 3151 3152Promise.prototype._migrateCallback0 = function (follower) { 3153 var bitField = follower._bitField; 3154 var fulfill = follower._fulfillmentHandler0; 3155 var reject = follower._rejectionHandler0; 3156 var promise = follower._promise0; 3157 var receiver = follower._receiverAt(0); 3158 if (receiver === undefined) receiver = UNDEFINED_BINDING; 3159 this._addCallbacks(fulfill, reject, promise, receiver, null); 3160}; 3161 3162Promise.prototype._migrateCallbackAt = function (follower, index) { 3163 var fulfill = follower._fulfillmentHandlerAt(index); 3164 var reject = follower._rejectionHandlerAt(index); 3165 var promise = follower._promiseAt(index); 3166 var receiver = follower._receiverAt(index); 3167 if (receiver === undefined) receiver = UNDEFINED_BINDING; 3168 this._addCallbacks(fulfill, reject, promise, receiver, null); 3169}; 3170 3171Promise.prototype._addCallbacks = function ( 3172 fulfill, 3173 reject, 3174 promise, 3175 receiver, 3176 domain 3177) { 3178 var index = this._length(); 3179 3180 if (index >= 65535 - 4) { 3181 index = 0; 3182 this._setLength(0); 3183 } 3184 3185 if (index === 0) { 3186 this._promise0 = promise; 3187 this._receiver0 = receiver; 3188 if (typeof fulfill === "function") { 3189 this._fulfillmentHandler0 = 3190 domain === null ? fulfill : util.domainBind(domain, fulfill); 3191 } 3192 if (typeof reject === "function") { 3193 this._rejectionHandler0 = 3194 domain === null ? reject : util.domainBind(domain, reject); 3195 } 3196 } else { 3197 var base = index * 4 - 4; 3198 this[base + 2] = promise; 3199 this[base + 3] = receiver; 3200 if (typeof fulfill === "function") { 3201 this[base + 0] = 3202 domain === null ? fulfill : util.domainBind(domain, fulfill); 3203 } 3204 if (typeof reject === "function") { 3205 this[base + 1] = 3206 domain === null ? reject : util.domainBind(domain, reject); 3207 } 3208 } 3209 this._setLength(index + 1); 3210 return index; 3211}; 3212 3213Promise.prototype._proxy = function (proxyable, arg) { 3214 this._addCallbacks(undefined, undefined, arg, proxyable, null); 3215}; 3216 3217Promise.prototype._resolveCallback = function(value, shouldBind) { 3218 if (((this._bitField & 117506048) !== 0)) return; 3219 if (value === this) 3220 return this._rejectCallback(makeSelfResolutionError(), false); 3221 var maybePromise = tryConvertToPromise(value, this); 3222 if (!(maybePromise instanceof Promise)) return this._fulfill(value); 3223 3224 if (shouldBind) this._propagateFrom(maybePromise, 2); 3225 3226 var promise = maybePromise._target(); 3227 3228 if (promise === this) { 3229 this._reject(makeSelfResolutionError()); 3230 return; 3231 } 3232 3233 var bitField = promise._bitField; 3234 if (((bitField & 50397184) === 0)) { 3235 var len = this._length(); 3236 if (len > 0) promise._migrateCallback0(this); 3237 for (var i = 1; i < len; ++i) { 3238 promise._migrateCallbackAt(this, i); 3239 } 3240 this._setFollowing(); 3241 this._setLength(0); 3242 this._setFollowee(promise); 3243 } else if (((bitField & 33554432) !== 0)) { 3244 this._fulfill(promise._value()); 3245 } else if (((bitField & 16777216) !== 0)) { 3246 this._reject(promise._reason()); 3247 } else { 3248 var reason = new CancellationError("late cancellation observer"); 3249 promise._attachExtraTrace(reason); 3250 this._reject(reason); 3251 } 3252}; 3253 3254Promise.prototype._rejectCallback = 3255function(reason, synchronous, ignoreNonErrorWarnings) { 3256 var trace = util.ensureErrorObject(reason); 3257 var hasStack = trace === reason; 3258 if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { 3259 var message = "a promise was rejected with a non-error: " + 3260 util.classString(reason); 3261 this._warn(message, true); 3262 } 3263 this._attachExtraTrace(trace, synchronous ? hasStack : false); 3264 this._reject(reason); 3265}; 3266 3267Promise.prototype._resolveFromExecutor = function (executor) { 3268 if (executor === INTERNAL) return; 3269 var promise = this; 3270 this._captureStackTrace(); 3271 this._pushContext(); 3272 var synchronous = true; 3273 var r = this._execute(executor, function(value) { 3274 promise._resolveCallback(value); 3275 }, function (reason) { 3276 promise._rejectCallback(reason, synchronous); 3277 }); 3278 synchronous = false; 3279 this._popContext(); 3280 3281 if (r !== undefined) { 3282 promise._rejectCallback(r, true); 3283 } 3284}; 3285 3286Promise.prototype._settlePromiseFromHandler = function ( 3287 handler, receiver, value, promise 3288) { 3289 var bitField = promise._bitField; 3290 if (((bitField & 65536) !== 0)) return; 3291 promise._pushContext(); 3292 var x; 3293 if (receiver === APPLY) { 3294 if (!value || typeof value.length !== "number") { 3295 x = errorObj; 3296 x.e = new TypeError("cannot .spread() a non-array: " + 3297 util.classString(value)); 3298 } else { 3299 x = tryCatch(handler).apply(this._boundValue(), value); 3300 } 3301 } else { 3302 x = tryCatch(handler).call(receiver, value); 3303 } 3304 var promiseCreated = promise._popContext(); 3305 bitField = promise._bitField; 3306 if (((bitField & 65536) !== 0)) return; 3307 3308 if (x === NEXT_FILTER) { 3309 promise._reject(value); 3310 } else if (x === errorObj) { 3311 promise._rejectCallback(x.e, false); 3312 } else { 3313 debug.checkForgottenReturns(x, promiseCreated, "", promise, this); 3314 promise._resolveCallback(x); 3315 } 3316}; 3317 3318Promise.prototype._target = function() { 3319 var ret = this; 3320 while (ret._isFollowing()) ret = ret._followee(); 3321 return ret; 3322}; 3323 3324Promise.prototype._followee = function() { 3325 return this._rejectionHandler0; 3326}; 3327 3328Promise.prototype._setFollowee = function(promise) { 3329 this._rejectionHandler0 = promise; 3330}; 3331 3332Promise.prototype._settlePromise = function(promise, handler, receiver, value) { 3333 var isPromise = promise instanceof Promise; 3334 var bitField = this._bitField; 3335 var asyncGuaranteed = ((bitField & 134217728) !== 0); 3336 if (((bitField & 65536) !== 0)) { 3337 if (isPromise) promise._invokeInternalOnCancel(); 3338 3339 if (receiver instanceof PassThroughHandlerContext && 3340 receiver.isFinallyHandler()) { 3341 receiver.cancelPromise = promise; 3342 if (tryCatch(handler).call(receiver, value) === errorObj) { 3343 promise._reject(errorObj.e); 3344 } 3345 } else if (handler === reflectHandler) { 3346 promise._fulfill(reflectHandler.call(receiver)); 3347 } else if (receiver instanceof Proxyable) { 3348 receiver._promiseCancelled(promise); 3349 } else if (isPromise || promise instanceof PromiseArray) { 3350 promise._cancel(); 3351 } else { 3352 receiver.cancel(); 3353 } 3354 } else if (typeof handler === "function") { 3355 if (!isPromise) { 3356 handler.call(receiver, value, promise); 3357 } else { 3358 if (asyncGuaranteed) promise._setAsyncGuaranteed(); 3359 this._settlePromiseFromHandler(handler, receiver, value, promise); 3360 } 3361 } else if (receiver instanceof Proxyable) { 3362 if (!receiver._isResolved()) { 3363 if (((bitField & 33554432) !== 0)) { 3364 receiver._promiseFulfilled(value, promise); 3365 } else { 3366 receiver._promiseRejected(value, promise); 3367 } 3368 } 3369 } else if (isPromise) { 3370 if (asyncGuaranteed) promise._setAsyncGuaranteed(); 3371 if (((bitField & 33554432) !== 0)) { 3372 promise._fulfill(value); 3373 } else { 3374 promise._reject(value); 3375 } 3376 } 3377}; 3378 3379Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { 3380 var handler = ctx.handler; 3381 var promise = ctx.promise; 3382 var receiver = ctx.receiver; 3383 var value = ctx.value; 3384 if (typeof handler === "function") { 3385 if (!(promise instanceof Promise)) { 3386 handler.call(receiver, value, promise); 3387 } else { 3388 this._settlePromiseFromHandler(handler, receiver, value, promise); 3389 } 3390 } else if (promise instanceof Promise) { 3391 promise._reject(value); 3392 } 3393}; 3394 3395Promise.prototype._settlePromiseCtx = function(ctx) { 3396 this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); 3397}; 3398 3399Promise.prototype._settlePromise0 = function(handler, value, bitField) { 3400 var promise = this._promise0; 3401 var receiver = this._receiverAt(0); 3402 this._promise0 = undefined; 3403 this._receiver0 = undefined; 3404 this._settlePromise(promise, handler, receiver, value); 3405}; 3406 3407Promise.prototype._clearCallbackDataAtIndex = function(index) { 3408 var base = index * 4 - 4; 3409 this[base + 2] = 3410 this[base + 3] = 3411 this[base + 0] = 3412 this[base + 1] = undefined; 3413}; 3414 3415Promise.prototype._fulfill = function (value) { 3416 var bitField = this._bitField; 3417 if (((bitField & 117506048) >>> 16)) return; 3418 if (value === this) { 3419 var err = makeSelfResolutionError(); 3420 this._attachExtraTrace(err); 3421 return this._reject(err); 3422 } 3423 this._setFulfilled(); 3424 this._rejectionHandler0 = value; 3425 3426 if ((bitField & 65535) > 0) { 3427 if (((bitField & 134217728) !== 0)) { 3428 this._settlePromises(); 3429 } else { 3430 async.settlePromises(this); 3431 } 3432 this._dereferenceTrace(); 3433 } 3434}; 3435 3436Promise.prototype._reject = function (reason) { 3437 var bitField = this._bitField; 3438 if (((bitField & 117506048) >>> 16)) return; 3439 this._setRejected(); 3440 this._fulfillmentHandler0 = reason; 3441 3442 if (this._isFinal()) { 3443 return async.fatalError(reason, util.isNode); 3444 } 3445 3446 if ((bitField & 65535) > 0) { 3447 async.settlePromises(this); 3448 } else { 3449 this._ensurePossibleRejectionHandled(); 3450 } 3451}; 3452 3453Promise.prototype._fulfillPromises = function (len, value) { 3454 for (var i = 1; i < len; i++) { 3455 var handler = this._fulfillmentHandlerAt(i); 3456 var promise = this._promiseAt(i); 3457 var receiver = this._receiverAt(i); 3458 this._clearCallbackDataAtIndex(i); 3459 this._settlePromise(promise, handler, receiver, value); 3460 } 3461}; 3462 3463Promise.prototype._rejectPromises = function (len, reason) { 3464 for (var i = 1; i < len; i++) { 3465 var handler = this._rejectionHandlerAt(i); 3466 var promise = this._promiseAt(i); 3467 var receiver = this._receiverAt(i); 3468 this._clearCallbackDataAtIndex(i); 3469 this._settlePromise(promise, handler, receiver, reason); 3470 } 3471}; 3472 3473Promise.prototype._settlePromises = function () { 3474 var bitField = this._bitField; 3475 var len = (bitField & 65535); 3476 3477 if (len > 0) { 3478 if (((bitField & 16842752) !== 0)) { 3479 var reason = this._fulfillmentHandler0; 3480 this._settlePromise0(this._rejectionHandler0, reason, bitField); 3481 this._rejectPromises(len, reason); 3482 } else { 3483 var value = this._rejectionHandler0; 3484 this._settlePromise0(this._fulfillmentHandler0, value, bitField); 3485 this._fulfillPromises(len, value); 3486 } 3487 this._setLength(0); 3488 } 3489 this._clearCancellationData(); 3490}; 3491 3492Promise.prototype._settledValue = function() { 3493 var bitField = this._bitField; 3494 if (((bitField & 33554432) !== 0)) { 3495 return this._rejectionHandler0; 3496 } else if (((bitField & 16777216) !== 0)) { 3497 return this._fulfillmentHandler0; 3498 } 3499}; 3500 3501if (typeof Symbol !== "undefined" && Symbol.toStringTag) { 3502 es5.defineProperty(Promise.prototype, Symbol.toStringTag, { 3503 get: function () { 3504 return "Object"; 3505 } 3506 }); 3507} 3508 3509function deferResolve(v) {this.promise._resolveCallback(v);} 3510function deferReject(v) {this.promise._rejectCallback(v, false);} 3511 3512Promise.defer = Promise.pending = function() { 3513 debug.deprecated("Promise.defer", "new Promise"); 3514 var promise = new Promise(INTERNAL); 3515 return { 3516 promise: promise, 3517 resolve: deferResolve, 3518 reject: deferReject 3519 }; 3520}; 3521 3522util.notEnumerableProp(Promise, 3523 "_makeSelfResolutionError", 3524 makeSelfResolutionError); 3525 3526_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, 3527 debug); 3528_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); 3529_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); 3530_dereq_("./direct_resolve")(Promise); 3531_dereq_("./synchronous_inspection")(Promise); 3532_dereq_("./join")( 3533 Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); 3534Promise.Promise = Promise; 3535Promise.version = "3.5.5"; 3536_dereq_('./call_get.js')(Promise); 3537_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); 3538_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); 3539_dereq_('./nodeify.js')(Promise); 3540_dereq_('./promisify.js')(Promise, INTERNAL); 3541_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); 3542_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); 3543_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); 3544_dereq_('./settle.js')(Promise, PromiseArray, debug); 3545_dereq_('./some.js')(Promise, PromiseArray, apiRejection); 3546_dereq_('./timers.js')(Promise, INTERNAL, debug); 3547_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); 3548_dereq_('./any.js')(Promise); 3549_dereq_('./each.js')(Promise, INTERNAL); 3550_dereq_('./filter.js')(Promise, INTERNAL); 3551 3552 util.toFastProperties(Promise); 3553 util.toFastProperties(Promise.prototype); 3554 function fillTypes(value) { 3555 var p = new Promise(INTERNAL); 3556 p._fulfillmentHandler0 = value; 3557 p._rejectionHandler0 = value; 3558 p._promise0 = value; 3559 p._receiver0 = value; 3560 } 3561 // Complete slack tracking, opt out of field-type tracking and 3562 // stabilize map 3563 fillTypes({a: 1}); 3564 fillTypes({b: 2}); 3565 fillTypes({c: 3}); 3566 fillTypes(1); 3567 fillTypes(function(){}); 3568 fillTypes(undefined); 3569 fillTypes(false); 3570 fillTypes(new Promise(INTERNAL)); 3571 debug.setBounds(Async.firstLineError, util.lastLineError); 3572 return Promise; 3573 3574}; 3575 3576},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ 3577"use strict"; 3578module.exports = function(Promise, INTERNAL, tryConvertToPromise, 3579 apiRejection, Proxyable) { 3580var util = _dereq_("./util"); 3581var isArray = util.isArray; 3582 3583function toResolutionValue(val) { 3584 switch(val) { 3585 case -2: return []; 3586 case -3: return {}; 3587 case -6: return new Map(); 3588 } 3589} 3590 3591function PromiseArray(values) { 3592 var promise = this._promise = new Promise(INTERNAL); 3593 if (values instanceof Promise) { 3594 promise._propagateFrom(values, 3); 3595 } 3596 promise._setOnCancel(this); 3597 this._values = values; 3598 this._length = 0; 3599 this._totalResolved = 0; 3600 this._init(undefined, -2); 3601} 3602util.inherits(PromiseArray, Proxyable); 3603 3604PromiseArray.prototype.length = function () { 3605 return this._length; 3606}; 3607 3608PromiseArray.prototype.promise = function () { 3609 return this._promise; 3610}; 3611 3612PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { 3613 var values = tryConvertToPromise(this._values, this._promise); 3614 if (values instanceof Promise) { 3615 values = values._target(); 3616 var bitField = values._bitField; 3617 ; 3618 this._values = values; 3619 3620 if (((bitField & 50397184) === 0)) { 3621 this._promise._setAsyncGuaranteed(); 3622 return values._then( 3623 init, 3624 this._reject, 3625 undefined, 3626 this, 3627 resolveValueIfEmpty 3628 ); 3629 } else if (((bitField & 33554432) !== 0)) { 3630 values = values._value(); 3631 } else if (((bitField & 16777216) !== 0)) { 3632 return this._reject(values._reason()); 3633 } else { 3634 return this._cancel(); 3635 } 3636 } 3637 values = util.asArray(values); 3638 if (values === null) { 3639 var err = apiRejection( 3640 "expecting an array or an iterable object but got " + util.classString(values)).reason(); 3641 this._promise._rejectCallback(err, false); 3642 return; 3643 } 3644 3645 if (values.length === 0) { 3646 if (resolveValueIfEmpty === -5) { 3647 this._resolveEmptyArray(); 3648 } 3649 else { 3650 this._resolve(toResolutionValue(resolveValueIfEmpty)); 3651 } 3652 return; 3653 } 3654 this._iterate(values); 3655}; 3656 3657PromiseArray.prototype._iterate = function(values) { 3658 var len = this.getActualLength(values.length); 3659 this._length = len; 3660 this._values = this.shouldCopyValues() ? new Array(len) : this._values; 3661 var result = this._promise; 3662 var isResolved = false; 3663 var bitField = null; 3664 for (var i = 0; i < len; ++i) { 3665 var maybePromise = tryConvertToPromise(values[i], result); 3666 3667 if (maybePromise instanceof Promise) { 3668 maybePromise = maybePromise._target(); 3669 bitField = maybePromise._bitField; 3670 } else { 3671 bitField = null; 3672 } 3673 3674 if (isResolved) { 3675 if (bitField !== null) { 3676 maybePromise.suppressUnhandledRejections(); 3677 } 3678 } else if (bitField !== null) { 3679 if (((bitField & 50397184) === 0)) { 3680 maybePromise._proxy(this, i); 3681 this._values[i] = maybePromise; 3682 } else if (((bitField & 33554432) !== 0)) { 3683 isResolved = this._promiseFulfilled(maybePromise._value(), i); 3684 } else if (((bitField & 16777216) !== 0)) { 3685 isResolved = this._promiseRejected(maybePromise._reason(), i); 3686 } else { 3687 isResolved = this._promiseCancelled(i); 3688 } 3689 } else { 3690 isResolved = this._promiseFulfilled(maybePromise, i); 3691 } 3692 } 3693 if (!isResolved) result._setAsyncGuaranteed(); 3694}; 3695 3696PromiseArray.prototype._isResolved = function () { 3697 return this._values === null; 3698}; 3699 3700PromiseArray.prototype._resolve = function (value) { 3701 this._values = null; 3702 this._promise._fulfill(value); 3703}; 3704 3705PromiseArray.prototype._cancel = function() { 3706 if (this._isResolved() || !this._promise._isCancellable()) return; 3707 this._values = null; 3708 this._promise._cancel(); 3709}; 3710 3711PromiseArray.prototype._reject = function (reason) { 3712 this._values = null; 3713 this._promise._rejectCallback(reason, false); 3714}; 3715 3716PromiseArray.prototype._promiseFulfilled = function (value, index) { 3717 this._values[index] = value; 3718 var totalResolved = ++this._totalResolved; 3719 if (totalResolved >= this._length) { 3720 this._resolve(this._values); 3721 return true; 3722 } 3723 return false; 3724}; 3725 3726PromiseArray.prototype._promiseCancelled = function() { 3727 this._cancel(); 3728 return true; 3729}; 3730 3731PromiseArray.prototype._promiseRejected = function (reason) { 3732 this._totalResolved++; 3733 this._reject(reason); 3734 return true; 3735}; 3736 3737PromiseArray.prototype._resultCancelled = function() { 3738 if (this._isResolved()) return; 3739 var values = this._values; 3740 this._cancel(); 3741 if (values instanceof Promise) { 3742 values.cancel(); 3743 } else { 3744 for (var i = 0; i < values.length; ++i) { 3745 if (values[i] instanceof Promise) { 3746 values[i].cancel(); 3747 } 3748 } 3749 } 3750}; 3751 3752PromiseArray.prototype.shouldCopyValues = function () { 3753 return true; 3754}; 3755 3756PromiseArray.prototype.getActualLength = function (len) { 3757 return len; 3758}; 3759 3760return PromiseArray; 3761}; 3762 3763},{"./util":36}],24:[function(_dereq_,module,exports){ 3764"use strict"; 3765module.exports = function(Promise, INTERNAL) { 3766var THIS = {}; 3767var util = _dereq_("./util"); 3768var nodebackForPromise = _dereq_("./nodeback"); 3769var withAppended = util.withAppended; 3770var maybeWrapAsError = util.maybeWrapAsError; 3771var canEvaluate = util.canEvaluate; 3772var TypeError = _dereq_("./errors").TypeError; 3773var defaultSuffix = "Async"; 3774var defaultPromisified = {__isPromisified__: true}; 3775var noCopyProps = [ 3776 "arity", "length", 3777 "name", 3778 "arguments", 3779 "caller", 3780 "callee", 3781 "prototype", 3782 "__isPromisified__" 3783]; 3784var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); 3785 3786var defaultFilter = function(name) { 3787 return util.isIdentifier(name) && 3788 name.charAt(0) !== "_" && 3789 name !== "constructor"; 3790}; 3791 3792function propsFilter(key) { 3793 return !noCopyPropsPattern.test(key); 3794} 3795 3796function isPromisified(fn) { 3797 try { 3798 return fn.__isPromisified__ === true; 3799 } 3800 catch (e) { 3801 return false; 3802 } 3803} 3804 3805function hasPromisified(obj, key, suffix) { 3806 var val = util.getDataPropertyOrDefault(obj, key + suffix, 3807 defaultPromisified); 3808 return val ? isPromisified(val) : false; 3809} 3810function checkValid(ret, suffix, suffixRegexp) { 3811 for (var i = 0; i < ret.length; i += 2) { 3812 var key = ret[i]; 3813 if (suffixRegexp.test(key)) { 3814 var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); 3815 for (var j = 0; j < ret.length; j += 2) { 3816 if (ret[j] === keyWithoutAsyncSuffix) { 3817 throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" 3818 .replace("%s", suffix)); 3819 } 3820 } 3821 } 3822 } 3823} 3824 3825function promisifiableMethods(obj, suffix, suffixRegexp, filter) { 3826 var keys = util.inheritedDataKeys(obj); 3827 var ret = []; 3828 for (var i = 0; i < keys.length; ++i) { 3829 var key = keys[i]; 3830 var value = obj[key]; 3831 var passesDefaultFilter = filter === defaultFilter 3832 ? true : defaultFilter(key, value, obj); 3833 if (typeof value === "function" && 3834 !isPromisified(value) && 3835 !hasPromisified(obj, key, suffix) && 3836 filter(key, value, obj, passesDefaultFilter)) { 3837 ret.push(key, value); 3838 } 3839 } 3840 checkValid(ret, suffix, suffixRegexp); 3841 return ret; 3842} 3843 3844var escapeIdentRegex = function(str) { 3845 return str.replace(/([$])/, "\\$"); 3846}; 3847 3848var makeNodePromisifiedEval; 3849if (!true) { 3850var switchCaseArgumentOrder = function(likelyArgumentCount) { 3851 var ret = [likelyArgumentCount]; 3852 var min = Math.max(0, likelyArgumentCount - 1 - 3); 3853 for(var i = likelyArgumentCount - 1; i >= min; --i) { 3854 ret.push(i); 3855 } 3856 for(var i = likelyArgumentCount + 1; i <= 3; ++i) { 3857 ret.push(i); 3858 } 3859 return ret; 3860}; 3861 3862var argumentSequence = function(argumentCount) { 3863 return util.filledRange(argumentCount, "_arg", ""); 3864}; 3865 3866var parameterDeclaration = function(parameterCount) { 3867 return util.filledRange( 3868 Math.max(parameterCount, 3), "_arg", ""); 3869}; 3870 3871var parameterCount = function(fn) { 3872 if (typeof fn.length === "number") { 3873 return Math.max(Math.min(fn.length, 1023 + 1), 0); 3874 } 3875 return 0; 3876}; 3877 3878makeNodePromisifiedEval = 3879function(callback, receiver, originalName, fn, _, multiArgs) { 3880 var newParameterCount = Math.max(0, parameterCount(fn) - 1); 3881 var argumentOrder = switchCaseArgumentOrder(newParameterCount); 3882 var shouldProxyThis = typeof callback === "string" || receiver === THIS; 3883 3884 function generateCallForArgumentCount(count) { 3885 var args = argumentSequence(count).join(", "); 3886 var comma = count > 0 ? ", " : ""; 3887 var ret; 3888 if (shouldProxyThis) { 3889 ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; 3890 } else { 3891 ret = receiver === undefined 3892 ? "ret = callback({{args}}, nodeback); break;\n" 3893 : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; 3894 } 3895 return ret.replace("{{args}}", args).replace(", ", comma); 3896 } 3897 3898 function generateArgumentSwitchCase() { 3899 var ret = ""; 3900 for (var i = 0; i < argumentOrder.length; ++i) { 3901 ret += "case " + argumentOrder[i] +":" + 3902 generateCallForArgumentCount(argumentOrder[i]); 3903 } 3904 3905 ret += " \n\ 3906 default: \n\ 3907 var args = new Array(len + 1); \n\ 3908 var i = 0; \n\ 3909 for (var i = 0; i < len; ++i) { \n\ 3910 args[i] = arguments[i]; \n\ 3911 } \n\ 3912 args[i] = nodeback; \n\ 3913 [CodeForCall] \n\ 3914 break; \n\ 3915 ".replace("[CodeForCall]", (shouldProxyThis 3916 ? "ret = callback.apply(this, args);\n" 3917 : "ret = callback.apply(receiver, args);\n")); 3918 return ret; 3919 } 3920 3921 var getFunctionCode = typeof callback === "string" 3922 ? ("this != null ? this['"+callback+"'] : fn") 3923 : "fn"; 3924 var body = "'use strict'; \n\ 3925 var ret = function (Parameters) { \n\ 3926 'use strict'; \n\ 3927 var len = arguments.length; \n\ 3928 var promise = new Promise(INTERNAL); \n\ 3929 promise._captureStackTrace(); \n\ 3930 var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ 3931 var ret; \n\ 3932 var callback = tryCatch([GetFunctionCode]); \n\ 3933 switch(len) { \n\ 3934 [CodeForSwitchCase] \n\ 3935 } \n\ 3936 if (ret === errorObj) { \n\ 3937 promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ 3938 } \n\ 3939 if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ 3940 return promise; \n\ 3941 }; \n\ 3942 notEnumerableProp(ret, '__isPromisified__', true); \n\ 3943 return ret; \n\ 3944 ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) 3945 .replace("[GetFunctionCode]", getFunctionCode); 3946 body = body.replace("Parameters", parameterDeclaration(newParameterCount)); 3947 return new Function("Promise", 3948 "fn", 3949 "receiver", 3950 "withAppended", 3951 "maybeWrapAsError", 3952 "nodebackForPromise", 3953 "tryCatch", 3954 "errorObj", 3955 "notEnumerableProp", 3956 "INTERNAL", 3957 body)( 3958 Promise, 3959 fn, 3960 receiver, 3961 withAppended, 3962 maybeWrapAsError, 3963 nodebackForPromise, 3964 util.tryCatch, 3965 util.errorObj, 3966 util.notEnumerableProp, 3967 INTERNAL); 3968}; 3969} 3970 3971function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { 3972 var defaultThis = (function() {return this;})(); 3973 var method = callback; 3974 if (typeof method === "string") { 3975 callback = fn; 3976 } 3977 function promisified() { 3978 var _receiver = receiver; 3979 if (receiver === THIS) _receiver = this; 3980 var promise = new Promise(INTERNAL); 3981 promise._captureStackTrace(); 3982 var cb = typeof method === "string" && this !== defaultThis 3983 ? this[method] : callback; 3984 var fn = nodebackForPromise(promise, multiArgs); 3985 try { 3986 cb.apply(_receiver, withAppended(arguments, fn)); 3987 } catch(e) { 3988 promise._rejectCallback(maybeWrapAsError(e), true, true); 3989 } 3990 if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); 3991 return promise; 3992 } 3993 util.notEnumerableProp(promisified, "__isPromisified__", true); 3994 return promisified; 3995} 3996 3997var makeNodePromisified = canEvaluate 3998 ? makeNodePromisifiedEval 3999 : makeNodePromisifiedClosure; 4000 4001function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { 4002 var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); 4003 var methods = 4004 promisifiableMethods(obj, suffix, suffixRegexp, filter); 4005 4006 for (var i = 0, len = methods.length; i < len; i+= 2) { 4007 var key = methods[i]; 4008 var fn = methods[i+1]; 4009 var promisifiedKey = key + suffix; 4010 if (promisifier === makeNodePromisified) { 4011 obj[promisifiedKey] = 4012 makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); 4013 } else { 4014 var promisified = promisifier(fn, function() { 4015 return makeNodePromisified(key, THIS, key, 4016 fn, suffix, multiArgs); 4017 }); 4018 util.notEnumerableProp(promisified, "__isPromisified__", true); 4019 obj[promisifiedKey] = promisified; 4020 } 4021 } 4022 util.toFastProperties(obj); 4023 return obj; 4024} 4025 4026function promisify(callback, receiver, multiArgs) { 4027 return makeNodePromisified(callback, receiver, undefined, 4028 callback, null, multiArgs); 4029} 4030 4031Promise.promisify = function (fn, options) { 4032 if (typeof fn !== "function") { 4033 throw new TypeError("expecting a function but got " + util.classString(fn)); 4034 } 4035 if (isPromisified(fn)) { 4036 return fn; 4037 } 4038 options = Object(options); 4039 var receiver = options.context === undefined ? THIS : options.context; 4040 var multiArgs = !!options.multiArgs; 4041 var ret = promisify(fn, receiver, multiArgs); 4042 util.copyDescriptors(fn, ret, propsFilter); 4043 return ret; 4044}; 4045 4046Promise.promisifyAll = function (target, options) { 4047 if (typeof target !== "function" && typeof target !== "object") { 4048 throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 4049 } 4050 options = Object(options); 4051 var multiArgs = !!options.multiArgs; 4052 var suffix = options.suffix; 4053 if (typeof suffix !== "string") suffix = defaultSuffix; 4054 var filter = options.filter; 4055 if (typeof filter !== "function") filter = defaultFilter; 4056 var promisifier = options.promisifier; 4057 if (typeof promisifier !== "function") promisifier = makeNodePromisified; 4058 4059 if (!util.isIdentifier(suffix)) { 4060 throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 4061 } 4062 4063 var keys = util.inheritedDataKeys(target); 4064 for (var i = 0; i < keys.length; ++i) { 4065 var value = target[keys[i]]; 4066 if (keys[i] !== "constructor" && 4067 util.isClass(value)) { 4068 promisifyAll(value.prototype, suffix, filter, promisifier, 4069 multiArgs); 4070 promisifyAll(value, suffix, filter, promisifier, multiArgs); 4071 } 4072 } 4073 4074 return promisifyAll(target, suffix, filter, promisifier, multiArgs); 4075}; 4076}; 4077 4078 4079},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ 4080"use strict"; 4081module.exports = function( 4082 Promise, PromiseArray, tryConvertToPromise, apiRejection) { 4083var util = _dereq_("./util"); 4084var isObject = util.isObject; 4085var es5 = _dereq_("./es5"); 4086var Es6Map; 4087if (typeof Map === "function") Es6Map = Map; 4088 4089var mapToEntries = (function() { 4090 var index = 0; 4091 var size = 0; 4092 4093 function extractEntry(value, key) { 4094 this[index] = value; 4095 this[index + size] = key; 4096 index++; 4097 } 4098 4099 return function mapToEntries(map) { 4100 size = map.size; 4101 index = 0; 4102 var ret = new Array(map.size * 2); 4103 map.forEach(extractEntry, ret); 4104 return ret; 4105 }; 4106})(); 4107 4108var entriesToMap = function(entries) { 4109 var ret = new Es6Map(); 4110 var length = entries.length / 2 | 0; 4111 for (var i = 0; i < length; ++i) { 4112 var key = entries[length + i]; 4113 var value = entries[i]; 4114 ret.set(key, value); 4115 } 4116 return ret; 4117}; 4118 4119function PropertiesPromiseArray(obj) { 4120 var isMap = false; 4121 var entries; 4122 if (Es6Map !== undefined && obj instanceof Es6Map) { 4123 entries = mapToEntries(obj); 4124 isMap = true; 4125 } else { 4126 var keys = es5.keys(obj); 4127 var len = keys.length; 4128 entries = new Array(len * 2); 4129 for (var i = 0; i < len; ++i) { 4130 var key = keys[i]; 4131 entries[i] = obj[key]; 4132 entries[i + len] = key; 4133 } 4134 } 4135 this.constructor$(entries); 4136 this._isMap = isMap; 4137 this._init$(undefined, isMap ? -6 : -3); 4138} 4139util.inherits(PropertiesPromiseArray, PromiseArray); 4140 4141PropertiesPromiseArray.prototype._init = function () {}; 4142 4143PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { 4144 this._values[index] = value; 4145 var totalResolved = ++this._totalResolved; 4146 if (totalResolved >= this._length) { 4147 var val; 4148 if (this._isMap) { 4149 val = entriesToMap(this._values); 4150 } else { 4151 val = {}; 4152 var keyOffset = this.length(); 4153 for (var i = 0, len = this.length(); i < len; ++i) { 4154 val[this._values[i + keyOffset]] = this._values[i]; 4155 } 4156 } 4157 this._resolve(val); 4158 return true; 4159 } 4160 return false; 4161}; 4162 4163PropertiesPromiseArray.prototype.shouldCopyValues = function () { 4164 return false; 4165}; 4166 4167PropertiesPromiseArray.prototype.getActualLength = function (len) { 4168 return len >> 1; 4169}; 4170 4171function props(promises) { 4172 var ret; 4173 var castValue = tryConvertToPromise(promises); 4174 4175 if (!isObject(castValue)) { 4176 return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 4177 } else if (castValue instanceof Promise) { 4178 ret = castValue._then( 4179 Promise.props, undefined, undefined, undefined, undefined); 4180 } else { 4181 ret = new PropertiesPromiseArray(castValue).promise(); 4182 } 4183 4184 if (castValue instanceof Promise) { 4185 ret._propagateFrom(castValue, 2); 4186 } 4187 return ret; 4188} 4189 4190Promise.prototype.props = function () { 4191 return props(this); 4192}; 4193 4194Promise.props = function (promises) { 4195 return props(promises); 4196}; 4197}; 4198 4199},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ 4200"use strict"; 4201function arrayMove(src, srcIndex, dst, dstIndex, len) { 4202 for (var j = 0; j < len; ++j) { 4203 dst[j + dstIndex] = src[j + srcIndex]; 4204 src[j + srcIndex] = void 0; 4205 } 4206} 4207 4208function Queue(capacity) { 4209 this._capacity = capacity; 4210 this._length = 0; 4211 this._front = 0; 4212} 4213 4214Queue.prototype._willBeOverCapacity = function (size) { 4215 return this._capacity < size; 4216}; 4217 4218Queue.prototype._pushOne = function (arg) { 4219 var length = this.length(); 4220 this._checkCapacity(length + 1); 4221 var i = (this._front + length) & (this._capacity - 1); 4222 this[i] = arg; 4223 this._length = length + 1; 4224}; 4225 4226Queue.prototype.push = function (fn, receiver, arg) { 4227 var length = this.length() + 3; 4228 if (this._willBeOverCapacity(length)) { 4229 this._pushOne(fn); 4230 this._pushOne(receiver); 4231 this._pushOne(arg); 4232 return; 4233 } 4234 var j = this._front + length - 3; 4235 this._checkCapacity(length); 4236 var wrapMask = this._capacity - 1; 4237 this[(j + 0) & wrapMask] = fn; 4238 this[(j + 1) & wrapMask] = receiver; 4239 this[(j + 2) & wrapMask] = arg; 4240 this._length = length; 4241}; 4242 4243Queue.prototype.shift = function () { 4244 var front = this._front, 4245 ret = this[front]; 4246 4247 this[front] = undefined; 4248 this._front = (front + 1) & (this._capacity - 1); 4249 this._length--; 4250 return ret; 4251}; 4252 4253Queue.prototype.length = function () { 4254 return this._length; 4255}; 4256 4257Queue.prototype._checkCapacity = function (size) { 4258 if (this._capacity < size) { 4259 this._resizeTo(this._capacity << 1); 4260 } 4261}; 4262 4263Queue.prototype._resizeTo = function (capacity) { 4264 var oldCapacity = this._capacity; 4265 this._capacity = capacity; 4266 var front = this._front; 4267 var length = this._length; 4268 var moveItemsCount = (front + length) & (oldCapacity - 1); 4269 arrayMove(this, 0, this, oldCapacity, moveItemsCount); 4270}; 4271 4272module.exports = Queue; 4273 4274},{}],27:[function(_dereq_,module,exports){ 4275"use strict"; 4276module.exports = function( 4277 Promise, INTERNAL, tryConvertToPromise, apiRejection) { 4278var util = _dereq_("./util"); 4279 4280var raceLater = function (promise) { 4281 return promise.then(function(array) { 4282 return race(array, promise); 4283 }); 4284}; 4285 4286function race(promises, parent) { 4287 var maybePromise = tryConvertToPromise(promises); 4288 4289 if (maybePromise instanceof Promise) { 4290 return raceLater(maybePromise); 4291 } else { 4292 promises = util.asArray(promises); 4293 if (promises === null) 4294 return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); 4295 } 4296 4297 var ret = new Promise(INTERNAL); 4298 if (parent !== undefined) { 4299 ret._propagateFrom(parent, 3); 4300 } 4301 var fulfill = ret._fulfill; 4302 var reject = ret._reject; 4303 for (var i = 0, len = promises.length; i < len; ++i) { 4304 var val = promises[i]; 4305 4306 if (val === undefined && !(i in promises)) { 4307 continue; 4308 } 4309 4310 Promise.cast(val)._then(fulfill, reject, undefined, ret, null); 4311 } 4312 return ret; 4313} 4314 4315Promise.race = function (promises) { 4316 return race(promises, undefined); 4317}; 4318 4319Promise.prototype.race = function () { 4320 return race(this, undefined); 4321}; 4322 4323}; 4324 4325},{"./util":36}],28:[function(_dereq_,module,exports){ 4326"use strict"; 4327module.exports = function(Promise, 4328 PromiseArray, 4329 apiRejection, 4330 tryConvertToPromise, 4331 INTERNAL, 4332 debug) { 4333var getDomain = Promise._getDomain; 4334var util = _dereq_("./util"); 4335var tryCatch = util.tryCatch; 4336 4337function ReductionPromiseArray(promises, fn, initialValue, _each) { 4338 this.constructor$(promises); 4339 var domain = getDomain(); 4340 this._fn = domain === null ? fn : util.domainBind(domain, fn); 4341 if (initialValue !== undefined) { 4342 initialValue = Promise.resolve(initialValue); 4343 initialValue._attachCancellationCallback(this); 4344 } 4345 this._initialValue = initialValue; 4346 this._currentCancellable = null; 4347 if(_each === INTERNAL) { 4348 this._eachValues = Array(this._length); 4349 } else if (_each === 0) { 4350 this._eachValues = null; 4351 } else { 4352 this._eachValues = undefined; 4353 } 4354 this._promise._captureStackTrace(); 4355 this._init$(undefined, -5); 4356} 4357util.inherits(ReductionPromiseArray, PromiseArray); 4358 4359ReductionPromiseArray.prototype._gotAccum = function(accum) { 4360 if (this._eachValues !== undefined && 4361 this._eachValues !== null && 4362 accum !== INTERNAL) { 4363 this._eachValues.push(accum); 4364 } 4365}; 4366 4367ReductionPromiseArray.prototype._eachComplete = function(value) { 4368 if (this._eachValues !== null) { 4369 this._eachValues.push(value); 4370 } 4371 return this._eachValues; 4372}; 4373 4374ReductionPromiseArray.prototype._init = function() {}; 4375 4376ReductionPromiseArray.prototype._resolveEmptyArray = function() { 4377 this._resolve(this._eachValues !== undefined ? this._eachValues 4378 : this._initialValue); 4379}; 4380 4381ReductionPromiseArray.prototype.shouldCopyValues = function () { 4382 return false; 4383}; 4384 4385ReductionPromiseArray.prototype._resolve = function(value) { 4386 this._promise._resolveCallback(value); 4387 this._values = null; 4388}; 4389 4390ReductionPromiseArray.prototype._resultCancelled = function(sender) { 4391 if (sender === this._initialValue) return this._cancel(); 4392 if (this._isResolved()) return; 4393 this._resultCancelled$(); 4394 if (this._currentCancellable instanceof Promise) { 4395 this._currentCancellable.cancel(); 4396 } 4397 if (this._initialValue instanceof Promise) { 4398 this._initialValue.cancel(); 4399 } 4400}; 4401 4402ReductionPromiseArray.prototype._iterate = function (values) { 4403 this._values = values; 4404 var value; 4405 var i; 4406 var length = values.length; 4407 if (this._initialValue !== undefined) { 4408 value = this._initialValue; 4409 i = 0; 4410 } else { 4411 value = Promise.resolve(values[0]); 4412 i = 1; 4413 } 4414 4415 this._currentCancellable = value; 4416 4417 if (!value.isRejected()) { 4418 for (; i < length; ++i) { 4419 var ctx = { 4420 accum: null, 4421 value: values[i], 4422 index: i, 4423 length: length, 4424 array: this 4425 }; 4426 value = value._then(gotAccum, undefined, undefined, ctx, undefined); 4427 } 4428 } 4429 4430 if (this._eachValues !== undefined) { 4431 value = value 4432 ._then(this._eachComplete, undefined, undefined, this, undefined); 4433 } 4434 value._then(completed, completed, undefined, value, this); 4435}; 4436 4437Promise.prototype.reduce = function (fn, initialValue) { 4438 return reduce(this, fn, initialValue, null); 4439}; 4440 4441Promise.reduce = function (promises, fn, initialValue, _each) { 4442 return reduce(promises, fn, initialValue, _each); 4443}; 4444 4445function completed(valueOrReason, array) { 4446 if (this.isFulfilled()) { 4447 array._resolve(valueOrReason); 4448 } else { 4449 array._reject(valueOrReason); 4450 } 4451} 4452 4453function reduce(promises, fn, initialValue, _each) { 4454 if (typeof fn !== "function") { 4455 return apiRejection("expecting a function but got " + util.classString(fn)); 4456 } 4457 var array = new ReductionPromiseArray(promises, fn, initialValue, _each); 4458 return array.promise(); 4459} 4460 4461function gotAccum(accum) { 4462 this.accum = accum; 4463 this.array._gotAccum(accum); 4464 var value = tryConvertToPromise(this.value, this.array._promise); 4465 if (value instanceof Promise) { 4466 this.array._currentCancellable = value; 4467 return value._then(gotValue, undefined, undefined, this, undefined); 4468 } else { 4469 return gotValue.call(this, value); 4470 } 4471} 4472 4473function gotValue(value) { 4474 var array = this.array; 4475 var promise = array._promise; 4476 var fn = tryCatch(array._fn); 4477 promise._pushContext(); 4478 var ret; 4479 if (array._eachValues !== undefined) { 4480 ret = fn.call(promise._boundValue(), value, this.index, this.length); 4481 } else { 4482 ret = fn.call(promise._boundValue(), 4483 this.accum, value, this.index, this.length); 4484 } 4485 if (ret instanceof Promise) { 4486 array._currentCancellable = ret; 4487 } 4488 var promiseCreated = promise._popContext(); 4489 debug.checkForgottenReturns( 4490 ret, 4491 promiseCreated, 4492 array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", 4493 promise 4494 ); 4495 return ret; 4496} 4497}; 4498 4499},{"./util":36}],29:[function(_dereq_,module,exports){ 4500"use strict"; 4501var util = _dereq_("./util"); 4502var schedule; 4503var noAsyncScheduler = function() { 4504 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 4505}; 4506var NativePromise = util.getNativePromise(); 4507if (util.isNode && typeof MutationObserver === "undefined") { 4508 var GlobalSetImmediate = global.setImmediate; 4509 var ProcessNextTick = process.nextTick; 4510 schedule = util.isRecentNode 4511 ? function(fn) { GlobalSetImmediate.call(global, fn); } 4512 : function(fn) { ProcessNextTick.call(process, fn); }; 4513} else if (typeof NativePromise === "function" && 4514 typeof NativePromise.resolve === "function") { 4515 var nativePromise = NativePromise.resolve(); 4516 schedule = function(fn) { 4517 nativePromise.then(fn); 4518 }; 4519} else if ((typeof MutationObserver !== "undefined") && 4520 !(typeof window !== "undefined" && 4521 window.navigator && 4522 (window.navigator.standalone || window.cordova)) && 4523 ("classList" in document.documentElement)) { 4524 schedule = (function() { 4525 var div = document.createElement("div"); 4526 var opts = {attributes: true}; 4527 var toggleScheduled = false; 4528 var div2 = document.createElement("div"); 4529 var o2 = new MutationObserver(function() { 4530 div.classList.toggle("foo"); 4531 toggleScheduled = false; 4532 }); 4533 o2.observe(div2, opts); 4534 4535 var scheduleToggle = function() { 4536 if (toggleScheduled) return; 4537 toggleScheduled = true; 4538 div2.classList.toggle("foo"); 4539 }; 4540 4541 return function schedule(fn) { 4542 var o = new MutationObserver(function() { 4543 o.disconnect(); 4544 fn(); 4545 }); 4546 o.observe(div, opts); 4547 scheduleToggle(); 4548 }; 4549 })(); 4550} else if (typeof setImmediate !== "undefined") { 4551 schedule = function (fn) { 4552 setImmediate(fn); 4553 }; 4554} else if (typeof setTimeout !== "undefined") { 4555 schedule = function (fn) { 4556 setTimeout(fn, 0); 4557 }; 4558} else { 4559 schedule = noAsyncScheduler; 4560} 4561module.exports = schedule; 4562 4563},{"./util":36}],30:[function(_dereq_,module,exports){ 4564"use strict"; 4565module.exports = 4566 function(Promise, PromiseArray, debug) { 4567var PromiseInspection = Promise.PromiseInspection; 4568var util = _dereq_("./util"); 4569 4570function SettledPromiseArray(values) { 4571 this.constructor$(values); 4572} 4573util.inherits(SettledPromiseArray, PromiseArray); 4574 4575SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { 4576 this._values[index] = inspection; 4577 var totalResolved = ++this._totalResolved; 4578 if (totalResolved >= this._length) { 4579 this._resolve(this._values); 4580 return true; 4581 } 4582 return false; 4583}; 4584 4585SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { 4586 var ret = new PromiseInspection(); 4587 ret._bitField = 33554432; 4588 ret._settledValueField = value; 4589 return this._promiseResolved(index, ret); 4590}; 4591SettledPromiseArray.prototype._promiseRejected = function (reason, index) { 4592 var ret = new PromiseInspection(); 4593 ret._bitField = 16777216; 4594 ret._settledValueField = reason; 4595 return this._promiseResolved(index, ret); 4596}; 4597 4598Promise.settle = function (promises) { 4599 debug.deprecated(".settle()", ".reflect()"); 4600 return new SettledPromiseArray(promises).promise(); 4601}; 4602 4603Promise.prototype.settle = function () { 4604 return Promise.settle(this); 4605}; 4606}; 4607 4608},{"./util":36}],31:[function(_dereq_,module,exports){ 4609"use strict"; 4610module.exports = 4611function(Promise, PromiseArray, apiRejection) { 4612var util = _dereq_("./util"); 4613var RangeError = _dereq_("./errors").RangeError; 4614var AggregateError = _dereq_("./errors").AggregateError; 4615var isArray = util.isArray; 4616var CANCELLATION = {}; 4617 4618 4619function SomePromiseArray(values) { 4620 this.constructor$(values); 4621 this._howMany = 0; 4622 this._unwrap = false; 4623 this._initialized = false; 4624} 4625util.inherits(SomePromiseArray, PromiseArray); 4626 4627SomePromiseArray.prototype._init = function () { 4628 if (!this._initialized) { 4629 return; 4630 } 4631 if (this._howMany === 0) { 4632 this._resolve([]); 4633 return; 4634 } 4635 this._init$(undefined, -5); 4636 var isArrayResolved = isArray(this._values); 4637 if (!this._isResolved() && 4638 isArrayResolved && 4639 this._howMany > this._canPossiblyFulfill()) { 4640 this._reject(this._getRangeError(this.length())); 4641 } 4642}; 4643 4644SomePromiseArray.prototype.init = function () { 4645 this._initialized = true; 4646 this._init(); 4647}; 4648 4649SomePromiseArray.prototype.setUnwrap = function () { 4650 this._unwrap = true; 4651}; 4652 4653SomePromiseArray.prototype.howMany = function () { 4654 return this._howMany; 4655}; 4656 4657SomePromiseArray.prototype.setHowMany = function (count) { 4658 this._howMany = count; 4659}; 4660 4661SomePromiseArray.prototype._promiseFulfilled = function (value) { 4662 this._addFulfilled(value); 4663 if (this._fulfilled() === this.howMany()) { 4664 this._values.length = this.howMany(); 4665 if (this.howMany() === 1 && this._unwrap) { 4666 this._resolve(this._values[0]); 4667 } else { 4668 this._resolve(this._values); 4669 } 4670 return true; 4671 } 4672 return false; 4673 4674}; 4675SomePromiseArray.prototype._promiseRejected = function (reason) { 4676 this._addRejected(reason); 4677 return this._checkOutcome(); 4678}; 4679 4680SomePromiseArray.prototype._promiseCancelled = function () { 4681 if (this._values instanceof Promise || this._values == null) { 4682 return this._cancel(); 4683 } 4684 this._addRejected(CANCELLATION); 4685 return this._checkOutcome(); 4686}; 4687 4688SomePromiseArray.prototype._checkOutcome = function() { 4689 if (this.howMany() > this._canPossiblyFulfill()) { 4690 var e = new AggregateError(); 4691 for (var i = this.length(); i < this._values.length; ++i) { 4692 if (this._values[i] !== CANCELLATION) { 4693 e.push(this._values[i]); 4694 } 4695 } 4696 if (e.length > 0) { 4697 this._reject(e); 4698 } else { 4699 this._cancel(); 4700 } 4701 return true; 4702 } 4703 return false; 4704}; 4705 4706SomePromiseArray.prototype._fulfilled = function () { 4707 return this._totalResolved; 4708}; 4709 4710SomePromiseArray.prototype._rejected = function () { 4711 return this._values.length - this.length(); 4712}; 4713 4714SomePromiseArray.prototype._addRejected = function (reason) { 4715 this._values.push(reason); 4716}; 4717 4718SomePromiseArray.prototype._addFulfilled = function (value) { 4719 this._values[this._totalResolved++] = value; 4720}; 4721 4722SomePromiseArray.prototype._canPossiblyFulfill = function () { 4723 return this.length() - this._rejected(); 4724}; 4725 4726SomePromiseArray.prototype._getRangeError = function (count) { 4727 var message = "Input array must contain at least " + 4728 this._howMany + " items but contains only " + count + " items"; 4729 return new RangeError(message); 4730}; 4731 4732SomePromiseArray.prototype._resolveEmptyArray = function () { 4733 this._reject(this._getRangeError(0)); 4734}; 4735 4736function some(promises, howMany) { 4737 if ((howMany | 0) !== howMany || howMany < 0) { 4738 return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 4739 } 4740 var ret = new SomePromiseArray(promises); 4741 var promise = ret.promise(); 4742 ret.setHowMany(howMany); 4743 ret.init(); 4744 return promise; 4745} 4746 4747Promise.some = function (promises, howMany) { 4748 return some(promises, howMany); 4749}; 4750 4751Promise.prototype.some = function (howMany) { 4752 return some(this, howMany); 4753}; 4754 4755Promise._SomePromiseArray = SomePromiseArray; 4756}; 4757 4758},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ 4759"use strict"; 4760module.exports = function(Promise) { 4761function PromiseInspection(promise) { 4762 if (promise !== undefined) { 4763 promise = promise._target(); 4764 this._bitField = promise._bitField; 4765 this._settledValueField = promise._isFateSealed() 4766 ? promise._settledValue() : undefined; 4767 } 4768 else { 4769 this._bitField = 0; 4770 this._settledValueField = undefined; 4771 } 4772} 4773 4774PromiseInspection.prototype._settledValue = function() { 4775 return this._settledValueField; 4776}; 4777 4778var value = PromiseInspection.prototype.value = function () { 4779 if (!this.isFulfilled()) { 4780 throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 4781 } 4782 return this._settledValue(); 4783}; 4784 4785var reason = PromiseInspection.prototype.error = 4786PromiseInspection.prototype.reason = function () { 4787 if (!this.isRejected()) { 4788 throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); 4789 } 4790 return this._settledValue(); 4791}; 4792 4793var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { 4794 return (this._bitField & 33554432) !== 0; 4795}; 4796 4797var isRejected = PromiseInspection.prototype.isRejected = function () { 4798 return (this._bitField & 16777216) !== 0; 4799}; 4800 4801var isPending = PromiseInspection.prototype.isPending = function () { 4802 return (this._bitField & 50397184) === 0; 4803}; 4804 4805var isResolved = PromiseInspection.prototype.isResolved = function () { 4806 return (this._bitField & 50331648) !== 0; 4807}; 4808 4809PromiseInspection.prototype.isCancelled = function() { 4810 return (this._bitField & 8454144) !== 0; 4811}; 4812 4813Promise.prototype.__isCancelled = function() { 4814 return (this._bitField & 65536) === 65536; 4815}; 4816 4817Promise.prototype._isCancelled = function() { 4818 return this._target().__isCancelled(); 4819}; 4820 4821Promise.prototype.isCancelled = function() { 4822 return (this._target()._bitField & 8454144) !== 0; 4823}; 4824 4825Promise.prototype.isPending = function() { 4826 return isPending.call(this._target()); 4827}; 4828 4829Promise.prototype.isRejected = function() { 4830 return isRejected.call(this._target()); 4831}; 4832 4833Promise.prototype.isFulfilled = function() { 4834 return isFulfilled.call(this._target()); 4835}; 4836 4837Promise.prototype.isResolved = function() { 4838 return isResolved.call(this._target()); 4839}; 4840 4841Promise.prototype.value = function() { 4842 return value.call(this._target()); 4843}; 4844 4845Promise.prototype.reason = function() { 4846 var target = this._target(); 4847 target._unsetRejectionIsUnhandled(); 4848 return reason.call(target); 4849}; 4850 4851Promise.prototype._value = function() { 4852 return this._settledValue(); 4853}; 4854 4855Promise.prototype._reason = function() { 4856 this._unsetRejectionIsUnhandled(); 4857 return this._settledValue(); 4858}; 4859 4860Promise.PromiseInspection = PromiseInspection; 4861}; 4862 4863},{}],33:[function(_dereq_,module,exports){ 4864"use strict"; 4865module.exports = function(Promise, INTERNAL) { 4866var util = _dereq_("./util"); 4867var errorObj = util.errorObj; 4868var isObject = util.isObject; 4869 4870function tryConvertToPromise(obj, context) { 4871 if (isObject(obj)) { 4872 if (obj instanceof Promise) return obj; 4873 var then = getThen(obj); 4874 if (then === errorObj) { 4875 if (context) context._pushContext(); 4876 var ret = Promise.reject(then.e); 4877 if (context) context._popContext(); 4878 return ret; 4879 } else if (typeof then === "function") { 4880 if (isAnyBluebirdPromise(obj)) { 4881 var ret = new Promise(INTERNAL); 4882 obj._then( 4883 ret._fulfill, 4884 ret._reject, 4885 undefined, 4886 ret, 4887 null 4888 ); 4889 return ret; 4890 } 4891 return doThenable(obj, then, context); 4892 } 4893 } 4894 return obj; 4895} 4896 4897function doGetThen(obj) { 4898 return obj.then; 4899} 4900 4901function getThen(obj) { 4902 try { 4903 return doGetThen(obj); 4904 } catch (e) { 4905 errorObj.e = e; 4906 return errorObj; 4907 } 4908} 4909 4910var hasProp = {}.hasOwnProperty; 4911function isAnyBluebirdPromise(obj) { 4912 try { 4913 return hasProp.call(obj, "_promise0"); 4914 } catch (e) { 4915 return false; 4916 } 4917} 4918 4919function doThenable(x, then, context) { 4920 var promise = new Promise(INTERNAL); 4921 var ret = promise; 4922 if (context) context._pushContext(); 4923 promise._captureStackTrace(); 4924 if (context) context._popContext(); 4925 var synchronous = true; 4926 var result = util.tryCatch(then).call(x, resolve, reject); 4927 synchronous = false; 4928 4929 if (promise && result === errorObj) { 4930 promise._rejectCallback(result.e, true, true); 4931 promise = null; 4932 } 4933 4934 function resolve(value) { 4935 if (!promise) return; 4936 promise._resolveCallback(value); 4937 promise = null; 4938 } 4939 4940 function reject(reason) { 4941 if (!promise) return; 4942 promise._rejectCallback(reason, synchronous, true); 4943 promise = null; 4944 } 4945 return ret; 4946} 4947 4948return tryConvertToPromise; 4949}; 4950 4951},{"./util":36}],34:[function(_dereq_,module,exports){ 4952"use strict"; 4953module.exports = function(Promise, INTERNAL, debug) { 4954var util = _dereq_("./util"); 4955var TimeoutError = Promise.TimeoutError; 4956 4957function HandleWrapper(handle) { 4958 this.handle = handle; 4959} 4960 4961HandleWrapper.prototype._resultCancelled = function() { 4962 clearTimeout(this.handle); 4963}; 4964 4965var afterValue = function(value) { return delay(+this).thenReturn(value); }; 4966var delay = Promise.delay = function (ms, value) { 4967 var ret; 4968 var handle; 4969 if (value !== undefined) { 4970 ret = Promise.resolve(value) 4971 ._then(afterValue, null, null, ms, undefined); 4972 if (debug.cancellation() && value instanceof Promise) { 4973 ret._setOnCancel(value); 4974 } 4975 } else { 4976 ret = new Promise(INTERNAL); 4977 handle = setTimeout(function() { ret._fulfill(); }, +ms); 4978 if (debug.cancellation()) { 4979 ret._setOnCancel(new HandleWrapper(handle)); 4980 } 4981 ret._captureStackTrace(); 4982 } 4983 ret._setAsyncGuaranteed(); 4984 return ret; 4985}; 4986 4987Promise.prototype.delay = function (ms) { 4988 return delay(ms, this); 4989}; 4990 4991var afterTimeout = function (promise, message, parent) { 4992 var err; 4993 if (typeof message !== "string") { 4994 if (message instanceof Error) { 4995 err = message; 4996 } else { 4997 err = new TimeoutError("operation timed out"); 4998 } 4999 } else { 5000 err = new TimeoutError(message); 5001 } 5002 util.markAsOriginatingFromRejection(err); 5003 promise._attachExtraTrace(err); 5004 promise._reject(err); 5005 5006 if (parent != null) { 5007 parent.cancel(); 5008 } 5009}; 5010 5011function successClear(value) { 5012 clearTimeout(this.handle); 5013 return value; 5014} 5015 5016function failureClear(reason) { 5017 clearTimeout(this.handle); 5018 throw reason; 5019} 5020 5021Promise.prototype.timeout = function (ms, message) { 5022 ms = +ms; 5023 var ret, parent; 5024 5025 var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { 5026 if (ret.isPending()) { 5027 afterTimeout(ret, message, parent); 5028 } 5029 }, ms)); 5030 5031 if (debug.cancellation()) { 5032 parent = this.then(); 5033 ret = parent._then(successClear, failureClear, 5034 undefined, handleWrapper, undefined); 5035 ret._setOnCancel(handleWrapper); 5036 } else { 5037 ret = this._then(successClear, failureClear, 5038 undefined, handleWrapper, undefined); 5039 } 5040 5041 return ret; 5042}; 5043 5044}; 5045 5046},{"./util":36}],35:[function(_dereq_,module,exports){ 5047"use strict"; 5048module.exports = function (Promise, apiRejection, tryConvertToPromise, 5049 createContext, INTERNAL, debug) { 5050 var util = _dereq_("./util"); 5051 var TypeError = _dereq_("./errors").TypeError; 5052 var inherits = _dereq_("./util").inherits; 5053 var errorObj = util.errorObj; 5054 var tryCatch = util.tryCatch; 5055 var NULL = {}; 5056 5057 function thrower(e) { 5058 setTimeout(function(){throw e;}, 0); 5059 } 5060 5061 function castPreservingDisposable(thenable) { 5062 var maybePromise = tryConvertToPromise(thenable); 5063 if (maybePromise !== thenable && 5064 typeof thenable._isDisposable === "function" && 5065 typeof thenable._getDisposer === "function" && 5066 thenable._isDisposable()) { 5067 maybePromise._setDisposable(thenable._getDisposer()); 5068 } 5069 return maybePromise; 5070 } 5071 function dispose(resources, inspection) { 5072 var i = 0; 5073 var len = resources.length; 5074 var ret = new Promise(INTERNAL); 5075 function iterator() { 5076 if (i >= len) return ret._fulfill(); 5077 var maybePromise = castPreservingDisposable(resources[i++]); 5078 if (maybePromise instanceof Promise && 5079 maybePromise._isDisposable()) { 5080 try { 5081 maybePromise = tryConvertToPromise( 5082 maybePromise._getDisposer().tryDispose(inspection), 5083 resources.promise); 5084 } catch (e) { 5085 return thrower(e); 5086 } 5087 if (maybePromise instanceof Promise) { 5088 return maybePromise._then(iterator, thrower, 5089 null, null, null); 5090 } 5091 } 5092 iterator(); 5093 } 5094 iterator(); 5095 return ret; 5096 } 5097 5098 function Disposer(data, promise, context) { 5099 this._data = data; 5100 this._promise = promise; 5101 this._context = context; 5102 } 5103 5104 Disposer.prototype.data = function () { 5105 return this._data; 5106 }; 5107 5108 Disposer.prototype.promise = function () { 5109 return this._promise; 5110 }; 5111 5112 Disposer.prototype.resource = function () { 5113 if (this.promise().isFulfilled()) { 5114 return this.promise().value(); 5115 } 5116 return NULL; 5117 }; 5118 5119 Disposer.prototype.tryDispose = function(inspection) { 5120 var resource = this.resource(); 5121 var context = this._context; 5122 if (context !== undefined) context._pushContext(); 5123 var ret = resource !== NULL 5124 ? this.doDispose(resource, inspection) : null; 5125 if (context !== undefined) context._popContext(); 5126 this._promise._unsetDisposable(); 5127 this._data = null; 5128 return ret; 5129 }; 5130 5131 Disposer.isDisposer = function (d) { 5132 return (d != null && 5133 typeof d.resource === "function" && 5134 typeof d.tryDispose === "function"); 5135 }; 5136 5137 function FunctionDisposer(fn, promise, context) { 5138 this.constructor$(fn, promise, context); 5139 } 5140 inherits(FunctionDisposer, Disposer); 5141 5142 FunctionDisposer.prototype.doDispose = function (resource, inspection) { 5143 var fn = this.data(); 5144 return fn.call(resource, resource, inspection); 5145 }; 5146 5147 function maybeUnwrapDisposer(value) { 5148 if (Disposer.isDisposer(value)) { 5149 this.resources[this.index]._setDisposable(value); 5150 return value.promise(); 5151 } 5152 return value; 5153 } 5154 5155 function ResourceList(length) { 5156 this.length = length; 5157 this.promise = null; 5158 this[length-1] = null; 5159 } 5160 5161 ResourceList.prototype._resultCancelled = function() { 5162 var len = this.length; 5163 for (var i = 0; i < len; ++i) { 5164 var item = this[i]; 5165 if (item instanceof Promise) { 5166 item.cancel(); 5167 } 5168 } 5169 }; 5170 5171 Promise.using = function () { 5172 var len = arguments.length; 5173 if (len < 2) return apiRejection( 5174 "you must pass at least 2 arguments to Promise.using"); 5175 var fn = arguments[len - 1]; 5176 if (typeof fn !== "function") { 5177 return apiRejection("expecting a function but got " + util.classString(fn)); 5178 } 5179 var input; 5180 var spreadArgs = true; 5181 if (len === 2 && Array.isArray(arguments[0])) { 5182 input = arguments[0]; 5183 len = input.length; 5184 spreadArgs = false; 5185 } else { 5186 input = arguments; 5187 len--; 5188 } 5189 var resources = new ResourceList(len); 5190 for (var i = 0; i < len; ++i) { 5191 var resource = input[i]; 5192 if (Disposer.isDisposer(resource)) { 5193 var disposer = resource; 5194 resource = resource.promise(); 5195 resource._setDisposable(disposer); 5196 } else { 5197 var maybePromise = tryConvertToPromise(resource); 5198 if (maybePromise instanceof Promise) { 5199 resource = 5200 maybePromise._then(maybeUnwrapDisposer, null, null, { 5201 resources: resources, 5202 index: i 5203 }, undefined); 5204 } 5205 } 5206 resources[i] = resource; 5207 } 5208 5209 var reflectedResources = new Array(resources.length); 5210 for (var i = 0; i < reflectedResources.length; ++i) { 5211 reflectedResources[i] = Promise.resolve(resources[i]).reflect(); 5212 } 5213 5214 var resultPromise = Promise.all(reflectedResources) 5215 .then(function(inspections) { 5216 for (var i = 0; i < inspections.length; ++i) { 5217 var inspection = inspections[i]; 5218 if (inspection.isRejected()) { 5219 errorObj.e = inspection.error(); 5220 return errorObj; 5221 } else if (!inspection.isFulfilled()) { 5222 resultPromise.cancel(); 5223 return; 5224 } 5225 inspections[i] = inspection.value(); 5226 } 5227 promise._pushContext(); 5228 5229 fn = tryCatch(fn); 5230 var ret = spreadArgs 5231 ? fn.apply(undefined, inspections) : fn(inspections); 5232 var promiseCreated = promise._popContext(); 5233 debug.checkForgottenReturns( 5234 ret, promiseCreated, "Promise.using", promise); 5235 return ret; 5236 }); 5237 5238 var promise = resultPromise.lastly(function() { 5239 var inspection = new Promise.PromiseInspection(resultPromise); 5240 return dispose(resources, inspection); 5241 }); 5242 resources.promise = promise; 5243 promise._setOnCancel(resources); 5244 return promise; 5245 }; 5246 5247 Promise.prototype._setDisposable = function (disposer) { 5248 this._bitField = this._bitField | 131072; 5249 this._disposer = disposer; 5250 }; 5251 5252 Promise.prototype._isDisposable = function () { 5253 return (this._bitField & 131072) > 0; 5254 }; 5255 5256 Promise.prototype._getDisposer = function () { 5257 return this._disposer; 5258 }; 5259 5260 Promise.prototype._unsetDisposable = function () { 5261 this._bitField = this._bitField & (~131072); 5262 this._disposer = undefined; 5263 }; 5264 5265 Promise.prototype.disposer = function (fn) { 5266 if (typeof fn === "function") { 5267 return new FunctionDisposer(fn, this, createContext()); 5268 } 5269 throw new TypeError(); 5270 }; 5271 5272}; 5273 5274},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ 5275"use strict"; 5276var es5 = _dereq_("./es5"); 5277var canEvaluate = typeof navigator == "undefined"; 5278 5279var errorObj = {e: {}}; 5280var tryCatchTarget; 5281var globalObject = typeof self !== "undefined" ? self : 5282 typeof window !== "undefined" ? window : 5283 typeof global !== "undefined" ? global : 5284 this !== undefined ? this : null; 5285 5286function tryCatcher() { 5287 try { 5288 var target = tryCatchTarget; 5289 tryCatchTarget = null; 5290 return target.apply(this, arguments); 5291 } catch (e) { 5292 errorObj.e = e; 5293 return errorObj; 5294 } 5295} 5296function tryCatch(fn) { 5297 tryCatchTarget = fn; 5298 return tryCatcher; 5299} 5300 5301var inherits = function(Child, Parent) { 5302 var hasProp = {}.hasOwnProperty; 5303 5304 function T() { 5305 this.constructor = Child; 5306 this.constructor$ = Parent; 5307 for (var propertyName in Parent.prototype) { 5308 if (hasProp.call(Parent.prototype, propertyName) && 5309 propertyName.charAt(propertyName.length-1) !== "$" 5310 ) { 5311 this[propertyName + "$"] = Parent.prototype[propertyName]; 5312 } 5313 } 5314 } 5315 T.prototype = Parent.prototype; 5316 Child.prototype = new T(); 5317 return Child.prototype; 5318}; 5319 5320 5321function isPrimitive(val) { 5322 return val == null || val === true || val === false || 5323 typeof val === "string" || typeof val === "number"; 5324 5325} 5326 5327function isObject(value) { 5328 return typeof value === "function" || 5329 typeof value === "object" && value !== null; 5330} 5331 5332function maybeWrapAsError(maybeError) { 5333 if (!isPrimitive(maybeError)) return maybeError; 5334 5335 return new Error(safeToString(maybeError)); 5336} 5337 5338function withAppended(target, appendee) { 5339 var len = target.length; 5340 var ret = new Array(len + 1); 5341 var i; 5342 for (i = 0; i < len; ++i) { 5343 ret[i] = target[i]; 5344 } 5345 ret[i] = appendee; 5346 return ret; 5347} 5348 5349function getDataPropertyOrDefault(obj, key, defaultValue) { 5350 if (es5.isES5) { 5351 var desc = Object.getOwnPropertyDescriptor(obj, key); 5352 5353 if (desc != null) { 5354 return desc.get == null && desc.set == null 5355 ? desc.value 5356 : defaultValue; 5357 } 5358 } else { 5359 return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; 5360 } 5361} 5362 5363function notEnumerableProp(obj, name, value) { 5364 if (isPrimitive(obj)) return obj; 5365 var descriptor = { 5366 value: value, 5367 configurable: true, 5368 enumerable: false, 5369 writable: true 5370 }; 5371 es5.defineProperty(obj, name, descriptor); 5372 return obj; 5373} 5374 5375function thrower(r) { 5376 throw r; 5377} 5378 5379var inheritedDataKeys = (function() { 5380 var excludedPrototypes = [ 5381 Array.prototype, 5382 Object.prototype, 5383 Function.prototype 5384 ]; 5385 5386 var isExcludedProto = function(val) { 5387 for (var i = 0; i < excludedPrototypes.length; ++i) { 5388 if (excludedPrototypes[i] === val) { 5389 return true; 5390 } 5391 } 5392 return false; 5393 }; 5394 5395 if (es5.isES5) { 5396 var getKeys = Object.getOwnPropertyNames; 5397 return function(obj) { 5398 var ret = []; 5399 var visitedKeys = Object.create(null); 5400 while (obj != null && !isExcludedProto(obj)) { 5401 var keys; 5402 try { 5403 keys = getKeys(obj); 5404 } catch (e) { 5405 return ret; 5406 } 5407 for (var i = 0; i < keys.length; ++i) { 5408 var key = keys[i]; 5409 if (visitedKeys[key]) continue; 5410 visitedKeys[key] = true; 5411 var desc = Object.getOwnPropertyDescriptor(obj, key); 5412 if (desc != null && desc.get == null && desc.set == null) { 5413 ret.push(key); 5414 } 5415 } 5416 obj = es5.getPrototypeOf(obj); 5417 } 5418 return ret; 5419 }; 5420 } else { 5421 var hasProp = {}.hasOwnProperty; 5422 return function(obj) { 5423 if (isExcludedProto(obj)) return []; 5424 var ret = []; 5425 5426 /*jshint forin:false */ 5427 enumeration: for (var key in obj) { 5428 if (hasProp.call(obj, key)) { 5429 ret.push(key); 5430 } else { 5431 for (var i = 0; i < excludedPrototypes.length; ++i) { 5432 if (hasProp.call(excludedPrototypes[i], key)) { 5433 continue enumeration; 5434 } 5435 } 5436 ret.push(key); 5437 } 5438 } 5439 return ret; 5440 }; 5441 } 5442 5443})(); 5444 5445var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; 5446function isClass(fn) { 5447 try { 5448 if (typeof fn === "function") { 5449 var keys = es5.names(fn.prototype); 5450 5451 var hasMethods = es5.isES5 && keys.length > 1; 5452 var hasMethodsOtherThanConstructor = keys.length > 0 && 5453 !(keys.length === 1 && keys[0] === "constructor"); 5454 var hasThisAssignmentAndStaticMethods = 5455 thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; 5456 5457 if (hasMethods || hasMethodsOtherThanConstructor || 5458 hasThisAssignmentAndStaticMethods) { 5459 return true; 5460 } 5461 } 5462 return false; 5463 } catch (e) { 5464 return false; 5465 } 5466} 5467 5468function toFastProperties(obj) { 5469 /*jshint -W027,-W055,-W031*/ 5470 function FakeConstructor() {} 5471 FakeConstructor.prototype = obj; 5472 var receiver = new FakeConstructor(); 5473 function ic() { 5474 return typeof receiver.foo; 5475 } 5476 ic(); 5477 ic(); 5478 return obj; 5479 eval(obj); 5480} 5481 5482var rident = /^[a-z$_][a-z$_0-9]*$/i; 5483function isIdentifier(str) { 5484 return rident.test(str); 5485} 5486 5487function filledRange(count, prefix, suffix) { 5488 var ret = new Array(count); 5489 for(var i = 0; i < count; ++i) { 5490 ret[i] = prefix + i + suffix; 5491 } 5492 return ret; 5493} 5494 5495function safeToString(obj) { 5496 try { 5497 return obj + ""; 5498 } catch (e) { 5499 return "[no string representation]"; 5500 } 5501} 5502 5503function isError(obj) { 5504 return obj instanceof Error || 5505 (obj !== null && 5506 typeof obj === "object" && 5507 typeof obj.message === "string" && 5508 typeof obj.name === "string"); 5509} 5510 5511function markAsOriginatingFromRejection(e) { 5512 try { 5513 notEnumerableProp(e, "isOperational", true); 5514 } 5515 catch(ignore) {} 5516} 5517 5518function originatesFromRejection(e) { 5519 if (e == null) return false; 5520 return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || 5521 e["isOperational"] === true); 5522} 5523 5524function canAttachTrace(obj) { 5525 return isError(obj) && es5.propertyIsWritable(obj, "stack"); 5526} 5527 5528var ensureErrorObject = (function() { 5529 if (!("stack" in new Error())) { 5530 return function(value) { 5531 if (canAttachTrace(value)) return value; 5532 try {throw new Error(safeToString(value));} 5533 catch(err) {return err;} 5534 }; 5535 } else { 5536 return function(value) { 5537 if (canAttachTrace(value)) return value; 5538 return new Error(safeToString(value)); 5539 }; 5540 } 5541})(); 5542 5543function classString(obj) { 5544 return {}.toString.call(obj); 5545} 5546 5547function copyDescriptors(from, to, filter) { 5548 var keys = es5.names(from); 5549 for (var i = 0; i < keys.length; ++i) { 5550 var key = keys[i]; 5551 if (filter(key)) { 5552 try { 5553 es5.defineProperty(to, key, es5.getDescriptor(from, key)); 5554 } catch (ignore) {} 5555 } 5556 } 5557} 5558 5559var asArray = function(v) { 5560 if (es5.isArray(v)) { 5561 return v; 5562 } 5563 return null; 5564}; 5565 5566if (typeof Symbol !== "undefined" && Symbol.iterator) { 5567 var ArrayFrom = typeof Array.from === "function" ? function(v) { 5568 return Array.from(v); 5569 } : function(v) { 5570 var ret = []; 5571 var it = v[Symbol.iterator](); 5572 var itResult; 5573 while (!((itResult = it.next()).done)) { 5574 ret.push(itResult.value); 5575 } 5576 return ret; 5577 }; 5578 5579 asArray = function(v) { 5580 if (es5.isArray(v)) { 5581 return v; 5582 } else if (v != null && typeof v[Symbol.iterator] === "function") { 5583 return ArrayFrom(v); 5584 } 5585 return null; 5586 }; 5587} 5588 5589var isNode = typeof process !== "undefined" && 5590 classString(process).toLowerCase() === "[object process]"; 5591 5592var hasEnvVariables = typeof process !== "undefined" && 5593 typeof process.env !== "undefined"; 5594 5595function env(key) { 5596 return hasEnvVariables ? process.env[key] : undefined; 5597} 5598 5599function getNativePromise() { 5600 if (typeof Promise === "function") { 5601 try { 5602 var promise = new Promise(function(){}); 5603 if ({}.toString.call(promise) === "[object Promise]") { 5604 return Promise; 5605 } 5606 } catch (e) {} 5607 } 5608} 5609 5610function domainBind(self, cb) { 5611 return self.bind(cb); 5612} 5613 5614var ret = { 5615 isClass: isClass, 5616 isIdentifier: isIdentifier, 5617 inheritedDataKeys: inheritedDataKeys, 5618 getDataPropertyOrDefault: getDataPropertyOrDefault, 5619 thrower: thrower, 5620 isArray: es5.isArray, 5621 asArray: asArray, 5622 notEnumerableProp: notEnumerableProp, 5623 isPrimitive: isPrimitive, 5624 isObject: isObject, 5625 isError: isError, 5626 canEvaluate: canEvaluate, 5627 errorObj: errorObj, 5628 tryCatch: tryCatch, 5629 inherits: inherits, 5630 withAppended: withAppended, 5631 maybeWrapAsError: maybeWrapAsError, 5632 toFastProperties: toFastProperties, 5633 filledRange: filledRange, 5634 toString: safeToString, 5635 canAttachTrace: canAttachTrace, 5636 ensureErrorObject: ensureErrorObject, 5637 originatesFromRejection: originatesFromRejection, 5638 markAsOriginatingFromRejection: markAsOriginatingFromRejection, 5639 classString: classString, 5640 copyDescriptors: copyDescriptors, 5641 hasDevTools: typeof chrome !== "undefined" && chrome && 5642 typeof chrome.loadTimes === "function", 5643 isNode: isNode, 5644 hasEnvVariables: hasEnvVariables, 5645 env: env, 5646 global: globalObject, 5647 getNativePromise: getNativePromise, 5648 domainBind: domainBind 5649}; 5650ret.isRecentNode = ret.isNode && (function() { 5651 var version; 5652 if (process.versions && process.versions.node) { 5653 version = process.versions.node.split(".").map(Number); 5654 } else if (process.version) { 5655 version = process.version.split(".").map(Number); 5656 } 5657 return (version[0] === 0 && version[1] > 10) || (version[0] > 0); 5658})(); 5659 5660if (ret.isNode) ret.toFastProperties(process); 5661 5662try {throw new Error(); } catch (e) {ret.lastLineError = e;} 5663module.exports = ret; 5664 5665},{"./es5":13}]},{},[4])(4) 5666}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }