From 2195fa910fd55578600470ed8d5dcc497a7b4144 Mon Sep 17 00:00:00 2001 From: Gordon Woodhull Date: Fri, 20 Feb 2015 19:06:15 -0500 Subject: [PATCH 1/3] upgrade bluebird and use line breaks in R stack traces fixes #1360 --- htdocs/js/rcloud.js | 4 +- htdocs/lib/dependencies_bundle.js | 7157 ++++++++++++------------ htdocs/lib/dependencies_bundle.min.js | 63 +- htdocs/lib/js/bluebird.js | 7253 ++++++++++++------------- 4 files changed, 6780 insertions(+), 7697 deletions(-) diff --git a/htdocs/js/rcloud.js b/htdocs/js/rcloud.js index 2d429aa1b5..50d17a7e05 100644 --- a/htdocs/js/rcloud.js +++ b/htdocs/js/rcloud.js @@ -25,8 +25,8 @@ RCloud.promisify_paths = (function() { function success(result) { if(result && RCloud.is_exception(result)) { var tb = result['traceback'] ? result['traceback'] : ""; - if (tb.join) tb = tb.join(" <- "); - throw new Error(command + ": " + result['error'].replace('\n', ' ') + " " + tb); + if (tb.join) tb = tb.join("\n"); + throw new Error(command + ": " + result.error + tb); } return result; } diff --git a/htdocs/lib/dependencies_bundle.js b/htdocs/lib/dependencies_bundle.js index d3cfb07fd5..3cbebe5de8 100644 --- a/htdocs/lib/dependencies_bundle.js +++ b/htdocs/lib/dependencies_bundle.js @@ -2066,34 +2066,9 @@ var requirejs, require, define; //Set up with config info. req(cfg); }(this)); -/** - * bluebird build version 1.1.1 - * Features enabled: core, timers, race, any, call_get, filter, generators, map, nodeify, promisify, props, reduce, settle, some, progress, cancel, synchronous_inspection -*/ -/** - * @preserve Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. +/* @preserve + * The MIT License (MIT) * - */ -!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.Promise=e():"undefined"!=typeof global?global.Promise=e():"undefined"!=typeof self&&(self.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 require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{}],2:[function(_dereq_,module,exports){ "use strict"; -var schedule = require("./schedule.js"); -var Queue = require("./queue.js"); -var errorObj = require("./util.js").errorObj; -var tryCatch1 = require("./util.js").tryCatch1; -var process = require("./global.js").process; +var firstLineError; +try {throw new Error(); } catch (e) {firstLineError = e;} +var schedule = _dereq_("./schedule.js"); +var Queue = _dereq_("./queue.js"); +var _process = typeof process !== "undefined" ? process : undefined; function Async() { this._isTickUsed = false; - this._length = 0; - this._lateBuffer = new Queue(); - this._functionBuffer = new Queue(25000 * 3); + this._lateQueue = new Queue(16); + this._normalQueue = new Queue(16); var self = this; - this.consumeFunctionBuffer = function Async$consumeFunctionBuffer() { - self._consumeFunctionBuffer(); + this.drainQueues = function () { + self._drainQueues(); }; + this._schedule = + schedule.isStatic ? schedule(this.drainQueues) : schedule; } -Async.prototype.haveItemsQueued = function Async$haveItemsQueued() { - return this._length > 0; +Async.prototype.haveItemsQueued = function () { + return this._normalQueue.length() > 0; }; -Async.prototype.invokeLater = function Async$invokeLater(fn, receiver, arg) { - if (process !== void 0 && - process.domain != null && +Async.prototype._withDomain = function(fn) { + if (_process !== undefined && + _process.domain != null && !fn.domain) { - fn = process.domain.bind(fn); + fn = _process.domain.bind(fn); } - this._lateBuffer.push(fn, receiver, arg); - this._queueTick(); + return fn; }; -Async.prototype.invoke = function Async$invoke(fn, receiver, arg) { - if (process !== void 0 && - process.domain != null && - !fn.domain) { - fn = process.domain.bind(fn); +Async.prototype.throwLater = function(fn, arg) { + if (arguments.length === 1) { + arg = fn; + fn = function () { throw arg; }; + } + fn = this._withDomain(fn); + if (typeof setTimeout !== "undefined") { + setTimeout(function() { + fn(arg); + }, 0); + } else try { + this._schedule(function() { + fn(arg); + }); + } catch (e) { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); } - var functionBuffer = this._functionBuffer; - functionBuffer.push(fn, receiver, arg); - this._length = functionBuffer.length(); +}; + +Async.prototype.invokeLater = function (fn, receiver, arg) { + fn = this._withDomain(fn); + this._lateQueue.push(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype.invokeFirst = function (fn, receiver, arg) { + fn = this._withDomain(fn); + this._normalQueue.unshift(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype.invoke = function (fn, receiver, arg) { + fn = this._withDomain(fn); + this._normalQueue.push(fn, receiver, arg); + this._queueTick(); +}; + +Async.prototype.settlePromises = function(promise) { + this._normalQueue._pushOne(promise); this._queueTick(); }; -Async.prototype._consumeFunctionBuffer = -function Async$_consumeFunctionBuffer() { - var functionBuffer = this._functionBuffer; - while(functionBuffer.length() > 0) { - var fn = functionBuffer.shift(); - var receiver = functionBuffer.shift(); - var arg = functionBuffer.shift(); +Async.prototype._drainQueue = function(queue) { + while (queue.length() > 0) { + var fn = queue.shift(); + if (typeof fn !== "function") { + fn._settlePromises(); + continue; + } + var receiver = queue.shift(); + var arg = queue.shift(); fn.call(receiver, arg); } +}; + +Async.prototype._drainQueues = function () { + this._drainQueue(this._normalQueue); this._reset(); - this._consumeLateBuffer(); -}; - -Async.prototype._consumeLateBuffer = function Async$_consumeLateBuffer() { - var buffer = this._lateBuffer; - while(buffer.length() > 0) { - var fn = buffer.shift(); - var receiver = buffer.shift(); - var arg = buffer.shift(); - var res = tryCatch1(fn, receiver, arg); - if (res === errorObj) { - this._queueTick(); - if (fn.domain != null) { - fn.domain.emit("error", res.e); - } - else { - throw res.e; - } - } - } + this._drainQueue(this._lateQueue); }; -Async.prototype._queueTick = function Async$_queue() { +Async.prototype._queueTick = function () { if (!this._isTickUsed) { - schedule(this.consumeFunctionBuffer); this._isTickUsed = true; + this._schedule(this.drainQueues); } }; -Async.prototype._reset = function Async$_reset() { +Async.prototype._reset = function () { this._isTickUsed = false; - this._length = 0; }; module.exports = new Async(); +module.exports.firstLineError = firstLineError; -},{"./global.js":15,"./queue.js":27,"./schedule.js":30,"./util.js":38}],3:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var Promise = require("./promise.js")(); -module.exports = Promise; -},{"./promise.js":19}],4:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./queue.js":28,"./schedule.js":31}],3:[function(_dereq_,module,exports){ "use strict"; -module.exports = function(Promise) { - Promise.prototype.call = function Promise$call(propertyName) { - var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} +module.exports = function(Promise, INTERNAL, tryConvertToPromise) { +var rejectThis = function(_, e) { + this._reject(e); +}; - return this._then(function(obj) { - return obj[propertyName].apply(obj, args); - }, - void 0, - void 0, - void 0, - void 0, - this.call - ); - }; +var targetRejected = function(e, context) { + context.promiseRejectionQueued = true; + context.bindingPromise._then(rejectThis, rejectThis, null, this, e); +}; - function Promise$getter(obj) { - var prop = typeof this === "string" - ? this - : ("" + this); - return obj[prop]; +var bindingResolved = function(thisArg, context) { + this._setBoundTo(thisArg); + if (this._isPending()) { + this._resolveCallback(context.target); } - Promise.prototype.get = function Promise$get(propertyName) { - return this._then( - Promise$getter, - void 0, - void 0, - propertyName, - void 0, - this.get - ); - }; }; -},{}],5:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { - var errors = require("./errors.js"); - var async = require("./async.js"); - var CancellationError = errors.CancellationError; - var SYNC_TOKEN = {}; - - Promise.prototype._cancel = function Promise$_cancel() { - if (!this.isCancellable()) return this; - var parent; - if ((parent = this._cancellationParent) !== void 0) { - parent.cancel(SYNC_TOKEN); - return; - } - var err = new CancellationError(); - this._attachExtraTrace(err); - this._rejectUnchecked(err); - }; +var bindingRejected = function(e, context) { + if (!context.promiseRejectionQueued) this._reject(e); +}; - Promise.prototype.cancel = function Promise$cancel(token) { - if (!this.isCancellable()) return this; - if (token === SYNC_TOKEN) { - this._cancel(); - return this; - } - async.invokeLater(this._cancel, this, void 0); - return this; - }; +Promise.prototype.bind = function (thisArg) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); + ret._propagateFrom(this, 1); + var target = this._target(); + if (maybePromise instanceof Promise) { + var context = { + promiseRejectionQueued: false, + promise: ret, + target: target, + bindingPromise: maybePromise + }; + target._then(INTERNAL, targetRejected, ret._progress, ret, context); + maybePromise._then( + bindingResolved, bindingRejected, ret._progress, ret, context); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(target); + } + return ret; +}; - Promise.prototype.cancellable = function Promise$cancellable() { - if (this._cancellable()) return this; - this._setCancellable(); - this._cancellationParent = void 0; - return this; - }; +Promise.prototype._setBoundTo = function (obj) { + if (obj !== undefined) { + this._bitField = this._bitField | 131072; + this._boundTo = obj; + } else { + this._bitField = this._bitField & (~131072); + } +}; - Promise.prototype.uncancellable = function Promise$uncancellable() { - var ret = new Promise(INTERNAL); - ret._setTrace(this.uncancellable, this); - ret._follow(this); - ret._unsetCancellable(); - if (this._isBound()) ret._setBoundTo(this._boundTo); - return ret; - }; +Promise.prototype._isBound = function () { + return (this._bitField & 131072) === 131072; +}; - Promise.prototype.fork = - function Promise$fork(didFulfill, didReject, didProgress) { - var ret = this._then(didFulfill, didReject, didProgress, - void 0, void 0, this.fork); +Promise.bind = function (thisArg, value) { + var maybePromise = tryConvertToPromise(thisArg); + var ret = new Promise(INTERNAL); - ret._setCancellable(); - ret._cancellationParent = void 0; - return ret; - }; + if (maybePromise instanceof Promise) { + maybePromise._then(function(thisArg) { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + }, ret._reject, ret._progress, ret, null); + } else { + ret._setBoundTo(thisArg); + ret._resolveCallback(value); + } + return ret; +}; }; -},{"./async.js":2,"./errors.js":9}],6:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{}],4:[function(_dereq_,module,exports){ "use strict"; -module.exports = function() { -var inherits = require("./util.js").inherits; -var defineProperty = require("./es5.js").defineProperty; - -var rignore = new RegExp( - "\\b(?:[\\w.]*Promise(?:Array|Spawn)?\\$_\\w+|" + - "tryCatch(?:1|2|Apply)|new \\w*PromiseArray|" + - "\\w*PromiseArray\\.\\w*PromiseArray|" + - "setTimeout|CatchFilter\\$_\\w+|makeNodePromisified|processImmediate|" + - "process._tickCallback|nextTick|Async\\$\\w+)\\b" -); - -var rtraceline = null; -var formatStack = null; -var areNamesMangled = false; +var old; +if (typeof Promise !== "undefined") old = Promise; +function noConflict() { + try { if (Promise === bluebird) Promise = old; } + catch (e) {} + return bluebird; +} +var bluebird = _dereq_("./promise.js")(); +bluebird.noConflict = noConflict; +module.exports = bluebird; -function formatNonError(obj) { - var str; - if (typeof obj === "function") { - str = "[function " + - (obj.name || "anonymous") + - "]"; - } - else { - str = obj.toString(); - var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; - if (ruselessToString.test(str)) { - try { - var newStr = JSON.stringify(obj); - str = newStr; - } - catch(e) { +},{"./promise.js":23}],5:[function(_dereq_,module,exports){ +"use strict"; +var cr = Object.create; +if (cr) { + var callerCache = cr(null); + var getterCache = cr(null); + callerCache[" size"] = getterCache[" size"] = 0; +} - } +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var isIdentifier = util.isIdentifier; + +var getMethodCaller; +var getGetter; +if (!true) { +var makeMethodCaller = function (methodName) { + return new Function("ensureMethod", " \n\ + return function(obj) { \n\ + 'use strict' \n\ + var len = this.length; \n\ + ensureMethod(obj, 'methodName'); \n\ + switch(len) { \n\ + case 1: return obj.methodName(this[0]); \n\ + case 2: return obj.methodName(this[0], this[1]); \n\ + case 3: return obj.methodName(this[0], this[1], this[2]); \n\ + case 0: return obj.methodName(); \n\ + default: \n\ + return obj.methodName.apply(obj, this); \n\ + } \n\ + }; \n\ + ".replace(/methodName/g, methodName))(ensureMethod); +}; + +var makeGetter = function (propertyName) { + return new Function("obj", " \n\ + 'use strict'; \n\ + return obj.propertyName; \n\ + ".replace("propertyName", propertyName)); +}; + +var getCompiled = function(name, compiler, cache) { + var ret = cache[name]; + if (typeof ret !== "function") { + if (!isIdentifier(name)) { + return null; } - if (str.length === 0) { - str = "(empty array)"; + ret = compiler(name); + cache[name] = ret; + cache[" size"]++; + if (cache[" size"] > 512) { + var keys = Object.keys(cache); + for (var i = 0; i < 256; ++i) delete cache[keys[i]]; + cache[" size"] = keys.length - 256; } } - return ("(<" + snip(str) + ">, no stack trace)"); + return ret; +}; + +getMethodCaller = function(name) { + return getCompiled(name, makeMethodCaller, callerCache); +}; + +getGetter = function(name) { + return getCompiled(name, makeGetter, getterCache); +}; } -function snip(str) { - var maxChars = 41; - if (str.length < maxChars) { - return str; +function ensureMethod(obj, methodName) { + var fn; + if (obj != null) fn = obj[methodName]; + if (typeof fn !== "function") { + var message = "Object " + util.classString(obj) + " has no method '" + + util.toString(methodName) + "'"; + throw new Promise.TypeError(message); } - return str.substr(0, maxChars - 3) + "..."; + return fn; } -function CapturedTrace(ignoreUntil, isTopLevel) { - if (!areNamesMangled) { +function caller(obj) { + var methodName = this.pop(); + var fn = ensureMethod(obj, methodName); + return fn.apply(obj, this); +} +Promise.prototype.call = function (methodName) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + if (!true) { + if (canEvaluate) { + var maybeCaller = getMethodCaller(methodName); + if (maybeCaller !== null) { + return this._then( + maybeCaller, undefined, undefined, args, undefined); + } + } } - this.captureStackTrace(ignoreUntil, isTopLevel); + args.push(methodName); + return this._then(caller, undefined, undefined, args, undefined); +}; +function namedGetter(obj) { + return obj[this]; } -inherits(CapturedTrace, Error); +function indexedGetter(obj) { + var index = +this; + if (index < 0) index = Math.max(0, index + obj.length); + return obj[index]; +} +Promise.prototype.get = function (propertyName) { + var isIndex = (typeof propertyName === "number"); + var getter; + if (!isIndex) { + if (canEvaluate) { + var maybeGetter = getGetter(propertyName); + getter = maybeGetter !== null ? maybeGetter : namedGetter; + } else { + getter = namedGetter; + } + } else { + getter = indexedGetter; + } + return this._then(getter, undefined, undefined, propertyName, undefined); +}; +}; + +},{"./util.js":38}],6:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var errors = _dereq_("./errors.js"); +var async = _dereq_("./async.js"); +var CancellationError = errors.CancellationError; -CapturedTrace.prototype.captureStackTrace = -function CapturedTrace$captureStackTrace(ignoreUntil, isTopLevel) { - captureStackTrace(this, ignoreUntil, isTopLevel); +Promise.prototype._cancel = function (reason) { + if (!this.isCancellable()) return this; + var parent; + var promiseToReject = this; + while ((parent = promiseToReject._cancellationParent) !== undefined && + parent.isCancellable()) { + promiseToReject = parent; + } + this._unsetCancellable(); + promiseToReject._target()._rejectCallback(reason, false, true); }; -CapturedTrace.possiblyUnhandledRejection = -function CapturedTrace$PossiblyUnhandledRejection(reason) { - if (typeof console === "object") { - var message; - if (typeof reason === "object" || typeof reason === "function") { - var stack = reason.stack; - message = "Possibly unhandled " + formatStack(stack, reason); +Promise.prototype.cancel = function (reason) { + if (!this.isCancellable()) return this; + if (reason === undefined) reason = new CancellationError(); + async.invokeLater(this._cancel, this, reason); + return this; +}; + +Promise.prototype.cancellable = function () { + if (this._cancellable()) return this; + this._setCancellable(); + this._cancellationParent = undefined; + return this; +}; + +Promise.prototype.uncancellable = function () { + var ret = this.then(); + ret._unsetCancellable(); + return ret; +}; + +Promise.prototype.fork = function (didFulfill, didReject, didProgress) { + var ret = this._then(didFulfill, didReject, didProgress, + undefined, undefined); + + ret._setCancellable(); + ret._cancellationParent = undefined; + return ret; +}; +}; + +},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var async = _dereq_("./async.js"); +var util = _dereq_("./util.js"); +var bluebirdFramePattern = + /[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/; +var stackFramePattern = null; +var formatStack = null; +var indentStackFrames = false; +var warn; + +function CapturedTrace(parent) { + this._parent = parent; + var length = this._length = 1 + (parent === undefined ? 0 : parent._length); + captureStackTrace(this, CapturedTrace); + if (length > 32) this.uncycle(); +} +util.inherits(CapturedTrace, Error); + +CapturedTrace.prototype.uncycle = function() { + var length = this._length; + if (length < 2) return; + var nodes = []; + var stackToIndex = {}; + + for (var i = 0, node = this; node !== undefined; ++i) { + nodes.push(node); + node = node._parent; + } + length = this._length = i; + for (var i = length - 1; i >= 0; --i) { + var stack = nodes[i].stack; + if (stackToIndex[stack] === undefined) { + stackToIndex[stack] = i; + } + } + for (var i = 0; i < length; ++i) { + var currentStack = nodes[i].stack; + var index = stackToIndex[currentStack]; + if (index !== undefined && index !== i) { + if (index > 0) { + nodes[index - 1]._parent = undefined; + nodes[index - 1]._length = 1; + } + nodes[i]._parent = undefined; + nodes[i]._length = 1; + var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; + + if (index < length - 1) { + cycleEdgeNode._parent = nodes[index + 1]; + cycleEdgeNode._parent.uncycle(); + cycleEdgeNode._length = + cycleEdgeNode._parent._length + 1; + } else { + cycleEdgeNode._parent = undefined; + cycleEdgeNode._length = 1; + } + var currentChildLength = cycleEdgeNode._length + 1; + for (var j = i - 2; j >= 0; --j) { + nodes[j]._length = currentChildLength; + currentChildLength++; + } + return; } - else { - message = "Possibly unhandled " + String(reason); + } +}; + +CapturedTrace.prototype.parent = function() { + return this._parent; +}; + +CapturedTrace.prototype.hasParent = function() { + return this._parent !== undefined; +}; + +CapturedTrace.prototype.attachExtraTrace = function(error) { + if (error.__stackCleaned__) return; + this.uncycle(); + var parsed = CapturedTrace.parseStackAndMessage(error); + var message = parsed.message; + var stacks = [parsed.stack]; + + var trace = this; + while (trace !== undefined) { + stacks.push(cleanStack(trace.stack.split("\n"))); + trace = trace._parent; + } + removeCommonRoots(stacks); + removeDuplicateOrEmptyJumps(stacks); + error.stack = reconstructStack(message, stacks); + util.notEnumerableProp(error, "__stackCleaned__", true); +}; + +function reconstructStack(message, stacks) { + for (var i = 0; i < stacks.length - 1; ++i) { + stacks[i].push("From previous event:"); + stacks[i] = stacks[i].join("\n"); + } + if (i < stacks.length) { + stacks[i] = stacks[i].join("\n"); + } + return message + "\n" + stacks.join("\n"); +} + +function removeDuplicateOrEmptyJumps(stacks) { + for (var i = 0; i < stacks.length; ++i) { + if (stacks[i].length === 0 || + ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { + stacks.splice(i, 1); + i--; + } + } +} + +function removeCommonRoots(stacks) { + var current = stacks[0]; + for (var i = 1; i < stacks.length; ++i) { + var prev = stacks[i]; + var currentLastIndex = current.length - 1; + var currentLastLine = current[currentLastIndex]; + var commonRootMeetPoint = -1; + + for (var j = prev.length - 1; j >= 0; --j) { + if (prev[j] === currentLastLine) { + commonRootMeetPoint = j; + break; + } + } + + for (var j = commonRootMeetPoint; j >= 0; --j) { + var line = prev[j]; + if (current[currentLastIndex] === line) { + current.pop(); + currentLastIndex--; + } else { + break; + } + } + current = prev; + } +} + +function cleanStack(stack) { + var ret = []; + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + var isTraceLine = stackFramePattern.test(line) || + " (No stack trace)" === line; + var isInternalFrame = isTraceLine && shouldIgnore(line); + if (isTraceLine && !isInternalFrame) { + if (indentStackFrames && line.charAt(0) !== " ") { + line = " " + line; + } + ret.push(line); + } + } + return ret; +} + +function stackFramesAsArray(error) { + var stack = error.stack.replace(/\s+$/g, "").split("\n"); + for (var i = 0; i < stack.length; ++i) { + var line = stack[i]; + if (" (No stack trace)" === line || stackFramePattern.test(line)) { + break; } - if (typeof console.error === "function" || - typeof console.error === "object") { - console.error(message); + } + if (i > 0) { + stack = stack.slice(i); + } + return stack; +} + +CapturedTrace.parseStackAndMessage = function(error) { + var stack = error.stack; + var message = error.toString(); + stack = typeof stack === "string" && stack.length > 0 + ? stackFramesAsArray(error) : [" (No stack trace)"]; + return { + message: message, + stack: cleanStack(stack) + }; +}; + +CapturedTrace.formatAndLogError = function(error, title) { + if (typeof console !== "undefined") { + var message; + if (typeof error === "object" || typeof error === "function") { + var stack = error.stack; + message = title + formatStack(stack, error); + } else { + message = title + String(error); } - else if (typeof console.log === "function" || - typeof console.error === "object") { + if (typeof warn === "function") { + warn(message); + } else if (typeof console.log === "function" || + typeof console.log === "object") { console.log(message); } } }; -areNamesMangled = CapturedTrace.prototype.captureStackTrace.name !== - "CapturedTrace$captureStackTrace"; +CapturedTrace.unhandledRejection = function (reason) { + CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: "); +}; + +CapturedTrace.isSupported = function () { + return typeof captureStackTrace === "function"; +}; -CapturedTrace.combine = function CapturedTrace$Combine(current, prev) { - var curLast = current.length - 1; - for (var i = prev.length - 1; i >= 0; --i) { - var line = prev[i]; - if (current[curLast] === line) { - current.pop(); - curLast--; +CapturedTrace.fireRejectionEvent = +function(name, localHandler, reason, promise) { + var localEventFired = false; + try { + if (typeof localHandler === "function") { + localEventFired = true; + if (name === "rejectionHandled") { + localHandler(promise); + } else { + localHandler(reason, promise); + } } - else { - break; + } catch (e) { + async.throwLater(e); + } + + var globalEventFired = false; + try { + globalEventFired = fireGlobalEvent(name, reason, promise); + } catch (e) { + globalEventFired = true; + async.throwLater(e); + } + + var domEventFired = false; + if (fireDomEvent) { + try { + domEventFired = fireDomEvent(name.toLowerCase(), { + reason: reason, + promise: promise + }); + } catch (e) { + domEventFired = true; + async.throwLater(e); } } - current.push("From previous event:"); - var lines = current.concat(prev); + if (!globalEventFired && !localEventFired && !domEventFired && + name === "unhandledRejection") { + CapturedTrace.formatAndLogError(reason, "Unhandled rejection "); + } +}; - var ret = []; +function formatNonError(obj) { + var str; + if (typeof obj === "function") { + str = "[function " + + (obj.name || "anonymous") + + "]"; + } else { + str = obj.toString(); + var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; + if (ruselessToString.test(str)) { + try { + var newStr = JSON.stringify(obj); + str = newStr; + } + catch(e) { + } + } + if (str.length === 0) { + str = "(empty array)"; + } + } + return ("(<" + snip(str) + ">, no stack trace)"); +} - for (var i = 0, len = lines.length; i < len; ++i) { +function snip(str) { + var maxChars = 41; + if (str.length < maxChars) { + return str; + } + return str.substr(0, maxChars - 3) + "..."; +} - if ((rignore.test(lines[i]) || - (i > 0 && !rtraceline.test(lines[i])) && - lines[i] !== "From previous event:") - ) { - continue; +var shouldIgnore = function() { return false; }; +var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; +function parseLineInfo(line) { + var matches = line.match(parseLineInfoRegex); + if (matches) { + return { + fileName: matches[1], + line: parseInt(matches[2], 10) + }; + } +} +CapturedTrace.setBounds = function(firstLineError, lastLineError) { + if (!CapturedTrace.isSupported()) return; + var firstStackLines = firstLineError.stack.split("\n"); + var lastStackLines = lastLineError.stack.split("\n"); + var firstIndex = -1; + var lastIndex = -1; + var firstFileName; + var lastFileName; + for (var i = 0; i < firstStackLines.length; ++i) { + var result = parseLineInfo(firstStackLines[i]); + if (result) { + firstFileName = result.fileName; + firstIndex = result.line; + break; } - ret.push(lines[i]); } - return ret; -}; + for (var i = 0; i < lastStackLines.length; ++i) { + var result = parseLineInfo(lastStackLines[i]); + if (result) { + lastFileName = result.fileName; + lastIndex = result.line; + break; + } + } + if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || + firstFileName !== lastFileName || firstIndex >= lastIndex) { + return; + } -CapturedTrace.isSupported = function CapturedTrace$IsSupported() { - return typeof captureStackTrace === "function"; + shouldIgnore = function(line) { + if (bluebirdFramePattern.test(line)) return true; + var info = parseLineInfo(line); + if (info) { + if (info.fileName === firstFileName && + (firstIndex <= info.line && info.line <= lastIndex)) { + return true; + } + } + return false; + }; }; var captureStackTrace = (function stackDetection() { - if (typeof Error.stackTraceLimit === "number" && - typeof Error.captureStackTrace === "function") { - rtraceline = /^\s*at\s*/; - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; + var v8stackFramePattern = /^\s*at\s*/; + var v8stackFormatter = function(stack, error) { + if (typeof stack === "string") return stack; - if (error.name !== void 0 && - error.message !== void 0) { - return error.name + ". " + error.message; - } - return formatNonError(error); + if (error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + if (typeof Error.stackTraceLimit === "number" && + typeof Error.captureStackTrace === "function") { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + var captureStackTrace = Error.captureStackTrace; + shouldIgnore = function(line) { + return bluebirdFramePattern.test(line); }; - var captureStackTrace = Error.captureStackTrace; - return function CapturedTrace$_captureStackTrace( - receiver, ignoreUntil) { + return function(receiver, ignoreUntil) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; captureStackTrace(receiver, ignoreUntil); + Error.stackTraceLimit = Error.stackTraceLimit - 6; }; } var err = new Error(); - if (!areNamesMangled && typeof err.stack === "string" && - typeof "".startsWith === "function" && - (err.stack.startsWith("stackDetection@")) && - stackDetection.name === "stackDetection") { + if (typeof err.stack === "string" && + err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { + stackFramePattern = /@/; + formatStack = v8stackFormatter; + indentStackFrames = true; + return function captureStackTrace(o) { + o.stack = new Error().stack; + }; + } - defineProperty(Error, "stackTraceLimit", { - writable: true, - enumerable: false, - configurable: false, - value: 25 - }); - rtraceline = /@/; - var rline = /[@\n]/; + var hasStackAfterThrow; + try { throw new Error(); } + catch(e) { + hasStackAfterThrow = ("stack" in e); + } + if (!("stack" in err) && hasStackAfterThrow) { + stackFramePattern = v8stackFramePattern; + formatStack = v8stackFormatter; + return function captureStackTrace(o) { + Error.stackTraceLimit = Error.stackTraceLimit + 6; + try { throw new Error(); } + catch(e) { o.stack = e.stack; } + Error.stackTraceLimit = Error.stackTraceLimit - 6; + }; + } - formatStack = function(stack, error) { - if (typeof stack === "string") { - return (error.name + ". " + error.message + "\n" + stack); - } + formatStack = function(stack, error) { + if (typeof stack === "string") return stack; + + if ((typeof error === "object" || + typeof error === "function") && + error.name !== undefined && + error.message !== undefined) { + return error.toString(); + } + return formatNonError(error); + }; + + return null; - if (error.name !== void 0 && - error.message !== void 0) { - return error.name + ". " + error.message; +})([]); + +var fireDomEvent; +var fireGlobalEvent = (function() { + if (util.isNode) { + return function(name, reason, promise) { + if (name === "rejectionHandled") { + return process.emit(name, promise); + } else { + return process.emit(name, reason, promise); } - return formatNonError(error); }; - - return function captureStackTrace(o, fn) { - var name = fn.name; - var stack = new Error().stack; - var split = stack.split(rline); - var i, len = split.length; - for (i = 0; i < len; i += 2) { - if (split[i] === name) { - break; - } + } else { + var customEventWorks = false; + var anyEventWorks = true; + try { + var ev = new self.CustomEvent("test"); + customEventWorks = ev instanceof CustomEvent; + } catch (e) {} + if (!customEventWorks) { + try { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent("testingtheevent", false, true, {}); + self.dispatchEvent(event); + } catch (e) { + anyEventWorks = false; } - split = split.slice(i + 2); - len = split.length - 2; - var ret = ""; - for (i = 0; i < len; i += 2) { - ret += split[i]; - ret += "@"; - ret += split[i + 1]; - ret += "\n"; + } + if (anyEventWorks) { + fireDomEvent = function(type, detail) { + var event; + if (customEventWorks) { + event = new self.CustomEvent(type, { + detail: detail, + bubbles: false, + cancelable: true + }); + } else if (self.dispatchEvent) { + event = document.createEvent("CustomEvent"); + event.initCustomEvent(type, false, true, detail); + } + + return event ? !self.dispatchEvent(event) : false; + }; + } + + var toWindowMethodNameMap = {}; + toWindowMethodNameMap["unhandledRejection"] = ("on" + + "unhandledRejection").toLowerCase(); + toWindowMethodNameMap["rejectionHandled"] = ("on" + + "rejectionHandled").toLowerCase(); + + return function(name, reason, promise) { + var methodName = toWindowMethodNameMap[name]; + var method = self[methodName]; + if (!method) return false; + if (name === "rejectionHandled") { + method.call(self, promise); + } else { + method.call(self, reason, promise); } - o.stack = ret; + return true; }; } - else { - formatStack = function(stack, error) { - if (typeof stack === "string") return stack; - - if ((typeof error === "object" || - typeof error === "function") && - error.name !== void 0 && - error.message !== void 0) { - return error.name + ". " + error.message; - } - return formatNonError(error); - }; +})(); - return null; +if (typeof console !== "undefined" && typeof console.warn !== "undefined") { + warn = function (message) { + console.warn(message); + }; + if (util.isNode && process.stderr.isTTY) { + warn = function(message) { + process.stderr.write("\u001b[31m" + message + "\u001b[39m\n"); + }; + } else if (!util.isNode && typeof (new Error().stack) === "string") { + warn = function(message) { + console.warn("%c" + message, "color: red"); + }; } -})(); +} return CapturedTrace; }; -},{"./es5.js":11,"./util.js":38}],7:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(NEXT_FILTER) { -var util = require("./util.js"); -var errors = require("./errors.js"); -var tryCatch1 = util.tryCatch1; +var util = _dereq_("./util.js"); +var errors = _dereq_("./errors.js"); +var tryCatch = util.tryCatch; var errorObj = util.errorObj; -var keys = require("./es5.js").keys; +var keys = _dereq_("./es5.js").keys; +var TypeError = errors.TypeError; function CatchFilter(instances, callback, promise) { this._instances = instances; @@ -2699,49 +2997,43 @@ function CatchFilter(instances, callback, promise) { this._promise = promise; } -function CatchFilter$_safePredicate(predicate, e) { +function safePredicate(predicate, e) { var safeObject = {}; - var retfilter = tryCatch1(predicate, safeObject, e); + var retfilter = tryCatch(predicate).call(safeObject, e); if (retfilter === errorObj) return retfilter; var safeKeys = keys(safeObject); if (safeKeys.length) { - errorObj.e = new TypeError( - "Catch filter must inherit from Error " - + "or be a simple predicate function"); + errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"); return errorObj; } return retfilter; } -CatchFilter.prototype.doFilter = function CatchFilter$_doFilter(e) { +CatchFilter.prototype.doFilter = function (e) { var cb = this._callback; var promise = this._promise; - var boundTo = promise._isBound() ? promise._boundTo : void 0; + var boundTo = promise._boundTo; for (var i = 0, len = this._instances.length; i < len; ++i) { var item = this._instances[i]; var itemIsErrorType = item === Error || (item != null && item.prototype instanceof Error); if (itemIsErrorType && e instanceof item) { - var ret = tryCatch1(cb, boundTo, e); + var ret = tryCatch(cb).call(boundTo, e); if (ret === errorObj) { NEXT_FILTER.e = ret.e; return NEXT_FILTER; } return ret; } else if (typeof item === "function" && !itemIsErrorType) { - var shouldHandle = CatchFilter$_safePredicate(item, e); + var shouldHandle = safePredicate(item, e); if (shouldHandle === errorObj) { - var trace = errors.canAttach(errorObj.e) - ? errorObj.e - : new Error(errorObj.e + ""); - this._promise._attachExtraTrace(trace); e = errorObj.e; break; } else if (shouldHandle) { - var ret = tryCatch1(cb, boundTo, e); + var ret = tryCatch(cb).call(boundTo, e); if (ret === errorObj) { NEXT_FILTER.e = ret.e; return NEXT_FILTER; @@ -2757,50 +3049,208 @@ CatchFilter.prototype.doFilter = function CatchFilter$_doFilter(e) { return CatchFilter; }; -},{"./errors.js":9,"./es5.js":11,"./util.js":38}],8:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace, isDebugging) { +var contextStack = []; +function Context() { + this._trace = new CapturedTrace(peekContext()); +} +Context.prototype._pushContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.push(this._trace); + } +}; + +Context.prototype._popContext = function () { + if (!isDebugging()) return; + if (this._trace !== undefined) { + contextStack.pop(); + } +}; + +function createContext() { + if (isDebugging()) return new Context(); +} + +function peekContext() { + var lastIndex = contextStack.length - 1; + if (lastIndex >= 0) { + return contextStack[lastIndex]; + } + return undefined; +} + +Promise.prototype._peekContext = peekContext; +Promise.prototype._pushContext = Context.prototype._pushContext; +Promise.prototype._popContext = Context.prototype._popContext; + +return createContext; +}; + +},{}],10:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, CapturedTrace) { +var async = _dereq_("./async.js"); +var Warning = _dereq_("./errors.js").Warning; +var util = _dereq_("./util.js"); +var canAttachTrace = util.canAttachTrace; +var unhandledRejectionHandled; +var possiblyUnhandledRejection; +var debugging = false || (util.isNode && + (!!process.env["BLUEBIRD_DEBUG"] || + process.env["NODE_ENV"] === "development")); + +Promise.prototype._ensurePossibleRejectionHandled = function () { + this._setRejectionIsUnhandled(); + async.invokeLater(this._notifyUnhandledRejection, this, undefined); +}; + +Promise.prototype._notifyUnhandledRejectionIsHandled = function () { + CapturedTrace.fireRejectionEvent("rejectionHandled", + unhandledRejectionHandled, undefined, this); +}; + +Promise.prototype._notifyUnhandledRejection = function () { + if (this._isRejectionUnhandled()) { + var reason = this._getCarriedStackTrace() || this._settledValue; + this._setUnhandledRejectionIsNotified(); + CapturedTrace.fireRejectionEvent("unhandledRejection", + possiblyUnhandledRejection, reason, this); + } +}; + +Promise.prototype._setUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField | 524288; +}; + +Promise.prototype._unsetUnhandledRejectionIsNotified = function () { + this._bitField = this._bitField & (~524288); +}; + +Promise.prototype._isUnhandledRejectionNotified = function () { + return (this._bitField & 524288) > 0; +}; + +Promise.prototype._setRejectionIsUnhandled = function () { + this._bitField = this._bitField | 2097152; +}; + +Promise.prototype._unsetRejectionIsUnhandled = function () { + this._bitField = this._bitField & (~2097152); + if (this._isUnhandledRejectionNotified()) { + this._unsetUnhandledRejectionIsNotified(); + this._notifyUnhandledRejectionIsHandled(); + } +}; + +Promise.prototype._isRejectionUnhandled = function () { + return (this._bitField & 2097152) > 0; +}; + +Promise.prototype._setCarriedStackTrace = function (capturedTrace) { + this._bitField = this._bitField | 1048576; + this._fulfillmentHandler0 = capturedTrace; +}; + +Promise.prototype._isCarryingStackTrace = function () { + return (this._bitField & 1048576) > 0; +}; + +Promise.prototype._getCarriedStackTrace = function () { + return this._isCarryingStackTrace() + ? this._fulfillmentHandler0 + : undefined; +}; + +Promise.prototype._captureStackTrace = function () { + if (debugging) { + this._trace = new CapturedTrace(this._peekContext()); + } + return this; +}; + +Promise.prototype._attachExtraTrace = function (error, ignoreSelf) { + if (debugging && canAttachTrace(error)) { + var trace = this._trace; + if (trace !== undefined) { + if (ignoreSelf) trace = trace._parent; + } + if (trace !== undefined) { + trace.attachExtraTrace(error); + } else if (!error.__stackCleaned__) { + var parsed = CapturedTrace.parseStackAndMessage(error); + error.stack = parsed.message + "\n" + parsed.stack.join("\n"); + util.notEnumerableProp(error, "__stackCleaned__", true); + } + } +}; + +Promise.prototype._warn = function(message) { + var warning = new Warning(message); + var ctx = this._peekContext(); + if (ctx) { + ctx.attachExtraTrace(warning); + } else { + var parsed = CapturedTrace.parseStackAndMessage(warning); + warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); + } + CapturedTrace.formatAndLogError(warning, ""); +}; + +Promise.onPossiblyUnhandledRejection = function (fn) { + possiblyUnhandledRejection = typeof fn === "function" ? fn : undefined; +}; + +Promise.onUnhandledRejectionHandled = function (fn) { + unhandledRejectionHandled = typeof fn === "function" ? fn : undefined; +}; + +Promise.longStackTraces = function () { + if (async.haveItemsQueued() && + debugging === false + ) { + throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a"); + } + debugging = CapturedTrace.isSupported(); +}; + +Promise.hasLongStackTraces = function () { + return debugging && CapturedTrace.isSupported(); +}; + +if (!CapturedTrace.isSupported()) { + Promise.longStackTraces = function(){}; + debugging = false; +} + +return function() { + return debugging; +}; +}; + +},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){ "use strict"; -var util = require("./util.js"); +var util = _dereq_("./util.js"); var isPrimitive = util.isPrimitive; var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; module.exports = function(Promise) { -var returner = function Promise$_returner() { +var returner = function () { return this; }; -var thrower = function Promise$_thrower() { +var thrower = function () { throw this; }; -var wrapper = function Promise$_wrapper(value, action) { +var wrapper = function (value, action) { if (action === 1) { - return function Promise$_thrower() { + return function () { throw value; }; - } - else if (action === 2) { - return function Promise$_returner() { + } else if (action === 2) { + return function () { return value; }; } @@ -2808,241 +3258,188 @@ var wrapper = function Promise$_wrapper(value, action) { Promise.prototype["return"] = -Promise.prototype.thenReturn = -function Promise$thenReturn(value) { +Promise.prototype.thenReturn = function (value) { if (wrapsPrimitiveReceiver && isPrimitive(value)) { return this._then( wrapper(value, 2), - void 0, - void 0, - void 0, - void 0, - this.thenReturn + undefined, + undefined, + undefined, + undefined ); } - return this._then(returner, void 0, void 0, - value, void 0, this.thenReturn); + return this._then(returner, undefined, undefined, value, undefined); }; Promise.prototype["throw"] = -Promise.prototype.thenThrow = -function Promise$thenThrow(reason) { +Promise.prototype.thenThrow = function (reason) { if (wrapsPrimitiveReceiver && isPrimitive(reason)) { return this._then( wrapper(reason, 1), - void 0, - void 0, - void 0, - void 0, - this.thenThrow + undefined, + undefined, + undefined, + undefined ); } - return this._then(thrower, void 0, void 0, - reason, void 0, this.thenThrow); + return this._then(thrower, undefined, undefined, reason, undefined); }; }; -},{"./util.js":38}],9:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./util.js":38}],12:[function(_dereq_,module,exports){ "use strict"; -var global = require("./global.js"); -var Objectfreeze = require("./es5.js").freeze; -var util = require("./util.js"); -var inherits = util.inherits; -var notEnumerableProp = util.notEnumerableProp; -var Error = global.Error; - -function markAsOriginatingFromRejection(e) { - try { - notEnumerableProp(e, "isAsync", true); - } - catch(ignore) {} -} +module.exports = function(Promise, INTERNAL) { +var PromiseReduce = Promise.reduce; -function originatesFromRejection(e) { - if (e == null) return false; - return ((e instanceof RejectionError) || - e["isAsync"] === true); -} +Promise.prototype.each = function (fn) { + return PromiseReduce(this, fn, null, INTERNAL); +}; -function isError(obj) { - return obj instanceof Error; -} +Promise.each = function (promises, fn) { + return PromiseReduce(promises, fn, null, INTERNAL); +}; +}; -function canAttach(obj) { - return isError(obj); -} +},{}],13:[function(_dereq_,module,exports){ +"use strict"; +var es5 = _dereq_("./es5.js"); +var Objectfreeze = es5.freeze; +var util = _dereq_("./util.js"); +var inherits = util.inherits; +var notEnumerableProp = util.notEnumerableProp; function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); - this.message = typeof message === "string" ? message : defaultMessage; - this.name = nameProperty; + notEnumerableProp(this, "message", + typeof message === "string" ? message : defaultMessage); + notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); + } else { + Error.call(this); } } inherits(SubError, Error); return SubError; } -var TypeError = global.TypeError; -if (typeof TypeError !== "function") { - TypeError = subError("TypeError", "type error"); -} -var RangeError = global.RangeError; -if (typeof RangeError !== "function") { - RangeError = subError("RangeError", "range error"); -} +var _TypeError, _RangeError; +var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); +var AggregateError = subError("AggregateError", "aggregate error"); +try { + _TypeError = TypeError; + _RangeError = RangeError; +} catch(e) { + _TypeError = subError("TypeError", "type error"); + _RangeError = subError("RangeError", "range error"); +} -function RejectionError(message) { - this.name = "RejectionError"; - this.message = message; +var methods = ("join pop push shift unshift slice filter forEach some " + + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); + +for (var i = 0; i < methods.length; ++i) { + if (typeof Array.prototype[methods[i]] === "function") { + AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; + } +} + +es5.defineProperty(AggregateError.prototype, "length", { + value: 0, + configurable: false, + writable: true, + enumerable: true +}); +AggregateError.prototype["isOperational"] = true; +var level = 0; +AggregateError.prototype.toString = function() { + var indent = Array(level * 4 + 1).join(" "); + var ret = "\n" + indent + "AggregateError of:" + "\n"; + level++; + indent = Array(level * 4 + 1).join(" "); + for (var i = 0; i < this.length; ++i) { + var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; + var lines = str.split("\n"); + for (var j = 0; j < lines.length; ++j) { + lines[j] = indent + lines[j]; + } + str = lines.join("\n"); + ret += str + "\n"; + } + level--; + return ret; +}; + +function OperationalError(message) { + if (!(this instanceof OperationalError)) + return new OperationalError(message); + notEnumerableProp(this, "name", "OperationalError"); + notEnumerableProp(this, "message", message); this.cause = message; - this.isAsync = true; + this["isOperational"] = true; if (message instanceof Error) { - this.message = message.message; - this.stack = message.stack; - } - else if (Error.captureStackTrace) { + notEnumerableProp(this, "message", message.message); + notEnumerableProp(this, "stack", message.stack); + } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } -inherits(RejectionError, Error); +inherits(OperationalError, Error); -var key = "__BluebirdErrorTypes__"; -var errorTypes = global[key]; +var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, TimeoutError: TimeoutError, - RejectionError: RejectionError + OperationalError: OperationalError, + RejectionError: OperationalError, + AggregateError: AggregateError }); - notEnumerableProp(global, key, errorTypes); + notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); } module.exports = { Error: Error, - TypeError: TypeError, - RangeError: RangeError, + TypeError: _TypeError, + RangeError: _RangeError, CancellationError: errorTypes.CancellationError, - RejectionError: errorTypes.RejectionError, + OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, - originatesFromRejection: originatesFromRejection, - markAsOriginatingFromRejection: markAsOriginatingFromRejection, - canAttach: canAttach -}; - -},{"./es5.js":11,"./global.js":15,"./util.js":38}],10:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise) { -var TypeError = require('./errors.js').TypeError; - -function apiRejection(msg) { - var error = new TypeError(msg); - var ret = Promise.rejected(error); - var parent = ret._peekContext(); - if (parent != null) { - parent._attachExtraTrace(error); - } - return ret; -} - -return apiRejection; + AggregateError: errorTypes.AggregateError, + Warning: Warning }; -},{"./errors.js":9}],11:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; - return this === void 0; + return this === undefined; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, + getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, + names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, - isES5: isES5 + isES5: isES5, + propertyIsWritable: function(obj, prop) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return !!(!descriptor || descriptor.writable || descriptor.set); + } }; -} - -else { +} else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; - function ObjectKeys(o) { + var ObjectKeys = function (o) { var ret = []; for (var key in o) { if (has.call(o, key)) { @@ -3050,754 +3447,791 @@ else { } } return ret; - } + }; - function ObjectDefineProperty(o, key, desc) { + var ObjectGetDescriptor = function(o, key) { + return {value: o[key]}; + }; + + var ObjectDefineProperty = function (o, key, desc) { o[key] = desc.value; return o; - } + }; - function ObjectFreeze(obj) { + var ObjectFreeze = function (obj) { return obj; - } + }; - function ObjectGetPrototypeOf(obj) { + var ObjectGetPrototypeOf = function (obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } - } + }; - function ArrayIsArray(obj) { + var ArrayIsArray = function (obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } - } + }; module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, + names: ObjectKeys, defineProperty: ObjectDefineProperty, + getDescriptor: ObjectGetDescriptor, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, - isES5: isES5 + isES5: isES5, + propertyIsWritable: function() { + return true; + } }; } -},{}],12:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{}],15:[function(_dereq_,module,exports){ "use strict"; -module.exports = function(Promise) { - var isArray = require("./util.js").isArray; +module.exports = function(Promise, INTERNAL) { +var PromiseMap = Promise.map; - function Promise$_filter(booleans) { - var values = this._settledValue; - var len = values.length; - var ret = new Array(len); - var j = 0; +Promise.prototype.filter = function (fn, options) { + return PromiseMap(this, fn, options, INTERNAL); +}; - for (var i = 0; i < len; ++i) { - if (booleans[i]) ret[j++] = values[i]; +Promise.filter = function (promises, fn, options) { + return PromiseMap(promises, fn, options, INTERNAL); +}; +}; - } - ret.length = j; - return ret; - } +},{}],16:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) { +var util = _dereq_("./util.js"); +var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; +var isPrimitive = util.isPrimitive; +var thrower = util.thrower; - var ref = {ref: null}; - Promise.filter = function Promise$Filter(promises, fn) { - return Promise.map(promises, fn, ref) - ._then(Promise$_filter, void 0, void 0, - ref.ref, void 0, Promise.filter); +function returnThis() { + return this; +} +function throwThis() { + throw this; +} +function return$(r) { + return function() { + return r; }; - - Promise.prototype.filter = function Promise$filter(fn) { - return this.map(fn, ref) - ._then(Promise$_filter, void 0, void 0, - ref.ref, void 0, this.filter); +} +function throw$(r) { + return function() { + throw r; }; -}; +} +function promisedFinally(ret, reasonOrValue, isFulfilled) { + var then; + if (wrapsPrimitiveReceiver && isPrimitive(reasonOrValue)) { + then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue); + } else { + then = isFulfilled ? returnThis : throwThis; + } + return ret._then(then, thrower, undefined, reasonOrValue, undefined); +} -},{"./util.js":38}],13:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, NEXT_FILTER) { - var util = require("./util.js"); - var wrapsPrimitiveReceiver = util.wrapsPrimitiveReceiver; - var isPrimitive = util.isPrimitive; - var thrower = util.thrower; +function finallyHandler(reasonOrValue) { + var promise = this.promise; + var handler = this.handler; + var ret = promise._isBound() + ? handler.call(promise._boundTo) + : handler(); - function returnThis() { - return this; - } - function throwThis() { - throw this; - } - function makeReturner(r) { - return function Promise$_returner() { - return r; - }; + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, reasonOrValue, + promise.isFulfilled()); + } } - function makeThrower(r) { - return function Promise$_thrower() { - throw r; - }; + + if (promise.isRejected()) { + NEXT_FILTER.e = reasonOrValue; + return NEXT_FILTER; + } else { + return reasonOrValue; } - function promisedFinally(ret, reasonOrValue, isFulfilled) { - var useConstantFunction = - wrapsPrimitiveReceiver && isPrimitive(reasonOrValue); +} - if (isFulfilled) { - return ret._then( - useConstantFunction - ? returnThis - : makeReturner(reasonOrValue), - thrower, void 0, reasonOrValue, void 0, promisedFinally); - } - else { - return ret._then( - useConstantFunction - ? throwThis - : makeThrower(reasonOrValue), - thrower, void 0, reasonOrValue, void 0, promisedFinally); +function tapHandler(value) { + var promise = this.promise; + var handler = this.handler; + + var ret = promise._isBound() + ? handler.call(promise._boundTo, value) + : handler(value); + + if (ret !== undefined) { + var maybePromise = tryConvertToPromise(ret, promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + return promisedFinally(maybePromise, value, true); } } + return value; +} - function finallyHandler(reasonOrValue) { - var promise = this.promise; - var handler = this.handler; +Promise.prototype._passThroughHandler = function (handler, isFinally) { + if (typeof handler !== "function") return this.then(); - var ret = promise._isBound() - ? handler.call(promise._boundTo) - : handler(); + var promiseAndHandler = { + promise: this, + handler: handler + }; - if (ret !== void 0) { - var maybePromise = Promise._cast(ret, finallyHandler, void 0); - if (maybePromise instanceof Promise) { - return promisedFinally(maybePromise, reasonOrValue, - promise.isFulfilled()); - } - } + return this._then( + isFinally ? finallyHandler : tapHandler, + isFinally ? finallyHandler : undefined, undefined, + promiseAndHandler, undefined); +}; - if (promise.isRejected()) { - NEXT_FILTER.e = reasonOrValue; - return NEXT_FILTER; - } - else { - return reasonOrValue; - } - } +Promise.prototype.lastly = +Promise.prototype["finally"] = function (handler) { + return this._passThroughHandler(handler, true); +}; - function tapHandler(value) { - var promise = this.promise; - var handler = this.handler; +Promise.prototype.tap = function (handler) { + return this._passThroughHandler(handler, false); +}; +}; - var ret = promise._isBound() - ? handler.call(promise._boundTo, value) - : handler(value); +},{"./util.js":38}],17:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + apiRejection, + INTERNAL, + tryConvertToPromise) { +var errors = _dereq_("./errors.js"); +var TypeError = errors.TypeError; +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; +var yieldHandlers = []; - if (ret !== void 0) { - var maybePromise = Promise._cast(ret, tapHandler, void 0); - if (maybePromise instanceof Promise) { - return promisedFinally(maybePromise, value, true); - } +function promiseFromYieldHandler(value, yieldHandlers, traceParent) { + for (var i = 0; i < yieldHandlers.length; ++i) { + traceParent._pushContext(); + var result = tryCatch(yieldHandlers[i])(value); + traceParent._popContext(); + if (result === errorObj) { + traceParent._pushContext(); + var ret = Promise.reject(errorObj.e); + traceParent._popContext(); + return ret; } - return value; + var maybePromise = tryConvertToPromise(result, traceParent); + if (maybePromise instanceof Promise) return maybePromise; } + return null; +} - Promise.prototype._passThroughHandler = - function Promise$_passThroughHandler(handler, isFinally, caller) { - if (typeof handler !== "function") return this.then(); +function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { + var promise = this._promise = new Promise(INTERNAL); + promise._captureStackTrace(); + this._stack = stack; + this._generatorFunction = generatorFunction; + this._receiver = receiver; + this._generator = undefined; + this._yieldHandlers = typeof yieldHandler === "function" + ? [yieldHandler].concat(yieldHandlers) + : yieldHandlers; +} - var promiseAndHandler = { - promise: this, - handler: handler - }; +PromiseSpawn.prototype.promise = function () { + return this._promise; +}; - return this._then( - isFinally ? finallyHandler : tapHandler, - isFinally ? finallyHandler : void 0, void 0, - promiseAndHandler, void 0, caller); - }; +PromiseSpawn.prototype._run = function () { + this._generator = this._generatorFunction.call(this._receiver); + this._receiver = + this._generatorFunction = undefined; + this._next(undefined); +}; - Promise.prototype.lastly = - Promise.prototype["finally"] = function Promise$finally(handler) { - return this._passThroughHandler(handler, true, this.lastly); - }; +PromiseSpawn.prototype._continue = function (result) { + if (result === errorObj) { + return this._promise._rejectCallback(result.e, false, true); + } - Promise.prototype.tap = function Promise$tap(handler) { - return this._passThroughHandler(handler, false, this.tap); - }; + var value = result.value; + if (result.done === true) { + this._promise._resolveCallback(value); + } else { + var maybePromise = tryConvertToPromise(value, this._promise); + if (!(maybePromise instanceof Promise)) { + maybePromise = + promiseFromYieldHandler(maybePromise, + this._yieldHandlers, + this._promise); + if (maybePromise === null) { + this._throw( + new TypeError( + "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) + + "From coroutine:\u000a" + + this._stack.split("\n").slice(1, -7).join("\n") + ) + ); + return; + } + } + maybePromise._then( + this._next, + this._throw, + undefined, + this, + null + ); + } }; -},{"./util.js":38}],14:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, apiRejection, INTERNAL) { - var PromiseSpawn = require("./promise_spawn.js")(Promise, INTERNAL); - var errors = require("./errors.js"); - var TypeError = errors.TypeError; - var deprecated = require("./util.js").deprecated; - - Promise.coroutine = function Promise$Coroutine(generatorFunction) { - if (typeof generatorFunction !== "function") { - throw new TypeError("generatorFunction must be a function"); - } - var PromiseSpawn$ = PromiseSpawn; - return function anonymous() { - var generator = generatorFunction.apply(this, arguments); - var spawn = new PromiseSpawn$(void 0, void 0, anonymous); - spawn._generator = generator; - spawn._next(void 0); - return spawn.promise(); - }; - }; +PromiseSpawn.prototype._throw = function (reason) { + this._promise._attachExtraTrace(reason); + this._promise._pushContext(); + var result = tryCatch(this._generator["throw"]) + .call(this._generator, reason); + this._promise._popContext(); + this._continue(result); +}; - Promise.coroutine.addYieldHandler = PromiseSpawn.addYieldHandler; +PromiseSpawn.prototype._next = function (value) { + this._promise._pushContext(); + var result = tryCatch(this._generator.next).call(this._generator, value); + this._promise._popContext(); + this._continue(result); +}; - Promise.spawn = function Promise$Spawn(generatorFunction) { - deprecated("Promise.spawn is deprecated. Use Promise.coroutine instead."); - if (typeof generatorFunction !== "function") { - return apiRejection("generatorFunction must be a function"); - } - var spawn = new PromiseSpawn(generatorFunction, this, Promise.spawn); - var ret = spawn.promise(); - spawn._run(Promise.spawn); - return ret; +Promise.coroutine = function (generatorFunction, options) { + if (typeof generatorFunction !== "function") { + throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); + } + var yieldHandler = Object(options).yieldHandler; + var PromiseSpawn$ = PromiseSpawn; + var stack = new Error().stack; + return function () { + var generator = generatorFunction.apply(this, arguments); + var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, + stack); + spawn._generator = generator; + spawn._next(undefined); + return spawn.promise(); }; }; -},{"./errors.js":9,"./promise_spawn.js":23,"./util.js":38}],15:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = (function(){ - if (typeof this !== "undefined") { - return this; - } - if (typeof process !== "undefined" && - typeof global !== "undefined" && - typeof process.execPath === "string") { - return global; - } - if (typeof window !== "undefined" && - typeof document !== "undefined" && - typeof navigator !== "undefined" && navigator !== null && - typeof navigator.appName === "string") { - if(window.wrappedJSObject !== undefined){ - return window.wrappedJSObject; - } - return window; +Promise.coroutine.addYieldHandler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + yieldHandlers.push(fn); +}; + +Promise.spawn = function (generatorFunction) { + if (typeof generatorFunction !== "function") { + return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a"); } -})(); + var spawn = new PromiseSpawn(generatorFunction, this); + var ret = spawn.promise(); + spawn._run(Promise.spawn); + return ret; +}; +}; -},{}],16:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){ "use strict"; -module.exports = function( - Promise, Promise$_CreatePromiseArray, PromiseArray, apiRejection) { - - function Promise$_mapper(values) { - var fn = this; - var receiver = void 0; - - if (typeof fn !== "function") { - receiver = fn.receiver; - fn = fn.fn; +module.exports = +function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { +var util = _dereq_("./util.js"); +var canEvaluate = util.canEvaluate; +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var reject; + +if (!true) { +if (canEvaluate) { + var thenCallback = function(i) { + return new Function("value", "holder", " \n\ + 'use strict'; \n\ + holder.pIndex = value; \n\ + holder.checkFulfillment(this); \n\ + ".replace(/Index/g, i)); + }; + + var caller = function(count) { + var values = []; + for (var i = 1; i <= count; ++i) values.push("holder.p" + i); + return new Function("holder", " \n\ + 'use strict'; \n\ + var callback = holder.fn; \n\ + return callback(values); \n\ + ".replace(/values/g, values.join(", "))); + }; + var thenCallbacks = []; + var callers = [undefined]; + for (var i = 1; i <= 5; ++i) { + thenCallbacks.push(thenCallback(i)); + callers.push(caller(i)); + } + + var Holder = function(total, fn) { + this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null; + this.fn = fn; + this.total = total; + this.now = 0; + }; + + Holder.prototype.callers = callers; + Holder.prototype.checkFulfillment = function(promise) { + var now = this.now; + now++; + var total = this.total; + if (now >= total) { + var handler = this.callers[total]; + promise._pushContext(); + var ret = tryCatch(handler)(this); + promise._popContext(); + if (ret === errorObj) { + promise._rejectCallback(ret.e, false, true); + } else { + promise._resolveCallback(ret); + } + } else { + this.now = now; } - var shouldDefer = false; + }; - var ret = new Array(values.length); + var reject = function (reason) { + this._reject(reason); + }; +} +} - if (receiver === void 0) { - for (var i = 0, len = values.length; i < len; ++i) { - var value = fn(values[i], i, len); - if (!shouldDefer) { - var maybePromise = Promise._cast(value, - Promise$_mapper, void 0); - if (maybePromise instanceof Promise) { - if (maybePromise.isFulfilled()) { - ret[i] = maybePromise._settledValue; - continue; - } - else { - shouldDefer = true; - } - value = maybePromise; - } - } - ret[i] = value; - } - } - else { - for (var i = 0, len = values.length; i < len; ++i) { - var value = fn.call(receiver, values[i], i, len); - if (!shouldDefer) { - var maybePromise = Promise._cast(value, - Promise$_mapper, void 0); +Promise.join = function () { + var last = arguments.length - 1; + var fn; + if (last > 0 && typeof arguments[last] === "function") { + fn = arguments[last]; + if (!true) { + if (last < 6 && canEvaluate) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + var holder = new Holder(last, fn); + var callbacks = thenCallbacks; + for (var i = 0; i < last; ++i) { + var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { - if (maybePromise.isFulfilled()) { - ret[i] = maybePromise._settledValue; - continue; - } - else { - shouldDefer = true; + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._then(callbacks[i], reject, + undefined, ret, holder); + } else if (maybePromise._isFulfilled()) { + callbacks[i].call(ret, + maybePromise._value(), holder); + } else { + ret._reject(maybePromise._reason()); } - value = maybePromise; + } else { + callbacks[i].call(ret, maybePromise, holder); } } - ret[i] = value; + return ret; } } - return shouldDefer - ? Promise$_CreatePromiseArray(ret, PromiseArray, - Promise$_mapper, void 0).promise() - : ret; } + var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} + if (fn) args.pop(); + var ret = new PromiseArray(args).promise(); + return fn !== undefined ? ret.spread(fn) : ret; +}; - function Promise$_Map(promises, fn, useBound, caller, ref) { - if (typeof fn !== "function") { - return apiRejection("fn must be a function"); - } +}; - if (useBound === true && promises._isBound()) { - fn = { - fn: fn, - receiver: promises._boundTo - }; - } +},{"./util.js":38}],19:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +var PENDING = {}; +var EMPTY_ARRAY = []; + +function MappingPromiseArray(promises, fn, limit, _filter) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._callback = fn; + this._preservedValues = _filter === INTERNAL + ? new Array(this.length()) + : null; + this._limit = limit; + this._inFlight = 0; + this._queue = limit >= 1 ? [] : EMPTY_ARRAY; + this._init$(undefined, -2); +} +util.inherits(MappingPromiseArray, PromiseArray); - var ret = Promise$_CreatePromiseArray( - promises, - PromiseArray, - caller, - useBound === true && promises._isBound() - ? promises._boundTo - : void 0 - ).promise(); +MappingPromiseArray.prototype._init = function () {}; - if (ref !== void 0) { - ref.ref = ret; +MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + var length = this.length(); + var preservedValues = this._preservedValues; + var limit = this._limit; + if (values[index] === PENDING) { + values[index] = value; + if (limit >= 1) { + this._inFlight--; + this._drainQueue(); + if (this._isResolved()) return; } + } else { + if (limit >= 1 && this._inFlight >= limit) { + values[index] = value; + this._queue.push(index); + return; + } + if (preservedValues !== null) preservedValues[index] = value; - return ret._then( - Promise$_mapper, - void 0, - void 0, - fn, - void 0, - caller - ); - } + var callback = this._callback; + var receiver = this._promise._boundTo; + this._promise._pushContext(); + var ret = tryCatch(callback).call(receiver, value, index, length); + this._promise._popContext(); + if (ret === errorObj) return this._reject(ret.e); - Promise.prototype.map = function Promise$map(fn, ref) { - return Promise$_Map(this, fn, true, this.map, ref); - }; + var maybePromise = tryConvertToPromise(ret, this._promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + if (limit >= 1) this._inFlight++; + values[index] = PENDING; + return maybePromise._proxyPromiseArray(this, index); + } else if (maybePromise._isFulfilled()) { + ret = maybePromise._value(); + } else { + return this._reject(maybePromise._reason()); + } + } + values[index] = ret; + } + var totalResolved = ++this._totalResolved; + if (totalResolved >= length) { + if (preservedValues !== null) { + this._filter(values, preservedValues); + } else { + this._resolve(values); + } - Promise.map = function Promise$Map(promises, fn, ref) { - return Promise$_Map(promises, fn, false, Promise.map, ref); - }; + } }; -},{}],17:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise) { - var util = require("./util.js"); - var async = require("./async.js"); - var tryCatch2 = util.tryCatch2; - var tryCatch1 = util.tryCatch1; - var errorObj = util.errorObj; - - function thrower(r) { - throw r; +MappingPromiseArray.prototype._drainQueue = function () { + var queue = this._queue; + var limit = this._limit; + var values = this._values; + while (queue.length > 0 && this._inFlight < limit) { + if (this._isResolved()) return; + var index = queue.pop(); + this._promiseFulfilled(values[index], index); } +}; - function Promise$_successAdapter(val, receiver) { - var nodeback = this; - var ret = tryCatch2(nodeback, receiver, null, val); - if (ret === errorObj) { - async.invokeLater(thrower, void 0, ret.e); - } - } - function Promise$_errorAdapter(reason, receiver) { - var nodeback = this; - var ret = tryCatch1(nodeback, receiver, reason); - if (ret === errorObj) { - async.invokeLater(thrower, void 0, ret.e); - } +MappingPromiseArray.prototype._filter = function (booleans, values) { + var len = values.length; + var ret = new Array(len); + var j = 0; + for (var i = 0; i < len; ++i) { + if (booleans[i]) ret[j++] = values[i]; } + ret.length = j; + this._resolve(ret); +}; - Promise.prototype.nodeify = function Promise$nodeify(nodeback) { - if (typeof nodeback == "function") { - this._then( - Promise$_successAdapter, - Promise$_errorAdapter, - void 0, - nodeback, - this._isBound() ? this._boundTo : null, - this.nodeify - ); - return; - } - return this; - }; +MappingPromiseArray.prototype.preservedValues = function () { + return this._preservedValues; }; -},{"./async.js":2,"./util.js":38}],18:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, isPromiseArrayProxy) { - var util = require("./util.js"); - var async = require("./async.js"); - var errors = require("./errors.js"); - var tryCatch1 = util.tryCatch1; - var errorObj = util.errorObj; +function map(promises, fn, options, _filter) { + var limit = typeof options === "object" && options !== null + ? options.concurrency + : 0; + limit = typeof limit === "number" && + isFinite(limit) && limit >= 1 ? limit : 0; + return new MappingPromiseArray(promises, fn, limit, _filter); +} - Promise.prototype.progressed = function Promise$progressed(handler) { - return this._then(void 0, void 0, handler, - void 0, void 0, this.progressed); - }; +Promise.prototype.map = function (fn, options) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); - Promise.prototype._progress = function Promise$_progress(progressValue) { - if (this._isFollowingOrFulfilledOrRejected()) return; - this._progressUnchecked(progressValue); + return map(this, fn, options, null).promise(); +}; - }; +Promise.map = function (promises, fn, options, _filter) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + return map(promises, fn, options, _filter).promise(); +}; - Promise.prototype._progressHandlerAt = - function Promise$_progressHandlerAt(index) { - if (index === 0) return this._progressHandler0; - return this[index + 2 - 5]; - }; - Promise.prototype._doProgressWith = - function Promise$_doProgressWith(progression) { - var progressValue = progression.value; - var handler = progression.handler; - var promise = progression.promise; - var receiver = progression.receiver; +}; - this._pushContext(); - var ret = tryCatch1(handler, receiver, progressValue); - this._popContext(); +},{"./util.js":38}],20:[function(_dereq_,module,exports){ +"use strict"; +module.exports = +function(Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; - if (ret === errorObj) { - if (ret.e != null && - ret.e.name !== "StopProgressPropagation") { - var trace = errors.canAttach(ret.e) - ? ret.e : new Error(ret.e + ""); - promise._attachExtraTrace(trace); - promise._progress(ret.e); - } - } - else if (Promise.is(ret)) { - ret._then(promise._progress, null, null, promise, void 0, - this._progress); - } - else { - promise._progress(ret); - } +Promise.method = function (fn) { + if (typeof fn !== "function") { + throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + return function () { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = tryCatch(fn).apply(this, arguments); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; }; +}; +Promise.attempt = Promise["try"] = function (fn, args, ctx) { + if (typeof fn !== "function") { + return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + } + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._pushContext(); + var value = util.isArray(args) + ? tryCatch(fn).apply(ctx, args) + : tryCatch(fn).call(ctx, args); + ret._popContext(); + ret._resolveFromSyncValue(value); + return ret; +}; - Promise.prototype._progressUnchecked = - function Promise$_progressUnchecked(progressValue) { - if (!this.isPending()) return; - var len = this._length(); +Promise.prototype._resolveFromSyncValue = function (value) { + if (value === util.errorObj) { + this._rejectCallback(value.e, false, true); + } else { + this._resolveCallback(value, true); + } +}; +}; - for (var i = 0; i < len; i += 5) { - var handler = this._progressHandlerAt(i); - var promise = this._promiseAt(i); - if (!Promise.is(promise)) { - var receiver = this._receiverAt(i); - if (typeof handler === "function") { - handler.call(receiver, progressValue, promise); - } - else if (Promise.is(receiver) && receiver._isProxied()) { - receiver._progressUnchecked(progressValue); - } - else if (isPromiseArrayProxy(receiver, promise)) { - receiver._promiseProgressed(progressValue, promise); - } - continue; - } +},{"./util.js":38}],21:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; - if (typeof handler === "function") { - async.invoke(this._doProgressWith, this, { - handler: handler, - promise: promise, - receiver: this._receiverAt(i), - value: progressValue - }); - } - else { - async.invoke(promise._progress, promise, progressValue); - } +function spreadAdapter(val, nodeback) { + var promise = this; + if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); + var ret = tryCatch(nodeback).apply(promise._boundTo, [null].concat(val)); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +function successAdapter(val, nodeback) { + var promise = this; + var receiver = promise._boundTo; + var ret = val === undefined + ? tryCatch(nodeback).call(receiver, null) + : tryCatch(nodeback).call(receiver, null, val); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} +function errorAdapter(reason, nodeback) { + var promise = this; + if (!reason) { + var target = promise._target(); + var newReason = target._getCarriedStackTrace(); + newReason.cause = reason; + reason = newReason; + } + var ret = tryCatch(nodeback).call(promise._boundTo, reason); + if (ret === errorObj) { + async.throwLater(ret.e); + } +} + +Promise.prototype.nodeify = function (nodeback, options) { + if (typeof nodeback == "function") { + var adapter = successAdapter; + if (options !== undefined && Object(options).spread) { + adapter = spreadAdapter; } - }; + this._then( + adapter, + errorAdapter, + undefined, + this, + nodeback + ); + } + return this; +}; }; -},{"./async.js":2,"./errors.js":9,"./util.js":38}],19:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){ "use strict"; -module.exports = function() { -var global = require("./global.js"); -var util = require("./util.js"); -var async = require("./async.js"); -var errors = require("./errors.js"); +module.exports = function(Promise, PromiseArray) { +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; -var INTERNAL = function(){}; -var APPLY = {}; -var NEXT_FILTER = {e: null}; +Promise.prototype.progressed = function (handler) { + return this._then(undefined, undefined, handler, undefined, undefined); +}; -var PromiseArray = require("./promise_array.js")(Promise, INTERNAL); -var CapturedTrace = require("./captured_trace.js")(); -var CatchFilter = require("./catch_filter.js")(NEXT_FILTER); -var PromiseResolver = require("./promise_resolver.js"); +Promise.prototype._progress = function (progressValue) { + if (this._isFollowingOrFulfilledOrRejected()) return; + this._target()._progressUnchecked(progressValue); -var isArray = util.isArray; +}; -var errorObj = util.errorObj; -var tryCatch1 = util.tryCatch1; -var tryCatch2 = util.tryCatch2; -var tryCatchApply = util.tryCatchApply; -var RangeError = errors.RangeError; -var TypeError = errors.TypeError; -var CancellationError = errors.CancellationError; -var TimeoutError = errors.TimeoutError; -var RejectionError = errors.RejectionError; -var originatesFromRejection = errors.originatesFromRejection; -var markAsOriginatingFromRejection = errors.markAsOriginatingFromRejection; -var canAttach = errors.canAttach; -var thrower = util.thrower; -var apiRejection = require("./errors_api_rejection")(Promise); +Promise.prototype._progressHandlerAt = function (index) { + return index === 0 + ? this._progressHandler0 + : this[(index << 2) + index - 5 + 2]; +}; +Promise.prototype._doProgressWith = function (progression) { + var progressValue = progression.value; + var handler = progression.handler; + var promise = progression.promise; + var receiver = progression.receiver; -var makeSelfResolutionError = function Promise$_makeSelfResolutionError() { - return new TypeError("circular promise resolution chain"); + var ret = tryCatch(handler).call(receiver, progressValue); + if (ret === errorObj) { + if (ret.e != null && + ret.e.name !== "StopProgressPropagation") { + var trace = util.canAttachTrace(ret.e) + ? ret.e : new Error(util.toString(ret.e)); + promise._attachExtraTrace(trace); + promise._progress(ret.e); + } + } else if (ret instanceof Promise) { + ret._then(promise._progress, null, null, promise, undefined); + } else { + promise._progress(ret); + } }; -function isPromise(obj) { - if (obj === void 0) return false; - return obj instanceof Promise; -} -function isPromiseArrayProxy(receiver, promiseSlotValue) { - if (receiver instanceof PromiseArray) { - return promiseSlotValue >= 0; +Promise.prototype._progressUnchecked = function (progressValue) { + var len = this._length(); + var progress = this._progress; + for (var i = 0; i < len; i++) { + var handler = this._progressHandlerAt(i); + var promise = this._promiseAt(i); + if (!(promise instanceof Promise)) { + var receiver = this._receiverAt(i); + if (typeof handler === "function") { + handler.call(receiver, progressValue, promise); + } else if (receiver instanceof PromiseArray && + !receiver._isResolved()) { + receiver._promiseProgressed(progressValue, promise); + } + continue; + } + + if (typeof handler === "function") { + async.invoke(this._doProgressWith, this, { + handler: handler, + promise: promise, + receiver: this._receiverAt(i), + value: progressValue + }); + } else { + async.invoke(progress, promise, progressValue); + } } - return false; -} +}; +}; +},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function() { +var makeSelfResolutionError = function () { + return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a"); +}; +var reflect = function() { + return new Promise.PromiseInspection(this._target()); +}; +var apiRejection = function(msg) { + return Promise.reject(new TypeError(msg)); +}; +var util = _dereq_("./util.js"); +var async = _dereq_("./async.js"); +var errors = _dereq_("./errors.js"); +var TypeError = Promise.TypeError = errors.TypeError; +Promise.RangeError = errors.RangeError; +Promise.CancellationError = errors.CancellationError; +Promise.TimeoutError = errors.TimeoutError; +Promise.OperationalError = errors.OperationalError; +Promise.RejectionError = errors.OperationalError; +Promise.AggregateError = errors.AggregateError; +var INTERNAL = function(){}; +var APPLY = {}; +var NEXT_FILTER = {e: null}; +var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL); +var PromiseArray = + _dereq_("./promise_array.js")(Promise, INTERNAL, + tryConvertToPromise, apiRejection); +var CapturedTrace = _dereq_("./captured_trace.js")(); +var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace); + /*jshint unused:false*/ +var createContext = + _dereq_("./context.js")(Promise, CapturedTrace, isDebugging); +var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER); +var PromiseResolver = _dereq_("./promise_resolver.js"); +var nodebackForPromise = PromiseResolver._nodebackForPromise; +var errorObj = util.errorObj; +var tryCatch = util.tryCatch; function Promise(resolver) { if (typeof resolver !== "function") { - throw new TypeError("the promise constructor requires a resolver function"); + throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a"); } if (this.constructor !== Promise) { - throw new TypeError("the promise constructor cannot be invoked directly"); + throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a"); } this._bitField = 0; - this._fulfillmentHandler0 = void 0; - this._rejectionHandler0 = void 0; - this._promise0 = void 0; - this._receiver0 = void 0; - this._settledValue = void 0; - this._boundTo = void 0; + this._fulfillmentHandler0 = undefined; + this._rejectionHandler0 = undefined; + this._progressHandler0 = undefined; + this._promise0 = undefined; + this._receiver0 = undefined; + this._settledValue = undefined; if (resolver !== INTERNAL) this._resolveFromResolver(resolver); } -Promise.prototype.bind = function Promise$bind(thisArg) { - var ret = new Promise(INTERNAL); - if (debugging) ret._setTrace(this.bind, this); - ret._follow(this); - ret._setBoundTo(thisArg); - if (this._cancellable()) { - ret._setCancellable(); - ret._cancellationParent = this; - } - return ret; -}; - -Promise.prototype.toString = function Promise$toString() { +Promise.prototype.toString = function () { return "[object Promise]"; }; -Promise.prototype.caught = Promise.prototype["catch"] = -function Promise$catch(fn) { +Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), @@ -3806,508 +4240,265 @@ function Promise$catch(fn) { var item = arguments[i]; if (typeof item === "function") { catchInstances[j++] = item; - } - else { - var catchFilterTypeError = - new TypeError( - "A catch filter must be an error constructor " - + "or a filter function"); - - this._attachExtraTrace(catchFilterTypeError); - async.invoke(this._reject, this, catchFilterTypeError); - return; + } else { + return Promise.reject( + new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a")); } } catchInstances.length = j; fn = arguments[i]; - - this._resetTrace(this.caught); var catchFilter = new CatchFilter(catchInstances, fn, this); - return this._then(void 0, catchFilter.doFilter, void 0, - catchFilter, void 0, this.caught); + return this._then(undefined, catchFilter.doFilter, undefined, + catchFilter, undefined); } - return this._then(void 0, fn, void 0, void 0, void 0, this.caught); + return this._then(undefined, fn, undefined, undefined, undefined); }; -Promise.prototype.then = -function Promise$then(didFulfill, didReject, didProgress) { - return this._then(didFulfill, didReject, didProgress, - void 0, void 0, this.then); +Promise.prototype.reflect = function () { + return this._then(reflect, reflect, undefined, this, undefined); }; +Promise.prototype.then = function (didFulfill, didReject, didProgress) { + if (isDebugging() && arguments.length > 0 && + typeof didFulfill !== "function" && + typeof didReject !== "function") { + var msg = ".then() only accepts functions but was passed: " + + util.classString(didFulfill); + if (arguments.length > 1) { + msg += ", " + util.classString(didReject); + } + this._warn(msg); + } + return this._then(didFulfill, didReject, didProgress, + undefined, undefined); +}; -Promise.prototype.done = -function Promise$done(didFulfill, didReject, didProgress) { +Promise.prototype.done = function (didFulfill, didReject, didProgress) { var promise = this._then(didFulfill, didReject, didProgress, - void 0, void 0, this.done); + undefined, undefined); promise._setIsFinal(); }; -Promise.prototype.spread = function Promise$spread(didFulfill, didReject) { - return this._then(didFulfill, didReject, void 0, - APPLY, void 0, this.spread); -}; - -Promise.prototype.isFulfilled = function Promise$isFulfilled() { - return (this._bitField & 268435456) > 0; -}; - - -Promise.prototype.isRejected = function Promise$isRejected() { - return (this._bitField & 134217728) > 0; -}; - -Promise.prototype.isPending = function Promise$isPending() { - return !this.isResolved(); -}; - - -Promise.prototype.isResolved = function Promise$isResolved() { - return (this._bitField & 402653184) > 0; +Promise.prototype.spread = function (didFulfill, didReject) { + return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined); }; - -Promise.prototype.isCancellable = function Promise$isCancellable() { +Promise.prototype.isCancellable = function () { return !this.isResolved() && this._cancellable(); }; -Promise.prototype.toJSON = function Promise$toJSON() { +Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, - fulfillmentValue: void 0, - rejectionReason: void 0 + fulfillmentValue: undefined, + rejectionReason: undefined }; if (this.isFulfilled()) { - ret.fulfillmentValue = this._settledValue; + ret.fulfillmentValue = this.value(); ret.isFulfilled = true; - } - else if (this.isRejected()) { - ret.rejectionReason = this._settledValue; + } else if (this.isRejected()) { + ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; -Promise.prototype.all = function Promise$all() { - return Promise$_all(this, true, this.all); -}; - - -Promise.is = isPromise; - -function Promise$_all(promises, useBound, caller) { - return Promise$_CreatePromiseArray( - promises, - PromiseArray, - caller, - useBound === true && promises._isBound() - ? promises._boundTo - : void 0 - ).promise(); -} -Promise.all = function Promise$All(promises) { - return Promise$_all(promises, false, Promise.all); +Promise.prototype.all = function () { + return new PromiseArray(this).promise(); }; -Promise.join = function Promise$Join() { - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} - return Promise$_CreatePromiseArray( - args, PromiseArray, Promise.join, void 0).promise(); +Promise.prototype.error = function (fn) { + return this.caught(util.originatesFromRejection, fn); }; -Promise.resolve = Promise.fulfilled = -function Promise$Resolve(value, caller) { - var ret = new Promise(INTERNAL); - if (debugging) ret._setTrace(typeof caller === "function" - ? caller - : Promise.resolve, void 0); - if (ret._tryFollow(value)) { - return ret; - } - ret._cleanValues(); - ret._setFulfilled(); - ret._settledValue = value; - return ret; +Promise.is = function (val) { + return val instanceof Promise; }; -Promise.reject = Promise.rejected = function Promise$Reject(reason) { +Promise.fromNode = function(fn) { var ret = new Promise(INTERNAL); - if (debugging) ret._setTrace(Promise.reject, void 0); - markAsOriginatingFromRejection(reason); - ret._cleanValues(); - ret._setRejected(); - ret._settledValue = reason; - if (!canAttach(reason)) { - var trace = new Error(reason + ""); - ret._setCarriedStackTrace(trace); + var result = tryCatch(fn)(nodebackForPromise(ret)); + if (result === errorObj) { + ret._rejectCallback(result.e, true, true); } - ret._ensurePossibleRejectionHandled(); return ret; }; -Promise.prototype.error = function Promise$_error(fn) { - return this.caught(originatesFromRejection, fn); -}; - -Promise.prototype._resolveFromSyncValue = -function Promise$_resolveFromSyncValue(value, caller) { - if (value === errorObj) { - this._cleanValues(); - this._setRejected(); - this._settledValue = value.e; - this._ensurePossibleRejectionHandled(); - } - else { - var maybePromise = Promise._cast(value, caller, void 0); - if (maybePromise instanceof Promise) { - this._follow(maybePromise); - } - else { - this._cleanValues(); - this._setFulfilled(); - this._settledValue = value; - } - } -}; - -Promise.method = function Promise$_Method(fn) { - if (typeof fn !== "function") { - throw new TypeError("fn must be a function"); - } - return function Promise$_method() { - var value; - switch(arguments.length) { - case 0: value = tryCatch1(fn, this, void 0); break; - case 1: value = tryCatch1(fn, this, arguments[0]); break; - case 2: value = tryCatch2(fn, this, arguments[0], arguments[1]); break; - default: - var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];} - value = tryCatchApply(fn, args, this); break; - } - var ret = new Promise(INTERNAL); - if (debugging) ret._setTrace(Promise$_method, void 0); - ret._resolveFromSyncValue(value, Promise$_method); - return ret; - }; -}; - -Promise.attempt = Promise["try"] = function Promise$_Try(fn, args, ctx) { - - if (typeof fn !== "function") { - return apiRejection("fn must be a function"); - } - var value = isArray(args) - ? tryCatchApply(fn, args, ctx) - : tryCatch1(fn, ctx, args); - - var ret = new Promise(INTERNAL); - if (debugging) ret._setTrace(Promise.attempt, void 0); - ret._resolveFromSyncValue(value, Promise.attempt); - return ret; +Promise.all = function (promises) { + return new PromiseArray(promises).promise(); }; -Promise.defer = Promise.pending = function Promise$Defer(caller) { +Promise.defer = Promise.pending = function () { var promise = new Promise(INTERNAL); - if (debugging) promise._setTrace(typeof caller === "function" - ? caller : Promise.defer, void 0); return new PromiseResolver(promise); }; -Promise.bind = function Promise$Bind(thisArg) { - var ret = new Promise(INTERNAL); - if (debugging) ret._setTrace(Promise.bind, void 0); - ret._setFulfilled(); - ret._setBoundTo(thisArg); - return ret; -}; - -Promise.cast = function Promise$_Cast(obj, caller) { - if (typeof caller !== "function") { - caller = Promise.cast; - } - var ret = Promise._cast(obj, caller, void 0); +Promise.cast = function (obj) { + var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { - return Promise.resolve(ret, caller); + var val = ret; + ret = new Promise(INTERNAL); + ret._fulfillUnchecked(val); } return ret; }; -Promise.onPossiblyUnhandledRejection = -function Promise$OnPossiblyUnhandledRejection(fn) { - if (typeof fn === "function") { - CapturedTrace.possiblyUnhandledRejection = fn; - } - else { - CapturedTrace.possiblyUnhandledRejection = void 0; - } -}; - -var debugging = false || !!( - typeof process !== "undefined" && - typeof process.execPath === "string" && - typeof process.env === "object" && - (process.env["BLUEBIRD_DEBUG"] || - process.env["NODE_ENV"] === "development") -); - - -Promise.longStackTraces = function Promise$LongStackTraces() { - if (async.haveItemsQueued() && - debugging === false - ) { - throw new Error("cannot enable long stack traces after promises have been created"); - } - debugging = CapturedTrace.isSupported(); -}; - -Promise.hasLongStackTraces = function Promise$HasLongStackTraces() { - return debugging && CapturedTrace.isSupported(); -}; - -Promise.prototype._setProxyHandlers = -function Promise$_setProxyHandlers(receiver, promiseSlotValue) { - var index = this._length(); - - if (index >= 1048575 - 5) { - index = 0; - this._setLength(0); - } - if (index === 0) { - this._promise0 = promiseSlotValue; - this._receiver0 = receiver; - } - else { - var i = index - 5; - this[i + 3] = promiseSlotValue; - this[i + 4] = receiver; - this[i + 0] = - this[i + 1] = - this[i + 2] = void 0; - } - this._setLength(index + 5); -}; +Promise.resolve = Promise.fulfilled = Promise.cast; -Promise.prototype._proxyPromiseArray = -function Promise$_proxyPromiseArray(promiseArray, index) { - this._setProxyHandlers(promiseArray, index); +Promise.reject = Promise.rejected = function (reason) { + var ret = new Promise(INTERNAL); + ret._captureStackTrace(); + ret._rejectCallback(reason, true); + return ret; }; -Promise.prototype._proxyPromise = function Promise$_proxyPromise(promise) { - promise._setProxied(); - this._setProxyHandlers(promise, -1); +Promise.setScheduler = function(fn) { + if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var prev = async._schedule; + async._schedule = fn; + return prev; }; -Promise.prototype._then = -function Promise$_then( +Promise.prototype._then = function ( didFulfill, didReject, didProgress, receiver, - internalData, - caller + internalData ) { - var haveInternalData = internalData !== void 0; + var haveInternalData = internalData !== undefined; var ret = haveInternalData ? internalData : new Promise(INTERNAL); - if (debugging && !haveInternalData) { - var haveSameContext = this._peekContext() === this._traceParent; - ret._traceParent = haveSameContext ? this._traceParent : this; - ret._setTrace(typeof caller === "function" - ? caller - : this._then, this); + if (!haveInternalData) { + ret._propagateFrom(this, 4 | 1); + ret._captureStackTrace(); } - if (!haveInternalData && this._isBound()) { - ret._setBoundTo(this._boundTo); + var target = this._target(); + if (target !== this) { + if (receiver === undefined) receiver = this._boundTo; + if (!haveInternalData) ret._setIsMigrated(); } var callbackIndex = - this._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); - - if (!haveInternalData && this._cancellable()) { - ret._setCancellable(); - ret._cancellationParent = this; - } + target._addCallbacks(didFulfill, didReject, didProgress, ret, receiver); - if (this.isResolved()) { - async.invoke(this._queueSettleAt, this, callbackIndex); + if (target._isResolved() && !target._isSettlePromisesQueued()) { + async.invoke( + target._settlePromiseAtPostResolution, target, callbackIndex); } return ret; }; -Promise.prototype._length = function Promise$_length() { - return this._bitField & 1048575; +Promise.prototype._settlePromiseAtPostResolution = function (index) { + if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); + this._settlePromiseAt(index); +}; + +Promise.prototype._length = function () { + return this._bitField & 131071; }; -Promise.prototype._isFollowingOrFulfilledOrRejected = -function Promise$_isFollowingOrFulfilledOrRejected() { +Promise.prototype._isFollowingOrFulfilledOrRejected = function () { return (this._bitField & 939524096) > 0; }; -Promise.prototype._isFollowing = function Promise$_isFollowing() { +Promise.prototype._isFollowing = function () { return (this._bitField & 536870912) === 536870912; }; -Promise.prototype._setLength = function Promise$_setLength(len) { - this._bitField = (this._bitField & -1048576) | - (len & 1048575); +Promise.prototype._setLength = function (len) { + this._bitField = (this._bitField & -131072) | + (len & 131071); }; -Promise.prototype._setFulfilled = function Promise$_setFulfilled() { +Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 268435456; }; -Promise.prototype._setRejected = function Promise$_setRejected() { +Promise.prototype._setRejected = function () { this._bitField = this._bitField | 134217728; }; -Promise.prototype._setFollowing = function Promise$_setFollowing() { +Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 536870912; }; -Promise.prototype._setIsFinal = function Promise$_setIsFinal() { +Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 33554432; }; -Promise.prototype._isFinal = function Promise$_isFinal() { +Promise.prototype._isFinal = function () { return (this._bitField & 33554432) > 0; }; -Promise.prototype._cancellable = function Promise$_cancellable() { +Promise.prototype._cancellable = function () { return (this._bitField & 67108864) > 0; }; -Promise.prototype._setCancellable = function Promise$_setCancellable() { +Promise.prototype._setCancellable = function () { this._bitField = this._bitField | 67108864; }; -Promise.prototype._unsetCancellable = function Promise$_unsetCancellable() { +Promise.prototype._unsetCancellable = function () { this._bitField = this._bitField & (~67108864); }; -Promise.prototype._setRejectionIsUnhandled = -function Promise$_setRejectionIsUnhandled() { - this._bitField = this._bitField | 2097152; -}; - -Promise.prototype._unsetRejectionIsUnhandled = -function Promise$_unsetRejectionIsUnhandled() { - this._bitField = this._bitField & (~2097152); -}; - -Promise.prototype._isRejectionUnhandled = -function Promise$_isRejectionUnhandled() { - return (this._bitField & 2097152) > 0; -}; - -Promise.prototype._setCarriedStackTrace = -function Promise$_setCarriedStackTrace(capturedTrace) { - this._bitField = this._bitField | 1048576; - this._fulfillmentHandler0 = capturedTrace; -}; - -Promise.prototype._unsetCarriedStackTrace = -function Promise$_unsetCarriedStackTrace() { - this._bitField = this._bitField & (~1048576); - this._fulfillmentHandler0 = void 0; +Promise.prototype._setIsMigrated = function () { + this._bitField = this._bitField | 4194304; }; -Promise.prototype._isCarryingStackTrace = -function Promise$_isCarryingStackTrace() { - return (this._bitField & 1048576) > 0; +Promise.prototype._unsetIsMigrated = function () { + this._bitField = this._bitField & (~4194304); }; -Promise.prototype._getCarriedStackTrace = -function Promise$_getCarriedStackTrace() { - return this._isCarryingStackTrace() - ? this._fulfillmentHandler0 - : void 0; +Promise.prototype._isMigrated = function () { + return (this._bitField & 4194304) > 0; }; -Promise.prototype._receiverAt = function Promise$_receiverAt(index) { - var ret; - if (index === 0) { - ret = this._receiver0; - } - else { - ret = this[index + 4 - 5]; - } - if (this._isBound() && ret === void 0) { +Promise.prototype._receiverAt = function (index) { + var ret = index === 0 + ? this._receiver0 + : this[ + index * 5 - 5 + 4]; + if (ret === undefined && this._isBound()) { return this._boundTo; } return ret; }; -Promise.prototype._promiseAt = function Promise$_promiseAt(index) { - if (index === 0) return this._promise0; - return this[index + 3 - 5]; -}; - -Promise.prototype._fulfillmentHandlerAt = -function Promise$_fulfillmentHandlerAt(index) { - if (index === 0) return this._fulfillmentHandler0; - return this[index + 0 - 5]; +Promise.prototype._promiseAt = function (index) { + return index === 0 + ? this._promise0 + : this[index * 5 - 5 + 3]; }; -Promise.prototype._rejectionHandlerAt = -function Promise$_rejectionHandlerAt(index) { - if (index === 0) return this._rejectionHandler0; - return this[index + 1 - 5]; +Promise.prototype._fulfillmentHandlerAt = function (index) { + return index === 0 + ? this._fulfillmentHandler0 + : this[index * 5 - 5 + 0]; }; -Promise.prototype._unsetAt = function Promise$_unsetAt(index) { - if (index === 0) { - this._rejectionHandler0 = - this._progressHandler0 = - this._promise0 = - this._receiver0 = void 0; - if (!this._isCarryingStackTrace()) { - this._fulfillmentHandler0 = void 0; - } - } - else { - this[index - 5 + 0] = - this[index - 5 + 1] = - this[index - 5 + 2] = - this[index - 5 + 3] = - this[index - 5 + 4] = void 0; - } +Promise.prototype._rejectionHandlerAt = function (index) { + return index === 0 + ? this._rejectionHandler0 + : this[index * 5 - 5 + 1]; }; -Promise.prototype._resolveFromResolver = -function Promise$_resolveFromResolver(resolver) { - var promise = this; - var localDebugging = debugging; - if (localDebugging) { - this._setTrace(this._resolveFromResolver, void 0); - this._pushContext(); - } - function Promise$_resolver(val) { - if (promise._tryFollow(val)) { - return; - } - promise._fulfill(val); - } - function Promise$_rejecter(val) { - var trace = canAttach(val) ? val : new Error(val + ""); - promise._attachExtraTrace(trace); - markAsOriginatingFromRejection(val); - promise._reject(val, trace === val ? void 0 : trace); - } - var r = tryCatch2(resolver, void 0, Promise$_resolver, Promise$_rejecter); - if (localDebugging) this._popContext(); - - if (r !== void 0 && r === errorObj) { - var e = r.e; - var trace = canAttach(e) ? e : new Error(e + ""); - promise._reject(e, trace); - } +Promise.prototype._migrateCallbacks = function (follower, index) { + var fulfill = follower._fulfillmentHandlerAt(index); + var reject = follower._rejectionHandlerAt(index); + var progress = follower._progressHandlerAt(index); + var promise = follower._promiseAt(index); + var receiver = follower._receiverAt(index); + if (promise instanceof Promise) promise._setIsMigrated(); + this._addCallbacks(fulfill, reject, progress, promise, receiver); }; -Promise.prototype._addCallbacks = function Promise$_addCallbacks( +Promise.prototype._addCallbacks = function ( fulfill, reject, progress, @@ -4316,757 +4507,485 @@ Promise.prototype._addCallbacks = function Promise$_addCallbacks( ) { var index = this._length(); - if (index >= 1048575 - 5) { + if (index >= 131071 - 5) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; - if (receiver !== void 0) this._receiver0 = receiver; + if (receiver !== undefined) this._receiver0 = receiver; if (typeof fulfill === "function" && !this._isCarryingStackTrace()) this._fulfillmentHandler0 = fulfill; if (typeof reject === "function") this._rejectionHandler0 = reject; if (typeof progress === "function") this._progressHandler0 = progress; - } - else { - var i = index - 5; - this[i + 3] = promise; - this[i + 4] = receiver; - this[i + 0] = typeof fulfill === "function" - ? fulfill : void 0; - this[i + 1] = typeof reject === "function" - ? reject : void 0; - this[i + 2] = typeof progress === "function" - ? progress : void 0; - } - this._setLength(index + 5); + } else { + var base = index * 5 - 5; + this[base + 3] = promise; + this[base + 4] = receiver; + if (typeof fulfill === "function") + this[base + 0] = fulfill; + if (typeof reject === "function") + this[base + 1] = reject; + if (typeof progress === "function") + this[base + 2] = progress; + } + this._setLength(index + 1); return index; }; +Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) { + var index = this._length(); - -Promise.prototype._setBoundTo = function Promise$_setBoundTo(obj) { - if (obj !== void 0) { - this._bitField = this._bitField | 8388608; - this._boundTo = obj; + if (index >= 131071 - 5) { + index = 0; + this._setLength(0); } - else { - this._bitField = this._bitField & (~8388608); + if (index === 0) { + this._promise0 = promiseSlotValue; + this._receiver0 = receiver; + } else { + var base = index * 5 - 5; + this[base + 3] = promiseSlotValue; + this[base + 4] = receiver; } + this._setLength(index + 1); }; -Promise.prototype._isBound = function Promise$_isBound() { - return (this._bitField & 8388608) === 8388608; -}; - -Promise.prototype._spreadSlowCase = -function Promise$_spreadSlowCase(targetFn, promise, values, boundTo) { - var promiseForAll = - Promise$_CreatePromiseArray - (values, PromiseArray, this._spreadSlowCase, boundTo) - .promise() - ._then(function() { - return targetFn.apply(boundTo, arguments); - }, void 0, void 0, APPLY, void 0, this._spreadSlowCase); - - promise._follow(promiseForAll); +Promise.prototype._proxyPromiseArray = function (promiseArray, index) { + this._setProxyHandlers(promiseArray, index); }; -Promise.prototype._callSpread = -function Promise$_callSpread(handler, promise, value, localDebugging) { - var boundTo = this._isBound() ? this._boundTo : void 0; - if (isArray(value)) { - var caller = this._settlePromiseFromHandler; - for (var i = 0, len = value.length; i < len; ++i) { - if (isPromise(Promise._cast(value[i], caller, void 0))) { - this._spreadSlowCase(handler, promise, value, boundTo); - return; - } +Promise.prototype._resolveCallback = function(value, shouldBind) { + if (this._isFollowingOrFulfilledOrRejected()) return; + if (value === this) + return this._rejectCallback(makeSelfResolutionError(), false, true); + var maybePromise = tryConvertToPromise(value, this); + if (!(maybePromise instanceof Promise)) return this._fulfill(value); + + var propagationFlags = 1 | (shouldBind ? 4 : 0); + this._propagateFrom(maybePromise, propagationFlags); + var promise = maybePromise._target(); + if (promise._isPending()) { + var len = this._length(); + for (var i = 0; i < len; ++i) { + promise._migrateCallbacks(this, i); } + this._setFollowing(); + this._setLength(0); + this._setFollowee(promise); + } else if (promise._isFulfilled()) { + this._fulfillUnchecked(promise._value()); + } else { + this._rejectUnchecked(promise._reason(), + promise._getCarriedStackTrace()); } - if (localDebugging) promise._pushContext(); - return tryCatchApply(handler, value, boundTo); -}; - -Promise.prototype._callHandler = -function Promise$_callHandler( - handler, receiver, promise, value, localDebugging) { - var x; - if (receiver === APPLY && !this.isRejected()) { - x = this._callSpread(handler, promise, value, localDebugging); - } - else { - if (localDebugging) promise._pushContext(); - x = tryCatch1(handler, receiver, value); - } - if (localDebugging) promise._popContext(); - return x; }; -Promise.prototype._settlePromiseFromHandler = -function Promise$_settlePromiseFromHandler( - handler, receiver, value, promise -) { - if (!isPromise(promise)) { - handler.call(receiver, value, promise); - return; - } - - var localDebugging = debugging; - var x = this._callHandler(handler, receiver, - promise, value, localDebugging); - - if (promise._isFollowing()) return; - - if (x === errorObj || x === promise || x === NEXT_FILTER) { - var err = x === promise - ? makeSelfResolutionError() - : x.e; - var trace = canAttach(err) ? err : new Error(err + ""); - if (x !== NEXT_FILTER) promise._attachExtraTrace(trace); - promise._rejectUnchecked(err, trace); - } - else { - var castValue = Promise._cast(x, - localDebugging ? this._settlePromiseFromHandler : void 0, - promise); - - if (isPromise(castValue)) { - if (castValue.isRejected() && - !castValue._isCarryingStackTrace() && - !canAttach(castValue._settledValue)) { - var trace = new Error(castValue._settledValue + ""); - promise._attachExtraTrace(trace); - castValue._setCarriedStackTrace(trace); - } - promise._follow(castValue); - if (castValue._cancellable()) { - promise._cancellationParent = castValue; - promise._setCancellable(); - } - } - else { - promise._fulfillUnchecked(x); - } +Promise.prototype._rejectCallback = +function(reason, synchronous, shouldNotMarkOriginatingFromRejection) { + if (!shouldNotMarkOriginatingFromRejection) { + util.markAsOriginatingFromRejection(reason); } + var trace = util.ensureErrorObject(reason); + var hasStack = trace === reason; + this._attachExtraTrace(trace, synchronous ? hasStack : false); + this._reject(reason, hasStack ? undefined : trace); }; -Promise.prototype._follow = -function Promise$_follow(promise) { - this._setFollowing(); - - if (promise.isPending()) { - if (promise._cancellable() ) { - this._cancellationParent = promise; - this._setCancellable(); - } - promise._proxyPromise(this); - } - else if (promise.isFulfilled()) { - this._fulfillUnchecked(promise._settledValue); - } - else { - this._rejectUnchecked(promise._settledValue, - promise._getCarriedStackTrace()); - } - - if (promise._isRejectionUnhandled()) promise._unsetRejectionIsUnhandled(); +Promise.prototype._resolveFromResolver = function (resolver) { + var promise = this; + this._captureStackTrace(); + this._pushContext(); + var synchronous = true; + var r = tryCatch(resolver)(function(value) { + if (promise === null) return; + promise._resolveCallback(value); + promise = null; + }, function (reason) { + if (promise === null) return; + promise._rejectCallback(reason, synchronous); + promise = null; + }); + synchronous = false; + this._popContext(); - if (debugging && - promise._traceParent == null) { - promise._traceParent = this; + if (r !== undefined && r === errorObj && promise !== null) { + promise._rejectCallback(r.e, true, true); + promise = null; } }; -Promise.prototype._tryFollow = -function Promise$_tryFollow(value) { - if (this._isFollowingOrFulfilledOrRejected() || - value === this) { - return false; +Promise.prototype._settlePromiseFromHandler = function ( + handler, receiver, value, promise +) { + if (promise._isRejected()) return; + promise._pushContext(); + var x; + if (receiver === APPLY && !this._isRejected()) { + x = tryCatch(handler).apply(this._boundTo, value); + } else { + x = tryCatch(handler).call(receiver, value); } - var maybePromise = Promise._cast(value, this._tryFollow, void 0); - if (!isPromise(maybePromise)) { - return false; + promise._popContext(); + + if (x === errorObj || x === promise || x === NEXT_FILTER) { + var err = x === promise ? makeSelfResolutionError() : x.e; + promise._rejectCallback(err, false, true); + } else { + promise._resolveCallback(x); } - this._follow(maybePromise); - return true; }; -Promise.prototype._resetTrace = function Promise$_resetTrace(caller) { - if (debugging) { - var context = this._peekContext(); - var isTopLevel = context === void 0; - this._trace = new CapturedTrace( - typeof caller === "function" - ? caller - : this._resetTrace, - isTopLevel - ); - } +Promise.prototype._target = function() { + var ret = this; + while (ret._isFollowing()) ret = ret._followee(); + return ret; }; -Promise.prototype._setTrace = function Promise$_setTrace(caller, parent) { - if (debugging) { - var context = this._peekContext(); - this._traceParent = context; - var isTopLevel = context === void 0; - if (parent !== void 0 && - parent._traceParent === context) { - this._trace = parent._trace; - } - else { - this._trace = new CapturedTrace( - typeof caller === "function" - ? caller - : this._setTrace, - isTopLevel - ); - } - } - return this; +Promise.prototype._followee = function() { + return this._rejectionHandler0; }; -Promise.prototype._attachExtraTrace = -function Promise$_attachExtraTrace(error) { - if (debugging) { - var promise = this; - var stack = error.stack; - stack = typeof stack === "string" - ? stack.split("\n") : []; - var headerLineCount = 1; - - while(promise != null && - promise._trace != null) { - stack = CapturedTrace.combine( - stack, - promise._trace.stack.split("\n") - ); - promise = promise._traceParent; - } +Promise.prototype._setFollowee = function(promise) { + this._rejectionHandler0 = promise; +}; - var max = Error.stackTraceLimit + headerLineCount; - var len = stack.length; - if (len > max) { - stack.length = max; - } - if (stack.length <= headerLineCount) { - error.stack = "(No stack trace)"; - } - else { - error.stack = stack.join("\n"); - } +Promise.prototype._cleanValues = function () { + if (this._cancellable()) { + this._cancellationParent = undefined; } }; -Promise.prototype._cleanValues = function Promise$_cleanValues() { - if (this._cancellable()) { - this._cancellationParent = void 0; +Promise.prototype._propagateFrom = function (parent, flags) { + if ((flags & 1) > 0 && parent._cancellable()) { + this._setCancellable(); + this._cancellationParent = parent; + } + if ((flags & 4) > 0 && parent._isBound()) { + this._setBoundTo(parent._boundTo); } }; -Promise.prototype._fulfill = function Promise$_fulfill(value) { +Promise.prototype._fulfill = function (value) { if (this._isFollowingOrFulfilledOrRejected()) return; this._fulfillUnchecked(value); }; -Promise.prototype._reject = -function Promise$_reject(reason, carriedStackTrace) { +Promise.prototype._reject = function (reason, carriedStackTrace) { if (this._isFollowingOrFulfilledOrRejected()) return; this._rejectUnchecked(reason, carriedStackTrace); }; -Promise.prototype._settlePromiseAt = function Promise$_settlePromiseAt(index) { - var handler = this.isFulfilled() +Promise.prototype._settlePromiseAt = function (index) { + var promise = this._promiseAt(index); + var isPromise = promise instanceof Promise; + + if (isPromise && promise._isMigrated()) { + promise._unsetIsMigrated(); + return async.invoke(this._settlePromiseAt, this, index); + } + var handler = this._isFulfilled() ? this._fulfillmentHandlerAt(index) : this._rejectionHandlerAt(index); + var carriedStackTrace = + this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined; var value = this._settledValue; var receiver = this._receiverAt(index); - var promise = this._promiseAt(index); - if (typeof handler === "function") { - this._settlePromiseFromHandler(handler, receiver, value, promise); - } - else { - var done = false; - var isFulfilled = this.isFulfilled(); - if (receiver !== void 0) { - if (receiver instanceof Promise && - receiver._isProxied()) { - receiver._unsetProxied(); - - if (isFulfilled) receiver._fulfillUnchecked(value); - else receiver._rejectUnchecked(value, - this._getCarriedStackTrace()); - done = true; - } - else if (isPromiseArrayProxy(receiver, promise)) { - if (isFulfilled) receiver._promiseFulfilled(value, promise); - else receiver._promiseRejected(value, promise); + this._clearCallbackDataAtIndex(index); - done = true; + if (typeof handler === "function") { + if (!isPromise) { + handler.call(receiver, value, promise); + } else { + this._settlePromiseFromHandler(handler, receiver, value, promise); + } + } else if (receiver instanceof PromiseArray) { + if (!receiver._isResolved()) { + if (this._isFulfilled()) { + receiver._promiseFulfilled(value, promise); + } + else { + receiver._promiseRejected(value, promise); } } - - if (!done) { - - if (isFulfilled) promise._fulfill(value); - else promise._reject(value, this._getCarriedStackTrace()); - + } else if (isPromise) { + if (this._isFulfilled()) { + promise._fulfill(value); + } else { + promise._reject(value, carriedStackTrace); } } - if (index >= 256) { - this._queueGC(); - } -}; - -Promise.prototype._isProxied = function Promise$_isProxied() { - return (this._bitField & 4194304) === 4194304; -}; - -Promise.prototype._setProxied = function Promise$_setProxied() { - this._bitField = this._bitField | 4194304; + if (index >= 4 && (index & 31) === 4) + async.invokeLater(this._setLength, this, 0); }; -Promise.prototype._unsetProxied = function Promise$_unsetProxied() { - this._bitField = this._bitField & (~4194304); +Promise.prototype._clearCallbackDataAtIndex = function(index) { + if (index === 0) { + if (!this._isCarryingStackTrace()) { + this._fulfillmentHandler0 = undefined; + } + this._rejectionHandler0 = + this._progressHandler0 = + this._receiver0 = + this._promise0 = undefined; + } else { + var base = index * 5 - 5; + this[base + 3] = + this[base + 4] = + this[base + 0] = + this[base + 1] = + this[base + 2] = undefined; + } }; -Promise.prototype._isGcQueued = function Promise$_isGcQueued() { - return (this._bitField & -1073741824) === -1073741824; +Promise.prototype._isSettlePromisesQueued = function () { + return (this._bitField & + -1073741824) === -1073741824; }; -Promise.prototype._setGcQueued = function Promise$_setGcQueued() { +Promise.prototype._setSettlePromisesQueued = function () { this._bitField = this._bitField | -1073741824; }; -Promise.prototype._unsetGcQueued = function Promise$_unsetGcQueued() { +Promise.prototype._unsetSettlePromisesQueued = function () { this._bitField = this._bitField & (~-1073741824); }; -Promise.prototype._queueGC = function Promise$_queueGC() { - if (this._isGcQueued()) return; - this._setGcQueued(); - async.invokeLater(this._gc, this, void 0); +Promise.prototype._queueSettlePromises = function() { + async.settlePromises(this); + this._setSettlePromisesQueued(); }; -Promise.prototype._gc = function Promise$gc() { - var len = this._length(); - this._unsetAt(0); - for (var i = 0; i < len; i++) { - delete this[i]; - } - this._setLength(0); - this._unsetGcQueued(); -}; - -Promise.prototype._queueSettleAt = function Promise$_queueSettleAt(index) { - if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled(); - async.invoke(this._settlePromiseAt, this, index); -}; - -Promise.prototype._fulfillUnchecked = -function Promise$_fulfillUnchecked(value) { - if (!this.isPending()) return; +Promise.prototype._fulfillUnchecked = function (value) { if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); - return this._rejectUnchecked(err, void 0); + return this._rejectUnchecked(err, undefined); } - this._cleanValues(); this._setFulfilled(); this._settledValue = value; - var len = this._length(); + this._cleanValues(); - if (len > 0) { - async.invoke(this._fulfillPromises, this, len); + if (this._length() > 0) { + this._queueSettlePromises(); } }; -Promise.prototype._rejectUncheckedCheckError = -function Promise$_rejectUncheckedCheckError(reason) { - var trace = canAttach(reason) ? reason : new Error(reason + ""); - this._rejectUnchecked(reason, trace === reason ? void 0 : trace); +Promise.prototype._rejectUncheckedCheckError = function (reason) { + var trace = util.ensureErrorObject(reason); + this._rejectUnchecked(reason, trace === reason ? undefined : trace); }; -Promise.prototype._rejectUnchecked = -function Promise$_rejectUnchecked(reason, trace) { - if (!this.isPending()) return; +Promise.prototype._rejectUnchecked = function (reason, trace) { if (reason === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._rejectUnchecked(err); } - this._cleanValues(); this._setRejected(); this._settledValue = reason; + this._cleanValues(); if (this._isFinal()) { - async.invokeLater(thrower, void 0, trace === void 0 ? reason : trace); + async.throwLater(function(e) { + if ("stack" in e) { + async.invokeFirst( + CapturedTrace.unhandledRejection, undefined, e); + } + throw e; + }, trace === undefined ? reason : trace); return; } - var len = this._length(); - - if (trace !== void 0) this._setCarriedStackTrace(trace); - if (len > 0) { - async.invoke(this._rejectPromises, this, null); + if (trace !== undefined && trace !== reason) { + this._setCarriedStackTrace(trace); } - else { + + if (this._length() > 0) { + this._queueSettlePromises(); + } else { this._ensurePossibleRejectionHandled(); } }; -Promise.prototype._rejectPromises = function Promise$_rejectPromises() { +Promise.prototype._settlePromises = function () { + this._unsetSettlePromisesQueued(); var len = this._length(); - for (var i = 0; i < len; i+= 5) { - this._settlePromiseAt(i); - } - this._unsetCarriedStackTrace(); -}; - -Promise.prototype._fulfillPromises = function Promise$_fulfillPromises(len) { - len = this._length(); - for (var i = 0; i < len; i+= 5) { + for (var i = 0; i < len; i++) { this._settlePromiseAt(i); } }; -Promise.prototype._ensurePossibleRejectionHandled = -function Promise$_ensurePossibleRejectionHandled() { - this._setRejectionIsUnhandled(); - if (CapturedTrace.possiblyUnhandledRejection !== void 0) { - async.invokeLater(this._notifyUnhandledRejection, this, void 0); - } -}; - -Promise.prototype._notifyUnhandledRejection = -function Promise$_notifyUnhandledRejection() { - if (this._isRejectionUnhandled()) { - var reason = this._settledValue; - var trace = this._getCarriedStackTrace(); - - this._unsetRejectionIsUnhandled(); - - if (trace !== void 0) { - this._unsetCarriedStackTrace(); - reason = trace; - } - if (typeof CapturedTrace.possiblyUnhandledRejection === "function") { - CapturedTrace.possiblyUnhandledRejection(reason, this); - } - } -}; - -var contextStack = []; -Promise.prototype._peekContext = function Promise$_peekContext() { - var lastIndex = contextStack.length - 1; - if (lastIndex >= 0) { - return contextStack[lastIndex]; - } - return void 0; - -}; - -Promise.prototype._pushContext = function Promise$_pushContext() { - if (!debugging) return; - contextStack.push(this); -}; - -Promise.prototype._popContext = function Promise$_popContext() { - if (!debugging) return; - contextStack.pop(); -}; - -function Promise$_CreatePromiseArray( - promises, PromiseArrayConstructor, caller, boundTo) { - - var list = null; - if (isArray(promises)) { - list = promises; - } - else { - list = Promise._cast(promises, caller, void 0); - if (list !== promises) { - list._setBoundTo(boundTo); - } - else if (!isPromise(list)) { - list = null; - } - } - if (list !== null) { - return new PromiseArrayConstructor( - list, - typeof caller === "function" - ? caller - : Promise$_CreatePromiseArray, - boundTo - ); - } - return { - promise: function() {return apiRejection("expecting an array, a promise or a thenable");} - }; -} - -var old = global.Promise; - -Promise.noConflict = function() { - if (global.Promise === Promise) { - global.Promise = old; - } - return Promise; -}; - -if (!CapturedTrace.isSupported()) { - Promise.longStackTraces = function(){}; - debugging = false; -} - Promise._makeSelfResolutionError = makeSelfResolutionError; -require("./finally.js")(Promise, NEXT_FILTER); -require("./direct_resolve.js")(Promise); -require("./thenables.js")(Promise, INTERNAL); -Promise.RangeError = RangeError; -Promise.CancellationError = CancellationError; -Promise.TimeoutError = TimeoutError; -Promise.TypeError = TypeError; -Promise.RejectionError = RejectionError; - -util.toFastProperties(Promise); -util.toFastProperties(Promise.prototype); -require('./timers.js')(Promise,INTERNAL); -require('./synchronous_inspection.js')(Promise); -require('./any.js')(Promise,Promise$_CreatePromiseArray,PromiseArray); -require('./race.js')(Promise,INTERNAL); -require('./call_get.js')(Promise); -require('./filter.js')(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection); -require('./generators.js')(Promise,apiRejection,INTERNAL); -require('./map.js')(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection); -require('./nodeify.js')(Promise); -require('./promisify.js')(Promise,INTERNAL); -require('./props.js')(Promise,PromiseArray); -require('./reduce.js')(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection,INTERNAL); -require('./settle.js')(Promise,Promise$_CreatePromiseArray,PromiseArray); -require('./some.js')(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection); -require('./progress.js')(Promise,isPromiseArrayProxy); -require('./cancel.js')(Promise,INTERNAL); - -Promise.prototype = Promise.prototype; -return Promise; - -}; - -},{"./any.js":1,"./async.js":2,"./call_get.js":4,"./cancel.js":5,"./captured_trace.js":6,"./catch_filter.js":7,"./direct_resolve.js":8,"./errors.js":9,"./errors_api_rejection":10,"./filter.js":12,"./finally.js":13,"./generators.js":14,"./global.js":15,"./map.js":16,"./nodeify.js":17,"./progress.js":18,"./promise_array.js":20,"./promise_resolver.js":22,"./promisify.js":24,"./props.js":26,"./race.js":28,"./reduce.js":29,"./settle.js":31,"./some.js":33,"./synchronous_inspection.js":35,"./thenables.js":36,"./timers.js":37,"./util.js":38}],20:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise); +_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise); +_dereq_("./direct_resolve.js")(Promise); +_dereq_("./synchronous_inspection.js")(Promise); +_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL); +Promise.Promise = Promise; +_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext); +_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise); +_dereq_('./nodeify.js')(Promise); +_dereq_('./cancel.js')(Promise); +_dereq_('./promisify.js')(Promise, INTERNAL); +_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); +_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); +_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL); +_dereq_('./settle.js')(Promise, PromiseArray); +_dereq_('./call_get.js')(Promise); +_dereq_('./some.js')(Promise, PromiseArray, apiRejection); +_dereq_('./progress.js')(Promise, PromiseArray); +_dereq_('./any.js')(Promise); +_dereq_('./each.js')(Promise, INTERNAL); +_dereq_('./timers.js')(Promise, INTERNAL); +_dereq_('./filter.js')(Promise, INTERNAL); + + util.toFastProperties(Promise); + util.toFastProperties(Promise.prototype); + function fillTypes(value) { + var p = new Promise(INTERNAL); + p._fulfillmentHandler0 = value; + p._rejectionHandler0 = value; + p._progressHandler0 = value; + p._promise0 = value; + p._receiver0 = value; + p._settledValue = value; + } + // Complete slack tracking, opt out of field-type tracking and + // stabilize map + fillTypes({a: 1}); + fillTypes({b: 2}); + fillTypes({c: 3}); + fillTypes(1); + fillTypes(function(){}); + fillTypes(undefined); + fillTypes(false); + fillTypes(new Promise(INTERNAL)); + CapturedTrace.setBounds(async.firstLineError, util.lastLineError); + return Promise; + +}; + +},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){ "use strict"; -module.exports = function(Promise, INTERNAL) { -var canAttach = require("./errors.js").canAttach; -var util = require("./util.js"); -var async = require("./async.js"); -var hasOwn = {}.hasOwnProperty; +module.exports = function(Promise, INTERNAL, tryConvertToPromise, + apiRejection) { +var util = _dereq_("./util.js"); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { - case -1: return void 0; case -2: return []; case -3: return {}; } } -function PromiseArray(values, caller, boundTo) { +function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); - var parent = void 0; - if (Promise.is(values)) { + var parent; + if (values instanceof Promise) { parent = values; - if (values._cancellable()) { - promise._setCancellable(); - promise._cancellationParent = values; - } - if (values._isBound()) { - promise._setBoundTo(boundTo); - } + promise._propagateFrom(parent, 1 | 4); } - promise._setTrace(caller, parent); this._values = values; this._length = 0; this._totalResolved = 0; - this._init(void 0, -2); + this._init(undefined, -2); } -PromiseArray.PropertiesPromiseArray = function() {}; - -PromiseArray.prototype.length = function PromiseArray$length() { +PromiseArray.prototype.length = function () { return this._length; }; -PromiseArray.prototype.promise = function PromiseArray$promise() { +PromiseArray.prototype.promise = function () { return this._promise; }; -PromiseArray.prototype._init = -function PromiseArray$_init(_, resolveValueIfEmpty) { - var values = this._values; - if (Promise.is(values)) { - if (values.isFulfilled()) { - values = values._settledValue; +PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { + var values = tryConvertToPromise(this._values, this._promise); + if (values instanceof Promise) { + values = values._target(); + this._values = values; + if (values._isFulfilled()) { + values = values._value(); if (!isArray(values)) { - var err = new Promise.TypeError("expecting an array, a promise or a thenable"); + var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); this.__hardReject__(err); return; } - this._values = values; - } - else if (values.isPending()) { + } else if (values._isPending()) { values._then( - this._init, + init, this._reject, - void 0, + undefined, this, - resolveValueIfEmpty, - this.constructor + resolveValueIfEmpty ); return; - } - else { - this._reject(values._settledValue); + } else { + this._reject(values._reason()); return; } + } else if (!isArray(values)) { + this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason()); + return; } if (values.length === 0) { - this._resolve(toResolutionValue(resolveValueIfEmpty)); - return; - } - var len = values.length; - var newLen = len; - var newValues; - if (this instanceof PromiseArray.PropertiesPromiseArray) { - newValues = this._values; - } - else { - newValues = new Array(len); - } - var isDirectScanNeeded = false; - for (var i = 0; i < len; ++i) { - var promise = values[i]; - if (promise === void 0 && !hasOwn.call(values, i)) { - newLen--; - continue; - } - var maybePromise = Promise._cast(promise, void 0, void 0); - if (maybePromise instanceof Promise) { - if (maybePromise.isPending()) { - maybePromise._proxyPromiseArray(this, i); - } - else { - maybePromise._unsetRejectionIsUnhandled(); - isDirectScanNeeded = true; - } - } - else { - isDirectScanNeeded = true; - } - newValues[i] = maybePromise; - } - if (newLen === 0) { - if (resolveValueIfEmpty === -2) { - this._resolve(newValues); + if (resolveValueIfEmpty === -5) { + this._resolveEmptyArray(); } else { this._resolve(toResolutionValue(resolveValueIfEmpty)); } return; } - this._values = newValues; - this._length = newLen; - if (isDirectScanNeeded) { - var scanMethod = newLen === len - ? this._scanDirectValues - : this._scanDirectValuesHoled; - async.invoke(scanMethod, this, len); - } -}; - -PromiseArray.prototype._settlePromiseAt = -function PromiseArray$_settlePromiseAt(index) { - var value = this._values[index]; - if (!Promise.is(value)) { - this._promiseFulfilled(value, index); - } - else if (value.isFulfilled()) { - this._promiseFulfilled(value._settledValue, index); - } - else if (value.isRejected()) { - this._promiseRejected(value._settledValue, index); - } -}; - -PromiseArray.prototype._scanDirectValuesHoled = -function PromiseArray$_scanDirectValuesHoled(len) { - for (var i = 0; i < len; ++i) { - if (this._isResolved()) { - break; - } - if (hasOwn.call(this._values, i)) { - this._settlePromiseAt(i); - } - } -}; - -PromiseArray.prototype._scanDirectValues = -function PromiseArray$_scanDirectValues(len) { + var len = this.getActualLength(values.length); + this._length = len; + this._values = this.shouldCopyValues() ? new Array(len) : this._values; + var promise = this._promise; for (var i = 0; i < len; ++i) { - if (this._isResolved()) { - break; + var isResolved = this._isResolved(); + var maybePromise = tryConvertToPromise(values[i], promise); + if (maybePromise instanceof Promise) { + maybePromise = maybePromise._target(); + if (isResolved) { + maybePromise._unsetRejectionIsUnhandled(); + } else if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, i); + } else if (maybePromise._isFulfilled()) { + this._promiseFulfilled(maybePromise._value(), i); + } else { + this._promiseRejected(maybePromise._reason(), i); + } + } else if (!isResolved) { + this._promiseFulfilled(maybePromise, i); } - this._settlePromiseAt(i); } }; -PromiseArray.prototype._isResolved = function PromiseArray$_isResolved() { +PromiseArray.prototype._isResolved = function () { return this._values === null; }; -PromiseArray.prototype._resolve = function PromiseArray$_resolve(value) { +PromiseArray.prototype._resolve = function (value) { this._values = null; this._promise._fulfill(value); }; PromiseArray.prototype.__hardReject__ = -PromiseArray.prototype._reject = function PromiseArray$_reject(reason) { +PromiseArray.prototype._reject = function (reason) { this._values = null; - var trace = canAttach(reason) ? reason : new Error(reason + ""); - this._promise._attachExtraTrace(trace); - this._promise._reject(reason, trace); + this._promise._rejectCallback(reason, false, true); }; -PromiseArray.prototype._promiseProgressed = -function PromiseArray$_promiseProgressed(progressValue, index) { - if (this._isResolved()) return; +PromiseArray.prototype._promiseProgressed = function (progressValue, index) { this._promise._progress({ index: index, value: progressValue @@ -5074,9 +4993,7 @@ function PromiseArray$_promiseProgressed(progressValue, index) { }; -PromiseArray.prototype._promiseFulfilled = -function PromiseArray$_promiseFulfilled(value, index) { - if (this._isResolved()) return; +PromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { @@ -5084,169 +5001,88 @@ function PromiseArray$_promiseFulfilled(value, index) { } }; -PromiseArray.prototype._promiseRejected = -function PromiseArray$_promiseRejected(reason, index) { - if (this._isResolved()) return; +PromiseArray.prototype._promiseRejected = function (reason, index) { this._totalResolved++; this._reject(reason); }; -return PromiseArray; -}; - -},{"./async.js":2,"./errors.js":9,"./util.js":38}],21:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var TypeError = require("./errors.js").TypeError; - -function PromiseInspection(promise) { - if (promise !== void 0) { - this._bitField = promise._bitField; - this._settledValue = promise.isResolved() - ? promise._settledValue - : void 0; - } - else { - this._bitField = 0; - this._settledValue = void 0; - } -} -PromiseInspection.prototype.isFulfilled = -function PromiseInspection$isFulfilled() { - return (this._bitField & 268435456) > 0; -}; - -PromiseInspection.prototype.isRejected = -function PromiseInspection$isRejected() { - return (this._bitField & 134217728) > 0; -}; - -PromiseInspection.prototype.isPending = function PromiseInspection$isPending() { - return (this._bitField & 402653184) === 0; -}; - -PromiseInspection.prototype.value = function PromiseInspection$value() { - if (!this.isFulfilled()) { - throw new TypeError("cannot get fulfillment value of a non-fulfilled promise"); - } - return this._settledValue; +PromiseArray.prototype.shouldCopyValues = function () { + return true; }; -PromiseInspection.prototype.error = function PromiseInspection$error() { - if (!this.isRejected()) { - throw new TypeError("cannot get rejection reason of a non-rejected promise"); - } - return this._settledValue; +PromiseArray.prototype.getActualLength = function (len) { + return len; }; -module.exports = PromiseInspection; +return PromiseArray; +}; -},{"./errors.js":9}],22:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./util.js":38}],25:[function(_dereq_,module,exports){ "use strict"; -var util = require("./util.js"); +var util = _dereq_("./util.js"); var maybeWrapAsError = util.maybeWrapAsError; -var errors = require("./errors.js"); +var errors = _dereq_("./errors.js"); var TimeoutError = errors.TimeoutError; -var RejectionError = errors.RejectionError; -var async = require("./async.js"); +var OperationalError = errors.OperationalError; var haveGetters = util.haveGetters; -var es5 = require("./es5.js"); +var es5 = _dereq_("./es5.js"); function isUntypedError(obj) { return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; } -function wrapAsRejectionError(obj) { +var rErrorKey = /^(?:name|message|stack|cause)$/; +function wrapAsOperationalError(obj) { var ret; if (isUntypedError(obj)) { - ret = new RejectionError(obj); - } - else { - ret = obj; + ret = new OperationalError(obj); + ret.name = obj.name; + ret.message = obj.message; + ret.stack = obj.stack; + var keys = es5.keys(obj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (!rErrorKey.test(key)) { + ret[key] = obj[key]; + } + } + return ret; } - errors.markAsOriginatingFromRejection(ret); - return ret; + util.markAsOriginatingFromRejection(obj); + return obj; } function nodebackForPromise(promise) { - function PromiseResolver$_callback(err, value) { + return function(err, value) { if (promise === null) return; if (err) { - var wrapped = wrapAsRejectionError(maybeWrapAsError(err)); + var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); promise._attachExtraTrace(wrapped); promise._reject(wrapped); - } - else { - if (arguments.length > 2) { - var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} - promise._fulfill(args); - } - else { - promise._fulfill(value); - } + } else if (arguments.length > 2) { + var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];} + promise._fulfill(args); + } else { + promise._fulfill(value); } promise = null; - } - return PromiseResolver$_callback; + }; } var PromiseResolver; if (!haveGetters) { - PromiseResolver = function PromiseResolver(promise) { + PromiseResolver = function (promise) { this.promise = promise; this.asCallback = nodebackForPromise(promise); this.callback = this.asCallback; }; } else { - PromiseResolver = function PromiseResolver(promise) { + PromiseResolver = function (promise) { this.promise = promise; }; } @@ -5262,415 +5098,266 @@ if (haveGetters) { PromiseResolver._nodebackForPromise = nodebackForPromise; -PromiseResolver.prototype.toString = function PromiseResolver$toString() { +PromiseResolver.prototype.toString = function () { return "[object PromiseResolver]"; }; PromiseResolver.prototype.resolve = -PromiseResolver.prototype.fulfill = function PromiseResolver$resolve(value) { - var promise = this.promise; - if (promise._tryFollow(value)) { - return; +PromiseResolver.prototype.fulfill = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); } - async.invoke(promise._fulfill, promise, value); + this.promise._resolveCallback(value); }; -PromiseResolver.prototype.reject = function PromiseResolver$reject(reason) { - var promise = this.promise; - errors.markAsOriginatingFromRejection(reason); - var trace = errors.canAttach(reason) ? reason : new Error(reason + ""); - promise._attachExtraTrace(trace); - async.invoke(promise._reject, promise, reason); - if (trace !== reason) { - async.invoke(this._setCarriedStackTrace, this, trace); +PromiseResolver.prototype.reject = function (reason) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); } + this.promise._rejectCallback(reason); }; -PromiseResolver.prototype.progress = -function PromiseResolver$progress(value) { - async.invoke(this.promise._progress, this.promise, value); +PromiseResolver.prototype.progress = function (value) { + if (!(this instanceof PromiseResolver)) { + throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a"); + } + this.promise._progress(value); }; -PromiseResolver.prototype.cancel = function PromiseResolver$cancel() { - async.invoke(this.promise.cancel, this.promise, void 0); +PromiseResolver.prototype.cancel = function (err) { + this.promise.cancel(err); }; -PromiseResolver.prototype.timeout = function PromiseResolver$timeout() { +PromiseResolver.prototype.timeout = function () { this.reject(new TimeoutError("timeout")); }; -PromiseResolver.prototype.isResolved = function PromiseResolver$isResolved() { +PromiseResolver.prototype.isResolved = function () { return this.promise.isResolved(); }; -PromiseResolver.prototype.toJSON = function PromiseResolver$toJSON() { +PromiseResolver.prototype.toJSON = function () { return this.promise.toJSON(); }; -PromiseResolver.prototype._setCarriedStackTrace = -function PromiseResolver$_setCarriedStackTrace(trace) { - if (this.promise.isRejected()) { - this.promise._setCarriedStackTrace(trace); - } -}; - module.exports = PromiseResolver; -},{"./async.js":2,"./errors.js":9,"./es5.js":11,"./util.js":38}],23:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { -var errors = require("./errors.js"); -var TypeError = errors.TypeError; -var util = require("./util.js"); -var isArray = util.isArray; -var errorObj = util.errorObj; -var tryCatch1 = util.tryCatch1; -var yieldHandlers = []; +var THIS = {}; +var util = _dereq_("./util.js"); +var nodebackForPromise = _dereq_("./promise_resolver.js") + ._nodebackForPromise; +var withAppended = util.withAppended; +var maybeWrapAsError = util.maybeWrapAsError; +var canEvaluate = util.canEvaluate; +var TypeError = _dereq_("./errors").TypeError; +var defaultSuffix = "Async"; +var defaultPromisified = {__isPromisified__: true}; +var noCopyPropsPattern = + /^(?:length|name|arguments|caller|prototype|__isPromisified__)$/; +var defaultFilter = function(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +}; + +function propsFilter(key) { + return !noCopyPropsPattern.test(key); +} -function promiseFromYieldHandler(value) { - var _yieldHandlers = yieldHandlers; - var _errorObj = errorObj; - var _Promise = Promise; - var len = _yieldHandlers.length; - for (var i = 0; i < len; ++i) { - var result = tryCatch1(_yieldHandlers[i], void 0, value); - if (result === _errorObj) { - return _Promise.reject(_errorObj.e); - } - var maybePromise = _Promise._cast(result, - promiseFromYieldHandler, void 0); - if (maybePromise instanceof _Promise) return maybePromise; +function isPromisified(fn) { + try { + return fn.__isPromisified__ === true; + } + catch (e) { + return false; } - return null; } -function PromiseSpawn(generatorFunction, receiver, caller) { - var promise = this._promise = new Promise(INTERNAL); - promise._setTrace(caller, void 0); - this._generatorFunction = generatorFunction; - this._receiver = receiver; - this._generator = void 0; +function hasPromisified(obj, key, suffix) { + var val = util.getDataPropertyOrDefault(obj, key + suffix, + defaultPromisified); + return val ? isPromisified(val) : false; } - -PromiseSpawn.prototype.promise = function PromiseSpawn$promise() { - return this._promise; -}; - -PromiseSpawn.prototype._run = function PromiseSpawn$_run() { - this._generator = this._generatorFunction.call(this._receiver); - this._receiver = - this._generatorFunction = void 0; - this._next(void 0); -}; - -PromiseSpawn.prototype._continue = function PromiseSpawn$_continue(result) { - if (result === errorObj) { - this._generator = void 0; - var trace = errors.canAttach(result.e) - ? result.e : new Error(result.e + ""); - this._promise._attachExtraTrace(trace); - this._promise._reject(result.e, trace); - return; - } - - var value = result.value; - if (result.done === true) { - this._generator = void 0; - if (!this._promise._tryFollow(value)) { - this._promise._fulfill(value); - } - } - else { - var maybePromise = Promise._cast(value, PromiseSpawn$_continue, void 0); - if (!(maybePromise instanceof Promise)) { - if (isArray(maybePromise)) { - maybePromise = Promise.all(maybePromise); - } - else { - maybePromise = promiseFromYieldHandler(maybePromise); - } - if (maybePromise === null) { - this._throw(new TypeError("A value was yielded that could not be treated as a promise")); - return; +function checkValid(ret, suffix, suffixRegexp) { + for (var i = 0; i < ret.length; i += 2) { + var key = ret[i]; + if (suffixRegexp.test(key)) { + var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); + for (var j = 0; j < ret.length; j += 2) { + if (ret[j] === keyWithoutAsyncSuffix) { + throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a" + .replace("%s", suffix)); + } } } - maybePromise._then( - this._next, - this._throw, - void 0, - this, - null, - void 0 - ); } -}; - -PromiseSpawn.prototype._throw = function PromiseSpawn$_throw(reason) { - if (errors.canAttach(reason)) - this._promise._attachExtraTrace(reason); - this._continue( - tryCatch1(this._generator["throw"], this._generator, reason) - ); -}; - -PromiseSpawn.prototype._next = function PromiseSpawn$_next(value) { - this._continue( - tryCatch1(this._generator.next, this._generator, value) - ); -}; +} -PromiseSpawn.addYieldHandler = function PromiseSpawn$AddYieldHandler(fn) { - if (typeof fn !== "function") throw new TypeError("fn must be a function"); - yieldHandlers.push(fn); -}; +function promisifiableMethods(obj, suffix, suffixRegexp, filter) { + var keys = util.inheritedDataKeys(obj); + var ret = []; + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var value = obj[key]; + var passesDefaultFilter = filter === defaultFilter + ? true : defaultFilter(key, value, obj); + if (typeof value === "function" && + !isPromisified(value) && + !hasPromisified(obj, key, suffix) && + filter(key, value, obj, passesDefaultFilter)) { + ret.push(key, value); + } + } + checkValid(ret, suffix, suffixRegexp); + return ret; +} -return PromiseSpawn; +var escapeIdentRegex = function(str) { + return str.replace(/([$])/, "\\$"); }; -},{"./errors.js":9,"./util.js":38}],24:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, INTERNAL) { -var THIS = {}; -var util = require("./util.js"); -var es5 = require("./es5.js"); -var nodebackForPromise = require("./promise_resolver.js") - ._nodebackForPromise; -var withAppended = util.withAppended; -var maybeWrapAsError = util.maybeWrapAsError; -var canEvaluate = util.canEvaluate; -var notEnumerableProp = util.notEnumerableProp; -var deprecated = util.deprecated; -var roriginal = new RegExp("__beforePromisified__" + "$"); -var hasProp = {}.hasOwnProperty; -function isPromisified(fn) { - return fn.__isPromisified__ === true; -} -var inheritedMethods = (function() { - if (es5.isES5) { - var create = Object.create; - var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - return function(cur) { - var original = cur; - var ret = []; - var visitedKeys = create(null); - while (cur !== null) { - var keys = es5.keys(cur); - for (var i = 0, len = keys.length; i < len; ++i) { - var key = keys[i]; - if (visitedKeys[key] || - roriginal.test(key) || - hasProp.call(original, key + "__beforePromisified__") - ) { - continue; - } - visitedKeys[key] = true; - var desc = getOwnPropertyDescriptor(cur, key); - if (desc != null && - typeof desc.value === "function" && - !isPromisified(desc.value)) { - ret.push(key, desc.value); - } - } - cur = es5.getPrototypeOf(cur); - } - return ret; - }; - } - else { - return function(obj) { - var ret = []; - /*jshint forin:false */ - for (var key in obj) { - if (roriginal.test(key) || - hasProp.call(obj, key + "__beforePromisified__")) { - continue; - } - var fn = obj[key]; - if (typeof fn === "function" && - !isPromisified(fn)) { - ret.push(key, fn); - } - } - return ret; - }; - } -})(); - -function switchCaseArgumentOrder(likelyArgumentCount) { +var makeNodePromisifiedEval; +if (!true) { +var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; - var min = Math.max(0, likelyArgumentCount - 1 - 5); + var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { - if (i === likelyArgumentCount) continue; ret.push(i); } - for(var i = likelyArgumentCount + 1; i <= 5; ++i) { + for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; -} +}; -function parameterDeclaration(parameterCount) { - var ret = new Array(parameterCount); - for(var i = 0; i < ret.length; ++i) { - ret[i] = "_arg" + i; - } - return ret.join(", "); -} +var argumentSequence = function(argumentCount) { + return util.filledRange(argumentCount, "_arg", ""); +}; + +var parameterDeclaration = function(parameterCount) { + return util.filledRange( + Math.max(parameterCount, 3), "_arg", ""); +}; -function parameterCount(fn) { +var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; -} - -function propertyAccess(id) { - var rident = /^[a-z$_][a-z$_0-9]*$/i; - - if (rident.test(id)) { - return "." + id; - } - else return "['" + id.replace(/(['\\])/g, "\\$1") + "']"; -} +}; -function makeNodePromisifiedEval(callback, receiver, originalName, fn) { +makeNodePromisifiedEval = +function(callback, receiver, originalName, fn) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); - - var callbackName = (typeof originalName === "string" ? - originalName + "Async" : - "promisified"); + var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { - var args = new Array(count); - for (var i = 0, len = args.length; i < len; ++i) { - args[i] = "arguments[" + i + "]"; - } - var comma = count > 0 ? "," : ""; - - if (typeof callback === "string" && - receiver === THIS) { - return "this" + propertyAccess(callback) + "("+args.join(",") + - comma +" fn);"+ - "break;"; + var args = argumentSequence(count).join(", "); + var comma = count > 0 ? ", " : ""; + var ret; + if (shouldProxyThis) { + ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; + } else { + ret = receiver === undefined + ? "ret = callback({{args}}, nodeback); break;\n" + : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } - return (receiver === void 0 - ? "callback("+args.join(",")+ comma +" fn);" - : "callback.call("+(receiver === THIS - ? "this" - : "receiver")+", "+args.join(",") + comma + " fn);") + - "break;"; + return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; - for(var i = 0; i < argumentOrder.length; ++i) { + for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } - ret += "default: var args = new Array(len + 1);" + - "var i = 0;" + - "for (var i = 0; i < len; ++i) { " + - " args[i] = arguments[i];" + - "}" + - "args[i] = fn;" + - - (typeof callback === "string" - ? "this" + propertyAccess(callback) + ".apply(" - : "callback.apply(") + - (receiver === THIS ? "this" : "receiver") + - ", args); break;"; + ret += " \n\ + default: \n\ + var args = new Array(len + 1); \n\ + var i = 0; \n\ + for (var i = 0; i < len; ++i) { \n\ + args[i] = arguments[i]; \n\ + } \n\ + args[i] = nodeback; \n\ + [CodeForCall] \n\ + break; \n\ + ".replace("[CodeForCall]", (shouldProxyThis + ? "ret = callback.apply(this, args);\n" + : "ret = callback.apply(receiver, args);\n")); return ret; } - return new Function("Promise", "callback", "receiver", - "withAppended", "maybeWrapAsError", "nodebackForPromise", - "INTERNAL", - "var ret = function " + callbackName + - "(" + parameterDeclaration(newParameterCount) + ") {\"use strict\";" + - "var len = arguments.length;" + - "var promise = new Promise(INTERNAL);"+ - "promise._setTrace(" + callbackName + ", void 0);" + - "var fn = nodebackForPromise(promise);"+ - "try {" + - "switch(len) {" + - generateArgumentSwitchCase() + - "}" + - "}" + - "catch(e){ " + - "var wrapped = maybeWrapAsError(e);" + - "promise._attachExtraTrace(wrapped);" + - "promise._reject(wrapped);" + - "}" + - "return promise;" + - "" + - "}; ret.__isPromisified__ = true; return ret;" - )(Promise, callback, receiver, withAppended, - maybeWrapAsError, nodebackForPromise, INTERNAL); + var getFunctionCode = typeof callback === "string" + ? ("this != null ? this['"+callback+"'] : fn") + : "fn"; + + return new Function("Promise", + "fn", + "receiver", + "withAppended", + "maybeWrapAsError", + "nodebackForPromise", + "tryCatch", + "errorObj", + "INTERNAL","'use strict'; \n\ + var ret = function (Parameters) { \n\ + 'use strict'; \n\ + var len = arguments.length; \n\ + var promise = new Promise(INTERNAL); \n\ + promise._captureStackTrace(); \n\ + var nodeback = nodebackForPromise(promise); \n\ + var ret; \n\ + var callback = tryCatch([GetFunctionCode]); \n\ + switch(len) { \n\ + [CodeForSwitchCase] \n\ + } \n\ + if (ret === errorObj) { \n\ + promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ + } \n\ + return promise; \n\ + }; \n\ + ret.__isPromisified__ = true; \n\ + return ret; \n\ + " + .replace("Parameters", parameterDeclaration(newParameterCount)) + .replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) + .replace("[GetFunctionCode]", getFunctionCode))( + Promise, + fn, + receiver, + withAppended, + maybeWrapAsError, + nodebackForPromise, + util.tryCatch, + util.errorObj, + INTERNAL + ); +}; } -function makeNodePromisifiedClosure(callback, receiver) { +function makeNodePromisifiedClosure(callback, receiver, _, fn) { + var defaultThis = (function() {return this;})(); + var method = callback; + if (typeof method === "string") { + callback = fn; + } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; - if (typeof callback === "string") { - callback = _receiver[callback]; - } var promise = new Promise(INTERNAL); - promise._setTrace(promisified, void 0); + promise._captureStackTrace(); + var cb = typeof method === "string" && this !== defaultThis + ? this[method] : callback; var fn = nodebackForPromise(promise); try { - callback.apply(_receiver, withAppended(arguments, fn)); - } - catch(e) { - var wrapped = maybeWrapAsError(e); - promise._attachExtraTrace(wrapped); - promise._reject(wrapped); + cb.apply(_receiver, withAppended(arguments, fn)); + } catch(e) { + promise._rejectCallback(maybeWrapAsError(e), true, true); } return promise; } @@ -5682,105 +5369,98 @@ var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; -function _promisify(callback, receiver, isAll) { - if (isAll) { - var methods = inheritedMethods(callback); - for (var i = 0, len = methods.length; i < len; i+= 2) { - var key = methods[i]; - var fn = methods[i+1]; - var originalKey = key + "__beforePromisified__"; - var promisifiedKey = key + "Async"; - notEnumerableProp(callback, originalKey, fn); - callback[promisifiedKey] = - makeNodePromisified(originalKey, THIS, - key, fn); - } - util.toFastProperties(callback); - return callback; - } - else { - return makeNodePromisified(callback, receiver, void 0, callback); +function promisifyAll(obj, suffix, filter, promisifier) { + var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); + var methods = + promisifiableMethods(obj, suffix, suffixRegexp, filter); + + for (var i = 0, len = methods.length; i < len; i+= 2) { + var key = methods[i]; + var fn = methods[i+1]; + var promisifiedKey = key + suffix; + obj[promisifiedKey] = promisifier === makeNodePromisified + ? makeNodePromisified(key, THIS, key, fn, suffix) + : promisifier(fn, function() { + return makeNodePromisified(key, THIS, key, fn, suffix); + }); } + util.toFastProperties(obj); + return obj; } -Promise.promisify = function Promise$Promisify(fn, receiver) { - if (typeof fn === "object" && fn !== null) { - deprecated("Promise.promisify for promisifying entire objects is deprecated. Use Promise.promisifyAll instead."); - return _promisify(fn, receiver, true); - } +function promisify(callback, receiver) { + return makeNodePromisified(callback, receiver, undefined, callback); +} + +Promise.promisify = function (fn, receiver) { if (typeof fn !== "function") { - throw new TypeError("fn must be a function"); + throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); } if (isPromisified(fn)) { return fn; } - return _promisify( - fn, - arguments.length < 2 ? THIS : receiver, - false); -}; - -Promise.promisifyAll = function Promise$PromisifyAll(target) { - if (typeof target !== "function" && typeof target !== "object") { - throw new TypeError("the target of promisifyAll must be an object or a function"); - } - return _promisify(target, void 0, true); -}; + var ret = promisify(fn, arguments.length < 2 ? THIS : receiver); + util.copyDescriptors(fn, ret, propsFilter); + return ret; }; - -},{"./es5.js":11,"./promise_resolver.js":22,"./util.js":38}],25:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray) { -var util = require("./util.js"); -var inherits = util.inherits; -var es5 = require("./es5.js"); - -function PropertiesPromiseArray(obj, caller, boundTo) { - var keys = es5.keys(obj); - var values = new Array(keys.length); - for (var i = 0, len = values.length; i < len; ++i) { - values[i] = obj[keys[i]]; +Promise.promisifyAll = function (target, options) { + if (typeof target !== "function" && typeof target !== "object") { + throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a"); + } + options = Object(options); + var suffix = options.suffix; + if (typeof suffix !== "string") suffix = defaultSuffix; + var filter = options.filter; + if (typeof filter !== "function") filter = defaultFilter; + var promisifier = options.promisifier; + if (typeof promisifier !== "function") promisifier = makeNodePromisified; + + if (!util.isIdentifier(suffix)) { + throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a"); } - this.constructor$(values, caller, boundTo); - if (!this._isResolved()) { - for (var i = 0, len = keys.length; i < len; ++i) { - values.push(keys[i]); + + var keys = util.inheritedDataKeys(target); + for (var i = 0; i < keys.length; ++i) { + var value = target[keys[i]]; + if (keys[i] !== "constructor" && + util.isClass(value)) { + promisifyAll(value.prototype, suffix, filter, promisifier); + promisifyAll(value, suffix, filter, promisifier); } } + + return promisifyAll(target, suffix, filter, promisifier); +}; +}; + + +},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function( + Promise, PromiseArray, tryConvertToPromise, apiRejection) { +var util = _dereq_("./util.js"); +var isObject = util.isObject; +var es5 = _dereq_("./es5.js"); + +function PropertiesPromiseArray(obj) { + var keys = es5.keys(obj); + var len = keys.length; + var values = new Array(len * 2); + for (var i = 0; i < len; ++i) { + var key = keys[i]; + values[i] = obj[key]; + values[i + len] = key; + } + this.constructor$(values); } -inherits(PropertiesPromiseArray, PromiseArray); +util.inherits(PropertiesPromiseArray, PromiseArray); -PropertiesPromiseArray.prototype._init = -function PropertiesPromiseArray$_init() { - this._init$(void 0, -3) ; +PropertiesPromiseArray.prototype._init = function () { + this._init$(undefined, -3) ; }; -PropertiesPromiseArray.prototype._promiseFulfilled = -function PropertiesPromiseArray$_promiseFulfilled(value, index) { - if (this._isResolved()) return; +PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { @@ -5793,150 +5473,69 @@ function PropertiesPromiseArray$_promiseFulfilled(value, index) { } }; -PropertiesPromiseArray.prototype._promiseProgressed = -function PropertiesPromiseArray$_promiseProgressed(value, index) { - if (this._isResolved()) return; - +PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) { this._promise._progress({ key: this._values[index + this.length()], value: value }); }; -PromiseArray.PropertiesPromiseArray = PropertiesPromiseArray; +PropertiesPromiseArray.prototype.shouldCopyValues = function () { + return false; +}; -return PropertiesPromiseArray; +PropertiesPromiseArray.prototype.getActualLength = function (len) { + return len >> 1; }; -},{"./es5.js":11,"./util.js":38}],26:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray) { - var PropertiesPromiseArray = require("./properties_promise_array.js")( - Promise, PromiseArray); - var util = require("./util.js"); - var apiRejection = require("./errors_api_rejection")(Promise); - var isObject = util.isObject; +function props(promises) { + var ret; + var castValue = tryConvertToPromise(promises); - function Promise$_Props(promises, useBound, caller) { - var ret; - var castValue = Promise._cast(promises, caller, void 0); + if (!isObject(castValue)) { + return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a"); + } else if (castValue instanceof Promise) { + ret = castValue._then( + Promise.props, undefined, undefined, undefined, undefined); + } else { + ret = new PropertiesPromiseArray(castValue).promise(); + } - if (!isObject(castValue)) { - return apiRejection("cannot await properties of a non-object"); - } - else if (Promise.is(castValue)) { - ret = castValue._then(Promise.props, void 0, void 0, - void 0, void 0, caller); - } - else { - ret = new PropertiesPromiseArray( - castValue, - caller, - useBound === true && castValue._isBound() - ? castValue._boundTo - : void 0 - ).promise(); - useBound = false; - } - if (useBound === true && castValue._isBound()) { - ret._setBoundTo(castValue._boundTo); - } - return ret; + if (castValue instanceof Promise) { + ret._propagateFrom(castValue, 4); } + return ret; +} - Promise.prototype.props = function Promise$props() { - return Promise$_Props(this, true, this.props); - }; +Promise.prototype.props = function () { + return props(this); +}; - Promise.props = function Promise$Props(promises) { - return Promise$_Props(promises, false, Promise.props); - }; +Promise.props = function (promises) { + return props(promises); +}; }; -},{"./errors_api_rejection":10,"./properties_promise_array.js":25,"./util.js":38}],27:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){ "use strict"; -function arrayCopy(src, srcIndex, dst, dstIndex, len) { +function arrayMove(src, srcIndex, dst, dstIndex, len) { for (var j = 0; j < len; ++j) { dst[j + dstIndex] = src[j + srcIndex]; + src[j + srcIndex] = void 0; } } -function pow2AtLeast(n) { - n = n >>> 0; - n = n - 1; - n = n | (n >> 1); - n = n | (n >> 2); - n = n | (n >> 4); - n = n | (n >> 8); - n = n | (n >> 16); - return n + 1; -} - -function getCapacity(capacity) { - if (typeof capacity !== "number") return 16; - return pow2AtLeast( - Math.min( - Math.max(16, capacity), 1073741824) - ); -} - function Queue(capacity) { - this._capacity = getCapacity(capacity); + this._capacity = capacity; this._length = 0; this._front = 0; - this._makeCapacity(); } -Queue.prototype._willBeOverCapacity = -function Queue$_willBeOverCapacity(size) { +Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; -Queue.prototype._pushOne = function Queue$_pushOne(arg) { +Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); @@ -5944,7 +5543,24 @@ Queue.prototype._pushOne = function Queue$_pushOne(arg) { this._length = length + 1; }; -Queue.prototype.push = function Queue$push(fn, receiver, arg) { +Queue.prototype._unshiftOne = function(value) { + var capacity = this._capacity; + this._checkCapacity(this.length() + 1); + var front = this._front; + var i = (((( front - 1 ) & + ( capacity - 1) ) ^ capacity ) - capacity ); + this[i] = value; + this._front = i; + this._length = this.length() + 1; +}; + +Queue.prototype.unshift = function(fn, receiver, arg) { + this._unshiftOne(arg); + this._unshiftOne(receiver); + this._unshiftOne(fn); +}; + +Queue.prototype.push = function (fn, receiver, arg) { var length = this.length() + 3; if (this._willBeOverCapacity(length)) { this._pushOne(fn); @@ -5961,528 +5577,272 @@ Queue.prototype.push = function Queue$push(fn, receiver, arg) { this._length = length; }; -Queue.prototype.shift = function Queue$shift() { +Queue.prototype.shift = function () { var front = this._front, ret = this[front]; - this[front] = void 0; + this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; -Queue.prototype.length = function Queue$length() { +Queue.prototype.length = function () { return this._length; }; -Queue.prototype._makeCapacity = function Queue$_makeCapacity() { - var len = this._capacity; - for (var i = 0; i < len; ++i) { - this[i] = void 0; - } -}; - -Queue.prototype._checkCapacity = function Queue$_checkCapacity(size) { +Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { - this._resizeTo(this._capacity << 3); + this._resizeTo(this._capacity << 1); } }; -Queue.prototype._resizeTo = function Queue$_resizeTo(capacity) { - var oldFront = this._front; +Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; - var oldQueue = new Array(oldCapacity); - var length = this.length(); - - arrayCopy(this, 0, oldQueue, 0, oldCapacity); this._capacity = capacity; - this._makeCapacity(); - this._front = 0; - if (oldFront + length <= oldCapacity) { - arrayCopy(oldQueue, oldFront, this, 0, length); - } - else { var lengthBeforeWrapping = - length - ((oldFront + length) & (oldCapacity - 1)); - - arrayCopy(oldQueue, oldFront, this, 0, lengthBeforeWrapping); - arrayCopy(oldQueue, 0, this, lengthBeforeWrapping, - length - lengthBeforeWrapping); - } + var front = this._front; + var length = this._length; + var moveItemsCount = (front + length) & (oldCapacity - 1); + arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; -},{}],28:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{}],29:[function(_dereq_,module,exports){ "use strict"; -module.exports = function(Promise, INTERNAL) { - var apiRejection = require("./errors_api_rejection.js")(Promise); - var isArray = require("./util.js").isArray; - - var raceLater = function Promise$_raceLater(promise) { - return promise.then(function Promise$_lateRacer(array) { - return Promise$_Race(array, Promise$_lateRacer, promise); - }); - }; +module.exports = function( + Promise, INTERNAL, tryConvertToPromise, apiRejection) { +var isArray = _dereq_("./util.js").isArray; - var hasOwn = {}.hasOwnProperty; - function Promise$_Race(promises, caller, parent) { - var maybePromise = Promise._cast(promises, caller, void 0); +var raceLater = function (promise) { + return promise.then(function(array) { + return race(array, promise); + }); +}; - if (Promise.is(maybePromise)) { - return raceLater(maybePromise); - } - else if (!isArray(promises)) { - return apiRejection("expecting an array, a promise or a thenable"); - } +function race(promises, parent) { + var maybePromise = tryConvertToPromise(promises); - var ret = new Promise(INTERNAL); - ret._setTrace(caller, parent); - if (parent !== void 0) { - if (parent._isBound()) { - ret._setBoundTo(parent._boundTo); - } - if (parent._cancellable()) { - ret._setCancellable(); - ret._cancellationParent = parent; - } - } - var fulfill = ret._fulfill; - var reject = ret._reject; - for (var i = 0, len = promises.length; i < len; ++i) { - var val = promises[i]; + if (maybePromise instanceof Promise) { + return raceLater(maybePromise); + } else if (!isArray(promises)) { + return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a"); + } - if (val === void 0 && !(hasOwn.call(promises, i))) { - continue; - } + var ret = new Promise(INTERNAL); + if (parent !== undefined) { + ret._propagateFrom(parent, 4 | 1); + } + var fulfill = ret._fulfill; + var reject = ret._reject; + for (var i = 0, len = promises.length; i < len; ++i) { + var val = promises[i]; - Promise.cast(val)._then( - fulfill, - reject, - void 0, - ret, - null, - caller - ); + if (val === undefined && !(i in promises)) { + continue; } - return ret; + + Promise.cast(val)._then(fulfill, reject, undefined, ret, null); } + return ret; +} - Promise.race = function Promise$Race(promises) { - return Promise$_Race(promises, Promise.race, void 0); - }; +Promise.race = function (promises) { + return race(promises, undefined); +}; - Promise.prototype.race = function Promise$race() { - return Promise$_Race(this, this.race, void 0); - }; +Promise.prototype.race = function () { + return race(this, undefined); +}; }; -},{"./errors_api_rejection.js":10,"./util.js":38}],29:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./util.js":38}],30:[function(_dereq_,module,exports){ "use strict"; -module.exports = function( - Promise, Promise$_CreatePromiseArray, - PromiseArray, apiRejection, INTERNAL) { - - function Reduction(callback, index, accum, items, receiver) { - this.promise = new Promise(INTERNAL); - this.index = index; - this.length = items.length; - this.items = items; - this.callback = callback; - this.receiver = receiver; - this.accum = accum; - } - - Reduction.prototype.reject = function Reduction$reject(e) { - this.promise._reject(e); - }; - - Reduction.prototype.fulfill = function Reduction$fulfill(value, index) { - this.accum = value; - this.index = index + 1; - this.iterate(); - }; - - Reduction.prototype.iterate = function Reduction$iterate() { - var i = this.index; - var len = this.length; - var items = this.items; - var result = this.accum; - var receiver = this.receiver; - var callback = this.callback; - var iterate = this.iterate; - - for(; i < len; ++i) { - result = Promise._cast( - callback.call( - receiver, - result, - items[i], - i, - len - ), - iterate, - void 0 - ); - - if (result instanceof Promise) { - result._then( - this.fulfill, this.reject, void 0, this, i, iterate); - return; - } - } - this.promise._fulfill(result); - }; - - function Promise$_reducer(fulfilleds, initialValue) { - var fn = this; - var receiver = void 0; - if (typeof fn !== "function") { - receiver = fn.receiver; - fn = fn.fn; - } - var len = fulfilleds.length; - var accum = void 0; - var startIndex = 0; - - if (initialValue !== void 0) { - accum = initialValue; - startIndex = 0; - } - else { - startIndex = 1; - if (len > 0) accum = fulfilleds[0]; +module.exports = function(Promise, + PromiseArray, + apiRejection, + tryConvertToPromise, + INTERNAL) { +var util = _dereq_("./util.js"); +var tryCatch = util.tryCatch; +var errorObj = util.errorObj; +function ReductionPromiseArray(promises, fn, accum, _each) { + this.constructor$(promises); + this._promise._captureStackTrace(); + this._preservedValues = _each === INTERNAL ? [] : null; + this._zerothIsAccum = (accum === undefined); + this._gotAccum = false; + this._reducingIndex = (this._zerothIsAccum ? 1 : 0); + this._valuesPhase = undefined; + var maybePromise = tryConvertToPromise(accum, this._promise); + var rejected = false; + var isPromise = maybePromise instanceof Promise; + if (isPromise) { + maybePromise = maybePromise._target(); + if (maybePromise._isPending()) { + maybePromise._proxyPromiseArray(this, -1); + } else if (maybePromise._isFulfilled()) { + accum = maybePromise._value(); + this._gotAccum = true; + } else { + this._reject(maybePromise._reason()); + rejected = true; } - var i = startIndex; + } + if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true; + this._callback = fn; + this._accum = accum; + if (!rejected) this._init$(undefined, -5); +} +util.inherits(ReductionPromiseArray, PromiseArray); - if (i >= len) { - return accum; - } +ReductionPromiseArray.prototype._init = function () {}; - var reduction = new Reduction(fn, i, accum, fulfilleds, receiver); - reduction.iterate(); - return reduction.promise; +ReductionPromiseArray.prototype._resolveEmptyArray = function () { + if (this._gotAccum || this._zerothIsAccum) { + this._resolve(this._preservedValues !== null + ? [] : this._accum); } +}; - function Promise$_unpackReducer(fulfilleds) { - var fn = this.fn; - var initialValue = this.initialValue; - return Promise$_reducer.call(fn, fulfilleds, initialValue); +ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) { + var values = this._values; + values[index] = value; + var length = this.length(); + var preservedValues = this._preservedValues; + var isEach = preservedValues !== null; + var gotAccum = this._gotAccum; + var valuesPhase = this._valuesPhase; + var valuesPhaseIndex; + if (!valuesPhase) { + valuesPhase = this._valuesPhase = new Array(length); + for (valuesPhaseIndex=0; valuesPhaseIndex - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -var global = require("./global.js"); -var schedule; -if (typeof process !== "undefined" && process !== null && - typeof process.cwd === "function" && - typeof process.nextTick === "function" && - typeof process.version === "string") { - schedule = function Promise$_Scheduler(fn) { - process.nextTick(fn); - }; -} -else if ((typeof global.MutationObserver === "function" || - typeof global.WebkitMutationObserver === "function" || - typeof global.WebKitMutationObserver === "function") && - typeof document !== "undefined" && - typeof document.createElement === "function") { - - - schedule = (function(){ - var MutationObserver = global.MutationObserver || - global.WebkitMutationObserver || - global.WebKitMutationObserver; - var div = document.createElement("div"); - var queuedFn = void 0; - var observer = new MutationObserver( - function Promise$_Scheduler() { - var fn = queuedFn; - queuedFn = void 0; - fn(); - } - ); - observer.observe(div, { - attributes: true - }); - return function Promise$_Scheduler(fn) { - queuedFn = fn; - div.setAttribute("class", "foo"); - }; - - })(); +function reduce(promises, fn, initialValue, _each) { + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + var array = new ReductionPromiseArray(promises, fn, initialValue, _each); + return array.promise(); } -else if (typeof global.postMessage === "function" && - typeof global.importScripts !== "function" && - typeof global.addEventListener === "function" && - typeof global.removeEventListener === "function") { - - var MESSAGE_KEY = "bluebird_message_key_" + Math.random(); - schedule = (function(){ - var queuedFn = void 0; - - function Promise$_Scheduler(e) { - if (e.source === global && - e.data === MESSAGE_KEY) { - var fn = queuedFn; - queuedFn = void 0; - fn(); - } - } - global.addEventListener("message", Promise$_Scheduler, false); +Promise.prototype.reduce = function (fn, initialValue) { + return reduce(this, fn, initialValue, null); +}; - return function Promise$_Scheduler(fn) { - queuedFn = fn; - global.postMessage( - MESSAGE_KEY, "*" - ); - }; +Promise.reduce = function (promises, fn, initialValue, _each) { + return reduce(promises, fn, initialValue, _each); +}; +}; - })(); +},{"./util.js":38}],31:[function(_dereq_,module,exports){ +"use strict"; +var schedule; +if (_dereq_("./util.js").isNode) { + var version = process.versions.node.split(".").map(Number); + schedule = (version[0] === 0 && version[1] > 10) || (version[0] > 0) + ? global.setImmediate : process.nextTick; } -else if (typeof global.MessageChannel === "function") { - schedule = (function(){ - var queuedFn = void 0; - - var channel = new global.MessageChannel(); - channel.port1.onmessage = function Promise$_Scheduler() { - var fn = queuedFn; - queuedFn = void 0; - fn(); - }; - - return function Promise$_Scheduler(fn) { - queuedFn = fn; - channel.port2.postMessage(null); - }; - })(); +else if (typeof MutationObserver !== "undefined") { + schedule = function(fn) { + var div = document.createElement("div"); + var observer = new MutationObserver(fn); + observer.observe(div, {attributes: true}); + return function() { div.classList.toggle("foo"); }; + }; + schedule.isStatic = true; } -else if (global.setTimeout) { - schedule = function Promise$_Scheduler(fn) { - setTimeout(fn, 4); +else if (typeof setTimeout !== "undefined") { + schedule = function (fn) { + setTimeout(fn, 0); }; } else { - schedule = function Promise$_Scheduler(fn) { - fn(); + schedule = function() { + throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); }; } - module.exports = schedule; -},{"./global.js":15}],31:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./util.js":38}],32:[function(_dereq_,module,exports){ "use strict"; module.exports = - function(Promise, Promise$_CreatePromiseArray, PromiseArray) { - - var SettledPromiseArray = require("./settled_promise_array.js")( - Promise, PromiseArray); - - function Promise$_Settle(promises, useBound, caller) { - return Promise$_CreatePromiseArray( - promises, - SettledPromiseArray, - caller, - useBound === true && promises._isBound() - ? promises._boundTo - : void 0 - ).promise(); - } - - Promise.settle = function Promise$Settle(promises) { - return Promise$_Settle(promises, false, Promise.settle); - }; - - Promise.prototype.settle = function Promise$settle() { - return Promise$_Settle(this, true, this.settle); - }; + function(Promise, PromiseArray) { +var PromiseInspection = Promise.PromiseInspection; +var util = _dereq_("./util.js"); -}; - -},{"./settled_promise_array.js":32}],32:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = function(Promise, PromiseArray) { -var PromiseInspection = require("./promise_inspection.js"); -var util = require("./util.js"); -var inherits = util.inherits; -function SettledPromiseArray(values, caller, boundTo) { - this.constructor$(values, caller, boundTo); +function SettledPromiseArray(values) { + this.constructor$(values); } -inherits(SettledPromiseArray, PromiseArray); +util.inherits(SettledPromiseArray, PromiseArray); -SettledPromiseArray.prototype._promiseResolved = -function SettledPromiseArray$_promiseResolved(index, inspection) { +SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { this._values[index] = inspection; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { @@ -6490,124 +5850,47 @@ function SettledPromiseArray$_promiseResolved(index, inspection) { } }; -SettledPromiseArray.prototype._promiseFulfilled = -function SettledPromiseArray$_promiseFulfilled(value, index) { - if (this._isResolved()) return; +SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 268435456; ret._settledValue = value; this._promiseResolved(index, ret); }; -SettledPromiseArray.prototype._promiseRejected = -function SettledPromiseArray$_promiseRejected(reason, index) { - if (this._isResolved()) return; +SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 134217728; ret._settledValue = reason; this._promiseResolved(index, ret); }; -return SettledPromiseArray; +Promise.settle = function (promises) { + return new SettledPromiseArray(promises).promise(); }; -},{"./promise_inspection.js":21,"./util.js":38}],33:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; -module.exports = -function(Promise, Promise$_CreatePromiseArray, PromiseArray, apiRejection) { - - var SomePromiseArray = require("./some_promise_array.js")(PromiseArray); - function Promise$_Some(promises, howMany, useBound, caller) { - if ((howMany | 0) !== howMany || howMany < 0) { - return apiRejection("expecting a positive integer"); - } - var ret = Promise$_CreatePromiseArray( - promises, - SomePromiseArray, - caller, - useBound === true && promises._isBound() - ? promises._boundTo - : void 0 - ); - var promise = ret.promise(); - if (promise.isRejected()) { - return promise; - } - ret.setHowMany(howMany); - ret.init(); - return promise; - } - - Promise.some = function Promise$Some(promises, howMany) { - return Promise$_Some(promises, howMany, false, Promise.some); - }; - - Promise.prototype.some = function Promise$some(count) { - return Promise$_Some(this, count, true, this.some); - }; - +Promise.prototype.settle = function () { + return new SettledPromiseArray(this).promise(); +}; }; -},{"./some_promise_array.js":34}],34:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./util.js":38}],33:[function(_dereq_,module,exports){ "use strict"; -module.exports = function (PromiseArray) { -var util = require("./util.js"); -var RangeError = require("./errors.js").RangeError; -var inherits = util.inherits; +module.exports = +function(Promise, PromiseArray, apiRejection) { +var util = _dereq_("./util.js"); +var RangeError = _dereq_("./errors.js").RangeError; +var AggregateError = _dereq_("./errors.js").AggregateError; var isArray = util.isArray; -function SomePromiseArray(values, caller, boundTo) { - this.constructor$(values, caller, boundTo); + +function SomePromiseArray(values) { + this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } -inherits(SomePromiseArray, PromiseArray); +util.inherits(SomePromiseArray, PromiseArray); -SomePromiseArray.prototype._init = function SomePromiseArray$_init() { +SomePromiseArray.prototype._init = function () { if (!this._initialized) { return; } @@ -6615,407 +5898,562 @@ SomePromiseArray.prototype._init = function SomePromiseArray$_init() { this._resolve([]); return; } - this._init$(void 0, -2); + this._init$(undefined, -5); var isArrayResolved = isArray(this._values); - this._holes = isArrayResolved ? this._values.length - this.length() : 0; - if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { - var message = "(Promise.some) input array contains less than " + - this._howMany + " promises"; - this._reject(new RangeError(message)); + this._reject(this._getRangeError(this.length())); } }; -SomePromiseArray.prototype.init = function SomePromiseArray$init() { +SomePromiseArray.prototype.init = function () { this._initialized = true; this._init(); }; -SomePromiseArray.prototype.setUnwrap = function SomePromiseArray$setUnwrap() { +SomePromiseArray.prototype.setUnwrap = function () { this._unwrap = true; }; -SomePromiseArray.prototype.howMany = function SomePromiseArray$howMany() { +SomePromiseArray.prototype.howMany = function () { return this._howMany; }; -SomePromiseArray.prototype.setHowMany = -function SomePromiseArray$setHowMany(count) { - if (this._isResolved()) return; +SomePromiseArray.prototype.setHowMany = function (count) { this._howMany = count; }; -SomePromiseArray.prototype._promiseFulfilled = -function SomePromiseArray$_promiseFulfilled(value) { - if (this._isResolved()) return; +SomePromiseArray.prototype._promiseFulfilled = function (value) { this._addFulfilled(value); if (this._fulfilled() === this.howMany()) { this._values.length = this.howMany(); if (this.howMany() === 1 && this._unwrap) { this._resolve(this._values[0]); - } - else { + } else { this._resolve(this._values); } } }; -SomePromiseArray.prototype._promiseRejected = -function SomePromiseArray$_promiseRejected(reason) { - if (this._isResolved()) return; +SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); if (this.howMany() > this._canPossiblyFulfill()) { - if (this._values.length === this.length()) { - this._reject([]); - } - else { - this._reject(this._values.slice(this.length() + this._holes)); + var e = new AggregateError(); + for (var i = this.length(); i < this._values.length; ++i) { + e.push(this._values[i]); } + this._reject(e); } }; -SomePromiseArray.prototype._fulfilled = function SomePromiseArray$_fulfilled() { +SomePromiseArray.prototype._fulfilled = function () { return this._totalResolved; }; -SomePromiseArray.prototype._rejected = function SomePromiseArray$_rejected() { - return this._values.length - this.length() - this._holes; +SomePromiseArray.prototype._rejected = function () { + return this._values.length - this.length(); }; -SomePromiseArray.prototype._addRejected = -function SomePromiseArray$_addRejected(reason) { +SomePromiseArray.prototype._addRejected = function (reason) { this._values.push(reason); }; -SomePromiseArray.prototype._addFulfilled = -function SomePromiseArray$_addFulfilled(value) { +SomePromiseArray.prototype._addFulfilled = function (value) { this._values[this._totalResolved++] = value; }; -SomePromiseArray.prototype._canPossiblyFulfill = -function SomePromiseArray$_canPossiblyFulfill() { +SomePromiseArray.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected(); }; -return SomePromiseArray; +SomePromiseArray.prototype._getRangeError = function (count) { + var message = "Input array must contain at least " + + this._howMany + " items but contains only " + count + " items"; + return new RangeError(message); }; -},{"./errors.js":9,"./util.js":38}],35:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +SomePromiseArray.prototype._resolveEmptyArray = function () { + this._reject(this._getRangeError(0)); +}; + +function some(promises, howMany) { + if ((howMany | 0) !== howMany || howMany < 0) { + return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a"); + } + var ret = new SomePromiseArray(promises); + var promise = ret.promise(); + ret.setHowMany(howMany); + ret.init(); + return promise; +} + +Promise.some = function (promises, howMany) { + return some(promises, howMany); +}; + +Promise.prototype.some = function (howMany) { + return some(this, howMany); +}; + +Promise._SomePromiseArray = SomePromiseArray; +}; + +},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { - var PromiseInspection = require("./promise_inspection.js"); +function PromiseInspection(promise) { + if (promise !== undefined) { + promise = promise._target(); + this._bitField = promise._bitField; + this._settledValue = promise._settledValue; + } + else { + this._bitField = 0; + this._settledValue = undefined; + } +} + +PromiseInspection.prototype.value = function () { + if (!this.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.error = +PromiseInspection.prototype.reason = function () { + if (!this.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + return this._settledValue; +}; + +PromiseInspection.prototype.isFulfilled = +Promise.prototype._isFulfilled = function () { + return (this._bitField & 268435456) > 0; +}; + +PromiseInspection.prototype.isRejected = +Promise.prototype._isRejected = function () { + return (this._bitField & 134217728) > 0; +}; + +PromiseInspection.prototype.isPending = +Promise.prototype._isPending = function () { + return (this._bitField & 402653184) === 0; +}; + +PromiseInspection.prototype.isResolved = +Promise.prototype._isResolved = function () { + return (this._bitField & 402653184) > 0; +}; + +Promise.prototype.isPending = function() { + return this._target()._isPending(); +}; + +Promise.prototype.isRejected = function() { + return this._target()._isRejected(); +}; + +Promise.prototype.isFulfilled = function() { + return this._target()._isFulfilled(); +}; + +Promise.prototype.isResolved = function() { + return this._target()._isResolved(); +}; + +Promise.prototype._value = function() { + return this._settledValue; +}; + +Promise.prototype._reason = function() { + this._unsetRejectionIsUnhandled(); + return this._settledValue; +}; + +Promise.prototype.value = function() { + var target = this._target(); + if (!target.isFulfilled()) { + throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a"); + } + return target._settledValue; +}; + +Promise.prototype.reason = function() { + var target = this._target(); + if (!target.isRejected()) { + throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a"); + } + target._unsetRejectionIsUnhandled(); + return target._settledValue; +}; + + +Promise.PromiseInspection = PromiseInspection; +}; + +},{}],35:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function(Promise, INTERNAL) { +var util = _dereq_("./util.js"); +var errorObj = util.errorObj; +var isObject = util.isObject; + +function tryConvertToPromise(obj, context) { + if (isObject(obj)) { + if (obj instanceof Promise) { + return obj; + } + else if (isAnyBluebirdPromise(obj)) { + var ret = new Promise(INTERNAL); + obj._then( + ret._fulfillUnchecked, + ret._rejectUncheckedCheckError, + ret._progressUnchecked, + ret, + null + ); + return ret; + } + var then = util.tryCatch(getThen)(obj); + if (then === errorObj) { + if (context) context._pushContext(); + var ret = Promise.reject(then.e); + if (context) context._popContext(); + return ret; + } else if (typeof then === "function") { + return doThenable(obj, then, context); + } + } + return obj; +} + +function getThen(obj) { + return obj.then; +} + +var hasProp = {}.hasOwnProperty; +function isAnyBluebirdPromise(obj) { + return hasProp.call(obj, "_promise0"); +} + +function doThenable(x, then, context) { + var promise = new Promise(INTERNAL); + var ret = promise; + if (context) context._pushContext(); + promise._captureStackTrace(); + if (context) context._popContext(); + var synchronous = true; + var result = util.tryCatch(then).call(x, + resolveFromThenable, + rejectFromThenable, + progressFromThenable); + synchronous = false; + if (promise && result === errorObj) { + promise._rejectCallback(result.e, true, true); + promise = null; + } + + function resolveFromThenable(value) { + if (!promise) return; + if (x === value) { + promise._rejectCallback( + Promise._makeSelfResolutionError(), false, true); + } else { + promise._resolveCallback(value); + } + promise = null; + } + + function rejectFromThenable(reason) { + if (!promise) return; + promise._rejectCallback(reason, synchronous, true); + promise = null; + } + + function progressFromThenable(value) { + if (!promise) return; + if (typeof promise._progress === "function") { + promise._progress(value); + } + } + return ret; +} - Promise.prototype.inspect = function Promise$inspect() { - return new PromiseInspection(this); - }; +return tryConvertToPromise; }; -},{"./promise_inspection.js":21}],36:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./util.js":38}],36:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { - var util = require("./util.js"); - var canAttach = require("./errors.js").canAttach; - var errorObj = util.errorObj; - var isObject = util.isObject; +var util = _dereq_("./util.js"); +var TimeoutError = Promise.TimeoutError; - function getThen(obj) { - try { - return obj.then; - } - catch(e) { - errorObj.e = e; - return errorObj; - } +var afterTimeout = function (promise, message) { + if (!promise.isPending()) return; + if (typeof message !== "string") { + message = "operation timed out"; } + var err = new TimeoutError(message); + util.markAsOriginatingFromRejection(err); + promise._attachExtraTrace(err); + promise._cancel(err); +}; - function Promise$_Cast(obj, caller, originalPromise) { - if (isObject(obj)) { - if (obj instanceof Promise) { - return obj; - } - else if (isAnyBluebirdPromise(obj)) { - var ret = new Promise(INTERNAL); - ret._setTrace(caller, void 0); - obj._then( - ret._fulfillUnchecked, - ret._rejectUncheckedCheckError, - ret._progressUnchecked, - ret, - null, - void 0 - ); - ret._setFollowing(); - return ret; - } - var then = getThen(obj); - if (then === errorObj) { - caller = typeof caller === "function" ? caller : Promise$_Cast; - if (originalPromise !== void 0 && canAttach(then.e)) { - originalPromise._attachExtraTrace(then.e); - } - return Promise.reject(then.e, caller); - } - else if (typeof then === "function") { - caller = typeof caller === "function" ? caller : Promise$_Cast; - return Promise$_doThenable(obj, then, caller, originalPromise); +var afterValue = function(value) { return delay(+this).thenReturn(value); }; +var delay = Promise.delay = function (value, ms) { + if (ms === undefined) { + ms = value; + value = undefined; + var ret = new Promise(INTERNAL); + setTimeout(function() { ret._fulfill(); }, ms); + return ret; + } + ms = +ms; + return Promise.resolve(value)._then(afterValue, null, null, ms, undefined); +}; + +Promise.prototype.delay = function (ms) { + return delay(this, ms); +}; + +function successClear(value) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + return value; +} + +function failureClear(reason) { + var handle = this; + if (handle instanceof Number) handle = +handle; + clearTimeout(handle); + throw reason; +} + +Promise.prototype.timeout = function (ms, message) { + ms = +ms; + var ret = this.then().cancellable(); + ret._cancellationParent = this; + var handle = setTimeout(function timeoutTimeout() { + afterTimeout(ret, message); + }, ms); + return ret._then(successClear, failureClear, undefined, handle, undefined); +}; + +}; + +},{"./util.js":38}],37:[function(_dereq_,module,exports){ +"use strict"; +module.exports = function (Promise, apiRejection, tryConvertToPromise, + createContext) { + var TypeError = _dereq_("./errors.js").TypeError; + var inherits = _dereq_("./util.js").inherits; + var PromiseInspection = Promise.PromiseInspection; + + function inspectionMapper(inspections) { + var len = inspections.length; + for (var i = 0; i < len; ++i) { + var inspection = inspections[i]; + if (inspection.isRejected()) { + return Promise.reject(inspection.error()); } + inspections[i] = inspection._settledValue; } - return obj; + return inspections; } - var hasProp = {}.hasOwnProperty; - function isAnyBluebirdPromise(obj) { - return hasProp.call(obj, "_promise0"); + function thrower(e) { + setTimeout(function(){throw e;}, 0); } - function Promise$_doThenable(x, then, caller, originalPromise) { - var resolver = Promise.defer(caller); - var called = false; - try { - then.call( - x, - Promise$_resolveFromThenable, - Promise$_rejectFromThenable, - Promise$_progressFromThenable - ); + function castPreservingDisposable(thenable) { + var maybePromise = tryConvertToPromise(thenable); + if (maybePromise !== thenable && + typeof thenable._isDisposable === "function" && + typeof thenable._getDisposer === "function" && + thenable._isDisposable()) { + maybePromise._setDisposable(thenable._getDisposer()); } - catch(e) { - if (!called) { - called = true; - var trace = canAttach(e) ? e : new Error(e + ""); - if (originalPromise !== void 0) { - originalPromise._attachExtraTrace(trace); + return maybePromise; + } + function dispose(resources, inspection) { + var i = 0; + var len = resources.length; + var ret = Promise.defer(); + function iterator() { + if (i >= len) return ret.resolve(); + var maybePromise = castPreservingDisposable(resources[i++]); + if (maybePromise instanceof Promise && + maybePromise._isDisposable()) { + try { + maybePromise = tryConvertToPromise( + maybePromise._getDisposer().tryDispose(inspection), + resources.promise); + } catch (e) { + return thrower(e); } - resolver.promise._reject(e, trace); - } - } - return resolver.promise; - - function Promise$_resolveFromThenable(y) { - if (called) return; - called = true; - - if (x === y) { - var e = Promise._makeSelfResolutionError(); - if (originalPromise !== void 0) { - originalPromise._attachExtraTrace(e); + if (maybePromise instanceof Promise) { + return maybePromise._then(iterator, thrower, + null, null, null); } - resolver.promise._reject(e, void 0); - return; } - resolver.resolve(y); + iterator(); } + iterator(); + return ret.promise; + } - function Promise$_rejectFromThenable(r) { - if (called) return; - called = true; - var trace = canAttach(r) ? r : new Error(r + ""); - if (originalPromise !== void 0) { - originalPromise._attachExtraTrace(trace); - } - resolver.promise._reject(r, trace); - } + function disposerSuccess(value) { + var inspection = new PromiseInspection(); + inspection._settledValue = value; + inspection._bitField = 268435456; + return dispose(this, inspection).thenReturn(value); + } - function Promise$_progressFromThenable(v) { - if (called) return; - var promise = resolver.promise; - if (typeof promise._progress === "function") { - promise._progress(v); - } - } + function disposerFail(reason) { + var inspection = new PromiseInspection(); + inspection._settledValue = reason; + inspection._bitField = 134217728; + return dispose(this, inspection).thenThrow(reason); } - Promise._cast = Promise$_Cast; -}; + function Disposer(data, promise, context) { + this._data = data; + this._promise = promise; + this._context = context; + } -},{"./errors.js":9,"./util.js":38}],37:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -"use strict"; + Disposer.prototype.data = function () { + return this._data; + }; -var global = require("./global.js"); -var setTimeout = function(fn, time) { - var $_len = arguments.length;var args = new Array($_len - 2); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];} - global.setTimeout(function() { - fn.apply(void 0, args); - }, time); -}; + Disposer.prototype.promise = function () { + return this._promise; + }; -var pass = {}; -global.setTimeout( function(_) { - if(_ === pass) { - setTimeout = global.setTimeout; - } -}, 1, pass); + Disposer.prototype.resource = function () { + if (this.promise().isFulfilled()) { + return this.promise().value(); + } + return null; + }; -module.exports = function(Promise, INTERNAL) { - var util = require("./util.js"); - var errors = require("./errors.js"); - var apiRejection = require("./errors_api_rejection")(Promise); - var TimeoutError = Promise.TimeoutError; + Disposer.prototype.tryDispose = function(inspection) { + var resource = this.resource(); + var context = this._context; + if (context !== undefined) context._pushContext(); + var ret = resource !== null + ? this.doDispose(resource, inspection) : null; + if (context !== undefined) context._popContext(); + this._promise._unsetDisposable(); + this._data = null; + return ret; + }; - var afterTimeout = function Promise$_afterTimeout(promise, message, ms) { - if (!promise.isPending()) return; - if (typeof message !== "string") { - message = "operation timed out after" + " " + ms + " ms" - } - var err = new TimeoutError(message); - errors.markAsOriginatingFromRejection(err); - promise._attachExtraTrace(err); - promise._rejectUnchecked(err); + Disposer.isDisposer = function (d) { + return (d != null && + typeof d.resource === "function" && + typeof d.tryDispose === "function"); }; - var afterDelay = function Promise$_afterDelay(value, promise) { - promise._fulfill(value); + function FunctionDisposer(fn, promise, context) { + this.constructor$(fn, promise, context); + } + inherits(FunctionDisposer, Disposer); + + FunctionDisposer.prototype.doDispose = function (resource, inspection) { + var fn = this.data(); + return fn.call(resource, resource, inspection); }; - Promise.delay = function Promise$Delay(value, ms, caller) { - if (ms === void 0) { - ms = value; - value = void 0; + function maybeUnwrapDisposer(value) { + if (Disposer.isDisposer(value)) { + this.resources[this.index]._setDisposable(value); + return value.promise(); } - ms = +ms; - if (typeof caller !== "function") { - caller = Promise.delay; - } - var maybePromise = Promise._cast(value, caller, void 0); - var promise = new Promise(INTERNAL); + return value; + } - if (Promise.is(maybePromise)) { - if (maybePromise._isBound()) { - promise._setBoundTo(maybePromise._boundTo); - } - if (maybePromise._cancellable()) { - promise._setCancellable(); - promise._cancellationParent = maybePromise; + Promise.using = function () { + var len = arguments.length; + if (len < 2) return apiRejection( + "you must pass at least 2 arguments to Promise.using"); + var fn = arguments[len - 1]; + if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a"); + len--; + var resources = new Array(len); + for (var i = 0; i < len; ++i) { + var resource = arguments[i]; + if (Disposer.isDisposer(resource)) { + var disposer = resource; + resource = resource.promise(); + resource._setDisposable(disposer); + } else { + var maybePromise = tryConvertToPromise(resource); + if (maybePromise instanceof Promise) { + resource = + maybePromise._then(maybeUnwrapDisposer, null, null, { + resources: resources, + index: i + }, undefined); + } } - promise._setTrace(caller, maybePromise); - promise._follow(maybePromise); - return promise.then(function(value) { - return Promise.delay(value, ms); - }); - } - else { - promise._setTrace(caller, void 0); - setTimeout(afterDelay, ms, value, promise); + resources[i] = resource; } + + var promise = Promise.settle(resources) + .then(inspectionMapper) + .then(function(vals) { + promise._pushContext(); + var ret; + try { + ret = fn.apply(undefined, vals); + } finally { + promise._popContext(); + } + return ret; + }) + ._then( + disposerSuccess, disposerFail, undefined, resources, undefined); + resources.promise = promise; return promise; }; - Promise.prototype.delay = function Promise$delay(ms) { - return Promise.delay(this, ms, this.delay); + Promise.prototype._setDisposable = function (disposer) { + this._bitField = this._bitField | 262144; + this._disposer = disposer; }; - Promise.prototype.timeout = function Promise$timeout(ms, message) { - ms = +ms; + Promise.prototype._isDisposable = function () { + return (this._bitField & 262144) > 0; + }; - var ret = new Promise(INTERNAL); - ret._setTrace(this.timeout, this); + Promise.prototype._getDisposer = function () { + return this._disposer; + }; - if (this._isBound()) ret._setBoundTo(this._boundTo); - if (this._cancellable()) { - ret._setCancellable(); - ret._cancellationParent = this; + Promise.prototype._unsetDisposable = function () { + this._bitField = this._bitField & (~262144); + this._disposer = undefined; + }; + + Promise.prototype.disposer = function (fn) { + if (typeof fn === "function") { + return new FunctionDisposer(fn, this, createContext()); } - ret._follow(this); - setTimeout(afterTimeout, ms, ret, message, ms); - return ret; + throw new TypeError(); }; }; -},{"./errors.js":9,"./errors_api_rejection":10,"./global.js":15,"./util.js":38}],38:[function(require,module,exports){ -/** - * Copyright (c) 2014 Petka Antonov - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions:

- * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ +},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){ "use strict"; -var global = require("./global.js"); -var es5 = require("./es5.js"); +var es5 = _dereq_("./es5.js"); +var canEvaluate = typeof navigator == "undefined"; var haveGetters = (function(){ try { var o = {}; @@ -7032,53 +6470,19 @@ var haveGetters = (function(){ })(); -var canEvaluate = (function() { - if (typeof window !== "undefined" && window !== null && - typeof window.document !== "undefined" && - typeof navigator !== "undefined" && navigator !== null && - typeof navigator.appName === "string" && - window === global) { - return false; - } - return true; -})(); - -function deprecated(msg) { - if (typeof console !== "undefined" && console !== null && - typeof console.warn === "function") { - console.warn("Bluebird: " + msg); - } -} - var errorObj = {e: {}}; -function tryCatch1(fn, receiver, arg) { - try { - return fn.call(receiver, arg); - } - catch (e) { - errorObj.e = e; - return errorObj; - } -} - -function tryCatch2(fn, receiver, arg, arg2) { +var tryCatchTarget; +function tryCatcher() { try { - return fn.call(receiver, arg, arg2); - } - catch (e) { + return tryCatchTarget.apply(this, arguments); + } catch (e) { errorObj.e = e; return errorObj; } } - -function tryCatchApply(fn, args, receiver) { - try { - return fn.apply(receiver, args); - } - catch (e) { - errorObj.e = e; - return errorObj; - } +function tryCatch(fn) { + tryCatchTarget = fn; + return tryCatcher; } var inherits = function(Child, Parent) { @@ -7100,9 +6504,6 @@ var inherits = function(Child, Parent) { return Child.prototype; }; -function asString(val) { - return typeof val === "string" ? val : ("" + val); -} function isPrimitive(val) { return val == null || val === true || val === false || @@ -7117,7 +6518,7 @@ function isObject(value) { function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; - return new Error(asString(maybeError)); + return new Error(safeToString(maybeError)); } function withAppended(target, appendee) { @@ -7131,6 +6532,18 @@ function withAppended(target, appendee) { return ret; } +function getDataPropertyOrDefault(obj, key, defaultValue) { + if (es5.isES5) { + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null) { + return desc.get == null && desc.set == null + ? desc.value + : defaultValue; + } + } else { + return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; + } +} function notEnumerableProp(obj, name, value) { if (isPrimitive(obj)) return obj; @@ -7153,6 +6566,59 @@ function thrower(r) { throw r; } +var inheritedDataKeys = (function() { + if (es5.isES5) { + var oProto = Object.prototype; + var getKeys = Object.getOwnPropertyNames; + return function(obj) { + var ret = []; + var visitedKeys = Object.create(null); + while (obj != null && obj !== oProto) { + var keys; + try { + keys = getKeys(obj); + } catch (e) { + return ret; + } + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (visitedKeys[key]) continue; + visitedKeys[key] = true; + var desc = Object.getOwnPropertyDescriptor(obj, key); + if (desc != null && desc.get == null && desc.set == null) { + ret.push(key); + } + } + obj = es5.getPrototypeOf(obj); + } + return ret; + }; + } else { + return function(obj) { + var ret = []; + /*jshint forin:false */ + for (var key in obj) { + ret.push(key); + } + return ret; + }; + } + +})(); + +function isClass(fn) { + try { + if (typeof fn === "function") { + var keys = es5.names(fn.prototype); + if (es5.isES5) return keys.length > 1; + return keys.length > 0 && + !(keys.length === 1 && keys[0] === "constructor"); + } + return false; + } catch (e) { + return false; + } +} function toFastProperties(obj) { /*jshint -W027*/ @@ -7162,7 +6628,78 @@ function toFastProperties(obj) { eval(obj); } +var rident = /^[a-z$_][a-z$_0-9]*$/i; +function isIdentifier(str) { + return rident.test(str); +} + +function filledRange(count, prefix, suffix) { + var ret = new Array(count); + for(var i = 0; i < count; ++i) { + ret[i] = prefix + i + suffix; + } + return ret; +} + +function safeToString(obj) { + try { + return obj + ""; + } catch (e) { + return "[no string representation]"; + } +} + +function markAsOriginatingFromRejection(e) { + try { + notEnumerableProp(e, "isOperational", true); + } + catch(ignore) {} +} + +function originatesFromRejection(e) { + if (e == null) return false; + return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || + e["isOperational"] === true); +} + +function canAttachTrace(obj) { + return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); +} + +var ensureErrorObject = (function() { + if (!("stack" in new Error())) { + return function(value) { + if (canAttachTrace(value)) return value; + try {throw new Error(safeToString(value));} + catch(err) {return err;} + }; + } else { + return function(value) { + if (canAttachTrace(value)) return value; + return new Error(safeToString(value)); + }; + } +})(); + +function classString(obj) { + return {}.toString.call(obj); +} + +function copyDescriptors(from, to, filter) { + var keys = es5.names(from); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + if (filter(key)) { + es5.defineProperty(to, key, es5.getDescriptor(from, key)); + } + } +} + var ret = { + isClass: isClass, + isIdentifier: isIdentifier, + inheritedDataKeys: inheritedDataKeys, + getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, haveGetters: haveGetters, @@ -7170,25 +6707,29 @@ var ret = { isPrimitive: isPrimitive, isObject: isObject, canEvaluate: canEvaluate, - deprecated: deprecated, errorObj: errorObj, - tryCatch1: tryCatch1, - tryCatch2: tryCatch2, - tryCatchApply: tryCatchApply, + tryCatch: tryCatch, inherits: inherits, withAppended: withAppended, - asString: asString, maybeWrapAsError: maybeWrapAsError, wrapsPrimitiveReceiver: wrapsPrimitiveReceiver, - toFastProperties: toFastProperties + toFastProperties: toFastProperties, + filledRange: filledRange, + toString: safeToString, + canAttachTrace: canAttachTrace, + ensureErrorObject: ensureErrorObject, + originatesFromRejection: originatesFromRejection, + markAsOriginatingFromRejection: markAsOriginatingFromRejection, + classString: classString, + copyDescriptors: copyDescriptors, + isNode: typeof process !== "undefined" && + classString(process).toLowerCase() === "[object process]" }; - +try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; -},{"./es5.js":11,"./global.js":15}]},{},[3]) -(3) -}); -;/* +},{"./es5.js":14}]},{},[4])(4) +}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }/* * This product includes color specifications and designs developed by Cynthia * Brewer (http://colorbrewer.org/). */ diff --git a/htdocs/lib/dependencies_bundle.min.js b/htdocs/lib/dependencies_bundle.min.js index daa7008d10..a522d02ff9 100644 --- a/htdocs/lib/dependencies_bundle.min.js +++ b/htdocs/lib/dependencies_bundle.min.js @@ -1,31 +1,32 @@ -var requirejs,require,define;(function(global){var req,s,head,baseElement,dataMain,src,interactiveScript,currentlyAddingScript,mainScript,subPath,version="2.1.11",commentRegExp=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/gm,cjsRequireRegExp=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,jsSuffixRegExp=/\.js$/,currDirRegExp=/^\.\//,op=Object.prototype,ostring=op.toString,hasOwn=op.hasOwnProperty,ap=Array.prototype,apsp=ap.splice,isBrowser=!!(typeof window!=="undefined"&&typeof navigator!=="undefined"&&window.document),isWebWorker=!isBrowser&&typeof importScripts!=="undefined",readyRegExp=isBrowser&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,defContextName="_",isOpera=typeof opera!=="undefined"&&opera.toString()==="[object Opera]",contexts={},cfg={},globalDefQueue=[],useInteractive=false;function isFunction(it){return ostring.call(it)==="[object Function]"}function isArray(it){return ostring.call(it)==="[object Array]"}function each(ary,func){if(ary){var i;for(i=0;i-1;i-=1){if(ary[i]&&func(ary[i],i,ary)){break}}}}function hasProp(obj,prop){return hasOwn.call(obj,prop)}function getOwn(obj,prop){return hasProp(obj,prop)&&obj[prop]}function eachProp(obj,func){var prop;for(prop in obj){if(hasProp(obj,prop)){if(func(obj[prop],prop)){break}}}}function mixin(target,source,force,deepStringMixin){if(source){eachProp(source,function(value,prop){if(force||!hasProp(target,prop)){if(deepStringMixin&&typeof value==="object"&&value&&!isArray(value)&&!isFunction(value)&&!(value instanceof RegExp)){if(!target[prop]){target[prop]={}}mixin(target[prop],value,force,deepStringMixin)}else{target[prop]=value}}})}return target}function bind(obj,fn){return function(){return fn.apply(obj,arguments)}}function scripts(){return document.getElementsByTagName("script")}function defaultOnError(err){throw err}function getGlobal(value){if(!value){return value}var g=global;each(value.split("."),function(part){g=g[part]});return g}function makeError(id,msg,err,requireModules){var e=new Error(msg+"\nhttp://requirejs.org/docs/errors.html#"+id);e.requireType=id;e.requireModules=requireModules;if(err){e.originalError=err}return e}if(typeof define!=="undefined"){return}if(typeof requirejs!=="undefined"){if(isFunction(requirejs)){return}cfg=requirejs;requirejs=undefined}if(typeof require!=="undefined"&&!isFunction(require)){cfg=require;require=undefined}function newContext(contextName){var inCheckLoaded,Module,context,handlers,checkLoadedTimeoutId,config={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},registry={},enabledRegistry={},undefEvents={},defQueue=[],defined={},urlFetched={},bundlesMap={},requireCounter=1,unnormalizedCounter=1;function trimDots(ary){var i,part,length=ary.length;for(i=0;i0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName,applyMap){var pkgMain,mapValue,nameParts,i,j,nameSegment,lastIndex,foundMap,foundI,foundStarMap,starI,baseParts=baseName&&baseName.split("/"),normalizedBaseParts=baseParts,map=config.map,starMap=map&&map["*"];if(name&&name.charAt(0)==="."){if(baseName){normalizedBaseParts=baseParts.slice(0,baseParts.length-1);name=name.split("/");lastIndex=name.length-1;if(config.nodeIdCompat&&jsSuffixRegExp.test(name[lastIndex])){name[lastIndex]=name[lastIndex].replace(jsSuffixRegExp,"")}name=normalizedBaseParts.concat(name);trimDots(name);name=name.join("/")}else if(name.indexOf("./")===0){name=name.substring(2)}}if(applyMap&&map&&(baseParts||starMap)){nameParts=name.split("/");outerLoop:for(i=nameParts.length;i>0;i-=1){nameSegment=nameParts.slice(0,i).join("/");if(baseParts){for(j=baseParts.length;j>0;j-=1){mapValue=getOwn(map,baseParts.slice(0,j).join("/"));if(mapValue){mapValue=getOwn(mapValue,nameSegment);if(mapValue){foundMap=mapValue;foundI=i;break outerLoop}}}}if(!foundStarMap&&starMap&&getOwn(starMap,nameSegment)){foundStarMap=getOwn(starMap,nameSegment);starI=i}}if(!foundMap&&foundStarMap){foundMap=foundStarMap;foundI=starI}if(foundMap){nameParts.splice(0,foundI,foundMap);name=nameParts.join("/")}}pkgMain=getOwn(config.pkgs,name);return pkgMain?pkgMain:name}function removeScript(name){if(isBrowser){each(scripts(),function(scriptNode){if(scriptNode.getAttribute("data-requiremodule")===name&&scriptNode.getAttribute("data-requirecontext")===context.contextName){scriptNode.parentNode.removeChild(scriptNode);return true}})}}function hasPathFallback(id){var pathConfig=getOwn(config.paths,id);if(pathConfig&&isArray(pathConfig)&&pathConfig.length>1){pathConfig.shift();context.require.undef(id);context.require([id]);return true}}function splitPrefix(name){var prefix,index=name?name.indexOf("!"):-1;if(index>-1){prefix=name.substring(0,index);name=name.substring(index+1,name.length)}return[prefix,name]}function makeModuleMap(name,parentModuleMap,isNormalized,applyMap){var url,pluginModule,suffix,nameParts,prefix=null,parentName=parentModuleMap?parentModuleMap.name:null,originalName=name,isDefine=true,normalizedName="";if(!name){isDefine=false;name="_@r"+(requireCounter+=1)}nameParts=splitPrefix(name);prefix=nameParts[0];name=nameParts[1];if(prefix){prefix=normalize(prefix,parentName,applyMap);pluginModule=getOwn(defined,prefix)}if(name){if(prefix){if(pluginModule&&pluginModule.normalize){normalizedName=pluginModule.normalize(name,function(name){return normalize(name,parentName,applyMap)})}else{normalizedName=normalize(name,parentName,applyMap)}}else{normalizedName=normalize(name,parentName,applyMap);nameParts=splitPrefix(normalizedName);prefix=nameParts[0];normalizedName=nameParts[1];isNormalized=true;url=context.nameToUrl(normalizedName)}}suffix=prefix&&!pluginModule&&!isNormalized?"_unnormalized"+(unnormalizedCounter+=1):"";return{prefix:prefix,name:normalizedName,parentMap:parentModuleMap,unnormalized:!!suffix,url:url,originalName:originalName,isDefine:isDefine,id:(prefix?prefix+"!"+normalizedName:normalizedName)+suffix}}function getModule(depMap){var id=depMap.id,mod=getOwn(registry,id);if(!mod){mod=registry[id]=new context.Module(depMap)}return mod}function on(depMap,name,fn){var id=depMap.id,mod=getOwn(registry,id);if(hasProp(defined,id)&&(!mod||mod.defineEmitComplete)){if(name==="defined"){fn(defined[id])}}else{mod=getModule(depMap);if(mod.error&&name==="error"){fn(mod.error)}else{mod.on(name,fn)}}}function onError(err,errback){var ids=err.requireModules,notified=false;if(errback){errback(err)}else{each(ids,function(id){var mod=getOwn(registry,id);if(mod){mod.error=err;if(mod.events.error){notified=true;mod.emit("error",err)}}});if(!notified){req.onError(err)}}}function takeGlobalQueue(){if(globalDefQueue.length){apsp.apply(defQueue,[defQueue.length,0].concat(globalDefQueue));globalDefQueue=[]}}handlers={require:function(mod){if(mod.require){return mod.require}else{return mod.require=context.makeRequire(mod.map)}},exports:function(mod){mod.usingExports=true;if(mod.map.isDefine){if(mod.exports){return defined[mod.map.id]=mod.exports}else{return mod.exports=defined[mod.map.id]={}}}},module:function(mod){if(mod.module){return mod.module}else{return mod.module={id:mod.map.id,uri:mod.map.url,config:function(){return getOwn(config.config,mod.map.id)||{}},exports:mod.exports||(mod.exports={})}}}};function cleanRegistry(id){delete registry[id];delete enabledRegistry[id]}function breakCycle(mod,traced,processed){var id=mod.map.id;if(mod.error){mod.emit("error",mod.error)}else{traced[id]=true;each(mod.depMaps,function(depMap,i){var depId=depMap.id,dep=getOwn(registry,depId);if(dep&&!mod.depMatched[i]&&!processed[depId]){if(getOwn(traced,depId)){mod.defineDep(i,defined[depId]);mod.check()}else{breakCycle(dep,traced,processed)}}});processed[id]=true}}function checkLoaded(){var err,usingPathFallback,waitInterval=config.waitSeconds*1e3,expired=waitInterval&&context.startTime+waitInterval<(new Date).getTime(),noLoads=[],reqCalls=[],stillLoading=false,needCycleCheck=true;if(inCheckLoaded){return}inCheckLoaded=true;eachProp(enabledRegistry,function(mod){var map=mod.map,modId=map.id;if(!mod.enabled){return}if(!map.isDefine){reqCalls.push(mod)}if(!mod.error){if(!mod.inited&&expired){if(hasPathFallback(modId)){usingPathFallback=true;stillLoading=true}else{noLoads.push(modId);removeScript(modId)}}else if(!mod.inited&&mod.fetched&&map.isDefine){stillLoading=true;if(!map.prefix){return needCycleCheck=false}}}});if(expired&&noLoads.length){err=makeError("timeout","Load timeout for modules: "+noLoads,null,noLoads);err.contextName=context.contextName;return onError(err)}if(needCycleCheck){each(reqCalls,function(mod){breakCycle(mod,{},{})})}if((!expired||usingPathFallback)&&stillLoading){if((isBrowser||isWebWorker)&&!checkLoadedTimeoutId){checkLoadedTimeoutId=setTimeout(function(){checkLoadedTimeoutId=0;checkLoaded()},50)}}inCheckLoaded=false}Module=function(map){this.events=getOwn(undefEvents,map.id)||{};this.map=map;this.shim=getOwn(config.shim,map.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};Module.prototype={init:function(depMaps,factory,errback,options){options=options||{};if(this.inited){return}this.factory=factory;if(errback){this.on("error",errback)}else if(this.events.error){errback=bind(this,function(err){this.emit("error",err)})}this.depMaps=depMaps&&depMaps.slice(0);this.errback=errback;this.inited=true;this.ignore=options.ignore;if(options.enabled||this.enabled){this.enable()}else{this.check()}},defineDep:function(i,depExports){if(!this.depMatched[i]){this.depMatched[i]=true;this.depCount-=1;this.depExports[i]=depExports}},fetch:function(){if(this.fetched){return}this.fetched=true;context.startTime=(new Date).getTime();var map=this.map;if(this.shim){context.makeRequire(this.map,{enableBuildCallback:true})(this.shim.deps||[],bind(this,function(){return map.prefix?this.callPlugin():this.load()}))}else{return map.prefix?this.callPlugin():this.load()}},load:function(){var url=this.map.url;if(!urlFetched[url]){urlFetched[url]=true;context.load(this.map.id,url)}},check:function(){if(!this.enabled||this.enabling){return}var err,cjsModule,id=this.map.id,depExports=this.depExports,exports=this.exports,factory=this.factory;if(!this.inited){this.fetch()}else if(this.error){this.emit("error",this.error)}else if(!this.defining){this.defining=true;if(this.depCount<1&&!this.defined){if(isFunction(factory)){if(this.events.error&&this.map.isDefine||req.onError!==defaultOnError){try{exports=context.execCb(id,factory,depExports,exports)}catch(e){err=e}}else{exports=context.execCb(id,factory,depExports,exports)}if(this.map.isDefine&&exports===undefined){cjsModule=this.module;if(cjsModule){exports=cjsModule.exports}else if(this.usingExports){exports=this.exports}}if(err){err.requireMap=this.map;err.requireModules=this.map.isDefine?[this.map.id]:null;err.requireType=this.map.isDefine?"define":"require";return onError(this.error=err)}}else{exports=factory}this.exports=exports;if(this.map.isDefine&&!this.ignore){defined[id]=exports;if(req.onResourceLoad){req.onResourceLoad(context,this.map,this.depMaps)}}cleanRegistry(id);this.defined=true}this.defining=false;if(this.defined&&!this.defineEmitted){this.defineEmitted=true;this.emit("defined",this.exports);this.defineEmitComplete=true}}},callPlugin:function(){var map=this.map,id=map.id,pluginMap=makeModuleMap(map.prefix);this.depMaps.push(pluginMap);on(pluginMap,"defined",bind(this,function(plugin){var load,normalizedMap,normalizedMod,bundleId=getOwn(bundlesMap,this.map.id),name=this.map.name,parentName=this.map.parentMap?this.map.parentMap.name:null,localRequire=context.makeRequire(map.parentMap,{enableBuildCallback:true});if(this.map.unnormalized){if(plugin.normalize){name=plugin.normalize(name,function(name){return normalize(name,parentName,true)})||""}normalizedMap=makeModuleMap(map.prefix+"!"+name,this.map.parentMap);on(normalizedMap,"defined",bind(this,function(value){this.init([],function(){return value},null,{enabled:true,ignore:true})}));normalizedMod=getOwn(registry,normalizedMap.id);if(normalizedMod){this.depMaps.push(normalizedMap);if(this.events.error){normalizedMod.on("error",bind(this,function(err){this.emit("error",err)}))}normalizedMod.enable()}return}if(bundleId){this.map.url=context.nameToUrl(bundleId);this.load();return}load=bind(this,function(value){this.init([],function(){return value},null,{enabled:true})});load.error=bind(this,function(err){this.inited=true;this.error=err;err.requireModules=[id];eachProp(registry,function(mod){if(mod.map.id.indexOf(id+"_unnormalized")===0){cleanRegistry(mod.map.id)}});onError(err)});load.fromText=bind(this,function(text,textAlt){var moduleName=map.name,moduleMap=makeModuleMap(moduleName),hasInteractive=useInteractive;if(textAlt){text=textAlt}if(hasInteractive){useInteractive=false}getModule(moduleMap);if(hasProp(config.config,id)){config.config[moduleName]=config.config[id]}try{req.exec(text)}catch(e){return onError(makeError("fromtexteval","fromText eval for "+id+" failed: "+e,e,[id]))}if(hasInteractive){useInteractive=true}this.depMaps.push(moduleMap);context.completeLoad(moduleName);localRequire([moduleName],load)});plugin.load(map.name,localRequire,load,config)}));context.enable(pluginMap,this);this.pluginMaps[pluginMap.id]=pluginMap},enable:function(){enabledRegistry[this.map.id]=this;this.enabled=true;this.enabling=true;each(this.depMaps,bind(this,function(depMap,i){var id,mod,handler;if(typeof depMap==="string"){depMap=makeModuleMap(depMap,this.map.isDefine?this.map:this.map.parentMap,false,!this.skipMap);this.depMaps[i]=depMap;handler=getOwn(handlers,depMap.id);if(handler){this.depExports[i]=handler(this);return}this.depCount+=1;on(depMap,"defined",bind(this,function(depExports){this.defineDep(i,depExports);this.check()}));if(this.errback){on(depMap,"error",bind(this,this.errback))}}id=depMap.id;mod=registry[id];if(!hasProp(handlers,id)&&mod&&!mod.enabled){context.enable(depMap,this)}}));eachProp(this.pluginMaps,bind(this,function(pluginMap){var mod=getOwn(registry,pluginMap.id);if(mod&&!mod.enabled){context.enable(pluginMap,this)}}));this.enabling=false;this.check()},on:function(name,cb){var cbs=this.events[name];if(!cbs){cbs=this.events[name]=[]}cbs.push(cb)},emit:function(name,evt){each(this.events[name],function(cb){cb(evt)});if(name==="error"){delete this.events[name]}}};function callGetModule(args){if(!hasProp(defined,args[0])){getModule(makeModuleMap(args[0],null,true)).init(args[1],args[2])}}function removeListener(node,func,name,ieName){if(node.detachEvent&&!isOpera){if(ieName){node.detachEvent(ieName,func)}}else{node.removeEventListener(name,func,false)}}function getScriptData(evt){var node=evt.currentTarget||evt.srcElement;removeListener(node,context.onScriptLoad,"load","onreadystatechange");removeListener(node,context.onScriptError,"error");return{node:node,id:node&&node.getAttribute("data-requiremodule")}}function intakeDefines(){var args;takeGlobalQueue();while(defQueue.length){args=defQueue.shift();if(args[0]===null){return onError(makeError("mismatch","Mismatched anonymous define() module: "+args[args.length-1]))}else{callGetModule(args)}}}context={config:config,contextName:contextName,registry:registry,defined:defined,urlFetched:urlFetched,defQueue:defQueue,Module:Module,makeModuleMap:makeModuleMap,nextTick:req.nextTick,onError:onError,configure:function(cfg){if(cfg.baseUrl){if(cfg.baseUrl.charAt(cfg.baseUrl.length-1)!=="/"){cfg.baseUrl+="/"}}var shim=config.shim,objs={paths:true,bundles:true,config:true,map:true};eachProp(cfg,function(value,prop){if(objs[prop]){if(!config[prop]){config[prop]={}}mixin(config[prop],value,true,true)}else{config[prop]=value}});if(cfg.bundles){eachProp(cfg.bundles,function(value,prop){each(value,function(v){if(v!==prop){bundlesMap[v]=prop}})})}if(cfg.shim){eachProp(cfg.shim,function(value,id){if(isArray(value)){value={deps:value}}if((value.exports||value.init)&&!value.exportsFn){value.exportsFn=context.makeShimExports(value)}shim[id]=value});config.shim=shim}if(cfg.packages){each(cfg.packages,function(pkgObj){var location,name;pkgObj=typeof pkgObj==="string"?{name:pkgObj}:pkgObj;name=pkgObj.name;location=pkgObj.location;if(location){config.paths[name]=pkgObj.location}config.pkgs[name]=pkgObj.name+"/"+(pkgObj.main||"main").replace(currDirRegExp,"").replace(jsSuffixRegExp,"")})}eachProp(registry,function(mod,id){if(!mod.inited&&!mod.map.unnormalized){mod.map=makeModuleMap(id)}});if(cfg.deps||cfg.callback){context.require(cfg.deps||[],cfg.callback)}},makeShimExports:function(value){function fn(){var ret;if(value.init){ret=value.init.apply(global,arguments)}return ret||value.exports&&getGlobal(value.exports)}return fn},makeRequire:function(relMap,options){options=options||{};function localRequire(deps,callback,errback){var id,map,requireMod;if(options.enableBuildCallback&&callback&&isFunction(callback)){callback.__requireJsBuild=true}if(typeof deps==="string"){if(isFunction(callback)){return onError(makeError("requireargs","Invalid require call"),errback)}if(relMap&&hasProp(handlers,deps)){return handlers[deps](registry[relMap.id])}if(req.get){return req.get(context,deps,relMap,localRequire)}map=makeModuleMap(deps,relMap,false,true);id=map.id;if(!hasProp(defined,id)){return onError(makeError("notloaded",'Module name "'+id+'" has not been loaded yet for context: '+contextName+(relMap?"":". Use require([])")))}return defined[id]}intakeDefines();context.nextTick(function(){intakeDefines();requireMod=getModule(makeModuleMap(null,relMap));requireMod.skipMap=options.skipMap;requireMod.init(deps,callback,errback,{enabled:true});checkLoaded()});return localRequire}mixin(localRequire,{isBrowser:isBrowser,toUrl:function(moduleNamePlusExt){var ext,index=moduleNamePlusExt.lastIndexOf("."),segment=moduleNamePlusExt.split("/")[0],isRelative=segment==="."||segment==="..";if(index!==-1&&(!isRelative||index>1)){ext=moduleNamePlusExt.substring(index,moduleNamePlusExt.length);moduleNamePlusExt=moduleNamePlusExt.substring(0,index)}return context.nameToUrl(normalize(moduleNamePlusExt,relMap&&relMap.id,true),ext,true)},defined:function(id){return hasProp(defined,makeModuleMap(id,relMap,false,true).id)},specified:function(id){id=makeModuleMap(id,relMap,false,true).id;return hasProp(defined,id)||hasProp(registry,id)}});if(!relMap){localRequire.undef=function(id){takeGlobalQueue();var map=makeModuleMap(id,relMap,true),mod=getOwn(registry,id);removeScript(id);delete defined[id];delete urlFetched[map.url];delete undefEvents[id];eachReverse(defQueue,function(args,i){if(args[0]===id){defQueue.splice(i,1)}});if(mod){if(mod.events.defined){undefEvents[id]=mod.events}cleanRegistry(id)}}}return localRequire},enable:function(depMap){var mod=getOwn(registry,depMap.id);if(mod){getModule(depMap).enable()}},completeLoad:function(moduleName){var found,args,mod,shim=getOwn(config.shim,moduleName)||{},shExports=shim.exports;takeGlobalQueue();while(defQueue.length){args=defQueue.shift();if(args[0]===null){args[0]=moduleName;if(found){break}found=true}else if(args[0]===moduleName){found=true}callGetModule(args)}mod=getOwn(registry,moduleName);if(!found&&!hasProp(defined,moduleName)&&mod&&!mod.inited){if(config.enforceDefine&&(!shExports||!getGlobal(shExports))){if(hasPathFallback(moduleName)){return}else{return onError(makeError("nodefine","No define call for "+moduleName,null,[moduleName]))}}else{callGetModule([moduleName,shim.deps||[],shim.exportsFn])}}checkLoaded()},nameToUrl:function(moduleName,ext,skipExt){var paths,syms,i,parentModule,url,parentPath,bundleId,pkgMain=getOwn(config.pkgs,moduleName);if(pkgMain){moduleName=pkgMain}bundleId=getOwn(bundlesMap,moduleName);if(bundleId){return context.nameToUrl(bundleId,ext,skipExt)}if(req.jsExtRegExp.test(moduleName)){url=moduleName+(ext||"")}else{paths=config.paths;syms=moduleName.split("/");for(i=syms.length;i>0;i-=1){parentModule=syms.slice(0,i).join("/");parentPath=getOwn(paths,parentModule);if(parentPath){if(isArray(parentPath)){parentPath=parentPath[0]}syms.splice(0,i,parentPath);break}}url=syms.join("/");url+=ext||(/^data\:|\?/.test(url)||skipExt?"":".js");url=(url.charAt(0)==="/"||url.match(/^[\w\+\.\-]+:/)?"":config.baseUrl)+url}return config.urlArgs?url+((url.indexOf("?")===-1?"?":"&")+config.urlArgs):url},load:function(id,url){req.load(context,id,url)},execCb:function(name,callback,args,exports){return callback.apply(exports,args)},onScriptLoad:function(evt){if(evt.type==="load"||readyRegExp.test((evt.currentTarget||evt.srcElement).readyState)){interactiveScript=null;var data=getScriptData(evt);context.completeLoad(data.id)}},onScriptError:function(evt){var data=getScriptData(evt);if(!hasPathFallback(data.id)){return onError(makeError("scripterror","Script error for: "+data.id,evt,[data.id]))}}};context.require=context.makeRequire();return context}req=requirejs=function(deps,callback,errback,optional){var context,config,contextName=defContextName;if(!isArray(deps)&&typeof deps!=="string"){config=deps;if(isArray(callback)){deps=callback;callback=errback;errback=optional}else{deps=[]}}if(config&&config.context){contextName=config.context}context=getOwn(contexts,contextName);if(!context){context=contexts[contextName]=req.s.newContext(contextName)}if(config){context.configure(config)}return context.require(deps,callback,errback)};req.config=function(config){return req(config)};req.nextTick=typeof setTimeout!=="undefined"?function(fn){setTimeout(fn,4)}:function(fn){fn()};if(!require){require=req}req.version=version;req.jsExtRegExp=/^\/|:|\?|\.js$/;req.isBrowser=isBrowser;s=req.s={contexts:contexts,newContext:newContext};req({});each(["toUrl","undef","defined","specified"],function(prop){req[prop]=function(){var ctx=contexts[defContextName];return ctx.require[prop].apply(ctx,arguments)}});if(isBrowser){head=s.head=document.getElementsByTagName("head")[0];baseElement=document.getElementsByTagName("base")[0];if(baseElement){head=s.head=baseElement.parentNode}}req.onError=defaultOnError;req.createNode=function(config,moduleName,url){var node=config.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");node.type=config.scriptType||"text/javascript";node.charset="utf-8";node.async=true;return node};req.load=function(context,moduleName,url){var config=context&&context.config||{},node;if(isBrowser){node=req.createNode(config,moduleName,url);node.setAttribute("data-requirecontext",context.contextName);node.setAttribute("data-requiremodule",moduleName);if(node.attachEvent&&!(node.attachEvent.toString&&node.attachEvent.toString().indexOf("[native code")<0)&&!isOpera){useInteractive=true;node.attachEvent("onreadystatechange",context.onScriptLoad)}else{node.addEventListener("load",context.onScriptLoad,false);node.addEventListener("error",context.onScriptError,false)}node.src=url;currentlyAddingScript=node;if(baseElement){head.insertBefore(node,baseElement)}else{head.appendChild(node)}currentlyAddingScript=null;return node}else if(isWebWorker){try{importScripts(url);context.completeLoad(moduleName)}catch(e){context.onError(makeError("importscripts","importScripts failed for "+moduleName+" at "+url,e,[moduleName]))}}};function getInteractiveScript(){if(interactiveScript&&interactiveScript.readyState==="interactive"){return interactiveScript}eachReverse(scripts(),function(script){if(script.readyState==="interactive"){return interactiveScript=script}});return interactiveScript}if(isBrowser&&!cfg.skipDataMain){eachReverse(scripts(),function(script){if(!head){head=script.parentNode}dataMain=script.getAttribute("data-main");if(dataMain){mainScript=dataMain;if(!cfg.baseUrl){src=mainScript.split("/");mainScript=src.pop();subPath=src.length?src.join("/")+"/":"./";cfg.baseUrl=subPath}mainScript=mainScript.replace(jsSuffixRegExp,"");if(req.jsExtRegExp.test(mainScript)){mainScript=dataMain}cfg.deps=cfg.deps?cfg.deps.concat(mainScript):[mainScript];return true}})}define=function(name,deps,callback){var node,context;if(typeof name!=="string"){callback=deps;deps=name;name=null}if(!isArray(deps)){callback=deps;deps=null}if(!deps&&isFunction(callback)){deps=[];if(callback.length){callback.toString().replace(commentRegExp,"").replace(cjsRequireRegExp,function(match,dep){deps.push(dep)});deps=(callback.length===1?["require"]:["require","exports","module"]).concat(deps)}}if(useInteractive){node=currentlyAddingScript||getInteractiveScript();if(node){if(!name){name=node.getAttribute("data-requiremodule")}context=contexts[node.getAttribute("data-requirecontext")]}}(context?context.defQueue:globalDefQueue).push([name,deps,callback])};define.amd={jQuery:true};req.exec=function(text){return eval(text)};req(cfg)})(this);!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.Promise=e():"undefined"!=typeof global?global.Promise=e():"undefined"!=typeof self&&(self.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 require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o0};Async.prototype.invokeLater=function Async$invokeLater(fn,receiver,arg){if(process!==void 0&&process.domain!=null&&!fn.domain){fn=process.domain.bind(fn)}this._lateBuffer.push(fn,receiver,arg);this._queueTick()};Async.prototype.invoke=function Async$invoke(fn,receiver,arg){if(process!==void 0&&process.domain!=null&&!fn.domain){fn=process.domain.bind(fn)}var functionBuffer=this._functionBuffer;functionBuffer.push(fn,receiver,arg);this._length=functionBuffer.length();this._queueTick()};Async.prototype._consumeFunctionBuffer=function Async$_consumeFunctionBuffer(){var functionBuffer=this._functionBuffer;while(functionBuffer.length()>0){var fn=functionBuffer.shift();var receiver=functionBuffer.shift();var arg=functionBuffer.shift();fn.call(receiver,arg)}this._reset();this._consumeLateBuffer()};Async.prototype._consumeLateBuffer=function Async$_consumeLateBuffer(){var buffer=this._lateBuffer;while(buffer.length()>0){var fn=buffer.shift();var receiver=buffer.shift();var arg=buffer.shift();var res=tryCatch1(fn,receiver,arg);if(res===errorObj){this._queueTick();if(fn.domain!=null){fn.domain.emit("error",res.e)}else{throw res.e}}}};Async.prototype._queueTick=function Async$_queue(){if(!this._isTickUsed){schedule(this.consumeFunctionBuffer);this._isTickUsed=true}};Async.prototype._reset=function Async$_reset(){this._isTickUsed=false;this._length=0};module.exports=new Async},{"./global.js":15,"./queue.js":27,"./schedule.js":30,"./util.js":38}],3:[function(require,module,exports){"use strict";var Promise=require("./promise.js")();module.exports=Promise},{"./promise.js":19}],4:[function(require,module,exports){"use strict";module.exports=function(Promise){Promise.prototype.call=function Promise$call(propertyName){var $_len=arguments.length;var args=new Array($_len-1);for(var $_i=1;$_i<$_len;++$_i){args[$_i-1]=arguments[$_i]}return this._then(function(obj){return obj[propertyName].apply(obj,args)},void 0,void 0,void 0,void 0,this.call)};function Promise$getter(obj){var prop=typeof this==="string"?this:""+this;return obj[prop]}Promise.prototype.get=function Promise$get(propertyName){return this._then(Promise$getter,void 0,void 0,propertyName,void 0,this.get)}}},{}],5:[function(require,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var errors=require("./errors.js");var async=require("./async.js");var CancellationError=errors.CancellationError;var SYNC_TOKEN={};Promise.prototype._cancel=function Promise$_cancel(){if(!this.isCancellable())return this;var parent;if((parent=this._cancellationParent)!==void 0){parent.cancel(SYNC_TOKEN);return}var err=new CancellationError;this._attachExtraTrace(err);this._rejectUnchecked(err)};Promise.prototype.cancel=function Promise$cancel(token){if(!this.isCancellable())return this;if(token===SYNC_TOKEN){this._cancel();return this}async.invokeLater(this._cancel,this,void 0);return this};Promise.prototype.cancellable=function Promise$cancellable(){if(this._cancellable())return this;this._setCancellable();this._cancellationParent=void 0;return this};Promise.prototype.uncancellable=function Promise$uncancellable(){var ret=new Promise(INTERNAL);ret._setTrace(this.uncancellable,this);ret._follow(this);ret._unsetCancellable();if(this._isBound())ret._setBoundTo(this._boundTo);return ret};Promise.prototype.fork=function Promise$fork(didFulfill,didReject,didProgress){var ret=this._then(didFulfill,didReject,didProgress,void 0,void 0,this.fork);ret._setCancellable();ret._cancellationParent=void 0;return ret}}},{"./async.js":2,"./errors.js":9}],6:[function(require,module,exports){"use strict";module.exports=function(){var inherits=require("./util.js").inherits;var defineProperty=require("./es5.js").defineProperty;var rignore=new RegExp("\\b(?:[\\w.]*Promise(?:Array|Spawn)?\\$_\\w+|"+"tryCatch(?:1|2|Apply)|new \\w*PromiseArray|"+"\\w*PromiseArray\\.\\w*PromiseArray|"+"setTimeout|CatchFilter\\$_\\w+|makeNodePromisified|processImmediate|"+"process._tickCallback|nextTick|Async\\$\\w+)\\b");var rtraceline=null;var formatStack=null;var areNamesMangled=false;function formatNonError(obj){var str;if(typeof obj==="function"){str="[function "+(obj.name||"anonymous")+"]"}else{str=obj.toString();var ruselessToString=/\[object [a-zA-Z0-9$_]+\]/;if(ruselessToString.test(str)){try{var newStr=JSON.stringify(obj);str=newStr}catch(e){}}if(str.length===0){str="(empty array)"}}return"(<"+snip(str)+">, no stack trace)"}function snip(str){var maxChars=41;if(str.length=0;--i){var line=prev[i];if(current[curLast]===line){current.pop();curLast--}else{break}}current.push("From previous event:");var lines=current.concat(prev);var ret=[];for(var i=0,len=lines.length;i0&&!rtraceline.test(lines[i])&&lines[i]!=="From previous event:"){continue}ret.push(lines[i])}return ret};CapturedTrace.isSupported=function CapturedTrace$IsSupported(){return typeof captureStackTrace==="function"};var captureStackTrace=function stackDetection(){if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){rtraceline=/^\s*at\s*/;formatStack=function(stack,error){if(typeof stack==="string")return stack;if(error.name!==void 0&&error.message!==void 0){return error.name+". "+error.message}return formatNonError(error)};var captureStackTrace=Error.captureStackTrace;return function CapturedTrace$_captureStackTrace(receiver,ignoreUntil){captureStackTrace(receiver,ignoreUntil)}}var err=new Error;if(!areNamesMangled&&typeof err.stack==="string"&&typeof"".startsWith==="function"&&err.stack.startsWith("stackDetection@")&&stackDetection.name==="stackDetection"){defineProperty(Error,"stackTraceLimit",{writable:true,enumerable:false,configurable:false,value:25});rtraceline=/@/;var rline=/[@\n]/;formatStack=function(stack,error){if(typeof stack==="string"){return error.name+". "+error.message+"\n"+stack}if(error.name!==void 0&&error.message!==void 0){return error.name+". "+error.message}return formatNonError(error)};return function captureStackTrace(o,fn){var name=fn.name;var stack=(new Error).stack;var split=stack.split(rline);var i,len=split.length;for(i=0;i=0}return false}function Promise(resolver){if(typeof resolver!=="function"){throw new TypeError("the promise constructor requires a resolver function")}if(this.constructor!==Promise){throw new TypeError("the promise constructor cannot be invoked directly")}this._bitField=0;this._fulfillmentHandler0=void 0;this._rejectionHandler0=void 0;this._promise0=void 0;this._receiver0=void 0;this._settledValue=void 0;this._boundTo=void 0;if(resolver!==INTERNAL)this._resolveFromResolver(resolver)}Promise.prototype.bind=function Promise$bind(thisArg){var ret=new Promise(INTERNAL);if(debugging)ret._setTrace(this.bind,this);ret._follow(this);ret._setBoundTo(thisArg);if(this._cancellable()){ret._setCancellable();ret._cancellationParent=this}return ret};Promise.prototype.toString=function Promise$toString(){return"[object Promise]"};Promise.prototype.caught=Promise.prototype["catch"]=function Promise$catch(fn){var len=arguments.length;if(len>1){var catchInstances=new Array(len-1),j=0,i;for(i=0;i0};Promise.prototype.isRejected=function Promise$isRejected(){return(this._bitField&134217728)>0};Promise.prototype.isPending=function Promise$isPending(){return!this.isResolved()};Promise.prototype.isResolved=function Promise$isResolved(){return(this._bitField&402653184)>0};Promise.prototype.isCancellable=function Promise$isCancellable(){return!this.isResolved()&&this._cancellable()};Promise.prototype.toJSON=function Promise$toJSON(){var ret={isFulfilled:false,isRejected:false,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled()){ret.fulfillmentValue=this._settledValue;ret.isFulfilled=true}else if(this.isRejected()){ret.rejectionReason=this._settledValue;ret.isRejected=true}return ret};Promise.prototype.all=function Promise$all(){return Promise$_all(this,true,this.all)};Promise.is=isPromise;function Promise$_all(promises,useBound,caller){return Promise$_CreatePromiseArray(promises,PromiseArray,caller,useBound===true&&promises._isBound()?promises._boundTo:void 0).promise()}Promise.all=function Promise$All(promises){return Promise$_all(promises,false,Promise.all)};Promise.join=function Promise$Join(){var $_len=arguments.length;var args=new Array($_len);for(var $_i=0;$_i<$_len;++$_i){args[$_i]=arguments[$_i]}return Promise$_CreatePromiseArray(args,PromiseArray,Promise.join,void 0).promise()};Promise.resolve=Promise.fulfilled=function Promise$Resolve(value,caller){var ret=new Promise(INTERNAL);if(debugging)ret._setTrace(typeof caller==="function"?caller:Promise.resolve,void 0);if(ret._tryFollow(value)){return ret}ret._cleanValues();ret._setFulfilled();ret._settledValue=value;return ret};Promise.reject=Promise.rejected=function Promise$Reject(reason){var ret=new Promise(INTERNAL);if(debugging)ret._setTrace(Promise.reject,void 0);markAsOriginatingFromRejection(reason);ret._cleanValues();ret._setRejected();ret._settledValue=reason;if(!canAttach(reason)){var trace=new Error(reason+"");ret._setCarriedStackTrace(trace)}ret._ensurePossibleRejectionHandled();return ret};Promise.prototype.error=function Promise$_error(fn){return this.caught(originatesFromRejection,fn)};Promise.prototype._resolveFromSyncValue=function Promise$_resolveFromSyncValue(value,caller){if(value===errorObj){this._cleanValues();this._setRejected();this._settledValue=value.e;this._ensurePossibleRejectionHandled()}else{var maybePromise=Promise._cast(value,caller,void 0);if(maybePromise instanceof Promise){this._follow(maybePromise)}else{this._cleanValues();this._setFulfilled();this._settledValue=value}}};Promise.method=function Promise$_Method(fn){if(typeof fn!=="function"){throw new TypeError("fn must be a function")}return function Promise$_method(){var value;switch(arguments.length){case 0:value=tryCatch1(fn,this,void 0);break;case 1:value=tryCatch1(fn,this,arguments[0]);break;case 2:value=tryCatch2(fn,this,arguments[0],arguments[1]);break;default:var $_len=arguments.length;var args=new Array($_len);for(var $_i=0;$_i<$_len;++$_i){args[$_i]=arguments[$_i]}value=tryCatchApply(fn,args,this);break}var ret=new Promise(INTERNAL);if(debugging)ret._setTrace(Promise$_method,void 0);ret._resolveFromSyncValue(value,Promise$_method);return ret}};Promise.attempt=Promise["try"]=function Promise$_Try(fn,args,ctx){if(typeof fn!=="function"){return apiRejection("fn must be a function")}var value=isArray(args)?tryCatchApply(fn,args,ctx):tryCatch1(fn,ctx,args);var ret=new Promise(INTERNAL);if(debugging)ret._setTrace(Promise.attempt,void 0);ret._resolveFromSyncValue(value,Promise.attempt);return ret};Promise.defer=Promise.pending=function Promise$Defer(caller){var promise=new Promise(INTERNAL);if(debugging)promise._setTrace(typeof caller==="function"?caller:Promise.defer,void 0);return new PromiseResolver(promise)};Promise.bind=function Promise$Bind(thisArg){var ret=new Promise(INTERNAL);if(debugging)ret._setTrace(Promise.bind,void 0);ret._setFulfilled();ret._setBoundTo(thisArg);return ret};Promise.cast=function Promise$_Cast(obj,caller){if(typeof caller!=="function"){caller=Promise.cast}var ret=Promise._cast(obj,caller,void 0);if(!(ret instanceof Promise)){return Promise.resolve(ret,caller)}return ret};Promise.onPossiblyUnhandledRejection=function Promise$OnPossiblyUnhandledRejection(fn){if(typeof fn==="function"){CapturedTrace.possiblyUnhandledRejection=fn}else{CapturedTrace.possiblyUnhandledRejection=void 0}};var debugging=false||!!(typeof process!=="undefined"&&typeof process.execPath==="string"&&typeof process.env==="object"&&(process.env["BLUEBIRD_DEBUG"]||process.env["NODE_ENV"]==="development"));Promise.longStackTraces=function Promise$LongStackTraces(){if(async.haveItemsQueued()&&debugging===false){throw new Error("cannot enable long stack traces after promises have been created")}debugging=CapturedTrace.isSupported()};Promise.hasLongStackTraces=function Promise$HasLongStackTraces(){return debugging&&CapturedTrace.isSupported()};Promise.prototype._setProxyHandlers=function Promise$_setProxyHandlers(receiver,promiseSlotValue){var index=this._length();if(index>=1048575-5){index=0;this._setLength(0)}if(index===0){this._promise0=promiseSlotValue;this._receiver0=receiver}else{var i=index-5;this[i+3]=promiseSlotValue;this[i+4]=receiver;this[i+0]=this[i+1]=this[i+2]=void 0}this._setLength(index+5)};Promise.prototype._proxyPromiseArray=function Promise$_proxyPromiseArray(promiseArray,index){this._setProxyHandlers(promiseArray,index)};Promise.prototype._proxyPromise=function Promise$_proxyPromise(promise){promise._setProxied();this._setProxyHandlers(promise,-1)};Promise.prototype._then=function Promise$_then(didFulfill,didReject,didProgress,receiver,internalData,caller){var haveInternalData=internalData!==void 0;var ret=haveInternalData?internalData:new Promise(INTERNAL);if(debugging&&!haveInternalData){var haveSameContext=this._peekContext()===this._traceParent;ret._traceParent=haveSameContext?this._traceParent:this;ret._setTrace(typeof caller==="function"?caller:this._then,this)}if(!haveInternalData&&this._isBound()){ret._setBoundTo(this._boundTo)}var callbackIndex=this._addCallbacks(didFulfill,didReject,didProgress,ret,receiver);if(!haveInternalData&&this._cancellable()){ret._setCancellable();ret._cancellationParent=this}if(this.isResolved()){async.invoke(this._queueSettleAt,this,callbackIndex)}return ret};Promise.prototype._length=function Promise$_length(){return this._bitField&1048575};Promise.prototype._isFollowingOrFulfilledOrRejected=function Promise$_isFollowingOrFulfilledOrRejected(){return(this._bitField&939524096)>0};Promise.prototype._isFollowing=function Promise$_isFollowing(){return(this._bitField&536870912)===536870912};Promise.prototype._setLength=function Promise$_setLength(len){this._bitField=this._bitField&-1048576|len&1048575};Promise.prototype._setFulfilled=function Promise$_setFulfilled(){this._bitField=this._bitField|268435456};Promise.prototype._setRejected=function Promise$_setRejected(){this._bitField=this._bitField|134217728};Promise.prototype._setFollowing=function Promise$_setFollowing(){this._bitField=this._bitField|536870912};Promise.prototype._setIsFinal=function Promise$_setIsFinal(){this._bitField=this._bitField|33554432};Promise.prototype._isFinal=function Promise$_isFinal(){return(this._bitField&33554432)>0};Promise.prototype._cancellable=function Promise$_cancellable(){return(this._bitField&67108864)>0};Promise.prototype._setCancellable=function Promise$_setCancellable(){this._bitField=this._bitField|67108864};Promise.prototype._unsetCancellable=function Promise$_unsetCancellable(){this._bitField=this._bitField&~67108864};Promise.prototype._setRejectionIsUnhandled=function Promise$_setRejectionIsUnhandled(){this._bitField=this._bitField|2097152};Promise.prototype._unsetRejectionIsUnhandled=function Promise$_unsetRejectionIsUnhandled(){this._bitField=this._bitField&~2097152};Promise.prototype._isRejectionUnhandled=function Promise$_isRejectionUnhandled(){return(this._bitField&2097152)>0};Promise.prototype._setCarriedStackTrace=function Promise$_setCarriedStackTrace(capturedTrace){this._bitField=this._bitField|1048576;this._fulfillmentHandler0=capturedTrace};Promise.prototype._unsetCarriedStackTrace=function Promise$_unsetCarriedStackTrace(){this._bitField=this._bitField&~1048576;this._fulfillmentHandler0=void 0};Promise.prototype._isCarryingStackTrace=function Promise$_isCarryingStackTrace(){return(this._bitField&1048576)>0};Promise.prototype._getCarriedStackTrace=function Promise$_getCarriedStackTrace(){return this._isCarryingStackTrace()?this._fulfillmentHandler0:void 0};Promise.prototype._receiverAt=function Promise$_receiverAt(index){var ret;if(index===0){ret=this._receiver0}else{ret=this[index+4-5]}if(this._isBound()&&ret===void 0){return this._boundTo}return ret};Promise.prototype._promiseAt=function Promise$_promiseAt(index){if(index===0)return this._promise0;return this[index+3-5]};Promise.prototype._fulfillmentHandlerAt=function Promise$_fulfillmentHandlerAt(index){if(index===0)return this._fulfillmentHandler0;return this[index+0-5]};Promise.prototype._rejectionHandlerAt=function Promise$_rejectionHandlerAt(index){if(index===0)return this._rejectionHandler0;return this[index+1-5]};Promise.prototype._unsetAt=function Promise$_unsetAt(index){if(index===0){this._rejectionHandler0=this._progressHandler0=this._promise0=this._receiver0=void 0;if(!this._isCarryingStackTrace()){this._fulfillmentHandler0=void 0}}else{this[index-5+0]=this[index-5+1]=this[index-5+2]=this[index-5+3]=this[index-5+4]=void 0}};Promise.prototype._resolveFromResolver=function Promise$_resolveFromResolver(resolver){var promise=this;var localDebugging=debugging;if(localDebugging){this._setTrace(this._resolveFromResolver,void 0);this._pushContext()}function Promise$_resolver(val){if(promise._tryFollow(val)){return}promise._fulfill(val)}function Promise$_rejecter(val){var trace=canAttach(val)?val:new Error(val+"");promise._attachExtraTrace(trace);markAsOriginatingFromRejection(val);promise._reject(val,trace===val?void 0:trace)}var r=tryCatch2(resolver,void 0,Promise$_resolver,Promise$_rejecter);if(localDebugging)this._popContext();if(r!==void 0&&r===errorObj){var e=r.e;var trace=canAttach(e)?e:new Error(e+"");promise._reject(e,trace)}};Promise.prototype._addCallbacks=function Promise$_addCallbacks(fulfill,reject,progress,promise,receiver){var index=this._length();if(index>=1048575-5){index=0;this._setLength(0)}if(index===0){this._promise0=promise;if(receiver!==void 0)this._receiver0=receiver;if(typeof fulfill==="function"&&!this._isCarryingStackTrace())this._fulfillmentHandler0=fulfill; -if(typeof reject==="function")this._rejectionHandler0=reject;if(typeof progress==="function")this._progressHandler0=progress}else{var i=index-5;this[i+3]=promise;this[i+4]=receiver;this[i+0]=typeof fulfill==="function"?fulfill:void 0;this[i+1]=typeof reject==="function"?reject:void 0;this[i+2]=typeof progress==="function"?progress:void 0}this._setLength(index+5);return index};Promise.prototype._setBoundTo=function Promise$_setBoundTo(obj){if(obj!==void 0){this._bitField=this._bitField|8388608;this._boundTo=obj}else{this._bitField=this._bitField&~8388608}};Promise.prototype._isBound=function Promise$_isBound(){return(this._bitField&8388608)===8388608};Promise.prototype._spreadSlowCase=function Promise$_spreadSlowCase(targetFn,promise,values,boundTo){var promiseForAll=Promise$_CreatePromiseArray(values,PromiseArray,this._spreadSlowCase,boundTo).promise()._then(function(){return targetFn.apply(boundTo,arguments)},void 0,void 0,APPLY,void 0,this._spreadSlowCase);promise._follow(promiseForAll)};Promise.prototype._callSpread=function Promise$_callSpread(handler,promise,value,localDebugging){var boundTo=this._isBound()?this._boundTo:void 0;if(isArray(value)){var caller=this._settlePromiseFromHandler;for(var i=0,len=value.length;imax){stack.length=max}if(stack.length<=headerLineCount){error.stack="(No stack trace)"}else{error.stack=stack.join("\n")}}};Promise.prototype._cleanValues=function Promise$_cleanValues(){if(this._cancellable()){this._cancellationParent=void 0}};Promise.prototype._fulfill=function Promise$_fulfill(value){if(this._isFollowingOrFulfilledOrRejected())return;this._fulfillUnchecked(value)};Promise.prototype._reject=function Promise$_reject(reason,carriedStackTrace){if(this._isFollowingOrFulfilledOrRejected())return;this._rejectUnchecked(reason,carriedStackTrace)};Promise.prototype._settlePromiseAt=function Promise$_settlePromiseAt(index){var handler=this.isFulfilled()?this._fulfillmentHandlerAt(index):this._rejectionHandlerAt(index);var value=this._settledValue;var receiver=this._receiverAt(index);var promise=this._promiseAt(index);if(typeof handler==="function"){this._settlePromiseFromHandler(handler,receiver,value,promise)}else{var done=false;var isFulfilled=this.isFulfilled();if(receiver!==void 0){if(receiver instanceof Promise&&receiver._isProxied()){receiver._unsetProxied();if(isFulfilled)receiver._fulfillUnchecked(value);else receiver._rejectUnchecked(value,this._getCarriedStackTrace());done=true}else if(isPromiseArrayProxy(receiver,promise)){if(isFulfilled)receiver._promiseFulfilled(value,promise);else receiver._promiseRejected(value,promise);done=true}}if(!done){if(isFulfilled)promise._fulfill(value);else promise._reject(value,this._getCarriedStackTrace())}}if(index>=256){this._queueGC()}};Promise.prototype._isProxied=function Promise$_isProxied(){return(this._bitField&4194304)===4194304};Promise.prototype._setProxied=function Promise$_setProxied(){this._bitField=this._bitField|4194304};Promise.prototype._unsetProxied=function Promise$_unsetProxied(){this._bitField=this._bitField&~4194304};Promise.prototype._isGcQueued=function Promise$_isGcQueued(){return(this._bitField&-1073741824)===-1073741824};Promise.prototype._setGcQueued=function Promise$_setGcQueued(){this._bitField=this._bitField|-1073741824};Promise.prototype._unsetGcQueued=function Promise$_unsetGcQueued(){this._bitField=this._bitField&~-1073741824};Promise.prototype._queueGC=function Promise$_queueGC(){if(this._isGcQueued())return;this._setGcQueued();async.invokeLater(this._gc,this,void 0)};Promise.prototype._gc=function Promise$gc(){var len=this._length();this._unsetAt(0);for(var i=0;i0){async.invoke(this._fulfillPromises,this,len)}};Promise.prototype._rejectUncheckedCheckError=function Promise$_rejectUncheckedCheckError(reason){var trace=canAttach(reason)?reason:new Error(reason+"");this._rejectUnchecked(reason,trace===reason?void 0:trace)};Promise.prototype._rejectUnchecked=function Promise$_rejectUnchecked(reason,trace){if(!this.isPending())return;if(reason===this){var err=makeSelfResolutionError();this._attachExtraTrace(err);return this._rejectUnchecked(err)}this._cleanValues();this._setRejected();this._settledValue=reason;if(this._isFinal()){async.invokeLater(thrower,void 0,trace===void 0?reason:trace);return}var len=this._length();if(trace!==void 0)this._setCarriedStackTrace(trace);if(len>0){async.invoke(this._rejectPromises,this,null)}else{this._ensurePossibleRejectionHandled()}};Promise.prototype._rejectPromises=function Promise$_rejectPromises(){var len=this._length();for(var i=0;i=0){return contextStack[lastIndex]}return void 0};Promise.prototype._pushContext=function Promise$_pushContext(){if(!debugging)return;contextStack.push(this)};Promise.prototype._popContext=function Promise$_popContext(){if(!debugging)return;contextStack.pop()};function Promise$_CreatePromiseArray(promises,PromiseArrayConstructor,caller,boundTo){var list=null;if(isArray(promises)){list=promises}else{list=Promise._cast(promises,caller,void 0);if(list!==promises){list._setBoundTo(boundTo)}else if(!isPromise(list)){list=null}}if(list!==null){return new PromiseArrayConstructor(list,typeof caller==="function"?caller:Promise$_CreatePromiseArray,boundTo)}return{promise:function(){return apiRejection("expecting an array, a promise or a thenable")}}}var old=global.Promise;Promise.noConflict=function(){if(global.Promise===Promise){global.Promise=old}return Promise};if(!CapturedTrace.isSupported()){Promise.longStackTraces=function(){};debugging=false}Promise._makeSelfResolutionError=makeSelfResolutionError;require("./finally.js")(Promise,NEXT_FILTER);require("./direct_resolve.js")(Promise);require("./thenables.js")(Promise,INTERNAL);Promise.RangeError=RangeError;Promise.CancellationError=CancellationError;Promise.TimeoutError=TimeoutError;Promise.TypeError=TypeError;Promise.RejectionError=RejectionError;util.toFastProperties(Promise);util.toFastProperties(Promise.prototype);require("./timers.js")(Promise,INTERNAL);require("./synchronous_inspection.js")(Promise);require("./any.js")(Promise,Promise$_CreatePromiseArray,PromiseArray);require("./race.js")(Promise,INTERNAL);require("./call_get.js")(Promise);require("./filter.js")(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection);require("./generators.js")(Promise,apiRejection,INTERNAL);require("./map.js")(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection);require("./nodeify.js")(Promise);require("./promisify.js")(Promise,INTERNAL);require("./props.js")(Promise,PromiseArray);require("./reduce.js")(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection,INTERNAL);require("./settle.js")(Promise,Promise$_CreatePromiseArray,PromiseArray);require("./some.js")(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection);require("./progress.js")(Promise,isPromiseArrayProxy);require("./cancel.js")(Promise,INTERNAL);Promise.prototype=Promise.prototype;return Promise}},{"./any.js":1,"./async.js":2,"./call_get.js":4,"./cancel.js":5,"./captured_trace.js":6,"./catch_filter.js":7,"./direct_resolve.js":8,"./errors.js":9,"./errors_api_rejection":10,"./filter.js":12,"./finally.js":13,"./generators.js":14,"./global.js":15,"./map.js":16,"./nodeify.js":17,"./progress.js":18,"./promise_array.js":20,"./promise_resolver.js":22,"./promisify.js":24,"./props.js":26,"./race.js":28,"./reduce.js":29,"./settle.js":31,"./some.js":33,"./synchronous_inspection.js":35,"./thenables.js":36,"./timers.js":37,"./util.js":38}],20:[function(require,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var canAttach=require("./errors.js").canAttach;var util=require("./util.js");var async=require("./async.js");var hasOwn={}.hasOwnProperty;var isArray=util.isArray;function toResolutionValue(val){switch(val){case-1:return void 0;case-2:return[];case-3:return{}}}function PromiseArray(values,caller,boundTo){var promise=this._promise=new Promise(INTERNAL);var parent=void 0;if(Promise.is(values)){parent=values;if(values._cancellable()){promise._setCancellable();promise._cancellationParent=values}if(values._isBound()){promise._setBoundTo(boundTo)}}promise._setTrace(caller,parent);this._values=values;this._length=0;this._totalResolved=0;this._init(void 0,-2)}PromiseArray.PropertiesPromiseArray=function(){};PromiseArray.prototype.length=function PromiseArray$length(){return this._length};PromiseArray.prototype.promise=function PromiseArray$promise(){return this._promise};PromiseArray.prototype._init=function PromiseArray$_init(_,resolveValueIfEmpty){var values=this._values;if(Promise.is(values)){if(values.isFulfilled()){values=values._settledValue;if(!isArray(values)){var err=new Promise.TypeError("expecting an array, a promise or a thenable");this.__hardReject__(err);return}this._values=values}else if(values.isPending()){values._then(this._init,this._reject,void 0,this,resolveValueIfEmpty,this.constructor);return}else{this._reject(values._settledValue);return}}if(values.length===0){this._resolve(toResolutionValue(resolveValueIfEmpty));return}var len=values.length;var newLen=len;var newValues;if(this instanceof PromiseArray.PropertiesPromiseArray){newValues=this._values}else{newValues=new Array(len)}var isDirectScanNeeded=false;for(var i=0;i=this._length){this._resolve(this._values)}};PromiseArray.prototype._promiseRejected=function PromiseArray$_promiseRejected(reason,index){if(this._isResolved())return;this._totalResolved++;this._reject(reason)};return PromiseArray}},{"./async.js":2,"./errors.js":9,"./util.js":38}],21:[function(require,module,exports){"use strict";var TypeError=require("./errors.js").TypeError;function PromiseInspection(promise){if(promise!==void 0){this._bitField=promise._bitField;this._settledValue=promise.isResolved()?promise._settledValue:void 0}else{this._bitField=0;this._settledValue=void 0}}PromiseInspection.prototype.isFulfilled=function PromiseInspection$isFulfilled(){return(this._bitField&268435456)>0};PromiseInspection.prototype.isRejected=function PromiseInspection$isRejected(){return(this._bitField&134217728)>0};PromiseInspection.prototype.isPending=function PromiseInspection$isPending(){return(this._bitField&402653184)===0};PromiseInspection.prototype.value=function PromiseInspection$value(){if(!this.isFulfilled()){throw new TypeError("cannot get fulfillment value of a non-fulfilled promise")}return this._settledValue};PromiseInspection.prototype.error=function PromiseInspection$error(){if(!this.isRejected()){throw new TypeError("cannot get rejection reason of a non-rejected promise")}return this._settledValue};module.exports=PromiseInspection},{"./errors.js":9}],22:[function(require,module,exports){"use strict";var util=require("./util.js");var maybeWrapAsError=util.maybeWrapAsError;var errors=require("./errors.js");var TimeoutError=errors.TimeoutError;var RejectionError=errors.RejectionError;var async=require("./async.js");var haveGetters=util.haveGetters;var es5=require("./es5.js");function isUntypedError(obj){return obj instanceof Error&&es5.getPrototypeOf(obj)===Error.prototype}function wrapAsRejectionError(obj){var ret;if(isUntypedError(obj)){ret=new RejectionError(obj)}else{ret=obj}errors.markAsOriginatingFromRejection(ret);return ret}function nodebackForPromise(promise){function PromiseResolver$_callback(err,value){if(promise===null)return;if(err){var wrapped=wrapAsRejectionError(maybeWrapAsError(err));promise._attachExtraTrace(wrapped);promise._reject(wrapped)}else{if(arguments.length>2){var $_len=arguments.length;var args=new Array($_len-1);for(var $_i=1;$_i<$_len;++$_i){args[$_i-1]=arguments[$_i]}promise._fulfill(args)}else{promise._fulfill(value)}}promise=null}return PromiseResolver$_callback}var PromiseResolver;if(!haveGetters){PromiseResolver=function PromiseResolver(promise){this.promise=promise;this.asCallback=nodebackForPromise(promise);this.callback=this.asCallback}}else{PromiseResolver=function PromiseResolver(promise){this.promise=promise}}if(haveGetters){var prop={get:function(){return nodebackForPromise(this.promise)}};es5.defineProperty(PromiseResolver.prototype,"asCallback",prop);es5.defineProperty(PromiseResolver.prototype,"callback",prop)}PromiseResolver._nodebackForPromise=nodebackForPromise;PromiseResolver.prototype.toString=function PromiseResolver$toString(){return"[object PromiseResolver]"};PromiseResolver.prototype.resolve=PromiseResolver.prototype.fulfill=function PromiseResolver$resolve(value){var promise=this.promise;if(promise._tryFollow(value)){return}async.invoke(promise._fulfill,promise,value)};PromiseResolver.prototype.reject=function PromiseResolver$reject(reason){var promise=this.promise;errors.markAsOriginatingFromRejection(reason);var trace=errors.canAttach(reason)?reason:new Error(reason+"");promise._attachExtraTrace(trace);async.invoke(promise._reject,promise,reason);if(trace!==reason){async.invoke(this._setCarriedStackTrace,this,trace)}};PromiseResolver.prototype.progress=function PromiseResolver$progress(value){async.invoke(this.promise._progress,this.promise,value)};PromiseResolver.prototype.cancel=function PromiseResolver$cancel(){async.invoke(this.promise.cancel,this.promise,void 0)};PromiseResolver.prototype.timeout=function PromiseResolver$timeout(){this.reject(new TimeoutError("timeout"))};PromiseResolver.prototype.isResolved=function PromiseResolver$isResolved(){return this.promise.isResolved()};PromiseResolver.prototype.toJSON=function PromiseResolver$toJSON(){return this.promise.toJSON()};PromiseResolver.prototype._setCarriedStackTrace=function PromiseResolver$_setCarriedStackTrace(trace){if(this.promise.isRejected()){this.promise._setCarriedStackTrace(trace)}};module.exports=PromiseResolver},{"./async.js":2,"./errors.js":9,"./es5.js":11,"./util.js":38}],23:[function(require,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var errors=require("./errors.js");var TypeError=errors.TypeError;var util=require("./util.js");var isArray=util.isArray;var errorObj=util.errorObj;var tryCatch1=util.tryCatch1;var yieldHandlers=[];function promiseFromYieldHandler(value){var _yieldHandlers=yieldHandlers;var _errorObj=errorObj;var _Promise=Promise;var len=_yieldHandlers.length;for(var i=0;i=min;--i){if(i===likelyArgumentCount)continue;ret.push(i)}for(var i=likelyArgumentCount+1;i<=5;++i){ret.push(i)}return ret}function parameterDeclaration(parameterCount){var ret=new Array(parameterCount);for(var i=0;i0?",":"";if(typeof callback==="string"&&receiver===THIS){return"this"+propertyAccess(callback)+"("+args.join(",")+comma+" fn);"+"break;"}return(receiver===void 0?"callback("+args.join(",")+comma+" fn);":"callback.call("+(receiver===THIS?"this":"receiver")+", "+args.join(",")+comma+" fn);")+"break;"}function generateArgumentSwitchCase(){var ret="";for(var i=0;i=this._length){var val={};var keyOffset=this.length();for(var i=0,len=this.length();i>>0;n=n-1;n=n|n>>1;n=n|n>>2;n=n|n>>4;n=n|n>>8;n=n|n>>16;return n+1}function getCapacity(capacity){if(typeof capacity!=="number")return 16;return pow2AtLeast(Math.min(Math.max(16,capacity),1073741824))}function Queue(capacity){this._capacity=getCapacity(capacity);this._length=0;this._front=0;this._makeCapacity()}Queue.prototype._willBeOverCapacity=function Queue$_willBeOverCapacity(size){return this._capacity0)accum=fulfilleds[0]}var i=startIndex;if(i>=len){return accum}var reduction=new Reduction(fn,i,accum,fulfilleds,receiver);reduction.iterate();return reduction.promise}function Promise$_unpackReducer(fulfilleds){var fn=this.fn;var initialValue=this.initialValue;return Promise$_reducer.call(fn,fulfilleds,initialValue)}function Promise$_slowReduce(promises,fn,initialValue,useBound,caller){return initialValue._then(function callee(initialValue){return Promise$_Reduce(promises,fn,initialValue,useBound,callee)},void 0,void 0,void 0,void 0,caller)}function Promise$_Reduce(promises,fn,initialValue,useBound,caller){if(typeof fn!=="function"){return apiRejection("fn must be a function")}if(useBound===true&&promises._isBound()){fn={fn:fn,receiver:promises._boundTo}}if(initialValue!==void 0){if(Promise.is(initialValue)){if(initialValue.isFulfilled()){initialValue=initialValue._settledValue}else{return Promise$_slowReduce(promises,fn,initialValue,useBound,caller)}}return Promise$_CreatePromiseArray(promises,PromiseArray,caller,useBound===true&&promises._isBound()?promises._boundTo:void 0).promise()._then(Promise$_unpackReducer,void 0,void 0,{fn:fn,initialValue:initialValue},void 0,Promise.reduce)}return Promise$_CreatePromiseArray(promises,PromiseArray,caller,useBound===true&&promises._isBound()?promises._boundTo:void 0).promise()._then(Promise$_reducer,void 0,void 0,fn,void 0,caller)}Promise.reduce=function Promise$Reduce(promises,fn,initialValue){return Promise$_Reduce(promises,fn,initialValue,false,Promise.reduce)};Promise.prototype.reduce=function Promise$reduce(fn,initialValue){return Promise$_Reduce(this,fn,initialValue,true,this.reduce)}}},{}],30:[function(require,module,exports){"use strict";var global=require("./global.js");var schedule;if(typeof process!=="undefined"&&process!==null&&typeof process.cwd==="function"&&typeof process.nextTick==="function"&&typeof process.version==="string"){schedule=function Promise$_Scheduler(fn){process.nextTick(fn)}}else if((typeof global.MutationObserver==="function"||typeof global.WebkitMutationObserver==="function"||typeof global.WebKitMutationObserver==="function")&&typeof document!=="undefined"&&typeof document.createElement==="function"){schedule=function(){var MutationObserver=global.MutationObserver||global.WebkitMutationObserver||global.WebKitMutationObserver;var div=document.createElement("div");var queuedFn=void 0;var observer=new MutationObserver(function Promise$_Scheduler(){var fn=queuedFn;queuedFn=void 0;fn()});observer.observe(div,{attributes:true});return function Promise$_Scheduler(fn){queuedFn=fn;div.setAttribute("class","foo")}}()}else if(typeof global.postMessage==="function"&&typeof global.importScripts!=="function"&&typeof global.addEventListener==="function"&&typeof global.removeEventListener==="function"){var MESSAGE_KEY="bluebird_message_key_"+Math.random();schedule=function(){var queuedFn=void 0;function Promise$_Scheduler(e){if(e.source===global&&e.data===MESSAGE_KEY){var fn=queuedFn;queuedFn=void 0;fn()}}global.addEventListener("message",Promise$_Scheduler,false);return function Promise$_Scheduler(fn){queuedFn=fn;global.postMessage(MESSAGE_KEY,"*")}}()}else if(typeof global.MessageChannel==="function"){schedule=function(){var queuedFn=void 0;var channel=new global.MessageChannel;channel.port1.onmessage=function Promise$_Scheduler(){var fn=queuedFn;queuedFn=void 0;fn()};return function Promise$_Scheduler(fn){queuedFn=fn;channel.port2.postMessage(null)}}()}else if(global.setTimeout){schedule=function Promise$_Scheduler(fn){setTimeout(fn,4)}}else{schedule=function Promise$_Scheduler(fn){fn()}}module.exports=schedule},{"./global.js":15}],31:[function(require,module,exports){"use strict";module.exports=function(Promise,Promise$_CreatePromiseArray,PromiseArray){var SettledPromiseArray=require("./settled_promise_array.js")(Promise,PromiseArray);function Promise$_Settle(promises,useBound,caller){return Promise$_CreatePromiseArray(promises,SettledPromiseArray,caller,useBound===true&&promises._isBound()?promises._boundTo:void 0).promise()}Promise.settle=function Promise$Settle(promises){return Promise$_Settle(promises,false,Promise.settle)};Promise.prototype.settle=function Promise$settle(){return Promise$_Settle(this,true,this.settle)}}},{"./settled_promise_array.js":32}],32:[function(require,module,exports){"use strict";module.exports=function(Promise,PromiseArray){var PromiseInspection=require("./promise_inspection.js");var util=require("./util.js");var inherits=util.inherits;function SettledPromiseArray(values,caller,boundTo){this.constructor$(values,caller,boundTo)}inherits(SettledPromiseArray,PromiseArray);SettledPromiseArray.prototype._promiseResolved=function SettledPromiseArray$_promiseResolved(index,inspection){this._values[index]=inspection;var totalResolved=++this._totalResolved;if(totalResolved>=this._length){this._resolve(this._values)}};SettledPromiseArray.prototype._promiseFulfilled=function SettledPromiseArray$_promiseFulfilled(value,index){if(this._isResolved())return;var ret=new PromiseInspection;ret._bitField=268435456;ret._settledValue=value;this._promiseResolved(index,ret)};SettledPromiseArray.prototype._promiseRejected=function SettledPromiseArray$_promiseRejected(reason,index){if(this._isResolved())return;var ret=new PromiseInspection;ret._bitField=134217728;ret._settledValue=reason;this._promiseResolved(index,ret)};return SettledPromiseArray}},{"./promise_inspection.js":21,"./util.js":38}],33:[function(require,module,exports){"use strict";module.exports=function(Promise,Promise$_CreatePromiseArray,PromiseArray,apiRejection){var SomePromiseArray=require("./some_promise_array.js")(PromiseArray);function Promise$_Some(promises,howMany,useBound,caller){if((howMany|0)!==howMany||howMany<0){return apiRejection("expecting a positive integer")}var ret=Promise$_CreatePromiseArray(promises,SomePromiseArray,caller,useBound===true&&promises._isBound()?promises._boundTo:void 0);var promise=ret.promise();if(promise.isRejected()){return promise}ret.setHowMany(howMany);ret.init();return promise}Promise.some=function Promise$Some(promises,howMany){return Promise$_Some(promises,howMany,false,Promise.some)};Promise.prototype.some=function Promise$some(count){return Promise$_Some(this,count,true,this.some)}}},{"./some_promise_array.js":34}],34:[function(require,module,exports){"use strict";module.exports=function(PromiseArray){var util=require("./util.js");var RangeError=require("./errors.js").RangeError;var inherits=util.inherits;var isArray=util.isArray;function SomePromiseArray(values,caller,boundTo){this.constructor$(values,caller,boundTo);this._howMany=0;this._unwrap=false;this._initialized=false}inherits(SomePromiseArray,PromiseArray);SomePromiseArray.prototype._init=function SomePromiseArray$_init(){if(!this._initialized){return}if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-2);var isArrayResolved=isArray(this._values);this._holes=isArrayResolved?this._values.length-this.length():0;if(!this._isResolved()&&isArrayResolved&&this._howMany>this._canPossiblyFulfill()){var message="(Promise.some) input array contains less than "+this._howMany+" promises";this._reject(new RangeError(message))}};SomePromiseArray.prototype.init=function SomePromiseArray$init(){this._initialized=true;this._init()};SomePromiseArray.prototype.setUnwrap=function SomePromiseArray$setUnwrap(){this._unwrap=true};SomePromiseArray.prototype.howMany=function SomePromiseArray$howMany(){return this._howMany};SomePromiseArray.prototype.setHowMany=function SomePromiseArray$setHowMany(count){if(this._isResolved())return;this._howMany=count};SomePromiseArray.prototype._promiseFulfilled=function SomePromiseArray$_promiseFulfilled(value){if(this._isResolved())return;this._addFulfilled(value);if(this._fulfilled()===this.howMany()){this._values.length=this.howMany();if(this.howMany()===1&&this._unwrap){this._resolve(this._values[0])}else{this._resolve(this._values)}}};SomePromiseArray.prototype._promiseRejected=function SomePromiseArray$_promiseRejected(reason){if(this._isResolved())return;this._addRejected(reason);if(this.howMany()>this._canPossiblyFulfill()){if(this._values.length===this.length()){this._reject([])}else{this._reject(this._values.slice(this.length()+this._holes))}}};SomePromiseArray.prototype._fulfilled=function SomePromiseArray$_fulfilled(){return this._totalResolved};SomePromiseArray.prototype._rejected=function SomePromiseArray$_rejected(){return this._values.length-this.length()-this._holes};SomePromiseArray.prototype._addRejected=function SomePromiseArray$_addRejected(reason){this._values.push(reason)};SomePromiseArray.prototype._addFulfilled=function SomePromiseArray$_addFulfilled(value){this._values[this._totalResolved++]=value};SomePromiseArray.prototype._canPossiblyFulfill=function SomePromiseArray$_canPossiblyFulfill(){return this.length()-this._rejected()};return SomePromiseArray}},{"./errors.js":9,"./util.js":38}],35:[function(require,module,exports){"use strict";module.exports=function(Promise){var PromiseInspection=require("./promise_inspection.js");Promise.prototype.inspect=function Promise$inspect(){return new PromiseInspection(this)}}},{"./promise_inspection.js":21}],36:[function(require,module,exports){"use strict";module.exports=function(Promise,INTERNAL){var util=require("./util.js");var canAttach=require("./errors.js").canAttach;var errorObj=util.errorObj;var isObject=util.isObject;function getThen(obj){try{return obj.then}catch(e){errorObj.e=e;return errorObj}}function Promise$_Cast(obj,caller,originalPromise){if(isObject(obj)){if(obj instanceof Promise){return obj}else if(isAnyBluebirdPromise(obj)){var ret=new Promise(INTERNAL);ret._setTrace(caller,void 0);obj._then(ret._fulfillUnchecked,ret._rejectUncheckedCheckError,ret._progressUnchecked,ret,null,void 0);ret._setFollowing();return ret}var then=getThen(obj);if(then===errorObj){caller=typeof caller==="function"?caller:Promise$_Cast;if(originalPromise!==void 0&&canAttach(then.e)){originalPromise._attachExtraTrace(then.e)}return Promise.reject(then.e,caller)}else if(typeof then==="function"){caller=typeof caller==="function"?caller:Promise$_Cast;return Promise$_doThenable(obj,then,caller,originalPromise)}}return obj}var hasProp={}.hasOwnProperty;function isAnyBluebirdPromise(obj){return hasProp.call(obj,"_promise0")}function Promise$_doThenable(x,then,caller,originalPromise){var resolver=Promise.defer(caller);var called=false;try{then.call(x,Promise$_resolveFromThenable,Promise$_rejectFromThenable,Promise$_progressFromThenable)}catch(e){if(!called){called=true;var trace=canAttach(e)?e:new Error(e+"");if(originalPromise!==void 0){originalPromise._attachExtraTrace(trace)}resolver.promise._reject(e,trace)}}return resolver.promise;function Promise$_resolveFromThenable(y){if(called)return;called=true;if(x===y){var e=Promise._makeSelfResolutionError();if(originalPromise!==void 0){originalPromise._attachExtraTrace(e)}resolver.promise._reject(e,void 0);return}resolver.resolve(y)}function Promise$_rejectFromThenable(r){if(called)return;called=true;var trace=canAttach(r)?r:new Error(r+"");if(originalPromise!==void 0){originalPromise._attachExtraTrace(trace)}resolver.promise._reject(r,trace)}function Promise$_progressFromThenable(v){if(called)return;var promise=resolver.promise;if(typeof promise._progress==="function"){promise._progress(v)}}}Promise._cast=Promise$_Cast}},{"./errors.js":9,"./util.js":38}],37:[function(require,module,exports){"use strict";var global=require("./global.js");var setTimeout=function(fn,time){var $_len=arguments.length;var args=new Array($_len-2);for(var $_i=2;$_i<$_len;++$_i){args[$_i-2]=arguments[$_i]}global.setTimeout(function(){fn.apply(void 0,args)},time)};var pass={};global.setTimeout(function(_){if(_===pass){setTimeout=global.setTimeout}},1,pass);module.exports=function(Promise,INTERNAL){var util=require("./util.js");var errors=require("./errors.js");var apiRejection=require("./errors_api_rejection")(Promise);var TimeoutError=Promise.TimeoutError;var afterTimeout=function Promise$_afterTimeout(promise,message,ms){if(!promise.isPending())return;if(typeof message!=="string"){message="operation timed out after"+" "+ms+" ms"}var err=new TimeoutError(message);errors.markAsOriginatingFromRejection(err);promise._attachExtraTrace(err);promise._rejectUnchecked(err)};var afterDelay=function Promise$_afterDelay(value,promise){promise._fulfill(value)};Promise.delay=function Promise$Delay(value,ms,caller){if(ms===void 0){ms=value;value=void 0}ms=+ms;if(typeof caller!=="function"){caller=Promise.delay}var maybePromise=Promise._cast(value,caller,void 0);var promise=new Promise(INTERNAL);if(Promise.is(maybePromise)){if(maybePromise._isBound()){promise._setBoundTo(maybePromise._boundTo)}if(maybePromise._cancellable()){promise._setCancellable();promise._cancellationParent=maybePromise}promise._setTrace(caller,maybePromise);promise._follow(maybePromise);return promise.then(function(value){return Promise.delay(value,ms)})}else{promise._setTrace(caller,void 0);setTimeout(afterDelay,ms,value,promise)}return promise};Promise.prototype.delay=function Promise$delay(ms){return Promise.delay(this,ms,this.delay)};Promise.prototype.timeout=function Promise$timeout(ms,message){ms=+ms;var ret=new Promise(INTERNAL);ret._setTrace(this.timeout,this);if(this._isBound())ret._setBoundTo(this._boundTo);if(this._cancellable()){ret._setCancellable();ret._cancellationParent=this}ret._follow(this);setTimeout(afterTimeout,ms,ret,message,ms);return ret}}},{"./errors.js":9,"./errors_api_rejection":10,"./global.js":15,"./util.js":38}],38:[function(require,module,exports){"use strict";var global=require("./global.js");var es5=require("./es5.js");var haveGetters=function(){try{var o={};es5.defineProperty(o,"f",{get:function(){return 3}});return o.f===3}catch(e){return false}}();var canEvaluate=function(){if(typeof window!=="undefined"&&window!==null&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"&&navigator!==null&&typeof navigator.appName==="string"&&window===global){return false}return true}();function deprecated(msg){if(typeof console!=="undefined"&&console!==null&&typeof console.warn==="function"){console.warn("Bluebird: "+msg)}}var errorObj={e:{}};function tryCatch1(fn,receiver,arg){try{return fn.call(receiver,arg)}catch(e){errorObj.e=e;return errorObj}}function tryCatch2(fn,receiver,arg,arg2){try{return fn.call(receiver,arg,arg2)}catch(e){errorObj.e=e;return errorObj}}function tryCatchApply(fn,args,receiver){try{return fn.apply(receiver,args)}catch(e){errorObj.e=e;return errorObj}}var inherits=function(Child,Parent){var hasProp={}.hasOwnProperty;function T(){this.constructor=Child;this.constructor$=Parent;for(var propertyName in Parent.prototype){if(hasProp.call(Parent.prototype,propertyName)&&propertyName.charAt(propertyName.length-1)!=="$"){this[propertyName+"$"]=Parent.prototype[propertyName]}}}T.prototype=Parent.prototype;Child.prototype=new T;return Child.prototype};function asString(val){return typeof val==="string"?val:""+val}function isPrimitive(val){return val==null||val===true||val===false||typeof val==="string"||typeof val==="number"}function isObject(value){return!isPrimitive(value)}function maybeWrapAsError(maybeError){if(!isPrimitive(maybeError))return maybeError;return new Error(asString(maybeError))}function withAppended(target,appendee){var len=target.length;var ret=new Array(len+1);var i;for(i=0;ib?1:a>=b?0:NaN}d3.descending=function(a,b){return ba?1:b>=a?0:NaN};d3.min=function(array,f){var i=-1,n=array.length,a,b;if(arguments.length===1){while(++ib)a=b}else{while(++ib)a=b}return a};d3.max=function(array,f){var i=-1,n=array.length,a,b;if(arguments.length===1){while(++ia)a=b}else{while(++ia)a=b}return a};d3.extent=function(array,f){var i=-1,n=array.length,a,b,c;if(arguments.length===1){while(++ib)a=b;if(cb)a=b;if(c1)array=array.map(f);array=array.filter(d3_number);return array.length?d3.quantile(array.sort(d3_ascending),.5):undefined};function d3_bisector(compare){return{left:function(a,x,lo,hi){if(arguments.length<3)lo=0;if(arguments.length<4)hi=a.length;while(lo>>1;if(compare(a[mid],x)<0)lo=mid+1;else hi=mid}return lo},right:function(a,x,lo,hi){if(arguments.length<3)lo=0;if(arguments.length<4)hi=a.length;while(lo>>1;if(compare(a[mid],x)>0)hi=mid;else lo=mid+1}return lo}}}var d3_bisect=d3_bisector(d3_ascending);d3.bisectLeft=d3_bisect.left;d3.bisect=d3.bisectRight=d3_bisect.right;d3.bisector=function(f){return d3_bisector(f.length===1?function(d,x){return d3_ascending(f(d),x)}:f)};d3.shuffle=function(array){var m=array.length,t,i;while(m){i=Math.random()*m--|0;t=array[m],array[m]=array[i],array[i]=t}return array};d3.permute=function(array,indexes){var i=indexes.length,permutes=new Array(i);while(i--)permutes[i]=array[indexes[i]];return permutes};d3.pairs=function(array){var i=0,n=array.length-1,p0,p1=array[0],pairs=new Array(n<0?0:n);while(i=0){array=arrays[n];m=array.length;while(--m>=0){merged[--j]=array[m]}}return merged};var abs=Math.abs;d3.range=function(start,stop,step){if(arguments.length<3){step=1;if(arguments.length<2){stop=start;start=0}}if((stop-start)/step===Infinity)throw new Error("infinite range");var range=[],k=d3_range_integerScale(abs(step)),i=-1,j;start*=k,stop*=k,step*=k;if(step<0)while((j=start+step*++i)>stop)range.push(j/k);else while((j=start+step*++i)=keys.length)return rollup?rollup.call(nest,array):sortValues?array.sort(sortValues):array;var i=-1,n=array.length,key=keys[depth++],keyValue,object,setter,valuesByKey=new d3_Map,values;while(++i=keys.length)return map;var array=[],sortKey=sortKeys[depth++];map.forEach(function(key,keyMap){array.push({key:key,values:entries(keyMap,depth)})});return sortKey?array.sort(function(a,b){return sortKey(a.key,b.key)}):array}nest.map=function(array,mapType){return map(mapType,array,0)};nest.entries=function(array){return entries(map(d3.map,array,0),0)};nest.key=function(d){keys.push(d);return nest};nest.sortKeys=function(order){sortKeys[keys.length-1]=order;return nest};nest.sortValues=function(order){sortValues=order;return nest};nest.rollup=function(f){rollup=f;return nest};return nest};d3.set=function(array){var set=new d3_Set;if(array)for(var i=0,n=array.length;i=0){name=type.substring(i+1);type=type.substring(0,i)}if(type)return arguments.length<2?this[type].on(name):this[type].on(name,listener);if(arguments.length===2){if(listener==null)for(type in this){if(this.hasOwnProperty(type))this[type].on(name,null)}return this}};function d3_dispatch_event(dispatch){var listeners=[],listenerByName=new d3_Map;function event(){var z=listeners,i=-1,n=z.length,l;while(++i=0){prefix=name.substring(0,i);name=name.substring(i+1)}return d3_nsPrefix.hasOwnProperty(prefix)?{space:d3_nsPrefix[prefix],local:name}:name}};d3_selectionPrototype.attr=function(name,value){if(arguments.length<2){if(typeof name==="string"){var node=this.node();name=d3.ns.qualify(name);return name.local?node.getAttributeNS(name.space,name.local):node.getAttribute(name)}for(value in name)this.each(d3_selection_attr(value,name[value]));return this}return this.each(d3_selection_attr(name,value))};function d3_selection_attr(name,value){name=d3.ns.qualify(name);function attrNull(){this.removeAttribute(name)}function attrNullNS(){this.removeAttributeNS(name.space,name.local)}function attrConstant(){this.setAttribute(name,value)}function attrConstantNS(){this.setAttributeNS(name.space,name.local,value)}function attrFunction(){var x=value.apply(this,arguments);if(x==null)this.removeAttribute(name);else this.setAttribute(name,x)}function attrFunctionNS(){var x=value.apply(this,arguments);if(x==null)this.removeAttributeNS(name.space,name.local);else this.setAttributeNS(name.space,name.local,x)}return value==null?name.local?attrNullNS:attrNull:typeof value==="function"?name.local?attrFunctionNS:attrFunction:name.local?attrConstantNS:attrConstant}function d3_collapse(s){return s.trim().replace(/\s+/g," ")}d3_selectionPrototype.classed=function(name,value){if(arguments.length<2){if(typeof name==="string"){var node=this.node(),n=(name=d3_selection_classes(name)).length,i=-1;if(value=node.classList){while(++i=0;){if(node=group[i]){if(next&&next!==node.nextSibling)next.parentNode.insertBefore(node,next);next=node}}}return this};d3_selectionPrototype.sort=function(comparator){comparator=d3_selection_sortComparator.apply(this,arguments);for(var j=-1,m=this.length;++j=i0)i0=i+1;while(!(node=group[i0])&&++i00)type=type.substring(0,i);var filter=d3_selection_onFilters.get(type);if(filter)type=filter,wrap=d3_selection_onFilter;function onRemove(){var l=this[name];if(l){this.removeEventListener(type,l,l.$);delete this[name]}}function onAdd(){var l=wrap(listener,d3_array(arguments));onRemove.call(this);this.addEventListener(type,this[name]=l,l.$=capture);l._=listener}function removeAll(){var re=new RegExp("^__on([^.]+)"+d3.requote(type)+"$"),match;for(var name in this){if(match=name.match(re)){var l=this[name];this.removeEventListener(match[1],l,l.$);delete this[name]}}}return i?listener?onAdd:onRemove:listener?d3_noop:removeAll}var d3_selection_onFilters=d3.map({mouseenter:"mouseover",mouseleave:"mouseout"});d3_selection_onFilters.forEach(function(k){if("on"+k in d3_document)d3_selection_onFilters.remove(k)});function d3_selection_onListener(listener,argumentz){return function(e){var o=d3.event;d3.event=e;argumentz[0]=this.__data__;try{listener.apply(this,argumentz)}finally{d3.event=o}}}function d3_selection_onFilter(listener,argumentz){var l=d3_selection_onListener(listener,argumentz);return function(e){var target=this,related=e.relatedTarget;if(!related||related!==target&&!(related.compareDocumentPosition(target)&8)){l.call(target,e)}}}var d3_event_dragSelect="onselectstart"in d3_document?null:d3_vendorSymbol(d3_documentElement.style,"userSelect"),d3_event_dragId=0;function d3_event_dragSuppress(){var name=".dragsuppress-"+ ++d3_event_dragId,click="click"+name,w=d3.select(d3_window).on("touchmove"+name,d3_eventPreventDefault).on("dragstart"+name,d3_eventPreventDefault).on("selectstart"+name,d3_eventPreventDefault);if(d3_event_dragSelect){var style=d3_documentElement.style,select=style[d3_event_dragSelect];style[d3_event_dragSelect]="none"}return function(suppressClick){w.on(name,null);if(d3_event_dragSelect)style[d3_event_dragSelect]=select;if(suppressClick){function off(){w.on(click,null)}w.on(click,function(){d3_eventPreventDefault();off()},true);setTimeout(off,0)}}}d3.mouse=function(container){return d3_mousePoint(container,d3_eventSource())};function d3_mousePoint(container,e){if(e.changedTouches)e=e.changedTouches[0];var svg=container.ownerSVGElement||container;if(svg.createSVGPoint){var point=svg.createSVGPoint();point.x=e.clientX,point.y=e.clientY;point=point.matrixTransform(container.getScreenCTM().inverse());return[point.x,point.y]}var rect=container.getBoundingClientRect();return[e.clientX-rect.left-container.clientLeft,e.clientY-rect.top-container.clientTop]}d3.touches=function(container,touches){if(arguments.length<2)touches=d3_eventSource().touches;return touches?d3_array(touches).map(function(touch){var point=d3_mousePoint(container,touch);point.identifier=touch.identifier;return point}):[]};d3.behavior.drag=function(){var event=d3_eventDispatch(drag,"drag","dragstart","dragend"),origin=null,mousedown=dragstart(d3_noop,d3.mouse,d3_behavior_dragMouseSubject,"mousemove","mouseup"),touchstart=dragstart(d3_behavior_dragTouchId,d3.touch,d3_behavior_dragTouchSubject,"touchmove","touchend");function drag(){this.on("mousedown.drag",mousedown).on("touchstart.drag",touchstart)}function dragstart(id,position,subject,move,end){return function(){var that=this,target=d3.event.target,parent=that.parentNode,dispatch=event.of(that,arguments),dragged=0,dragId=id(),dragName=".drag"+(dragId==null?"":"-"+dragId),dragOffset,dragSubject=d3.select(subject()).on(move+dragName,moved).on(end+dragName,ended),dragRestore=d3_event_dragSuppress(),position0=position(parent,dragId);if(origin){dragOffset=origin.apply(that,arguments);dragOffset=[dragOffset.x-position0[0],dragOffset.y-position0[1]]}else{dragOffset=[0,0]}dispatch({type:"dragstart"});function moved(){var position1=position(parent,dragId),dx,dy;if(!position1)return;dx=position1[0]-position0[0];dy=position1[1]-position0[1];dragged|=dx|dy;position0=position1;dispatch({type:"drag",x:position1[0]+dragOffset[0],y:position1[1]+dragOffset[1],dx:dx,dy:dy})}function ended(){if(!position(parent,dragId))return;dragSubject.on(move+dragName,null).on(end+dragName,null);dragRestore(dragged&&d3.event.target===target);dispatch({type:"dragend"})}}}drag.origin=function(x){if(!arguments.length)return origin;origin=x;return drag};return d3.rebind(drag,event,"on")};function d3_behavior_dragTouchId(){return d3.event.changedTouches[0].identifier}function d3_behavior_dragTouchSubject(){return d3.event.target}function d3_behavior_dragMouseSubject(){return d3_window}var π=Math.PI,τ=2*π,halfπ=π/2,ε=1e-6,ε2=ε*ε,d3_radians=π/180,d3_degrees=180/π;function d3_sgn(x){return x>0?1:x<0?-1:0}function d3_cross2d(a,b,c){return(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0])}function d3_acos(x){return x>1?0:x<-1?π:Math.acos(x)}function d3_asin(x){return x>1?halfπ:x<-1?-halfπ:Math.asin(x)}function d3_sinh(x){return((x=Math.exp(x))-1/x)/2}function d3_cosh(x){return((x=Math.exp(x))+1/x)/2}function d3_tanh(x){return((x=Math.exp(2*x))-1)/(x+1)}function d3_haversin(x){return(x=Math.sin(x/2))*x}var ρ=Math.SQRT2,ρ2=2,ρ4=4;d3.interpolateZoom=function(p0,p1){var ux0=p0[0],uy0=p0[1],w0=p0[2],ux1=p1[0],uy1=p1[1],w1=p1[2];var dx=ux1-ux0,dy=uy1-uy0,d2=dx*dx+dy*dy,d1=Math.sqrt(d2),b0=(w1*w1-w0*w0+ρ4*d2)/(2*w0*ρ2*d1),b1=(w1*w1-w0*w0-ρ4*d2)/(2*w1*ρ2*d1),r0=Math.log(Math.sqrt(b0*b0+1)-b0),r1=Math.log(Math.sqrt(b1*b1+1)-b1),dr=r1-r0,S=(dr||Math.log(w1/w0))/ρ;function interpolate(t){var s=t*S;if(dr){var coshr0=d3_cosh(r0),u=w0/(ρ2*d1)*(coshr0*d3_tanh(ρ*s+r0)-d3_sinh(r0));return[ux0+u*dx,uy0+u*dy,w0*coshr0/d3_cosh(ρ*s+r0)]}return[ux0+t*dx,uy0+t*dy,w0*Math.exp(ρ*s)]}interpolate.duration=S*1e3;return interpolate};d3.behavior.zoom=function(){var view={x:0,y:0,k:1},translate0,center,size=[960,500],scaleExtent=d3_behavior_zoomInfinity,mousedown="mousedown.zoom",mousemove="mousemove.zoom",mouseup="mouseup.zoom",mousewheelTimer,touchstart="touchstart.zoom",touchtime,event=d3_eventDispatch(zoom,"zoomstart","zoom","zoomend"),x0,x1,y0,y1;function zoom(g){g.on(mousedown,mousedowned).on(d3_behavior_zoomWheel+".zoom",mousewheeled).on(mousemove,mousewheelreset).on("dblclick.zoom",dblclicked).on(touchstart,touchstarted)}zoom.event=function(g){g.each(function(){var dispatch=event.of(this,arguments),view1=view;if(d3_transitionInheritId){d3.select(this).transition().each("start.zoom",function(){view=this.__chart__||{x:0,y:0,k:1};zoomstarted(dispatch)}).tween("zoom:zoom",function(){var dx=size[0],dy=size[1],cx=dx/2,cy=dy/2,i=d3.interpolateZoom([(cx-view.x)/view.k,(cy-view.y)/view.k,dx/view.k],[(cx-view1.x)/view1.k,(cy-view1.y)/view1.k,dx/view1.k]);return function(t){var l=i(t),k=dx/l[2];this.__chart__=view={x:cx-l[0]*k,y:cy-l[1]*k,k:k};zoomed(dispatch)}}).each("end.zoom",function(){zoomended(dispatch)})}else{this.__chart__=view; -zoomstarted(dispatch);zoomed(dispatch);zoomended(dispatch)}})};zoom.translate=function(_){if(!arguments.length)return[view.x,view.y];view={x:+_[0],y:+_[1],k:view.k};rescale();return zoom};zoom.scale=function(_){if(!arguments.length)return view.k;view={x:view.x,y:view.y,k:+_};rescale();return zoom};zoom.scaleExtent=function(_){if(!arguments.length)return scaleExtent;scaleExtent=_==null?d3_behavior_zoomInfinity:[+_[0],+_[1]];return zoom};zoom.center=function(_){if(!arguments.length)return center;center=_&&[+_[0],+_[1]];return zoom};zoom.size=function(_){if(!arguments.length)return size;size=_&&[+_[0],+_[1]];return zoom};zoom.x=function(z){if(!arguments.length)return x1;x1=z;x0=z.copy();view={x:0,y:0,k:1};return zoom};zoom.y=function(z){if(!arguments.length)return y1;y1=z;y0=z.copy();view={x:0,y:0,k:1};return zoom};function location(p){return[(p[0]-view.x)/view.k,(p[1]-view.y)/view.k]}function point(l){return[l[0]*view.k+view.x,l[1]*view.k+view.y]}function scaleTo(s){view.k=Math.max(scaleExtent[0],Math.min(scaleExtent[1],s))}function translateTo(p,l){l=point(l);view.x+=p[0]-l[0];view.y+=p[1]-l[1]}function rescale(){if(x1)x1.domain(x0.range().map(function(x){return(x-view.x)/view.k}).map(x0.invert));if(y1)y1.domain(y0.range().map(function(y){return(y-view.y)/view.k}).map(y0.invert))}function zoomstarted(dispatch){dispatch({type:"zoomstart"})}function zoomed(dispatch){rescale();dispatch({type:"zoom",scale:view.k,translate:[view.x,view.y]})}function zoomended(dispatch){dispatch({type:"zoomend"})}function mousedowned(){var that=this,target=d3.event.target,dispatch=event.of(that,arguments),dragged=0,subject=d3.select(d3_window).on(mousemove,moved).on(mouseup,ended),location0=location(d3.mouse(that)),dragRestore=d3_event_dragSuppress();d3_selection_interrupt.call(that);zoomstarted(dispatch);function moved(){dragged=1;translateTo(d3.mouse(that),location0);zoomed(dispatch)}function ended(){subject.on(mousemove,d3_window===that?mousewheelreset:null).on(mouseup,null);dragRestore(dragged&&d3.event.target===target);zoomended(dispatch)}}function touchstarted(){var that=this,dispatch=event.of(that,arguments),locations0={},distance0=0,scale0,zoomName=".zoom-"+d3.event.changedTouches[0].identifier,touchmove="touchmove"+zoomName,touchend="touchend"+zoomName,targets=[],subject=d3.select(that).on(mousedown,null).on(touchstart,started),dragRestore=d3_event_dragSuppress();d3_selection_interrupt.call(that);started();zoomstarted(dispatch);function relocate(){var touches=d3.touches(that);scale0=view.k;touches.forEach(function(t){if(t.identifier in locations0)locations0[t.identifier]=location(t)});return touches}function started(){var target=d3.event.target;d3.select(target).on(touchmove,moved).on(touchend,ended);targets.push(target);var changed=d3.event.changedTouches;for(var i=0,n=changed.length;i1){var p=touches[0],q=touches[1],dx=p[0]-q[0],dy=p[1]-q[1];distance0=dx*dx+dy*dy}}function moved(){var touches=d3.touches(that),p0,l0,p1,l1;for(var i=0,n=touches.length;i1?1:s;l=l<0?0:l>1?1:l;m2=l<=.5?l*(1+s):l+s-l*s;m1=2*l-m2;function v(h){if(h>360)h-=360;else if(h<0)h+=360;if(h<60)return m1+(m2-m1)*h/60;if(h<180)return m2;if(h<240)return m1+(m2-m1)*(240-h)/60;return m1}function vv(h){return Math.round(v(h)*255)}return d3_rgb(vv(h+120),vv(h),vv(h-120))}d3.hcl=function(h,c,l){return arguments.length===1?h instanceof d3_Hcl?d3_hcl(h.h,h.c,h.l):h instanceof d3_Lab?d3_lab_hcl(h.l,h.a,h.b):d3_lab_hcl((h=d3_rgb_lab((h=d3.rgb(h)).r,h.g,h.b)).l,h.a,h.b):d3_hcl(+h,+c,+l)};function d3_hcl(h,c,l){return new d3_Hcl(h,c,l)}function d3_Hcl(h,c,l){this.h=h;this.c=c;this.l=l}var d3_hclPrototype=d3_Hcl.prototype=new d3_Color;d3_hclPrototype.brighter=function(k){return d3_hcl(this.h,this.c,Math.min(100,this.l+d3_lab_K*(arguments.length?k:1)))};d3_hclPrototype.darker=function(k){return d3_hcl(this.h,this.c,Math.max(0,this.l-d3_lab_K*(arguments.length?k:1)))};d3_hclPrototype.rgb=function(){return d3_hcl_lab(this.h,this.c,this.l).rgb()};function d3_hcl_lab(h,c,l){if(isNaN(h))h=0;if(isNaN(c))c=0;return d3_lab(l,Math.cos(h*=d3_radians)*c,Math.sin(h)*c)}d3.lab=function(l,a,b){return arguments.length===1?l instanceof d3_Lab?d3_lab(l.l,l.a,l.b):l instanceof d3_Hcl?d3_hcl_lab(l.l,l.c,l.h):d3_rgb_lab((l=d3.rgb(l)).r,l.g,l.b):d3_lab(+l,+a,+b)};function d3_lab(l,a,b){return new d3_Lab(l,a,b)}function d3_Lab(l,a,b){this.l=l;this.a=a;this.b=b}var d3_lab_K=18;var d3_lab_X=.95047,d3_lab_Y=1,d3_lab_Z=1.08883;var d3_labPrototype=d3_Lab.prototype=new d3_Color;d3_labPrototype.brighter=function(k){return d3_lab(Math.min(100,this.l+d3_lab_K*(arguments.length?k:1)),this.a,this.b)};d3_labPrototype.darker=function(k){return d3_lab(Math.max(0,this.l-d3_lab_K*(arguments.length?k:1)),this.a,this.b)};d3_labPrototype.rgb=function(){return d3_lab_rgb(this.l,this.a,this.b)};function d3_lab_rgb(l,a,b){var y=(l+16)/116,x=y+a/500,z=y-b/200;x=d3_lab_xyz(x)*d3_lab_X;y=d3_lab_xyz(y)*d3_lab_Y;z=d3_lab_xyz(z)*d3_lab_Z;return d3_rgb(d3_xyz_rgb(3.2404542*x-1.5371385*y-.4985314*z),d3_xyz_rgb(-.969266*x+1.8760108*y+.041556*z),d3_xyz_rgb(.0556434*x-.2040259*y+1.0572252*z))}function d3_lab_hcl(l,a,b){return l>0?d3_hcl(Math.atan2(b,a)*d3_degrees,Math.sqrt(a*a+b*b),l):d3_hcl(NaN,NaN,l)}function d3_lab_xyz(x){return x>.206893034?x*x*x:(x-4/29)/7.787037}function d3_xyz_lab(x){return x>.008856?Math.pow(x,1/3):7.787037*x+4/29}function d3_xyz_rgb(r){return Math.round(255*(r<=.00304?12.92*r:1.055*Math.pow(r,1/2.4)-.055))}d3.rgb=function(r,g,b){return arguments.length===1?r instanceof d3_Rgb?d3_rgb(r.r,r.g,r.b):d3_rgb_parse(""+r,d3_rgb,d3_hsl_rgb):d3_rgb(~~r,~~g,~~b)};function d3_rgbNumber(value){return d3_rgb(value>>16,value>>8&255,value&255)}function d3_rgbString(value){return d3_rgbNumber(value)+""}function d3_rgb(r,g,b){return new d3_Rgb(r,g,b)}function d3_Rgb(r,g,b){this.r=r;this.g=g;this.b=b}var d3_rgbPrototype=d3_Rgb.prototype=new d3_Color;d3_rgbPrototype.brighter=function(k){k=Math.pow(.7,arguments.length?k:1);var r=this.r,g=this.g,b=this.b,i=30;if(!r&&!g&&!b)return d3_rgb(i,i,i);if(r&&r>4;r=r>>4|r;g=color&240;g=g>>4|g;b=color&15;b=b<<4|b}else if(format.length===7){r=(color&16711680)>>16;g=(color&65280)>>8;b=color&255}}return rgb(r,g,b)}function d3_rgb_hsl(r,g,b){var min=Math.min(r/=255,g/=255,b/=255),max=Math.max(r,g,b),d=max-min,h,s,l=(max+min)/2;if(d){s=l<.5?d/(max+min):d/(2-max-min);if(r==max)h=(g-b)/d+(g0&&l<1?0:h}return d3_hsl(h,s,l)}function d3_rgb_lab(r,g,b){r=d3_rgb_xyz(r);g=d3_rgb_xyz(g);b=d3_rgb_xyz(b);var x=d3_xyz_lab((.4124564*r+.3575761*g+.1804375*b)/d3_lab_X),y=d3_xyz_lab((.2126729*r+.7151522*g+.072175*b)/d3_lab_Y),z=d3_xyz_lab((.0193339*r+.119192*g+.9503041*b)/d3_lab_Z);return d3_lab(116*y-16,500*(x-y),200*(y-z))}function d3_rgb_xyz(r){return(r/=255)<=.04045?r/12.92:Math.pow((r+.055)/1.055,2.4)}function d3_rgb_parseNumber(c){var f=parseFloat(c);return c.charAt(c.length-1)==="%"?Math.round(f*2.55):f}var d3_rgb_names=d3.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});d3_rgb_names.forEach(function(key,value){d3_rgb_names.set(key,d3_rgbNumber(value))});function d3_functor(v){return typeof v==="function"?v:function(){return v}}d3.functor=d3_functor;function d3_identity(d){return d}d3.xhr=d3_xhrType(d3_identity);function d3_xhrType(response){return function(url,mimeType,callback){if(arguments.length===2&&typeof mimeType==="function")callback=mimeType,mimeType=null;return d3_xhr(url,mimeType,response,callback)}}function d3_xhr(url,mimeType,response,callback){var xhr={},dispatch=d3.dispatch("beforesend","progress","load","error"),headers={},request=new XMLHttpRequest,responseType=null;if(d3_window.XDomainRequest&&!("withCredentials"in request)&&/^(http(s)?:)?\/\//.test(url))request=new XDomainRequest;"onload"in request?request.onload=request.onerror=respond:request.onreadystatechange=function(){request.readyState>3&&respond()};function respond(){var status=request.status,result;if(!status&&request.responseText||status>=200&&status<300||status===304){try{result=response.call(xhr,request)}catch(e){dispatch.error.call(xhr,e);return}dispatch.load.call(xhr,result)}else{dispatch.error.call(xhr,request)}}request.onprogress=function(event){var o=d3.event;d3.event=event;try{dispatch.progress.call(xhr,request)}finally{d3.event=o}};xhr.header=function(name,value){name=(name+"").toLowerCase();if(arguments.length<2)return headers[name];if(value==null)delete headers[name];else headers[name]=value+"";return xhr};xhr.mimeType=function(value){if(!arguments.length)return mimeType;mimeType=value==null?null:value+"";return xhr};xhr.responseType=function(value){if(!arguments.length)return responseType;responseType=value;return xhr};xhr.response=function(value){response=value;return xhr};["get","post"].forEach(function(method){xhr[method]=function(){return xhr.send.apply(xhr,[method].concat(d3_array(arguments)))}});xhr.send=function(method,data,callback){if(arguments.length===2&&typeof data==="function")callback=data,data=null;request.open(method,url,true);if(mimeType!=null&&!("accept"in headers))headers["accept"]=mimeType+",*/*";if(request.setRequestHeader)for(var name in headers)request.setRequestHeader(name,headers[name]);if(mimeType!=null&&request.overrideMimeType)request.overrideMimeType(mimeType);if(responseType!=null)request.responseType=responseType;if(callback!=null)xhr.on("error",callback).on("load",function(request){callback(null,request)});dispatch.beforesend.call(xhr,request);request.send(data==null?null:data);return xhr};xhr.abort=function(){request.abort();return xhr};d3.rebind(xhr,dispatch,"on");return callback==null?xhr:xhr.get(d3_xhr_fixCallback(callback))}function d3_xhr_fixCallback(callback){return callback.length===1?function(error,request){callback(error==null?request:null)}:callback}d3.dsv=function(delimiter,mimeType){var reFormat=new RegExp('["'+delimiter+"\n]"),delimiterCode=delimiter.charCodeAt(0);function dsv(url,row,callback){if(arguments.length<3)callback=row,row=null;var xhr=d3_xhr(url,mimeType,row==null?response:typedResponse(row),callback);xhr.row=function(_){return arguments.length?xhr.response((row=_)==null?response:typedResponse(_)):row};return xhr}function response(request){return dsv.parse(request.responseText)}function typedResponse(f){return function(request){return dsv.parse(request.responseText,f)}}dsv.parse=function(text,f){var o;return dsv.parseRows(text,function(row,i){if(o)return o(row,i-1);var a=new Function("d","return {"+row.map(function(name,i){return JSON.stringify(name)+": d["+i+"]"}).join(",")+"}");o=f?function(row,i){return f(a(row),i)}:a})};dsv.parseRows=function(text,f){var EOL={},EOF={},rows=[],N=text.length,I=0,n=0,t,eol;function token(){if(I>=N)return EOF;if(eol)return eol=false,EOL;var j=I;if(text.charCodeAt(j)===34){var i=j;while(i++24){if(isFinite(delay)){clearTimeout(d3_timer_timeout);d3_timer_timeout=setTimeout(d3_timer_step,delay)}d3_timer_interval=0}else{d3_timer_interval=1;d3_timer_frame(d3_timer_step)}}d3.timer.flush=function(){d3_timer_mark();d3_timer_sweep()};function d3_timer_mark(){var now=Date.now();d3_timer_active=d3_timer_queueHead;while(d3_timer_active){if(now>=d3_timer_active.t)d3_timer_active.f=d3_timer_active.c(now-d3_timer_active.t);d3_timer_active=d3_timer_active.n}return now}function d3_timer_sweep(){var t0,t1=d3_timer_queueHead,time=Infinity;while(t1){if(t1.f){t1=t0?t0.n=t1.n:d3_timer_queueHead=t1.n}else{if(t1.t8?function(d){return d/k}:function(d){return d*k},symbol:d}}function d3_locale_numberFormat(locale){var locale_decimal=locale.decimal,locale_thousands=locale.thousands,locale_grouping=locale.grouping,locale_currency=locale.currency,formatGroup=locale_grouping?function(value){var i=value.length,t=[],j=0,g=locale_grouping[0];while(i>0&&g>0){t.push(value.substring(i-=g,i+g));g=locale_grouping[j=(j+1)%locale_grouping.length]}return t.reverse().join(locale_thousands)}:d3_identity;return function(specifier){var match=d3_format_re.exec(specifier),fill=match[1]||" ",align=match[2]||">",sign=match[3]||"",symbol=match[4]||"",zfill=match[5],width=+match[6],comma=match[7],precision=match[8],type=match[9],scale=1,prefix="",suffix="",integer=false;if(precision)precision=+precision.substring(1);if(zfill||fill==="0"&&align==="="){zfill=fill="0";align="=";if(comma)width-=Math.floor((width-1)/4)}switch(type){case"n":comma=true;type="g";break;case"%":scale=100;suffix="%";type="f";break;case"p":scale=100;suffix="%";type="r";break;case"b":case"o":case"x":case"X":if(symbol==="#")prefix="0"+type.toLowerCase();case"c":case"d":integer=true;precision=0;break;case"s":scale=-1;type="r";break}if(symbol==="$")prefix=locale_currency[0],suffix=locale_currency[1];if(type=="r"&&!precision)type="g";if(precision!=null){if(type=="g")precision=Math.max(1,Math.min(21,precision));else if(type=="e"||type=="f")precision=Math.max(0,Math.min(20,precision))}type=d3_format_types.get(type)||d3_format_typeDefault;var zcomma=zfill&,return function(value){var fullSuffix=suffix;if(integer&&value%1)return"";var negative=value<0||value===0&&1/value<0?(value=-value,"-"):sign;if(scale<0){var unit=d3.formatPrefix(value,precision);value=unit.scale(value);fullSuffix=unit.symbol+suffix}else{value*=scale}value=type(value,precision);var i=value.lastIndexOf("."),before=i<0?value:value.substring(0,i),after=i<0?"":locale_decimal+value.substring(i+1);if(!zfill&&comma)before=formatGroup(before);var length=prefix.length+before.length+after.length+(zcomma?0:negative.length),padding=length"?padding+negative+value:align==="^"?padding.substring(0,length>>=1)+negative+value+padding.substring(length):negative+(zcomma?value:padding+value))+fullSuffix}}}var d3_format_re=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;var d3_format_types=d3.map({b:function(x){return x.toString(2)},c:function(x){return String.fromCharCode(x)},o:function(x){return x.toString(8)},x:function(x){return x.toString(16)},X:function(x){return x.toString(16).toUpperCase()},g:function(x,p){return x.toPrecision(p)},e:function(x,p){return x.toExponential(p)},f:function(x,p){return x.toFixed(p)},r:function(x,p){return(x=d3.round(x,d3_format_precision(x,p))).toFixed(Math.max(0,Math.min(20,d3_format_precision(x*(1+1e-15),p))))}});function d3_format_typeDefault(x){return x+""}var d3_time=d3.time={},d3_date=Date;function d3_date_utc(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}d3_date_utc.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){d3_time_prototype.setUTCDate.apply(this._,arguments)},setDay:function(){d3_time_prototype.setUTCDay.apply(this._,arguments)},setFullYear:function(){d3_time_prototype.setUTCFullYear.apply(this._,arguments)},setHours:function(){d3_time_prototype.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){d3_time_prototype.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){d3_time_prototype.setUTCMinutes.apply(this._,arguments)},setMonth:function(){d3_time_prototype.setUTCMonth.apply(this._,arguments)},setSeconds:function(){d3_time_prototype.setUTCSeconds.apply(this._,arguments)},setTime:function(){d3_time_prototype.setTime.apply(this._,arguments)}};var d3_time_prototype=Date.prototype;function d3_time_interval(local,step,number){function round(date){var d0=local(date),d1=offset(d0,1);return date-d01){while(time=m)return-1;c=template.charCodeAt(i++);if(c===37){t=template.charAt(i++);p=d3_time_parsers[t in d3_time_formatPads?template.charAt(i++):t];if(!p||(j=p(date,string,j))<0)return-1}else if(c!=string.charCodeAt(j++)){return-1}}return j}d3_time_format.utc=function(template){var local=d3_time_format(template);function format(date){try{d3_date=d3_date_utc;var utc=new d3_date;utc._=date;return local(utc)}finally{d3_date=Date}}format.parse=function(string){try{d3_date=d3_date_utc;var date=local.parse(string);return date&&date._}finally{d3_date=Date}};format.toString=local.toString;return format};d3_time_format.multi=d3_time_format.utc.multi=d3_time_formatMulti;var d3_time_periodLookup=d3.map(),d3_time_dayRe=d3_time_formatRe(locale_days),d3_time_dayLookup=d3_time_formatLookup(locale_days),d3_time_dayAbbrevRe=d3_time_formatRe(locale_shortDays),d3_time_dayAbbrevLookup=d3_time_formatLookup(locale_shortDays),d3_time_monthRe=d3_time_formatRe(locale_months),d3_time_monthLookup=d3_time_formatLookup(locale_months),d3_time_monthAbbrevRe=d3_time_formatRe(locale_shortMonths),d3_time_monthAbbrevLookup=d3_time_formatLookup(locale_shortMonths);locale_periods.forEach(function(p,i){d3_time_periodLookup.set(p.toLowerCase(),i)});var d3_time_formats={a:function(d){return locale_shortDays[d.getDay()]},A:function(d){return locale_days[d.getDay()]},b:function(d){return locale_shortMonths[d.getMonth()]},B:function(d){return locale_months[d.getMonth()]},c:d3_time_format(locale_dateTime),d:function(d,p){return d3_time_formatPad(d.getDate(),p,2)},e:function(d,p){return d3_time_formatPad(d.getDate(),p,2)},H:function(d,p){return d3_time_formatPad(d.getHours(),p,2)},I:function(d,p){return d3_time_formatPad(d.getHours()%12||12,p,2)},j:function(d,p){return d3_time_formatPad(1+d3_time.dayOfYear(d),p,3)},L:function(d,p){return d3_time_formatPad(d.getMilliseconds(),p,3)},m:function(d,p){return d3_time_formatPad(d.getMonth()+1,p,2)},M:function(d,p){return d3_time_formatPad(d.getMinutes(),p,2)},p:function(d){return locale_periods[+(d.getHours()>=12)]},S:function(d,p){return d3_time_formatPad(d.getSeconds(),p,2)},U:function(d,p){return d3_time_formatPad(d3_time.sundayOfYear(d),p,2)},w:function(d){return d.getDay()},W:function(d,p){return d3_time_formatPad(d3_time.mondayOfYear(d),p,2)},x:d3_time_format(locale_date),X:d3_time_format(locale_time),y:function(d,p){return d3_time_formatPad(d.getFullYear()%100,p,2)},Y:function(d,p){return d3_time_formatPad(d.getFullYear()%1e4,p,4)},Z:d3_time_zone,"%":function(){return"%" -}};var d3_time_parsers={a:d3_time_parseWeekdayAbbrev,A:d3_time_parseWeekday,b:d3_time_parseMonthAbbrev,B:d3_time_parseMonth,c:d3_time_parseLocaleFull,d:d3_time_parseDay,e:d3_time_parseDay,H:d3_time_parseHour24,I:d3_time_parseHour24,j:d3_time_parseDayOfYear,L:d3_time_parseMilliseconds,m:d3_time_parseMonthNumber,M:d3_time_parseMinutes,p:d3_time_parseAmPm,S:d3_time_parseSeconds,U:d3_time_parseWeekNumberSunday,w:d3_time_parseWeekdayNumber,W:d3_time_parseWeekNumberMonday,x:d3_time_parseLocaleDate,X:d3_time_parseLocaleTime,y:d3_time_parseYear,Y:d3_time_parseFullYear,Z:d3_time_parseZone,"%":d3_time_parseLiteralPercent};function d3_time_parseWeekdayAbbrev(date,string,i){d3_time_dayAbbrevRe.lastIndex=0;var n=d3_time_dayAbbrevRe.exec(string.substring(i));return n?(date.w=d3_time_dayAbbrevLookup.get(n[0].toLowerCase()),i+n[0].length):-1}function d3_time_parseWeekday(date,string,i){d3_time_dayRe.lastIndex=0;var n=d3_time_dayRe.exec(string.substring(i));return n?(date.w=d3_time_dayLookup.get(n[0].toLowerCase()),i+n[0].length):-1}function d3_time_parseMonthAbbrev(date,string,i){d3_time_monthAbbrevRe.lastIndex=0;var n=d3_time_monthAbbrevRe.exec(string.substring(i));return n?(date.m=d3_time_monthAbbrevLookup.get(n[0].toLowerCase()),i+n[0].length):-1}function d3_time_parseMonth(date,string,i){d3_time_monthRe.lastIndex=0;var n=d3_time_monthRe.exec(string.substring(i));return n?(date.m=d3_time_monthLookup.get(n[0].toLowerCase()),i+n[0].length):-1}function d3_time_parseLocaleFull(date,string,i){return d3_time_parse(date,d3_time_formats.c.toString(),string,i)}function d3_time_parseLocaleDate(date,string,i){return d3_time_parse(date,d3_time_formats.x.toString(),string,i)}function d3_time_parseLocaleTime(date,string,i){return d3_time_parse(date,d3_time_formats.X.toString(),string,i)}function d3_time_parseAmPm(date,string,i){var n=d3_time_periodLookup.get(string.substring(i,i+=2).toLowerCase());return n==null?-1:(date.p=n,i)}return d3_time_format}var d3_time_formatPads={"-":"",_:" ",0:"0"},d3_time_numberRe=/^\s*\d+/,d3_time_percentRe=/^%/;function d3_time_formatPad(value,fill,width){var sign=value<0?"-":"",string=(sign?-value:value)+"",length=string.length;return sign+(length68?1900:2e3)}function d3_time_parseMonthNumber(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.m=n[0]-1,i+n[0].length):-1}function d3_time_parseDay(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.d=+n[0],i+n[0].length):-1}function d3_time_parseDayOfYear(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+3));return n?(date.j=+n[0],i+n[0].length):-1}function d3_time_parseHour24(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.H=+n[0],i+n[0].length):-1}function d3_time_parseMinutes(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.M=+n[0],i+n[0].length):-1}function d3_time_parseSeconds(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+2));return n?(date.S=+n[0],i+n[0].length):-1}function d3_time_parseMilliseconds(date,string,i){d3_time_numberRe.lastIndex=0;var n=d3_time_numberRe.exec(string.substring(i,i+3));return n?(date.L=+n[0],i+n[0].length):-1}function d3_time_zone(d){var z=d.getTimezoneOffset(),zs=z>0?"-":"+",zh=~~(abs(z)/60),zm=abs(z)%60;return zs+d3_time_formatPad(zh,"0",2)+d3_time_formatPad(zm,"0",2)}function d3_time_parseLiteralPercent(date,string,i){d3_time_percentRe.lastIndex=0;var n=d3_time_percentRe.exec(string.substring(i,i+1));return n?i+n[0].length:-1}function d3_time_formatMulti(formats){var n=formats.length,i=-1;while(++i=0?1:-1,adλ=sdλ*dλ,cosφ=Math.cos(φ),sinφ=Math.sin(φ),k=sinφ0*sinφ,u=cosφ0*cosφ+k*Math.cos(adλ),v=k*sdλ*Math.sin(adλ);d3_geo_areaRingSum.add(Math.atan2(v,u));λ0=λ,cosφ0=cosφ,sinφ0=sinφ}d3_geo_area.lineEnd=function(){nextPoint(λ00,φ00)}}function d3_geo_cartesian(spherical){var λ=spherical[0],φ=spherical[1],cosφ=Math.cos(φ);return[cosφ*Math.cos(λ),cosφ*Math.sin(λ),Math.sin(φ)]}function d3_geo_cartesianDot(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]}function d3_geo_cartesianCross(a,b){return[a[1]*b[2]-a[2]*b[1],a[2]*b[0]-a[0]*b[2],a[0]*b[1]-a[1]*b[0]]}function d3_geo_cartesianAdd(a,b){a[0]+=b[0];a[1]+=b[1];a[2]+=b[2]}function d3_geo_cartesianScale(vector,k){return[vector[0]*k,vector[1]*k,vector[2]*k]}function d3_geo_cartesianNormalize(d){var l=Math.sqrt(d[0]*d[0]+d[1]*d[1]+d[2]*d[2]);d[0]/=l;d[1]/=l;d[2]/=l}function d3_geo_spherical(cartesian){return[Math.atan2(cartesian[1],cartesian[0]),d3_asin(cartesian[2])]}function d3_geo_sphericalEqual(a,b){return abs(a[0]-b[0])<ε&&abs(a[1]-b[1])<ε}d3.geo.bounds=function(){var λ0,φ0,λ1,φ1,λ_,λ__,φ__,p0,dλSum,ranges,range;var bound={point:point,lineStart:lineStart,lineEnd:lineEnd,polygonStart:function(){bound.point=ringPoint;bound.lineStart=ringStart;bound.lineEnd=ringEnd;dλSum=0;d3_geo_area.polygonStart()},polygonEnd:function(){d3_geo_area.polygonEnd();bound.point=point;bound.lineStart=lineStart;bound.lineEnd=lineEnd;if(d3_geo_areaRingSum<0)λ0=-(λ1=180),φ0=-(φ1=90);else if(dλSum>ε)φ1=90;else if(dλSum<-ε)φ0=-90;range[0]=λ0,range[1]=λ1}};function point(λ,φ){ranges.push(range=[λ0=λ,λ1=λ]);if(φ<φ0)φ0=φ;if(φ>φ1)φ1=φ}function linePoint(λ,φ){var p=d3_geo_cartesian([λ*d3_radians,φ*d3_radians]);if(p0){var normal=d3_geo_cartesianCross(p0,p),equatorial=[normal[1],-normal[0],0],inflection=d3_geo_cartesianCross(equatorial,normal);d3_geo_cartesianNormalize(inflection);inflection=d3_geo_spherical(inflection);var dλ=λ-λ_,s=dλ>0?1:-1,λi=inflection[0]*d3_degrees*s,antimeridian=abs(dλ)>180;if(antimeridian^(s*λ_<λi&&λiφ1)φ1=φi}else if(λi=(λi+360)%360-180,antimeridian^(s*λ_<λi&&λiφ1)φ1=φ}if(antimeridian){if(λ<λ_){if(angle(λ0,λ)>angle(λ0,λ1))λ1=λ}else{if(angle(λ,λ1)>angle(λ0,λ1))λ0=λ}}else{if(λ1>=λ0){if(λ<λ0)λ0=λ;if(λ>λ1)λ1=λ}else{if(λ>λ_){if(angle(λ0,λ)>angle(λ0,λ1))λ1=λ}else{if(angle(λ,λ1)>angle(λ0,λ1))λ0=λ}}}}else{point(λ,φ)}p0=p,λ_=λ}function lineStart(){bound.point=linePoint}function lineEnd(){range[0]=λ0,range[1]=λ1;bound.point=point;p0=null}function ringPoint(λ,φ){if(p0){var dλ=λ-λ_;dλSum+=abs(dλ)>180?dλ+(dλ>0?360:-360):dλ}else λ__=λ,φ__=φ;d3_geo_area.point(λ,φ);linePoint(λ,φ)}function ringStart(){d3_geo_area.lineStart()}function ringEnd(){ringPoint(λ__,φ__);d3_geo_area.lineEnd();if(abs(dλSum)>ε)λ0=-(λ1=180);range[0]=λ0,range[1]=λ1;p0=null}function angle(λ0,λ1){return(λ1-=λ0)<0?λ1+360:λ1}function compareRanges(a,b){return a[0]-b[0]}function withinRange(x,range){return range[0]<=range[1]?range[0]<=x&&x<=range[1]:xangle(a[0],a[1]))a[1]=b[1];if(angle(b[0],a[1])>angle(a[0],a[1]))a[0]=b[0]}else{merged.push(a=b)}}var best=-Infinity,dλ;for(var n=merged.length-1,i=0,a=merged[n],b;i<=n;a=b,++i){b=merged[i];if((dλ=angle(a[1],b[0]))>best)best=dλ,λ0=b[0],λ1=a[1]}}ranges=range=null;return λ0===Infinity||φ0===Infinity?[[NaN,NaN],[NaN,NaN]]:[[λ0,φ0],[λ1,φ1]]}}();d3.geo.centroid=function(object){d3_geo_centroidW0=d3_geo_centroidW1=d3_geo_centroidX0=d3_geo_centroidY0=d3_geo_centroidZ0=d3_geo_centroidX1=d3_geo_centroidY1=d3_geo_centroidZ1=d3_geo_centroidX2=d3_geo_centroidY2=d3_geo_centroidZ2=0;d3.geo.stream(object,d3_geo_centroid);var x=d3_geo_centroidX2,y=d3_geo_centroidY2,z=d3_geo_centroidZ2,m=x*x+y*y+z*z;if(m<ε2){x=d3_geo_centroidX1,y=d3_geo_centroidY1,z=d3_geo_centroidZ1;if(d3_geo_centroidW1<ε)x=d3_geo_centroidX0,y=d3_geo_centroidY0,z=d3_geo_centroidZ0;m=x*x+y*y+z*z;if(m<ε2)return[NaN,NaN]}return[Math.atan2(y,x)*d3_degrees,d3_asin(z/Math.sqrt(m))*d3_degrees]};var d3_geo_centroidW0,d3_geo_centroidW1,d3_geo_centroidX0,d3_geo_centroidY0,d3_geo_centroidZ0,d3_geo_centroidX1,d3_geo_centroidY1,d3_geo_centroidZ1,d3_geo_centroidX2,d3_geo_centroidY2,d3_geo_centroidZ2;var d3_geo_centroid={sphere:d3_noop,point:d3_geo_centroidPoint,lineStart:d3_geo_centroidLineStart,lineEnd:d3_geo_centroidLineEnd,polygonStart:function(){d3_geo_centroid.lineStart=d3_geo_centroidRingStart},polygonEnd:function(){d3_geo_centroid.lineStart=d3_geo_centroidLineStart}};function d3_geo_centroidPoint(λ,φ){λ*=d3_radians;var cosφ=Math.cos(φ*=d3_radians);d3_geo_centroidPointXYZ(cosφ*Math.cos(λ),cosφ*Math.sin(λ),Math.sin(φ))}function d3_geo_centroidPointXYZ(x,y,z){++d3_geo_centroidW0;d3_geo_centroidX0+=(x-d3_geo_centroidX0)/d3_geo_centroidW0;d3_geo_centroidY0+=(y-d3_geo_centroidY0)/d3_geo_centroidW0;d3_geo_centroidZ0+=(z-d3_geo_centroidZ0)/d3_geo_centroidW0}function d3_geo_centroidLineStart(){var x0,y0,z0;d3_geo_centroid.point=function(λ,φ){λ*=d3_radians;var cosφ=Math.cos(φ*=d3_radians);x0=cosφ*Math.cos(λ);y0=cosφ*Math.sin(λ);z0=Math.sin(φ);d3_geo_centroid.point=nextPoint;d3_geo_centroidPointXYZ(x0,y0,z0)};function nextPoint(λ,φ){λ*=d3_radians;var cosφ=Math.cos(φ*=d3_radians),x=cosφ*Math.cos(λ),y=cosφ*Math.sin(λ),z=Math.sin(φ),w=Math.atan2(Math.sqrt((w=y0*z-z0*y)*w+(w=z0*x-x0*z)*w+(w=x0*y-y0*x)*w),x0*x+y0*y+z0*z);d3_geo_centroidW1+=w;d3_geo_centroidX1+=w*(x0+(x0=x));d3_geo_centroidY1+=w*(y0+(y0=y));d3_geo_centroidZ1+=w*(z0+(z0=z));d3_geo_centroidPointXYZ(x0,y0,z0)}}function d3_geo_centroidLineEnd(){d3_geo_centroid.point=d3_geo_centroidPoint}function d3_geo_centroidRingStart(){var λ00,φ00,x0,y0,z0;d3_geo_centroid.point=function(λ,φ){λ00=λ,φ00=φ;d3_geo_centroid.point=nextPoint;λ*=d3_radians;var cosφ=Math.cos(φ*=d3_radians);x0=cosφ*Math.cos(λ);y0=cosφ*Math.sin(λ);z0=Math.sin(φ);d3_geo_centroidPointXYZ(x0,y0,z0)};d3_geo_centroid.lineEnd=function(){nextPoint(λ00,φ00);d3_geo_centroid.lineEnd=d3_geo_centroidLineEnd;d3_geo_centroid.point=d3_geo_centroidPoint};function nextPoint(λ,φ){λ*=d3_radians;var cosφ=Math.cos(φ*=d3_radians),x=cosφ*Math.cos(λ),y=cosφ*Math.sin(λ),z=Math.sin(φ),cx=y0*z-z0*y,cy=z0*x-x0*z,cz=x0*y-y0*x,m=Math.sqrt(cx*cx+cy*cy+cz*cz),u=x0*x+y0*y+z0*z,v=m&&-d3_acos(u)/m,w=Math.atan2(m,u);d3_geo_centroidX2+=v*cx;d3_geo_centroidY2+=v*cy;d3_geo_centroidZ2+=v*cz;d3_geo_centroidW1+=w;d3_geo_centroidX1+=w*(x0+(x0=x));d3_geo_centroidY1+=w*(y0+(y0=y));d3_geo_centroidZ1+=w*(z0+(z0=z));d3_geo_centroidPointXYZ(x0,y0,z0)}}function d3_true(){return true}function d3_geo_clipPolygon(segments,compare,clipStartInside,interpolate,listener){var subject=[],clip=[];segments.forEach(function(segment){if((n=segment.length-1)<=0)return;var n,p0=segment[0],p1=segment[n];if(d3_geo_sphericalEqual(p0,p1)){listener.lineStart();for(var i=0;i=0;--i)listener.point((point=points[i])[0],point[1])}else{interpolate(current.x,current.p.x,-1,listener)}current=current.p}current=current.o;points=current.z;isSubject=!isSubject}while(!current.v);listener.lineEnd()}}function d3_geo_clipPolygonLinkCircular(array){if(!(n=array.length))return;var n,i=0,a=array[0],b;while(++i0){if(!polygonStarted)listener.polygonStart(),polygonStarted=true;listener.lineStart();while(++i1&&clean&2)ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));segments.push(ringSegments.filter(d3_geo_clipSegmentLength1))}return clip}}function d3_geo_clipSegmentLength1(segment){return segment.length>1}function d3_geo_clipBufferListener(){var lines=[],line;return{lineStart:function(){lines.push(line=[])},point:function(λ,φ){line.push([λ,φ])},lineEnd:d3_noop,buffer:function(){var buffer=lines;lines=[];line=null;return buffer},rejoin:function(){if(lines.length>1)lines.push(lines.pop().concat(lines.shift()))}}}function d3_geo_clipSort(a,b){return((a=a.x)[0]<0?a[1]-halfπ-ε:halfπ-a[1])-((b=b.x)[0]<0?b[1]-halfπ-ε:halfπ-b[1])}function d3_geo_pointInPolygon(point,polygon){var meridian=point[0],parallel=point[1],meridianNormal=[Math.sin(meridian),-Math.cos(meridian),0],polarAngle=0,winding=0;d3_geo_areaRingSum.reset();for(var i=0,n=polygon.length;i=0?1:-1,adλ=sdλ*dλ,antimeridian=adλ>π,k=sinφ0*sinφ;d3_geo_areaRingSum.add(Math.atan2(k*sdλ*Math.sin(adλ),cosφ0*cosφ+k*Math.cos(adλ)));polarAngle+=antimeridian?dλ+sdλ*τ:dλ;if(antimeridian^λ0>=meridian^λ>=meridian){var arc=d3_geo_cartesianCross(d3_geo_cartesian(point0),d3_geo_cartesian(point));d3_geo_cartesianNormalize(arc);var intersection=d3_geo_cartesianCross(meridianNormal,arc);d3_geo_cartesianNormalize(intersection);var φarc=(antimeridian^dλ>=0?-1:1)*d3_asin(intersection[2]);if(parallel>φarc||parallel===φarc&&(arc[0]||arc[1])){winding+=antimeridian^dλ>=0?1:-1}}if(!j++)break;λ0=λ,sinφ0=sinφ,cosφ0=cosφ,point0=point}}return(polarAngle<-ε||polarAngle<ε&&d3_geo_areaRingSum<0)^winding&1}var d3_geo_clipAntimeridian=d3_geo_clip(d3_true,d3_geo_clipAntimeridianLine,d3_geo_clipAntimeridianInterpolate,[-π,-π/2]);function d3_geo_clipAntimeridianLine(listener){var λ0=NaN,φ0=NaN,sλ0=NaN,clean;return{lineStart:function(){listener.lineStart();clean=1},point:function(λ1,φ1){var sλ1=λ1>0?π:-π,dλ=abs(λ1-λ0);if(abs(dλ-π)<ε){listener.point(λ0,φ0=(φ0+φ1)/2>0?halfπ:-halfπ);listener.point(sλ0,φ0);listener.lineEnd();listener.lineStart();listener.point(sλ1,φ0);listener.point(λ1,φ0);clean=0}else if(sλ0!==sλ1&&dλ>=π){if(abs(λ0-sλ0)<ε)λ0-=sλ0*ε;if(abs(λ1-sλ1)<ε)λ1-=sλ1*ε;φ0=d3_geo_clipAntimeridianIntersect(λ0,φ0,λ1,φ1);listener.point(sλ0,φ0);listener.lineEnd();listener.lineStart();listener.point(sλ1,φ0);clean=0}listener.point(λ0=λ1,φ0=φ1);sλ0=sλ1},lineEnd:function(){listener.lineEnd();λ0=φ0=NaN},clean:function(){return 2-clean}}}function d3_geo_clipAntimeridianIntersect(λ0,φ0,λ1,φ1){var cosφ0,cosφ1,sinλ0_λ1=Math.sin(λ0-λ1);return abs(sinλ0_λ1)>ε?Math.atan((Math.sin(φ0)*(cosφ1=Math.cos(φ1))*Math.sin(λ1)-Math.sin(φ1)*(cosφ0=Math.cos(φ0))*Math.sin(λ0))/(cosφ0*cosφ1*sinλ0_λ1)):(φ0+φ1)/2}function d3_geo_clipAntimeridianInterpolate(from,to,direction,listener){var φ;if(from==null){φ=direction*halfπ;listener.point(-π,φ);listener.point(0,φ);listener.point(π,φ);listener.point(π,0);listener.point(π,-φ);listener.point(0,-φ);listener.point(-π,-φ);listener.point(-π,0);listener.point(-π,φ)}else if(abs(from[0]-to[0])>ε){var s=from[0]0,notHemisphere=abs(cr)>ε,interpolate=d3_geo_circleInterpolate(radius,6*d3_radians);return d3_geo_clip(visible,clipLine,interpolate,smallRadius?[0,-radius]:[-π,radius-π]);function visible(λ,φ){return Math.cos(λ)*Math.cos(φ)>cr}function clipLine(listener){var point0,c0,v0,v00,clean;return{lineStart:function(){v00=v0=false;clean=1},point:function(λ,φ){var point1=[λ,φ],point2,v=visible(λ,φ),c=smallRadius?v?0:code(λ,φ):v?code(λ+(λ<0?π:-π),φ):0;if(!point0&&(v00=v0=v))listener.lineStart();if(v!==v0){point2=intersect(point0,point1);if(d3_geo_sphericalEqual(point0,point2)||d3_geo_sphericalEqual(point1,point2)){point1[0]+=ε;point1[1]+=ε;v=visible(point1[0],point1[1])}}if(v!==v0){clean=0;if(v){listener.lineStart();point2=intersect(point1,point0);listener.point(point2[0],point2[1])}else{point2=intersect(point0,point1);listener.point(point2[0],point2[1]);listener.lineEnd()}point0=point2}else if(notHemisphere&&point0&&smallRadius^v){var t;if(!(c&c0)&&(t=intersect(point1,point0,true))){clean=0;if(smallRadius){listener.lineStart();listener.point(t[0][0],t[0][1]);listener.point(t[1][0],t[1][1]);listener.lineEnd()}else{listener.point(t[1][0],t[1][1]);listener.lineEnd();listener.lineStart();listener.point(t[0][0],t[0][1])}}}if(v&&(!point0||!d3_geo_sphericalEqual(point0,point1))){listener.point(point1[0],point1[1])}point0=point1,v0=v,c0=c},lineEnd:function(){if(v0)listener.lineEnd();point0=null},clean:function(){return clean|(v00&&v0)<<1}}}function intersect(a,b,two){var pa=d3_geo_cartesian(a),pb=d3_geo_cartesian(b);var n1=[1,0,0],n2=d3_geo_cartesianCross(pa,pb),n2n2=d3_geo_cartesianDot(n2,n2),n1n2=n2[0],determinant=n2n2-n1n2*n1n2;if(!determinant)return!two&&a;var c1=cr*n2n2/determinant,c2=-cr*n1n2/determinant,n1xn2=d3_geo_cartesianCross(n1,n2),A=d3_geo_cartesianScale(n1,c1),B=d3_geo_cartesianScale(n2,c2);d3_geo_cartesianAdd(A,B);var u=n1xn2,w=d3_geo_cartesianDot(A,u),uu=d3_geo_cartesianDot(u,u),t2=w*w-uu*(d3_geo_cartesianDot(A,A)-1);if(t2<0)return;var t=Math.sqrt(t2),q=d3_geo_cartesianScale(u,(-w-t)/uu);d3_geo_cartesianAdd(q,A);q=d3_geo_spherical(q);if(!two)return q;var λ0=a[0],λ1=b[0],φ0=a[1],φ1=b[1],z;if(λ1<λ0)z=λ0,λ0=λ1,λ1=z;var δλ=λ1-λ0,polar=abs(δλ-π)<ε,meridian=polar||δλ<ε;if(!polar&&φ1<φ0)z=φ0,φ0=φ1,φ1=z;if(meridian?polar?φ0+φ1>0^q[1]<(abs(q[0]-λ0)<ε?φ0:φ1):φ0<=q[1]&&q[1]<=φ1:δλ>π^(λ0<=q[0]&&q[0]<=λ1)){var q1=d3_geo_cartesianScale(u,(-w+t)/uu);d3_geo_cartesianAdd(q1,A);return[q,d3_geo_spherical(q1)]}}function code(λ,φ){var r=smallRadius?radius:π-radius,code=0;if(λ<-r)code|=1;else if(λ>r)code|=2;if(φ<-r)code|=4;else if(φ>r)code|=8;return code}}function d3_geom_clipLine(x0,y0,x1,y1){return function(line){var a=line.a,b=line.b,ax=a.x,ay=a.y,bx=b.x,by=b.y,t0=0,t1=1,dx=bx-ax,dy=by-ay,r;r=x0-ax;if(!dx&&r>0)return;r/=dx;if(dx<0){if(r0){if(r>t1)return;if(r>t0)t0=r}r=x1-ax;if(!dx&&r<0)return;r/=dx;if(dx<0){if(r>t1)return;if(r>t0)t0=r}else if(dx>0){if(r0)return;r/=dy;if(dy<0){if(r0){if(r>t1)return;if(r>t0)t0=r}r=y1-ay;if(!dy&&r<0)return;r/=dy;if(dy<0){if(r>t1)return;if(r>t0)t0=r}else if(dy>0){if(r0)line.a={x:ax+t0*dx,y:ay+t0*dy};if(t1<1)line.b={x:ax+t1*dx,y:ay+t1*dy};return line}}var d3_geo_clipExtentMAX=1e9;d3.geo.clipExtent=function(){var x0,y0,x1,y1,stream,clip,clipExtent={stream:function(output){if(stream)stream.valid=false;stream=clip(output);stream.valid=true;return stream},extent:function(_){if(!arguments.length)return[[x0,y0],[x1,y1]];clip=d3_geo_clipExtent(x0=+_[0][0],y0=+_[0][1],x1=+_[1][0],y1=+_[1][1]);if(stream)stream.valid=false,stream=null;return clipExtent}};return clipExtent.extent([[0,0],[960,500]])};function d3_geo_clipExtent(x0,y0,x1,y1){return function(listener){var listener_=listener,bufferListener=d3_geo_clipBufferListener(),clipLine=d3_geom_clipLine(x0,y0,x1,y1),segments,polygon,ring;var clip={point:point,lineStart:lineStart,lineEnd:lineEnd,polygonStart:function(){listener=bufferListener;segments=[];polygon=[];clean=true},polygonEnd:function(){listener=listener_;segments=d3.merge(segments);var clipStartInside=insidePolygon([x0,y1]),inside=clean&&clipStartInside,visible=segments.length;if(inside||visible){listener.polygonStart();if(inside){listener.lineStart();interpolate(null,null,1,listener);listener.lineEnd()}if(visible){d3_geo_clipPolygon(segments,compare,clipStartInside,interpolate,listener)}listener.polygonEnd()}segments=polygon=ring=null}};function insidePolygon(p){var wn=0,n=polygon.length,y=p[1];for(var i=0;iy&&d3_cross2d(a,b,p)>0)++wn}else{if(b[1]<=y&&d3_cross2d(a,b,p)<0)--wn}a=b}}return wn!==0}function interpolate(from,to,direction,listener){var a=0,a1=0;if(from==null||(a=corner(from,direction))!==(a1=corner(to,direction))||comparePoints(from,to)<0^direction>0){do{listener.point(a===0||a===3?x0:x1,a>1?y1:y0)}while((a=(a+direction+4)%4)!==a1)}else{listener.point(to[0],to[1])}}function pointVisible(x,y){return x0<=x&&x<=x1&&y0<=y&&y<=y1}function point(x,y){if(pointVisible(x,y))listener.point(x,y)}var x__,y__,v__,x_,y_,v_,first,clean;function lineStart(){clip.point=linePoint;if(polygon)polygon.push(ring=[]);first=true;v_=false;x_=y_=NaN}function lineEnd(){if(segments){linePoint(x__,y__);if(v__&&v_)bufferListener.rejoin();segments.push(bufferListener.buffer())}clip.point=point;if(v_)listener.lineEnd()}function linePoint(x,y){x=Math.max(-d3_geo_clipExtentMAX,Math.min(d3_geo_clipExtentMAX,x));y=Math.max(-d3_geo_clipExtentMAX,Math.min(d3_geo_clipExtentMAX,y));var v=pointVisible(x,y);if(polygon)ring.push([x,y]);if(first){x__=x,y__=y,v__=v;first=false;if(v){listener.lineStart();listener.point(x,y)}}else{if(v&&v_)listener.point(x,y);else{var l={a:{x:x_,y:y_},b:{x:x,y:y}};if(clipLine(l)){if(!v_){listener.lineStart();listener.point(l.a.x,l.a.y)}listener.point(l.b.x,l.b.y);if(!v)listener.lineEnd();clean=false}else if(v){listener.lineStart();listener.point(x,y);clean=false}}}x_=x,y_=y,v_=v}return clip};function corner(p,direction){return abs(p[0]-x0)<ε?direction>0?0:3:abs(p[0]-x1)<ε?direction>0?2:1:abs(p[1]-y0)<ε?direction>0?1:0:direction>0?3:2}function compare(a,b){return comparePoints(a.x,b.x)}function comparePoints(a,b){var ca=corner(a,1),cb=corner(b,1);return ca!==cb?ca-cb:ca===0?b[1]-a[1]:ca===1?a[0]-b[0]:ca===2?a[1]-b[1]:b[0]-a[0]}}function d3_geo_compose(a,b){function compose(x,y){return x=a(x,y),b(x[0],x[1])}if(a.invert&&b.invert)compose.invert=function(x,y){return x=b.invert(x,y),x&&a.invert(x[0],x[1])};return compose}function d3_geo_conic(projectAt){var φ0=0,φ1=π/3,m=d3_geo_projectionMutator(projectAt),p=m(φ0,φ1);p.parallels=function(_){if(!arguments.length)return[φ0/π*180,φ1/π*180];return m(φ0=_[0]*π/180,φ1=_[1]*π/180)};return p}function d3_geo_conicEqualArea(φ0,φ1){var sinφ0=Math.sin(φ0),n=(sinφ0+Math.sin(φ1))/2,C=1+sinφ0*(2*n-sinφ0),ρ0=Math.sqrt(C)/n;function forward(λ,φ){var ρ=Math.sqrt(C-2*n*Math.sin(φ))/n;return[ρ*Math.sin(λ*=n),ρ0-ρ*Math.cos(λ)]}forward.invert=function(x,y){var ρ0_y=ρ0-y;return[Math.atan2(x,ρ0_y)/n,d3_asin((C-(x*x+ρ0_y*ρ0_y)*n*n)/(2*n))]};return forward}(d3.geo.conicEqualArea=function(){return d3_geo_conic(d3_geo_conicEqualArea)}).raw=d3_geo_conicEqualArea;d3.geo.albers=function(){return d3.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)};d3.geo.albersUsa=function(){var lower48=d3.geo.albers();var alaska=d3.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]);var hawaii=d3.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]);var point,pointStream={point:function(x,y){point=[x,y]}},lower48Point,alaskaPoint,hawaiiPoint;function albersUsa(coordinates){var x=coordinates[0],y=coordinates[1];point=null;(lower48Point(x,y),point)||(alaskaPoint(x,y),point)||hawaiiPoint(x,y);return point}albersUsa.invert=function(coordinates){var k=lower48.scale(),t=lower48.translate(),x=(coordinates[0]-t[0])/k,y=(coordinates[1]-t[1])/k;return(y>=.12&&y<.234&&x>=-.425&&x<-.214?alaska:y>=.166&&y<.234&&x>=-.214&&x<-.115?hawaii:lower48).invert(coordinates)};albersUsa.stream=function(stream){var lower48Stream=lower48.stream(stream),alaskaStream=alaska.stream(stream),hawaiiStream=hawaii.stream(stream);return{point:function(x,y){lower48Stream.point(x,y);alaskaStream.point(x,y);hawaiiStream.point(x,y)},sphere:function(){lower48Stream.sphere();alaskaStream.sphere();hawaiiStream.sphere()},lineStart:function(){lower48Stream.lineStart();alaskaStream.lineStart();hawaiiStream.lineStart()},lineEnd:function(){lower48Stream.lineEnd();alaskaStream.lineEnd();hawaiiStream.lineEnd()},polygonStart:function(){lower48Stream.polygonStart(); -alaskaStream.polygonStart();hawaiiStream.polygonStart()},polygonEnd:function(){lower48Stream.polygonEnd();alaskaStream.polygonEnd();hawaiiStream.polygonEnd()}}};albersUsa.precision=function(_){if(!arguments.length)return lower48.precision();lower48.precision(_);alaska.precision(_);hawaii.precision(_);return albersUsa};albersUsa.scale=function(_){if(!arguments.length)return lower48.scale();lower48.scale(_);alaska.scale(_*.35);hawaii.scale(_);return albersUsa.translate(lower48.translate())};albersUsa.translate=function(_){if(!arguments.length)return lower48.translate();var k=lower48.scale(),x=+_[0],y=+_[1];lower48Point=lower48.translate(_).clipExtent([[x-.455*k,y-.238*k],[x+.455*k,y+.238*k]]).stream(pointStream).point;alaskaPoint=alaska.translate([x-.307*k,y+.201*k]).clipExtent([[x-.425*k+ε,y+.12*k+ε],[x-.214*k-ε,y+.234*k-ε]]).stream(pointStream).point;hawaiiPoint=hawaii.translate([x-.205*k,y+.212*k]).clipExtent([[x-.214*k+ε,y+.166*k+ε],[x-.115*k-ε,y+.234*k-ε]]).stream(pointStream).point;return albersUsa};return albersUsa.scale(1070)};var d3_geo_pathAreaSum,d3_geo_pathAreaPolygon,d3_geo_pathArea={point:d3_noop,lineStart:d3_noop,lineEnd:d3_noop,polygonStart:function(){d3_geo_pathAreaPolygon=0;d3_geo_pathArea.lineStart=d3_geo_pathAreaRingStart},polygonEnd:function(){d3_geo_pathArea.lineStart=d3_geo_pathArea.lineEnd=d3_geo_pathArea.point=d3_noop;d3_geo_pathAreaSum+=abs(d3_geo_pathAreaPolygon/2)}};function d3_geo_pathAreaRingStart(){var x00,y00,x0,y0;d3_geo_pathArea.point=function(x,y){d3_geo_pathArea.point=nextPoint;x00=x0=x,y00=y0=y};function nextPoint(x,y){d3_geo_pathAreaPolygon+=y0*x-x0*y;x0=x,y0=y}d3_geo_pathArea.lineEnd=function(){nextPoint(x00,y00)}}var d3_geo_pathBoundsX0,d3_geo_pathBoundsY0,d3_geo_pathBoundsX1,d3_geo_pathBoundsY1;var d3_geo_pathBounds={point:d3_geo_pathBoundsPoint,lineStart:d3_noop,lineEnd:d3_noop,polygonStart:d3_noop,polygonEnd:d3_noop};function d3_geo_pathBoundsPoint(x,y){if(xd3_geo_pathBoundsX1)d3_geo_pathBoundsX1=x;if(yd3_geo_pathBoundsY1)d3_geo_pathBoundsY1=y}function d3_geo_pathBuffer(){var pointCircle=d3_geo_pathBufferCircle(4.5),buffer=[];var stream={point:point,lineStart:function(){stream.point=pointLineStart},lineEnd:lineEnd,polygonStart:function(){stream.lineEnd=lineEndPolygon},polygonEnd:function(){stream.lineEnd=lineEnd;stream.point=point},pointRadius:function(_){pointCircle=d3_geo_pathBufferCircle(_);return stream},result:function(){if(buffer.length){var result=buffer.join("");buffer=[];return result}}};function point(x,y){buffer.push("M",x,",",y,pointCircle)}function pointLineStart(x,y){buffer.push("M",x,",",y);stream.point=pointLine}function pointLine(x,y){buffer.push("L",x,",",y)}function lineEnd(){stream.point=point}function lineEndPolygon(){buffer.push("Z")}return stream}function d3_geo_pathBufferCircle(radius){return"m0,"+radius+"a"+radius+","+radius+" 0 1,1 0,"+-2*radius+"a"+radius+","+radius+" 0 1,1 0,"+2*radius+"z"}var d3_geo_pathCentroid={point:d3_geo_pathCentroidPoint,lineStart:d3_geo_pathCentroidLineStart,lineEnd:d3_geo_pathCentroidLineEnd,polygonStart:function(){d3_geo_pathCentroid.lineStart=d3_geo_pathCentroidRingStart},polygonEnd:function(){d3_geo_pathCentroid.point=d3_geo_pathCentroidPoint;d3_geo_pathCentroid.lineStart=d3_geo_pathCentroidLineStart;d3_geo_pathCentroid.lineEnd=d3_geo_pathCentroidLineEnd}};function d3_geo_pathCentroidPoint(x,y){d3_geo_centroidX0+=x;d3_geo_centroidY0+=y;++d3_geo_centroidZ0}function d3_geo_pathCentroidLineStart(){var x0,y0;d3_geo_pathCentroid.point=function(x,y){d3_geo_pathCentroid.point=nextPoint;d3_geo_pathCentroidPoint(x0=x,y0=y)};function nextPoint(x,y){var dx=x-x0,dy=y-y0,z=Math.sqrt(dx*dx+dy*dy);d3_geo_centroidX1+=z*(x0+x)/2;d3_geo_centroidY1+=z*(y0+y)/2;d3_geo_centroidZ1+=z;d3_geo_pathCentroidPoint(x0=x,y0=y)}}function d3_geo_pathCentroidLineEnd(){d3_geo_pathCentroid.point=d3_geo_pathCentroidPoint}function d3_geo_pathCentroidRingStart(){var x00,y00,x0,y0;d3_geo_pathCentroid.point=function(x,y){d3_geo_pathCentroid.point=nextPoint;d3_geo_pathCentroidPoint(x00=x0=x,y00=y0=y)};function nextPoint(x,y){var dx=x-x0,dy=y-y0,z=Math.sqrt(dx*dx+dy*dy);d3_geo_centroidX1+=z*(x0+x)/2;d3_geo_centroidY1+=z*(y0+y)/2;d3_geo_centroidZ1+=z;z=y0*x-x0*y;d3_geo_centroidX2+=z*(x0+x);d3_geo_centroidY2+=z*(y0+y);d3_geo_centroidZ2+=z*3;d3_geo_pathCentroidPoint(x0=x,y0=y)}d3_geo_pathCentroid.lineEnd=function(){nextPoint(x00,y00)}}function d3_geo_pathContext(context){var pointRadius=4.5;var stream={point:point,lineStart:function(){stream.point=pointLineStart},lineEnd:lineEnd,polygonStart:function(){stream.lineEnd=lineEndPolygon},polygonEnd:function(){stream.lineEnd=lineEnd;stream.point=point},pointRadius:function(_){pointRadius=_;return stream},result:d3_noop};function point(x,y){context.moveTo(x,y);context.arc(x,y,pointRadius,0,τ)}function pointLineStart(x,y){context.moveTo(x,y);stream.point=pointLine}function pointLine(x,y){context.lineTo(x,y)}function lineEnd(){stream.point=point}function lineEndPolygon(){context.closePath()}return stream}function d3_geo_resample(project){var δ2=.5,cosMinDistance=Math.cos(30*d3_radians),maxDepth=16;function resample(stream){return(maxDepth?resampleRecursive:resampleNone)(stream)}function resampleNone(stream){return d3_geo_transformPoint(stream,function(x,y){x=project(x,y);stream.point(x[0],x[1])})}function resampleRecursive(stream){var λ00,φ00,x00,y00,a00,b00,c00,λ0,x0,y0,a0,b0,c0;var resample={point:point,lineStart:lineStart,lineEnd:lineEnd,polygonStart:function(){stream.polygonStart();resample.lineStart=ringStart},polygonEnd:function(){stream.polygonEnd();resample.lineStart=lineStart}};function point(x,y){x=project(x,y);stream.point(x[0],x[1])}function lineStart(){x0=NaN;resample.point=linePoint;stream.lineStart()}function linePoint(λ,φ){var c=d3_geo_cartesian([λ,φ]),p=project(λ,φ);resampleLineTo(x0,y0,λ0,a0,b0,c0,x0=p[0],y0=p[1],λ0=λ,a0=c[0],b0=c[1],c0=c[2],maxDepth,stream);stream.point(x0,y0)}function lineEnd(){resample.point=point;stream.lineEnd()}function ringStart(){lineStart();resample.point=ringPoint;resample.lineEnd=ringEnd}function ringPoint(λ,φ){linePoint(λ00=λ,φ00=φ),x00=x0,y00=y0,a00=a0,b00=b0,c00=c0;resample.point=linePoint}function ringEnd(){resampleLineTo(x0,y0,λ0,a0,b0,c0,x00,y00,λ00,a00,b00,c00,maxDepth,stream);resample.lineEnd=lineEnd;lineEnd()}return resample}function resampleLineTo(x0,y0,λ0,a0,b0,c0,x1,y1,λ1,a1,b1,c1,depth,stream){var dx=x1-x0,dy=y1-y0,d2=dx*dx+dy*dy;if(d2>4*δ2&&depth--){var a=a0+a1,b=b0+b1,c=c0+c1,m=Math.sqrt(a*a+b*b+c*c),φ2=Math.asin(c/=m),λ2=abs(abs(c)-1)<ε||abs(λ0-λ1)<ε?(λ0+λ1)/2:Math.atan2(b,a),p=project(λ2,φ2),x2=p[0],y2=p[1],dx2=x2-x0,dy2=y2-y0,dz=dy*dx2-dx*dy2;if(dz*dz/d2>δ2||abs((dx*dx2+dy*dy2)/d2-.5)>.3||a0*a1+b0*b1+c0*c10&&16;return resample};return resample}d3.geo.path=function(){var pointRadius=4.5,projection,context,projectStream,contextStream,cacheStream;function path(object){if(object){if(typeof pointRadius==="function")contextStream.pointRadius(+pointRadius.apply(this,arguments));if(!cacheStream||!cacheStream.valid)cacheStream=projectStream(contextStream);d3.geo.stream(object,cacheStream)}return contextStream.result()}path.area=function(object){d3_geo_pathAreaSum=0;d3.geo.stream(object,projectStream(d3_geo_pathArea));return d3_geo_pathAreaSum};path.centroid=function(object){d3_geo_centroidX0=d3_geo_centroidY0=d3_geo_centroidZ0=d3_geo_centroidX1=d3_geo_centroidY1=d3_geo_centroidZ1=d3_geo_centroidX2=d3_geo_centroidY2=d3_geo_centroidZ2=0;d3.geo.stream(object,projectStream(d3_geo_pathCentroid));return d3_geo_centroidZ2?[d3_geo_centroidX2/d3_geo_centroidZ2,d3_geo_centroidY2/d3_geo_centroidZ2]:d3_geo_centroidZ1?[d3_geo_centroidX1/d3_geo_centroidZ1,d3_geo_centroidY1/d3_geo_centroidZ1]:d3_geo_centroidZ0?[d3_geo_centroidX0/d3_geo_centroidZ0,d3_geo_centroidY0/d3_geo_centroidZ0]:[NaN,NaN]};path.bounds=function(object){d3_geo_pathBoundsX1=d3_geo_pathBoundsY1=-(d3_geo_pathBoundsX0=d3_geo_pathBoundsY0=Infinity);d3.geo.stream(object,projectStream(d3_geo_pathBounds));return[[d3_geo_pathBoundsX0,d3_geo_pathBoundsY0],[d3_geo_pathBoundsX1,d3_geo_pathBoundsY1]]};path.projection=function(_){if(!arguments.length)return projection;projectStream=(projection=_)?_.stream||d3_geo_pathProjectStream(_):d3_identity;return reset()};path.context=function(_){if(!arguments.length)return context;contextStream=(context=_)==null?new d3_geo_pathBuffer:new d3_geo_pathContext(_);if(typeof pointRadius!=="function")contextStream.pointRadius(pointRadius);return reset()};path.pointRadius=function(_){if(!arguments.length)return pointRadius;pointRadius=typeof _==="function"?_:(contextStream.pointRadius(+_),+_);return path};function reset(){cacheStream=null;return path}return path.projection(d3.geo.albersUsa()).context(null)};function d3_geo_pathProjectStream(project){var resample=d3_geo_resample(function(x,y){return project([x*d3_degrees,y*d3_degrees])});return function(stream){return d3_geo_projectionRadians(resample(stream))}}d3.geo.transform=function(methods){return{stream:function(stream){var transform=new d3_geo_transform(stream);for(var k in methods)transform[k]=methods[k];return transform}}};function d3_geo_transform(stream){this.stream=stream}d3_geo_transform.prototype={point:function(x,y){this.stream.point(x,y)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};function d3_geo_transformPoint(stream,point){return{point:point,sphere:function(){stream.sphere()},lineStart:function(){stream.lineStart()},lineEnd:function(){stream.lineEnd()},polygonStart:function(){stream.polygonStart()},polygonEnd:function(){stream.polygonEnd()}}}d3.geo.projection=d3_geo_projection;d3.geo.projectionMutator=d3_geo_projectionMutator;function d3_geo_projection(project){return d3_geo_projectionMutator(function(){return project})()}function d3_geo_projectionMutator(projectAt){var project,rotate,projectRotate,projectResample=d3_geo_resample(function(x,y){x=project(x,y);return[x[0]*k+δx,δy-x[1]*k]}),k=150,x=480,y=250,λ=0,φ=0,δλ=0,δφ=0,δγ=0,δx,δy,preclip=d3_geo_clipAntimeridian,postclip=d3_identity,clipAngle=null,clipExtent=null,stream;function projection(point){point=projectRotate(point[0]*d3_radians,point[1]*d3_radians);return[point[0]*k+δx,δy-point[1]*k]}function invert(point){point=projectRotate.invert((point[0]-δx)/k,(δy-point[1])/k);return point&&[point[0]*d3_degrees,point[1]*d3_degrees]}projection.stream=function(output){if(stream)stream.valid=false;stream=d3_geo_projectionRadians(preclip(rotate,projectResample(postclip(output))));stream.valid=true;return stream};projection.clipAngle=function(_){if(!arguments.length)return clipAngle;preclip=_==null?(clipAngle=_,d3_geo_clipAntimeridian):d3_geo_clipCircle((clipAngle=+_)*d3_radians);return invalidate()};projection.clipExtent=function(_){if(!arguments.length)return clipExtent;clipExtent=_;postclip=_?d3_geo_clipExtent(_[0][0],_[0][1],_[1][0],_[1][1]):d3_identity;return invalidate()};projection.scale=function(_){if(!arguments.length)return k;k=+_;return reset()};projection.translate=function(_){if(!arguments.length)return[x,y];x=+_[0];y=+_[1];return reset()};projection.center=function(_){if(!arguments.length)return[λ*d3_degrees,φ*d3_degrees];λ=_[0]%360*d3_radians;φ=_[1]%360*d3_radians;return reset()};projection.rotate=function(_){if(!arguments.length)return[δλ*d3_degrees,δφ*d3_degrees,δγ*d3_degrees];δλ=_[0]%360*d3_radians;δφ=_[1]%360*d3_radians;δγ=_.length>2?_[2]%360*d3_radians:0;return reset()};d3.rebind(projection,projectResample,"precision");function reset(){projectRotate=d3_geo_compose(rotate=d3_geo_rotation(δλ,δφ,δγ),project);var center=project(λ,φ);δx=x-center[0]*k;δy=y+center[1]*k;return invalidate()}function invalidate(){if(stream)stream.valid=false,stream=null;return projection}return function(){project=projectAt.apply(this,arguments);projection.invert=project.invert&&invert;return reset()}}function d3_geo_projectionRadians(stream){return d3_geo_transformPoint(stream,function(x,y){stream.point(x*d3_radians,y*d3_radians)})}function d3_geo_equirectangular(λ,φ){return[λ,φ]}(d3.geo.equirectangular=function(){return d3_geo_projection(d3_geo_equirectangular)}).raw=d3_geo_equirectangular.invert=d3_geo_equirectangular;d3.geo.rotation=function(rotate){rotate=d3_geo_rotation(rotate[0]%360*d3_radians,rotate[1]*d3_radians,rotate.length>2?rotate[2]*d3_radians:0);function forward(coordinates){coordinates=rotate(coordinates[0]*d3_radians,coordinates[1]*d3_radians);return coordinates[0]*=d3_degrees,coordinates[1]*=d3_degrees,coordinates}forward.invert=function(coordinates){coordinates=rotate.invert(coordinates[0]*d3_radians,coordinates[1]*d3_radians);return coordinates[0]*=d3_degrees,coordinates[1]*=d3_degrees,coordinates};return forward};function d3_geo_identityRotation(λ,φ){return[λ>π?λ-τ:λ<-π?λ+τ:λ,φ]}d3_geo_identityRotation.invert=d3_geo_equirectangular;function d3_geo_rotation(δλ,δφ,δγ){return δλ?δφ||δγ?d3_geo_compose(d3_geo_rotationλ(δλ),d3_geo_rotationφγ(δφ,δγ)):d3_geo_rotationλ(δλ):δφ||δγ?d3_geo_rotationφγ(δφ,δγ):d3_geo_identityRotation}function d3_geo_forwardRotationλ(δλ){return function(λ,φ){return λ+=δλ,[λ>π?λ-τ:λ<-π?λ+τ:λ,φ]}}function d3_geo_rotationλ(δλ){var rotation=d3_geo_forwardRotationλ(δλ);rotation.invert=d3_geo_forwardRotationλ(-δλ);return rotation}function d3_geo_rotationφγ(δφ,δγ){var cosδφ=Math.cos(δφ),sinδφ=Math.sin(δφ),cosδγ=Math.cos(δγ),sinδγ=Math.sin(δγ);function rotation(λ,φ){var cosφ=Math.cos(φ),x=Math.cos(λ)*cosφ,y=Math.sin(λ)*cosφ,z=Math.sin(φ),k=z*cosδφ+x*sinδφ;return[Math.atan2(y*cosδγ-k*sinδγ,x*cosδφ-z*sinδφ),d3_asin(k*cosδγ+y*sinδγ)]}rotation.invert=function(λ,φ){var cosφ=Math.cos(φ),x=Math.cos(λ)*cosφ,y=Math.sin(λ)*cosφ,z=Math.sin(φ),k=z*cosδγ-y*sinδγ;return[Math.atan2(y*cosδγ+z*sinδγ,x*cosδφ+k*sinδφ),d3_asin(k*cosδφ-x*sinδφ)]};return rotation}d3.geo.circle=function(){var origin=[0,0],angle,precision=6,interpolate;function circle(){var center=typeof origin==="function"?origin.apply(this,arguments):origin,rotate=d3_geo_rotation(-center[0]*d3_radians,-center[1]*d3_radians,0).invert,ring=[];interpolate(null,null,1,{point:function(x,y){ring.push(x=rotate(x,y));x[0]*=d3_degrees,x[1]*=d3_degrees}});return{type:"Polygon",coordinates:[ring]}}circle.origin=function(x){if(!arguments.length)return origin;origin=x;return circle};circle.angle=function(x){if(!arguments.length)return angle;interpolate=d3_geo_circleInterpolate((angle=+x)*d3_radians,precision*d3_radians);return circle};circle.precision=function(_){if(!arguments.length)return precision;interpolate=d3_geo_circleInterpolate(angle*d3_radians,(precision=+_)*d3_radians);return circle};return circle.angle(90)};function d3_geo_circleInterpolate(radius,precision){var cr=Math.cos(radius),sr=Math.sin(radius);return function(from,to,direction,listener){var step=direction*precision;if(from!=null){from=d3_geo_circleAngle(cr,from);to=d3_geo_circleAngle(cr,to);if(direction>0?fromto)from+=direction*τ}else{from=radius+direction*τ;to=radius-.5*step}for(var point,t=from;direction>0?t>to:tε}).map(x)).concat(d3.range(Math.ceil(y0/dy)*dy,y1,dy).filter(function(y){return abs(y%DY)>ε}).map(y))}graticule.lines=function(){return lines().map(function(coordinates){return{type:"LineString",coordinates:coordinates}})};graticule.outline=function(){return{type:"Polygon",coordinates:[X(X0).concat(Y(Y1).slice(1),X(X1).reverse().slice(1),Y(Y0).reverse().slice(1))]}};graticule.extent=function(_){if(!arguments.length)return graticule.minorExtent();return graticule.majorExtent(_).minorExtent(_)};graticule.majorExtent=function(_){if(!arguments.length)return[[X0,Y0],[X1,Y1]];X0=+_[0][0],X1=+_[1][0];Y0=+_[0][1],Y1=+_[1][1];if(X0>X1)_=X0,X0=X1,X1=_;if(Y0>Y1)_=Y0,Y0=Y1,Y1=_;return graticule.precision(precision)};graticule.minorExtent=function(_){if(!arguments.length)return[[x0,y0],[x1,y1]];x0=+_[0][0],x1=+_[1][0];y0=+_[0][1],y1=+_[1][1];if(x0>x1)_=x0,x0=x1,x1=_;if(y0>y1)_=y0,y0=y1,y1=_;return graticule.precision(precision)};graticule.step=function(_){if(!arguments.length)return graticule.minorStep();return graticule.majorStep(_).minorStep(_)};graticule.majorStep=function(_){if(!arguments.length)return[DX,DY];DX=+_[0],DY=+_[1];return graticule};graticule.minorStep=function(_){if(!arguments.length)return[dx,dy];dx=+_[0],dy=+_[1];return graticule};graticule.precision=function(_){if(!arguments.length)return precision;precision=+_;x=d3_geo_graticuleX(y0,y1,90);y=d3_geo_graticuleY(x0,x1,precision);X=d3_geo_graticuleX(Y0,Y1,90);Y=d3_geo_graticuleY(X0,X1,precision);return graticule};return graticule.majorExtent([[-180,-90+ε],[180,90-ε]]).minorExtent([[-180,-80-ε],[180,80+ε]])};function d3_geo_graticuleX(y0,y1,dy){var y=d3.range(y0,y1-ε,dy).concat(y1);return function(x){return y.map(function(y){return[x,y]})}}function d3_geo_graticuleY(x0,x1,dx){var x=d3.range(x0,x1-ε,dx).concat(x1);return function(y){return x.map(function(x){return[x,y]})}}function d3_source(d){return d.source}function d3_target(d){return d.target}d3.geo.greatArc=function(){var source=d3_source,source_,target=d3_target,target_;function greatArc(){return{type:"LineString",coordinates:[source_||source.apply(this,arguments),target_||target.apply(this,arguments)]}}greatArc.distance=function(){return d3.geo.distance(source_||source.apply(this,arguments),target_||target.apply(this,arguments))};greatArc.source=function(_){if(!arguments.length)return source;source=_,source_=typeof _==="function"?null:_;return greatArc};greatArc.target=function(_){if(!arguments.length)return target;target=_,target_=typeof _==="function"?null:_;return greatArc};greatArc.precision=function(){return arguments.length?greatArc:0};return greatArc};d3.geo.interpolate=function(source,target){return d3_geo_interpolate(source[0]*d3_radians,source[1]*d3_radians,target[0]*d3_radians,target[1]*d3_radians)};function d3_geo_interpolate(x0,y0,x1,y1){var cy0=Math.cos(y0),sy0=Math.sin(y0),cy1=Math.cos(y1),sy1=Math.sin(y1),kx0=cy0*Math.cos(x0),ky0=cy0*Math.sin(x0),kx1=cy1*Math.cos(x1),ky1=cy1*Math.sin(x1),d=2*Math.asin(Math.sqrt(d3_haversin(y1-y0)+cy0*cy1*d3_haversin(x1-x0))),k=1/Math.sin(d);var interpolate=d?function(t){var B=Math.sin(t*=d)*k,A=Math.sin(d-t)*k,x=A*kx0+B*kx1,y=A*ky0+B*ky1,z=A*sy0+B*sy1;return[Math.atan2(y,x)*d3_degrees,Math.atan2(z,Math.sqrt(x*x+y*y))*d3_degrees]}:function(){return[x0*d3_degrees,y0*d3_degrees]};interpolate.distance=d;return interpolate}d3.geo.length=function(object){d3_geo_lengthSum=0;d3.geo.stream(object,d3_geo_length);return d3_geo_lengthSum};var d3_geo_lengthSum;var d3_geo_length={sphere:d3_noop,point:d3_noop,lineStart:d3_geo_lengthLineStart,lineEnd:d3_noop,polygonStart:d3_noop,polygonEnd:d3_noop};function d3_geo_lengthLineStart(){var λ0,sinφ0,cosφ0;d3_geo_length.point=function(λ,φ){λ0=λ*d3_radians,sinφ0=Math.sin(φ*=d3_radians),cosφ0=Math.cos(φ);d3_geo_length.point=nextPoint};d3_geo_length.lineEnd=function(){d3_geo_length.point=d3_geo_length.lineEnd=d3_noop};function nextPoint(λ,φ){var sinφ=Math.sin(φ*=d3_radians),cosφ=Math.cos(φ),t=abs((λ*=d3_radians)-λ0),cosΔλ=Math.cos(t);d3_geo_lengthSum+=Math.atan2(Math.sqrt((t=cosφ*Math.sin(t))*t+(t=cosφ0*sinφ-sinφ0*cosφ*cosΔλ)*t),sinφ0*sinφ+cosφ0*cosφ*cosΔλ);λ0=λ,sinφ0=sinφ,cosφ0=cosφ}}function d3_geo_azimuthal(scale,angle){function azimuthal(λ,φ){var cosλ=Math.cos(λ),cosφ=Math.cos(φ),k=scale(cosλ*cosφ);return[k*cosφ*Math.sin(λ),k*Math.sin(φ)]}azimuthal.invert=function(x,y){var ρ=Math.sqrt(x*x+y*y),c=angle(ρ),sinc=Math.sin(c),cosc=Math.cos(c);return[Math.atan2(x*sinc,ρ*cosc),Math.asin(ρ&&y*sinc/ρ)]};return azimuthal}var d3_geo_azimuthalEqualArea=d3_geo_azimuthal(function(cosλcosφ){return Math.sqrt(2/(1+cosλcosφ))},function(ρ){return 2*Math.asin(ρ/2)});(d3.geo.azimuthalEqualArea=function(){return d3_geo_projection(d3_geo_azimuthalEqualArea)}).raw=d3_geo_azimuthalEqualArea;var d3_geo_azimuthalEquidistant=d3_geo_azimuthal(function(cosλcosφ){var c=Math.acos(cosλcosφ);return c&&c/Math.sin(c)},d3_identity);(d3.geo.azimuthalEquidistant=function(){return d3_geo_projection(d3_geo_azimuthalEquidistant)}).raw=d3_geo_azimuthalEquidistant;function d3_geo_conicConformal(φ0,φ1){var cosφ0=Math.cos(φ0),t=function(φ){return Math.tan(π/4+φ/2)},n=φ0===φ1?Math.sin(φ0):Math.log(cosφ0/Math.cos(φ1))/Math.log(t(φ1)/t(φ0)),F=cosφ0*Math.pow(t(φ0),n)/n;if(!n)return d3_geo_mercator;function forward(λ,φ){if(F>0){if(φ<-halfπ+ε)φ=-halfπ+ε}else{if(φ>halfπ-ε)φ=halfπ-ε}var ρ=F/Math.pow(t(φ),n);return[ρ*Math.sin(n*λ),F-ρ*Math.cos(n*λ)]}forward.invert=function(x,y){var ρ0_y=F-y,ρ=d3_sgn(n)*Math.sqrt(x*x+ρ0_y*ρ0_y);return[Math.atan2(x,ρ0_y)/n,2*Math.atan(Math.pow(F/ρ,1/n))-halfπ]};return forward}(d3.geo.conicConformal=function(){return d3_geo_conic(d3_geo_conicConformal)}).raw=d3_geo_conicConformal;function d3_geo_conicEquidistant(φ0,φ1){var cosφ0=Math.cos(φ0),n=φ0===φ1?Math.sin(φ0):(cosφ0-Math.cos(φ1))/(φ1-φ0),G=cosφ0/n+φ0;if(abs(n)<ε)return d3_geo_equirectangular;function forward(λ,φ){var ρ=G-φ;return[ρ*Math.sin(n*λ),G-ρ*Math.cos(n*λ)]}forward.invert=function(x,y){var ρ0_y=G-y;return[Math.atan2(x,ρ0_y)/n,G-d3_sgn(n)*Math.sqrt(x*x+ρ0_y*ρ0_y)]};return forward}(d3.geo.conicEquidistant=function(){return d3_geo_conic(d3_geo_conicEquidistant)}).raw=d3_geo_conicEquidistant;var d3_geo_gnomonic=d3_geo_azimuthal(function(cosλcosφ){return 1/cosλcosφ},Math.atan);(d3.geo.gnomonic=function(){return d3_geo_projection(d3_geo_gnomonic)}).raw=d3_geo_gnomonic;function d3_geo_mercator(λ,φ){return[λ,Math.log(Math.tan(π/4+φ/2))]}d3_geo_mercator.invert=function(x,y){return[x,2*Math.atan(Math.exp(y))-halfπ]};function d3_geo_mercatorProjection(project){var m=d3_geo_projection(project),scale=m.scale,translate=m.translate,clipExtent=m.clipExtent,clipAuto;m.scale=function(){var v=scale.apply(m,arguments);return v===m?clipAuto?m.clipExtent(null):m:v};m.translate=function(){var v=translate.apply(m,arguments);return v===m?clipAuto?m.clipExtent(null):m:v};m.clipExtent=function(_){var v=clipExtent.apply(m,arguments);if(v===m){if(clipAuto=_==null){var k=π*scale(),t=translate();clipExtent([[t[0]-k,t[1]-k],[t[0]+k,t[1]+k]])}}else if(clipAuto){v=null}return v};return m.clipExtent(null)}(d3.geo.mercator=function(){return d3_geo_mercatorProjection(d3_geo_mercator)}).raw=d3_geo_mercator;var d3_geo_orthographic=d3_geo_azimuthal(function(){return 1},Math.asin);(d3.geo.orthographic=function(){return d3_geo_projection(d3_geo_orthographic)}).raw=d3_geo_orthographic;var d3_geo_stereographic=d3_geo_azimuthal(function(cosλcosφ){return 1/(1+cosλcosφ)},function(ρ){return 2*Math.atan(ρ)});(d3.geo.stereographic=function(){return d3_geo_projection(d3_geo_stereographic)}).raw=d3_geo_stereographic;function d3_geo_transverseMercator(λ,φ){return[Math.log(Math.tan(π/4+φ/2)),-λ]}d3_geo_transverseMercator.invert=function(x,y){return[-y,2*Math.atan(Math.exp(x))-halfπ]};(d3.geo.transverseMercator=function(){var projection=d3_geo_mercatorProjection(d3_geo_transverseMercator),center=projection.center,rotate=projection.rotate;projection.center=function(_){return _?center([-_[1],_[0]]):(_=center(),[-_[1],_[0]])};projection.rotate=function(_){return _?rotate([_[0],_[1],_.length>2?_[2]+90:90]):(_=rotate(),[_[0],_[1],_[2]-90])};return projection.rotate([0,0])}).raw=d3_geo_transverseMercator;d3.geom={};function d3_geom_pointX(d){return d[0]}function d3_geom_pointY(d){return d[1]}d3.geom.hull=function(vertices){var x=d3_geom_pointX,y=d3_geom_pointY;if(arguments.length)return hull(vertices);function hull(data){if(data.length<3)return[];var fx=d3_functor(x),fy=d3_functor(y),i,n=data.length,points=[],flippedPoints=[];for(i=0;i=0;--i)polygon.push(data[points[upper[i]][2]]);for(i=+skipLeft;i1&&d3_cross2d(points[hull[hs-2]],points[hull[hs-1]],points[i])<=0)--hs;hull[hs++]=i}return hull.slice(0,hs)}function d3_geom_hullOrder(a,b){return a[0]-b[0]||a[1]-b[1]}d3.geom.polygon=function(coordinates){d3_subclass(coordinates,d3_geom_polygonPrototype);return coordinates};var d3_geom_polygonPrototype=d3.geom.polygon.prototype=[];d3_geom_polygonPrototype.area=function(){var i=-1,n=this.length,a,b=this[n-1],area=0;while(++iε)node=node.L;else{dxr=x-d3_geom_voronoiRightBreakPoint(node,directrix);if(dxr>ε){if(!node.R){lArc=node;break}node=node.R}else{if(dxl>-ε){lArc=node.P;rArc=node}else if(dxr>-ε){lArc=node;rArc=node.N}else{lArc=rArc=node}break}}}var newArc=d3_geom_voronoiCreateBeach(site);d3_geom_voronoiBeaches.insert(lArc,newArc);if(!lArc&&!rArc)return;if(lArc===rArc){d3_geom_voronoiDetachCircle(lArc);rArc=d3_geom_voronoiCreateBeach(lArc.site);d3_geom_voronoiBeaches.insert(newArc,rArc);newArc.edge=rArc.edge=d3_geom_voronoiCreateEdge(lArc.site,newArc.site);d3_geom_voronoiAttachCircle(lArc);d3_geom_voronoiAttachCircle(rArc);return}if(!rArc){newArc.edge=d3_geom_voronoiCreateEdge(lArc.site,newArc.site);return}d3_geom_voronoiDetachCircle(lArc);d3_geom_voronoiDetachCircle(rArc);var lSite=lArc.site,ax=lSite.x,ay=lSite.y,bx=site.x-ax,by=site.y-ay,rSite=rArc.site,cx=rSite.x-ax,cy=rSite.y-ay,d=2*(bx*cy-by*cx),hb=bx*bx+by*by,hc=cx*cx+cy*cy,vertex={x:(cy*hb-by*hc)/d+ax,y:(bx*hc-cx*hb)/d+ay};d3_geom_voronoiSetEdgeEnd(rArc.edge,lSite,rSite,vertex);newArc.edge=d3_geom_voronoiCreateEdge(lSite,site,null,vertex);rArc.edge=d3_geom_voronoiCreateEdge(site,rSite,null,vertex);d3_geom_voronoiAttachCircle(lArc);d3_geom_voronoiAttachCircle(rArc)}function d3_geom_voronoiLeftBreakPoint(arc,directrix){var site=arc.site,rfocx=site.x,rfocy=site.y,pby2=rfocy-directrix;if(!pby2)return rfocx;var lArc=arc.P;if(!lArc)return-Infinity;site=lArc.site;var lfocx=site.x,lfocy=site.y,plby2=lfocy-directrix;if(!plby2)return lfocx;var hl=lfocx-rfocx,aby2=1/pby2-1/plby2,b=hl/plby2;if(aby2)return(-b+Math.sqrt(b*b-2*aby2*(hl*hl/(-2*plby2)-lfocy+plby2/2+rfocy-pby2/2)))/aby2+rfocx;return(rfocx+lfocx)/2}function d3_geom_voronoiRightBreakPoint(arc,directrix){var rArc=arc.N;if(rArc)return d3_geom_voronoiLeftBreakPoint(rArc,directrix);var site=arc.site;return site.y===directrix?site.x:Infinity}function d3_geom_voronoiCell(site){this.site=site;this.edges=[]}d3_geom_voronoiCell.prototype.prepare=function(){var halfEdges=this.edges,iHalfEdge=halfEdges.length,edge;while(iHalfEdge--){edge=halfEdges[iHalfEdge].edge;if(!edge.b||!edge.a)halfEdges.splice(iHalfEdge,1)}halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);return halfEdges.length};function d3_geom_voronoiCloseCells(extent){var x0=extent[0][0],x1=extent[1][0],y0=extent[0][1],y1=extent[1][1],x2,y2,x3,y3,cells=d3_geom_voronoiCells,iCell=cells.length,cell,iHalfEdge,halfEdges,nHalfEdges,start,end;while(iCell--){cell=cells[iCell];if(!cell||!cell.prepare())continue;halfEdges=cell.edges;nHalfEdges=halfEdges.length;iHalfEdge=0;while(iHalfEdgeε||abs(y3-y2)>ε){halfEdges.splice(iHalfEdge,0,new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site,end,abs(x3-x0)<ε&&y1-y3>ε?{x:x0,y:abs(x2-x0)<ε?y2:y1}:abs(y3-y1)<ε&&x1-x3>ε?{x:abs(y2-y1)<ε?x2:x1,y:y1}:abs(x3-x1)<ε&&y3-y0>ε?{x:x1,y:abs(x2-x1)<ε?y2:y0}:abs(y3-y0)<ε&&x3-x0>ε?{x:abs(y2-y0)<ε?x2:x0,y:y0}:null),cell.site,null)); -++nHalfEdges}}}}function d3_geom_voronoiHalfEdgeOrder(a,b){return b.angle-a.angle}function d3_geom_voronoiCircle(){d3_geom_voronoiRedBlackNode(this);this.x=this.y=this.arc=this.site=this.cy=null}function d3_geom_voronoiAttachCircle(arc){var lArc=arc.P,rArc=arc.N;if(!lArc||!rArc)return;var lSite=lArc.site,cSite=arc.site,rSite=rArc.site;if(lSite===rSite)return;var bx=cSite.x,by=cSite.y,ax=lSite.x-bx,ay=lSite.y-by,cx=rSite.x-bx,cy=rSite.y-by;var d=2*(ax*cy-ay*cx);if(d>=-ε2)return;var ha=ax*ax+ay*ay,hc=cx*cx+cy*cy,x=(cy*ha-ay*hc)/d,y=(ax*hc-cx*ha)/d,cy=y+by;var circle=d3_geom_voronoiCirclePool.pop()||new d3_geom_voronoiCircle;circle.arc=arc;circle.site=cSite;circle.x=x+bx;circle.y=cy+Math.sqrt(x*x+y*y);circle.cy=cy;arc.circle=circle;var before=null,node=d3_geom_voronoiCircles._;while(node){if(circle.y=x1)return;if(lx>rx){if(!va)va={x:fx,y:y0};else if(va.y>=y1)return;vb={x:fx,y:y1}}else{if(!va)va={x:fx,y:y1};else if(va.y1){if(lx>rx){if(!va)va={x:(y0-fb)/fm,y:y0};else if(va.y>=y1)return;vb={x:(y1-fb)/fm,y:y1}}else{if(!va)va={x:(y1-fb)/fm,y:y1};else if(va.y=x1)return;vb={x:x1,y:fm*x1+fb}}else{if(!va)va={x:x1,y:fm*x1+fb};else if(va.x=x0&&site.x<=x1&&site.y>=y0&&site.y<=y1?[[x0,y1],[x1,y1],[x1,y0],[x0,y0]]:[];polygon.point=data[i]});return polygons}function sites(data){return data.map(function(d,i){return{x:Math.round(fx(d,i)/ε)*ε,y:Math.round(fy(d,i)/ε)*ε,i:i}})}voronoi.links=function(data){return d3_geom_voronoi(sites(data)).edges.filter(function(edge){return edge.l&&edge.r}).map(function(edge){return{source:data[edge.l.i],target:data[edge.r.i]}})};voronoi.triangles=function(data){var triangles=[];d3_geom_voronoi(sites(data)).cells.forEach(function(cell,i){var site=cell.site,edges=cell.edges.sort(d3_geom_voronoiHalfEdgeOrder),j=-1,m=edges.length,e0,s0,e1=edges[m-1].edge,s1=e1.l===site?e1.r:e1.l;while(++jx2_)x2_=d.x;if(d.y>y2_)y2_=d.y;xs.push(d.x);ys.push(d.y)}else for(i=0;ix2_)x2_=x_;if(y_>y2_)y2_=y_;xs.push(x_);ys.push(y_)}}var dx=x2_-x1_,dy=y2_-y1_;if(dx>dy)y2_=y1_+dx;else x2_=x1_+dy;function insert(n,d,x,y,x1,y1,x2,y2){if(isNaN(x)||isNaN(y))return;if(n.leaf){var nx=n.x,ny=n.y;if(nx!=null){if(abs(nx-x)+abs(ny-y)<.01){insertChild(n,d,x,y,x1,y1,x2,y2)}else{var nPoint=n.point;n.x=n.y=n.point=null;insertChild(n,nPoint,nx,ny,x1,y1,x2,y2);insertChild(n,d,x,y,x1,y1,x2,y2)}}else{n.x=x,n.y=y,n.point=d}}else{insertChild(n,d,x,y,x1,y1,x2,y2)}}function insertChild(n,d,x,y,x1,y1,x2,y2){var sx=(x1+x2)*.5,sy=(y1+y2)*.5,right=x>=sx,bottom=y>=sy,i=(bottom<<1)+right;n.leaf=false;n=n.nodes[i]||(n.nodes[i]=d3_geom_quadtreeNode());if(right)x1=sx;else x2=sx;if(bottom)y1=sy;else y2=sy;insert(n,d,x,y,x1,y1,x2,y2)}var root=d3_geom_quadtreeNode();root.add=function(d){insert(root,d,+fx(d,++i),+fy(d,i),x1_,y1_,x2_,y2_)};root.visit=function(f){d3_geom_quadtreeVisit(f,root,x1_,y1_,x2_,y2_)};i=-1;if(x1==null){while(++ibi){bs=b.substring(bi,bs);if(s[i])s[i]+=bs;else s[++i]=bs}if((am=am[0])===(bm=bm[0])){if(s[i])s[i]+=bm;else s[++i]=bm}else{s[++i]=null;q.push({i:i,x:d3_interpolateNumber(am,bm)})}bi=d3_interpolate_numberB.lastIndex}if(bi=0&&!(f=d3.interpolators[i](a,b)));return f}d3.interpolators=[function(a,b){var t=typeof b;return(t==="string"?d3_rgb_names.has(b)||/^(#|rgb\(|hsl\()/.test(b)?d3_interpolateRgb:d3_interpolateString:b instanceof d3_Color?d3_interpolateRgb:Array.isArray(b)?d3_interpolateArray:t==="object"&&isNaN(b)?d3_interpolateObject:d3_interpolateNumber)(a,b)}];d3.interpolateArray=d3_interpolateArray;function d3_interpolateArray(a,b){var x=[],c=[],na=a.length,nb=b.length,n0=Math.min(a.length,b.length),i;for(i=0;i=0?name.substring(0,i):name,m=i>=0?name.substring(i+1):"in";t=d3_ease.get(t)||d3_ease_default;m=d3_ease_mode.get(m)||d3_identity;return d3_ease_clamp(m(t.apply(null,d3_arraySlice.call(arguments,1))))};function d3_ease_clamp(f){return function(t){return t<=0?0:t>=1?1:f(t)}}function d3_ease_reverse(f){return function(t){return 1-f(1-t)}}function d3_ease_reflect(f){return function(t){return.5*(t<.5?f(2*t):2-f(2-2*t))}}function d3_ease_quad(t){return t*t}function d3_ease_cubic(t){return t*t*t}function d3_ease_cubicInOut(t){if(t<=0)return 0;if(t>=1)return 1;var t2=t*t,t3=t2*t;return 4*(t<.5?t3:3*(t-t2)+t3-.75)}function d3_ease_poly(e){return function(t){return Math.pow(t,e)}}function d3_ease_sin(t){return 1-Math.cos(t*halfπ)}function d3_ease_exp(t){return Math.pow(2,10*(t-1))}function d3_ease_circle(t){return 1-Math.sqrt(1-t*t)}function d3_ease_elastic(a,p){var s;if(arguments.length<2)p=.45;if(arguments.length)s=p/τ*Math.asin(1/a);else a=1,s=p/4;return function(t){return 1+a*Math.pow(2,-10*t)*Math.sin((t-s)*τ/p)}}function d3_ease_back(s){if(!s)s=1.70158;return function(t){return t*t*((s+1)*t-s)}}function d3_ease_bounce(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}d3.interpolateHcl=d3_interpolateHcl;function d3_interpolateHcl(a,b){a=d3.hcl(a);b=d3.hcl(b);var ah=a.h,ac=a.c,al=a.l,bh=b.h-ah,bc=b.c-ac,bl=b.l-al;if(isNaN(bc))bc=0,ac=isNaN(ac)?b.c:ac;if(isNaN(bh))bh=0,ah=isNaN(ah)?b.h:ah;else if(bh>180)bh-=360;else if(bh<-180)bh+=360;return function(t){return d3_hcl_lab(ah+bh*t,ac+bc*t,al+bl*t)+""}}d3.interpolateHsl=d3_interpolateHsl;function d3_interpolateHsl(a,b){a=d3.hsl(a);b=d3.hsl(b);var ah=a.h,as=a.s,al=a.l,bh=b.h-ah,bs=b.s-as,bl=b.l-al;if(isNaN(bs))bs=0,as=isNaN(as)?b.s:as;if(isNaN(bh))bh=0,ah=isNaN(ah)?b.h:ah;else if(bh>180)bh-=360;else if(bh<-180)bh+=360;return function(t){return d3_hsl_rgb(ah+bh*t,as+bs*t,al+bl*t)+""}}d3.interpolateLab=d3_interpolateLab;function d3_interpolateLab(a,b){a=d3.lab(a);b=d3.lab(b);var al=a.l,aa=a.a,ab=a.b,bl=b.l-al,ba=b.a-aa,bb=b.b-ab;return function(t){return d3_lab_rgb(al+bl*t,aa+ba*t,ab+bb*t)+""}}d3.interpolateRound=d3_interpolateRound;function d3_interpolateRound(a,b){b-=a;return function(t){return Math.round(a+b*t)}}d3.transform=function(string){var g=d3_document.createElementNS(d3.ns.prefix.svg,"g");return(d3.transform=function(string){if(string!=null){g.setAttribute("transform",string);var t=g.transform.baseVal.consolidate()}return new d3_transform(t?t.matrix:d3_transformIdentity)})(string)};function d3_transform(m){var r0=[m.a,m.b],r1=[m.c,m.d],kx=d3_transformNormalize(r0),kz=d3_transformDot(r0,r1),ky=d3_transformNormalize(d3_transformCombine(r1,r0,-kz))||0;if(r0[0]*r1[1]180)rb+=360;else if(rb-ra>180)ra+=360;q.push({i:s.push(s.pop()+"rotate(",null,")")-2,x:d3_interpolateNumber(ra,rb)})}else if(rb){s.push(s.pop()+"rotate("+rb+")")}if(wa!=wb){q.push({i:s.push(s.pop()+"skewX(",null,")")-2,x:d3_interpolateNumber(wa,wb)})}else if(wb){s.push(s.pop()+"skewX("+wb+")")}if(ka[0]!=kb[0]||ka[1]!=kb[1]){n=s.push(s.pop()+"scale(",null,",",null,")");q.push({i:n-4,x:d3_interpolateNumber(ka[0],kb[0])},{i:n-2,x:d3_interpolateNumber(ka[1],kb[1])})}else if(kb[0]!=1||kb[1]!=1){s.push(s.pop()+"scale("+kb+")")}n=q.length;return function(t){var i=-1,o;while(++i0)alpha=x;else alpha=0}else if(x>0){event.start({type:"start",alpha:alpha=x});d3.timer(force.tick)}return force};force.start=function(){var i,n=nodes.length,m=links.length,w=size[0],h=size[1],neighbors,o;for(i=0;i=0){stack.push(child=childs[n]);child.parent=node;child.depth=node.depth+1}if(value)node.value=0;node.children=childs}else{if(value)node.value=+value.call(hierarchy,node,node.depth)||0;delete node.children}}d3_layout_hierarchyVisitAfter(root,function(node){var childs,parent;if(sort&&(childs=node.children))childs.sort(sort);if(value&&(parent=node.parent))parent.value+=node.value});return nodes}hierarchy.sort=function(x){if(!arguments.length)return sort;sort=x;return hierarchy};hierarchy.children=function(x){if(!arguments.length)return children;children=x;return hierarchy};hierarchy.value=function(x){if(!arguments.length)return value;value=x;return hierarchy};hierarchy.revalue=function(root){if(value){d3_layout_hierarchyVisitBefore(root,function(node){if(node.children)node.value=0});d3_layout_hierarchyVisitAfter(root,function(node){var parent;if(!node.children)node.value=+value.call(hierarchy,node,node.depth)||0;if(parent=node.parent)parent.value+=node.value})}return root};return hierarchy};function d3_layout_hierarchyRebind(object,hierarchy){d3.rebind(object,hierarchy,"sort","children","value");object.nodes=object;object.links=d3_layout_hierarchyLinks;return object}function d3_layout_hierarchyVisitBefore(node,callback){var nodes=[node];while((node=nodes.pop())!=null){callback(node);if((children=node.children)&&(n=children.length)){var n,children;while(--n>=0)nodes.push(children[n])}}}function d3_layout_hierarchyVisitAfter(node,callback){var nodes=[node],nodes2=[];while((node=nodes.pop())!=null){nodes2.push(node);if((children=node.children)&&(n=children.length)){var i=-1,n,children;while(++imax)max=o;sums.push(o)}for(j=0;jv){j=i;v=k}}return j}function d3_layout_stackReduceSum(d){return d.reduce(d3_layout_stackSum,0)}function d3_layout_stackSum(p,d){return p+d[1]}d3.layout.histogram=function(){var frequency=true,valuer=Number,ranger=d3_layout_histogramRange,binner=d3_layout_histogramBinSturges;function histogram(data,i){var bins=[],values=data.map(valuer,this),range=ranger.call(this,values,i),thresholds=binner.call(this,range,values,i),bin,i=-1,n=values.length,m=thresholds.length-1,k=frequency?1:1/n,x;while(++i0){i=-1;while(++i=range[0]&&x<=range[1]){bin=bins[d3.bisect(thresholds,x,1,m)-1];bin.y+=k;bin.push(data[i])}}}return bins}histogram.value=function(x){if(!arguments.length)return valuer;valuer=x;return histogram};histogram.range=function(x){if(!arguments.length)return ranger;ranger=d3_functor(x);return histogram};histogram.bins=function(x){if(!arguments.length)return binner;binner=typeof x==="number"?function(range){return d3_layout_histogramBinFixed(range,x)}:d3_functor(x);return histogram};histogram.frequency=function(x){if(!arguments.length)return frequency;frequency=!!x;return histogram};return histogram};function d3_layout_histogramBinSturges(range,values){return d3_layout_histogramBinFixed(range,Math.ceil(Math.log(values.length)/Math.LN2+1))}function d3_layout_histogramBinFixed(range,n){var x=-1,b=+range[0],m=(range[1]-b)/n,f=[];while(++x<=n)f[x]=m*x+b;return f}function d3_layout_histogramRange(values){return[d3.min(values),d3.max(values)]}d3.layout.pack=function(){var hierarchy=d3.layout.hierarchy().sort(d3_layout_packSort),padding=0,size=[1,1],radius;function pack(d,i){var nodes=hierarchy.call(this,d,i),root=nodes[0],w=size[0],h=size[1],r=radius==null?Math.sqrt:typeof radius==="function"?radius:function(){return radius};root.x=root.y=0;d3_layout_hierarchyVisitAfter(root,function(d){d.r=+r(d.value)});d3_layout_hierarchyVisitAfter(root,d3_layout_packSiblings);if(padding){var dr=padding*(radius?1:Math.max(2*root.r/w,2*root.r/h))/2;d3_layout_hierarchyVisitAfter(root,function(d){d.r+=dr});d3_layout_hierarchyVisitAfter(root,d3_layout_packSiblings);d3_layout_hierarchyVisitAfter(root,function(d){d.r-=dr})}d3_layout_packTransform(root,w/2,h/2,radius?1:1/Math.max(2*root.r/w,2*root.r/h));return nodes}pack.size=function(_){if(!arguments.length)return size;size=_;return pack};pack.radius=function(_){if(!arguments.length)return radius;radius=_==null||typeof _==="function"?_:+_;return pack};pack.padding=function(_){if(!arguments.length)return padding;padding=+_;return pack};return d3_layout_hierarchyRebind(pack,hierarchy)};function d3_layout_packSort(a,b){return a.value-b.value}function d3_layout_packInsert(a,b){var c=a._pack_next;a._pack_next=b;b._pack_prev=a;b._pack_next=c;c._pack_prev=b}function d3_layout_packSplice(a,b){a._pack_next=b;b._pack_prev=a}function d3_layout_packIntersects(a,b){var dx=b.x-a.x,dy=b.y-a.y,dr=a.r+b.r;return.999*dr*dr>dx*dx+dy*dy}function d3_layout_packSiblings(node){if(!(nodes=node.children)||!(n=nodes.length))return;var nodes,xMin=Infinity,xMax=-Infinity,yMin=Infinity,yMax=-Infinity,a,b,c,i,j,k,n;function bound(node){xMin=Math.min(node.x-node.r,xMin);xMax=Math.max(node.x+node.r,xMax);yMin=Math.min(node.y-node.r,yMin);yMax=Math.max(node.y+node.r,yMax)}nodes.forEach(d3_layout_packLink);a=nodes[0];a.x=-a.r;a.y=0;bound(a);if(n>1){b=nodes[1];b.x=b.r;b.y=0;bound(b);if(n>2){c=nodes[2];d3_layout_packPlace(a,b,c);bound(c);d3_layout_packInsert(a,c);a._pack_prev=c;d3_layout_packInsert(c,b);b=a._pack_next;for(i=3;iright.x)right=node;if(node.depth>bottom.depth)bottom=node});var tx=separation(left,right)/2-left.x,kx=size[0]/(right.x+separation(right,left)/2+tx),ky=size[1]/(bottom.depth||1);d3_layout_hierarchyVisitBefore(root0,function(node){node.x=(node.x+tx)*kx;node.y=node.depth*ky})}return nodes}function wrapTree(root0){var root1={A:null,children:[root0]},queue=[root1],node1;while((node1=queue.pop())!=null){for(var children=node1.children,child,i=0,n=children.length;i0){d3_layout_treeMove(d3_layout_treeAncestor(vim,v,ancestor),v,shift);sip+=shift;sop+=shift}sim+=vim.m;sip+=vip.m;som+=vom.m;sop+=vop.m}if(vim&&!d3_layout_treeRight(vop)){vop.t=vim;vop.m+=sim-sop}if(vip&&!d3_layout_treeLeft(vom)){vom.t=vip;vom.m+=sip-som;ancestor=v}}return ancestor}function sizeNode(node){node.x*=size[0];node.y=node.depth*size[1]}tree.separation=function(x){if(!arguments.length)return separation;separation=x;return tree};tree.size=function(x){if(!arguments.length)return nodeSize?null:size;nodeSize=(size=x)==null?sizeNode:null;return tree};tree.nodeSize=function(x){if(!arguments.length)return nodeSize?size:null;nodeSize=(size=x)==null?null:sizeNode;return tree};return d3_layout_hierarchyRebind(tree,hierarchy)};function d3_layout_treeSeparation(a,b){return a.parent==b.parent?1:2}function d3_layout_treeLeft(v){var children=v.children;return children.length?children[0]:v.t}function d3_layout_treeRight(v){var children=v.children,n;return(n=children.length)?children[n-1]:v.t}function d3_layout_treeMove(wm,wp,shift){var change=shift/(wp.i-wm.i);wp.c-=change;wp.s+=shift;wm.c+=change;wp.z+=shift;wp.m+=shift}function d3_layout_treeShift(v){var shift=0,change=0,children=v.children,i=children.length,w;while(--i>=0){w=children[i];w.z+=shift;w.m+=shift;shift+=w.s+(change+=w.c)}}function d3_layout_treeAncestor(vim,v,ancestor){return vim.a.parent===v.parent?vim.a:ancestor}d3.layout.cluster=function(){var hierarchy=d3.layout.hierarchy().sort(null).value(null),separation=d3_layout_treeSeparation,size=[1,1],nodeSize=false;function cluster(d,i){var nodes=hierarchy.call(this,d,i),root=nodes[0],previousNode,x=0;d3_layout_hierarchyVisitAfter(root,function(node){var children=node.children;if(children&&children.length){node.x=d3_layout_clusterX(children);node.y=d3_layout_clusterY(children)}else{node.x=previousNode?x+=separation(node,previousNode):0;node.y=0;previousNode=node}});var left=d3_layout_clusterLeft(root),right=d3_layout_clusterRight(root),x0=left.x-separation(left,right)/2,x1=right.x+separation(right,left)/2;d3_layout_hierarchyVisitAfter(root,nodeSize?function(node){node.x=(node.x-root.x)*size[0];node.y=(root.y-node.y)*size[1]}:function(node){node.x=(node.x-x0)/(x1-x0)*size[0];node.y=(1-(root.y?node.y/root.y:1))*size[1]});return nodes}cluster.separation=function(x){if(!arguments.length)return separation;separation=x;return cluster};cluster.size=function(x){if(!arguments.length)return nodeSize?null:size;nodeSize=(size=x)==null;return cluster};cluster.nodeSize=function(x){if(!arguments.length)return nodeSize?size:null;nodeSize=(size=x)!=null;return cluster};return d3_layout_hierarchyRebind(cluster,hierarchy)};function d3_layout_clusterY(children){return 1+d3.max(children,function(child){return child.y})}function d3_layout_clusterX(children){return children.reduce(function(x,child){return x+child.x},0)/children.length}function d3_layout_clusterLeft(node){var children=node.children;return children&&children.length?d3_layout_clusterLeft(children[0]):node}function d3_layout_clusterRight(node){var children=node.children,n;return children&&(n=children.length)?d3_layout_clusterRight(children[n-1]):node}d3.layout.treemap=function(){var hierarchy=d3.layout.hierarchy(),round=Math.round,size=[1,1],padding=null,pad=d3_layout_treemapPadNull,sticky=false,stickies,mode="squarify",ratio=.5*(1+Math.sqrt(5));function scale(children,k){var i=-1,n=children.length,child,area;while(++i0){row.push(child=remaining[n-1]);row.area+=child.area;if(mode!=="squarify"||(score=worst(row,u))<=best){remaining.pop();best=score}else{row.area-=row.pop().area;position(row,u,rect,false);u=Math.min(rect.dx,rect.dy);row.length=row.area=0;best=Infinity}}if(row.length){position(row,u,rect,true);row.length=row.area=0}children.forEach(squarify)}}function stickify(node){var children=node.children;if(children&&children.length){var rect=pad(node),remaining=children.slice(),child,row=[];scale(remaining,rect.dx*rect.dy/node.value);row.area=0;while(child=remaining.pop()){row.push(child);row.area+=child.area;if(child.z!=null){position(row,child.z?rect.dx:rect.dy,rect,!remaining.length);row.length=row.area=0}}children.forEach(stickify)}}function worst(row,u){var s=row.area,r,rmax=0,rmin=Infinity,i=-1,n=row.length;while(++irmax)rmax=r}s*=s;u*=u;return s?Math.max(u*rmax*ratio/s,s/(u*rmin*ratio)):Infinity}function position(row,u,rect,flush){var i=-1,n=row.length,x=rect.x,y=rect.y,v=u?round(row.area/u):0,o;if(u==rect.dx){if(flush||v>rect.dy)v=rect.dy;while(++irect.dx)v=rect.dx;while(++i1);return µ+σ*x*Math.sqrt(-2*Math.log(r)/r)}},logNormal:function(){var random=d3.random.normal.apply(d3,arguments);return function(){return Math.exp(random())}},bates:function(m){var random=d3.random.irwinHall(m);return function(){return random()/m}},irwinHall:function(m){return function(){for(var s=0,j=0;j2?d3_scale_polylinear:d3_scale_bilinear,uninterpolate=clamp?d3_uninterpolateClamp:d3_uninterpolateNumber;output=linear(domain,range,uninterpolate,interpolate);input=linear(range,domain,uninterpolate,d3_interpolate);return scale}function scale(x){return output(x)}scale.invert=function(y){return input(y)};scale.domain=function(x){if(!arguments.length)return domain;domain=x.map(Number);return rescale()};scale.range=function(x){if(!arguments.length)return range;range=x;return rescale()};scale.rangeRound=function(x){return scale.range(x).interpolate(d3_interpolateRound)};scale.clamp=function(x){if(!arguments.length)return clamp;clamp=x;return rescale()};scale.interpolate=function(x){if(!arguments.length)return interpolate;interpolate=x;return rescale()};scale.ticks=function(m){return d3_scale_linearTicks(domain,m)};scale.tickFormat=function(m,format){return d3_scale_linearTickFormat(domain,m,format)};scale.nice=function(m){d3_scale_linearNice(domain,m);return rescale()};scale.copy=function(){return d3_scale_linear(domain,range,interpolate,clamp)};return rescale()}function d3_scale_linearRebind(scale,linear){return d3.rebind(scale,linear,"range","rangeRound","interpolate","clamp")}function d3_scale_linearNice(domain,m){return d3_scale_nice(domain,d3_scale_niceStep(d3_scale_linearTickRange(domain,m)[2]))}function d3_scale_linearTickRange(domain,m){if(m==null)m=10;var extent=d3_scaleExtent(domain),span=extent[1]-extent[0],step=Math.pow(10,Math.floor(Math.log(span/m)/Math.LN10)),err=m/span*step;if(err<=.15)step*=10;else if(err<=.35)step*=5;else if(err<=.75)step*=2;extent[0]=Math.ceil(extent[0]/step)*step;extent[1]=Math.floor(extent[1]/step)*step+step*.5;extent[2]=step;return extent}function d3_scale_linearTicks(domain,m){return d3.range.apply(d3,d3_scale_linearTickRange(domain,m))}function d3_scale_linearTickFormat(domain,m,format){var range=d3_scale_linearTickRange(domain,m);if(format){var match=d3_format_re.exec(format);match.shift();if(match[8]==="s"){var prefix=d3.formatPrefix(Math.max(abs(range[0]),abs(range[1])));if(!match[7])match[7]="."+d3_scale_linearPrecision(prefix.scale(range[2]));match[8]="f";format=d3.format(match.join(""));return function(d){return format(prefix.scale(d))+prefix.symbol}}if(!match[7])match[7]="."+d3_scale_linearFormatPrecision(match[8],range);format=match.join("")}else{format=",."+d3_scale_linearPrecision(range[2])+"f"}return d3.format(format)}var d3_scale_linearFormatSignificant={s:1,g:1,p:1,r:1,e:1};function d3_scale_linearPrecision(value){return-Math.floor(Math.log(value)/Math.LN10+.01)}function d3_scale_linearFormatPrecision(type,range){var p=d3_scale_linearPrecision(range[2]);return type in d3_scale_linearFormatSignificant?Math.abs(p-d3_scale_linearPrecision(Math.max(abs(range[0]),abs(range[1]))))+ +(type!=="e"):p-(type==="%")*2}d3.scale.log=function(){return d3_scale_log(d3.scale.linear().domain([0,1]),10,true,[1,10])};function d3_scale_log(linear,base,positive,domain){function log(x){return(positive?Math.log(x<0?0:x):-Math.log(x>0?0:-x))/Math.log(base)}function pow(x){return positive?Math.pow(base,x):-Math.pow(base,-x)}function scale(x){return linear(log(x))}scale.invert=function(x){return pow(linear.invert(x))};scale.domain=function(x){if(!arguments.length)return domain;positive=x[0]>=0;linear.domain((domain=x.map(Number)).map(log));return scale};scale.base=function(_){if(!arguments.length)return base;base=+_;linear.domain(domain.map(log));return scale};scale.nice=function(){var niced=d3_scale_nice(domain.map(log),positive?Math:d3_scale_logNiceNegative);linear.domain(niced);domain=niced.map(pow);return scale};scale.ticks=function(){var extent=d3_scaleExtent(domain),ticks=[],u=extent[0],v=extent[1],i=Math.floor(log(u)),j=Math.ceil(log(v)),n=base%1?2:base;if(isFinite(j-i)){if(positive){for(;i0;k--)ticks.push(pow(i)*k)}for(i=0;ticks[i]v;j--){}ticks=ticks.slice(i,j)}return ticks};scale.tickFormat=function(n,format){if(!arguments.length)return d3_scale_logFormat;if(arguments.length<2)format=d3_scale_logFormat;else if(typeof format!=="function")format=d3.format(format);var k=Math.max(.1,n/scale.ticks().length),f=positive?(e=1e-12,Math.ceil):(e=-1e-12,Math.floor),e;return function(d){return d/pow(f(log(d)+e))<=k?format(d):""}};scale.copy=function(){return d3_scale_log(linear.copy(),base,positive,domain)};return d3_scale_linearRebind(scale,linear)}var d3_scale_logFormat=d3.format(".0e"),d3_scale_logNiceNegative={floor:function(x){return-Math.ceil(-x)},ceil:function(x){return-Math.floor(-x)}};d3.scale.pow=function(){return d3_scale_pow(d3.scale.linear(),1,[0,1])};function d3_scale_pow(linear,exponent,domain){var powp=d3_scale_powPow(exponent),powb=d3_scale_powPow(1/exponent);function scale(x){return linear(powp(x))}scale.invert=function(x){return powb(linear.invert(x))};scale.domain=function(x){if(!arguments.length)return domain;linear.domain((domain=x.map(Number)).map(powp));return scale};scale.ticks=function(m){return d3_scale_linearTicks(domain,m)};scale.tickFormat=function(m,format){return d3_scale_linearTickFormat(domain,m,format)};scale.nice=function(m){return scale.domain(d3_scale_linearNice(domain,m))};scale.exponent=function(x){if(!arguments.length)return exponent;powp=d3_scale_powPow(exponent=x);powb=d3_scale_powPow(1/exponent);linear.domain(domain.map(powp));return scale};scale.copy=function(){return d3_scale_pow(linear.copy(),exponent,domain)};return d3_scale_linearRebind(scale,linear)}function d3_scale_powPow(e){return function(x){return x<0?-Math.pow(-x,e):Math.pow(x,e)}}d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)};d3.scale.ordinal=function(){return d3_scale_ordinal([],{t:"range",a:[[]]})};function d3_scale_ordinal(domain,ranger){var index,range,rangeBand;function scale(x){return range[((index.get(x)||(ranger.t==="range"?index.set(x,domain.push(x)):NaN))-1)%range.length]}function steps(start,step){return d3.range(domain.length).map(function(i){return start+step*i})}scale.domain=function(x){if(!arguments.length)return domain;domain=[];index=new d3_Map;var i=-1,n=x.length,xi;while(++i0?thresholds[y-1]:domain[0],y=d3_svg_arcMax?r0?"M0,"+r1+"A"+r1+","+r1+" 0 1,1 0,"+-r1+"A"+r1+","+r1+" 0 1,1 0,"+r1+"M0,"+r0+"A"+r0+","+r0+" 0 1,0 0,"+-r0+"A"+r0+","+r0+" 0 1,0 0,"+r0+"Z":"M0,"+r1+"A"+r1+","+r1+" 0 1,1 0,"+-r1+"A"+r1+","+r1+" 0 1,1 0,"+r1+"Z":r0?"M"+r1*c0+","+r1*s0+"A"+r1+","+r1+" 0 "+df+",1 "+r1*c1+","+r1*s1+"L"+r0*c1+","+r0*s1+"A"+r0+","+r0+" 0 "+df+",0 "+r0*c0+","+r0*s0+"Z":"M"+r1*c0+","+r1*s0+"A"+r1+","+r1+" 0 "+df+",1 "+r1*c1+","+r1*s1+"L0,0"+"Z"}arc.innerRadius=function(v){if(!arguments.length)return innerRadius;innerRadius=d3_functor(v); -return arc};arc.outerRadius=function(v){if(!arguments.length)return outerRadius;outerRadius=d3_functor(v);return arc};arc.startAngle=function(v){if(!arguments.length)return startAngle;startAngle=d3_functor(v);return arc};arc.endAngle=function(v){if(!arguments.length)return endAngle;endAngle=d3_functor(v);return arc};arc.centroid=function(){var r=(innerRadius.apply(this,arguments)+outerRadius.apply(this,arguments))/2,a=(startAngle.apply(this,arguments)+endAngle.apply(this,arguments))/2+d3_svg_arcOffset;return[Math.cos(a)*r,Math.sin(a)*r]};return arc};var d3_svg_arcOffset=-halfπ,d3_svg_arcMax=τ-ε;function d3_svg_arcInnerRadius(d){return d.innerRadius}function d3_svg_arcOuterRadius(d){return d.outerRadius}function d3_svg_arcStartAngle(d){return d.startAngle}function d3_svg_arcEndAngle(d){return d.endAngle}function d3_svg_line(projection){var x=d3_geom_pointX,y=d3_geom_pointY,defined=d3_true,interpolate=d3_svg_lineLinear,interpolateKey=interpolate.key,tension=.7;function line(data){var segments=[],points=[],i=-1,n=data.length,d,fx=d3_functor(x),fy=d3_functor(y);function segment(){segments.push("M",interpolate(projection(points),tension))}while(++i1)path.push("H",p[0]);return path.join("")}function d3_svg_lineStepBefore(points){var i=0,n=points.length,p=points[0],path=[p[0],",",p[1]];while(++i1){t=tangents[1];p=points[pi];pi++;path+="C"+(p0[0]+t0[0])+","+(p0[1]+t0[1])+","+(p[0]-t[0])+","+(p[1]-t[1])+","+p[0]+","+p[1];for(var i=2;i9){s=d*3/Math.sqrt(s);m[i]=s*a;m[i+1]=s*b}}}i=-1;while(++i<=j){s=(points[Math.min(j,i+1)][0]-points[Math.max(0,i-1)][0])/(6*(1+m[i]*m[i]));tangents.push([s||0,m[i]*s||0])}return tangents}function d3_svg_lineMonotone(points){return points.length<3?d3_svg_lineLinear(points):points[0]+d3_svg_lineHermite(points,d3_svg_lineMonotoneTangents(points))}d3.svg.line.radial=function(){var line=d3_svg_line(d3_svg_lineRadial);line.radius=line.x,delete line.x;line.angle=line.y,delete line.y;return line};function d3_svg_lineRadial(points){var point,i=-1,n=points.length,r,a;while(++iπ)+",1 "+p}function curve(r0,p0,r1,p1){return"Q 0,0 "+p1}chord.radius=function(v){if(!arguments.length)return radius;radius=d3_functor(v);return chord};chord.source=function(v){if(!arguments.length)return source;source=d3_functor(v);return chord};chord.target=function(v){if(!arguments.length)return target;target=d3_functor(v);return chord};chord.startAngle=function(v){if(!arguments.length)return startAngle;startAngle=d3_functor(v);return chord};chord.endAngle=function(v){if(!arguments.length)return endAngle;endAngle=d3_functor(v);return chord};return chord};function d3_svg_chordRadius(d){return d.radius}d3.svg.diagonal=function(){var source=d3_source,target=d3_target,projection=d3_svg_diagonalProjection;function diagonal(d,i){var p0=source.call(this,d,i),p3=target.call(this,d,i),m=(p0.y+p3.y)/2,p=[p0,{x:p0.x,y:m},{x:p3.x,y:m},p3];p=p.map(projection);return"M"+p[0]+"C"+p[1]+" "+p[2]+" "+p[3]}diagonal.source=function(x){if(!arguments.length)return source;source=d3_functor(x);return diagonal};diagonal.target=function(x){if(!arguments.length)return target;target=d3_functor(x);return diagonal};diagonal.projection=function(x){if(!arguments.length)return projection;projection=x;return diagonal};return diagonal};function d3_svg_diagonalProjection(d){return[d.x,d.y]}d3.svg.diagonal.radial=function(){var diagonal=d3.svg.diagonal(),projection=d3_svg_diagonalProjection,projection_=diagonal.projection;diagonal.projection=function(x){return arguments.length?projection_(d3_svg_diagonalRadialProjection(projection=x)):projection};return diagonal};function d3_svg_diagonalRadialProjection(projection){return function(){var d=projection.apply(this,arguments),r=d[0],a=d[1]+d3_svg_arcOffset;return[r*Math.cos(a),r*Math.sin(a)]}}d3.svg.symbol=function(){var type=d3_svg_symbolType,size=d3_svg_symbolSize;function symbol(d,i){return(d3_svg_symbols.get(type.call(this,d,i))||d3_svg_symbolCircle)(size.call(this,d,i))}symbol.type=function(x){if(!arguments.length)return type;type=d3_functor(x);return symbol};symbol.size=function(x){if(!arguments.length)return size;size=d3_functor(x);return symbol};return symbol};function d3_svg_symbolSize(){return 64}function d3_svg_symbolType(){return"circle"}function d3_svg_symbolCircle(size){var r=Math.sqrt(size/π);return"M0,"+r+"A"+r+","+r+" 0 1,1 0,"+-r+"A"+r+","+r+" 0 1,1 0,"+r+"Z"}var d3_svg_symbols=d3.map({circle:d3_svg_symbolCircle,cross:function(size){var r=Math.sqrt(size/5)/2;return"M"+-3*r+","+-r+"H"+-r+"V"+-3*r+"H"+r+"V"+-r+"H"+3*r+"V"+r+"H"+r+"V"+3*r+"H"+-r+"V"+r+"H"+-3*r+"Z"},diamond:function(size){var ry=Math.sqrt(size/(2*d3_svg_symbolTan30)),rx=ry*d3_svg_symbolTan30;return"M0,"+-ry+"L"+rx+",0"+" 0,"+ry+" "+-rx+",0"+"Z"},square:function(size){var r=Math.sqrt(size)/2;return"M"+-r+","+-r+"L"+r+","+-r+" "+r+","+r+" "+-r+","+r+"Z"},"triangle-down":function(size){var rx=Math.sqrt(size/d3_svg_symbolSqrt3),ry=rx*d3_svg_symbolSqrt3/2;return"M0,"+ry+"L"+rx+","+-ry+" "+-rx+","+-ry+"Z"},"triangle-up":function(size){var rx=Math.sqrt(size/d3_svg_symbolSqrt3),ry=rx*d3_svg_symbolSqrt3/2;return"M0,"+-ry+"L"+rx+","+ry+" "+-rx+","+ry+"Z"}});d3.svg.symbolTypes=d3_svg_symbols.keys();var d3_svg_symbolSqrt3=Math.sqrt(3),d3_svg_symbolTan30=Math.tan(30*d3_radians);function d3_transition(groups,id){d3_subclass(groups,d3_transitionPrototype);groups.id=id;return groups}var d3_transitionPrototype=[],d3_transitionId=0,d3_transitionInheritId,d3_transitionInherit;d3_transitionPrototype.call=d3_selectionPrototype.call;d3_transitionPrototype.empty=d3_selectionPrototype.empty;d3_transitionPrototype.node=d3_selectionPrototype.node;d3_transitionPrototype.size=d3_selectionPrototype.size;d3.transition=function(selection){return arguments.length?d3_transitionInheritId?selection.transition():selection:d3_selectionRoot.transition()};d3.transition.prototype=d3_transitionPrototype;d3_transitionPrototype.select=function(selector){var id=this.id,subgroups=[],subgroup,subnode,node;selector=d3_selection_selector(selector);for(var j=-1,m=this.length;++jid)return stop();lock.active=id;transition.event&&transition.event.start.call(node,d,i);transition.tween.forEach(function(key,value){if(value=value.call(node,d,i)){tweened.push(value)}});d3.timer(function(){timer.c=tick(elapsed||1)?d3_true:tick;return 1},0,time)}function tick(elapsed){if(lock.active!==id)return stop();var t=elapsed/duration,e=ease(t),n=tweened.length;while(n>0){tweened[--n].call(node,e)}if(t>=1){transition.event&&transition.event.end.call(node,d,i);return stop()}}function stop(){if(--lock.count)delete lock[id];else delete node.__transition__;return 1}},0,time)}}d3.svg.axis=function(){var scale=d3.scale.linear(),orient=d3_svg_axisDefaultOrient,innerTickSize=6,outerTickSize=6,tickPadding=3,tickArguments_=[10],tickValues=null,tickFormat_;function axis(g){g.each(function(){var g=d3.select(this);var scale0=this.__chart__||scale,scale1=this.__chart__=scale.copy();var ticks=tickValues==null?scale1.ticks?scale1.ticks.apply(scale1,tickArguments_):scale1.domain():tickValues,tickFormat=tickFormat_==null?scale1.tickFormat?scale1.tickFormat.apply(scale1,tickArguments_):d3_identity:tickFormat_,tick=g.selectAll(".tick").data(ticks,scale1),tickEnter=tick.enter().insert("g",".domain").attr("class","tick").style("opacity",ε),tickExit=d3.transition(tick.exit()).style("opacity",ε).remove(),tickUpdate=d3.transition(tick.order()).style("opacity",1),tickTransform;var range=d3_scaleRange(scale1),path=g.selectAll(".domain").data([0]),pathUpdate=(path.enter().append("path").attr("class","domain"),d3.transition(path));tickEnter.append("line");tickEnter.append("text");var lineEnter=tickEnter.select("line"),lineUpdate=tickUpdate.select("line"),text=tick.select("text").text(tickFormat),textEnter=tickEnter.select("text"),textUpdate=tickUpdate.select("text");switch(orient){case"bottom":{tickTransform=d3_svg_axisX;lineEnter.attr("y2",innerTickSize);textEnter.attr("y",Math.max(innerTickSize,0)+tickPadding);lineUpdate.attr("x2",0).attr("y2",innerTickSize);textUpdate.attr("x",0).attr("y",Math.max(innerTickSize,0)+tickPadding);text.attr("dy",".71em").style("text-anchor","middle");pathUpdate.attr("d","M"+range[0]+","+outerTickSize+"V0H"+range[1]+"V"+outerTickSize);break}case"top":{tickTransform=d3_svg_axisX;lineEnter.attr("y2",-innerTickSize);textEnter.attr("y",-(Math.max(innerTickSize,0)+tickPadding));lineUpdate.attr("x2",0).attr("y2",-innerTickSize);textUpdate.attr("x",0).attr("y",-(Math.max(innerTickSize,0)+tickPadding));text.attr("dy","0em").style("text-anchor","middle");pathUpdate.attr("d","M"+range[0]+","+-outerTickSize+"V0H"+range[1]+"V"+-outerTickSize);break}case"left":{tickTransform=d3_svg_axisY;lineEnter.attr("x2",-innerTickSize);textEnter.attr("x",-(Math.max(innerTickSize,0)+tickPadding));lineUpdate.attr("x2",-innerTickSize).attr("y2",0);textUpdate.attr("x",-(Math.max(innerTickSize,0)+tickPadding)).attr("y",0);text.attr("dy",".32em").style("text-anchor","end");pathUpdate.attr("d","M"+-outerTickSize+","+range[0]+"H0V"+range[1]+"H"+-outerTickSize);break}case"right":{tickTransform=d3_svg_axisY;lineEnter.attr("x2",innerTickSize);textEnter.attr("x",Math.max(innerTickSize,0)+tickPadding);lineUpdate.attr("x2",innerTickSize).attr("y2",0);textUpdate.attr("x",Math.max(innerTickSize,0)+tickPadding).attr("y",0);text.attr("dy",".32em").style("text-anchor","start");pathUpdate.attr("d","M"+outerTickSize+","+range[0]+"H0V"+range[1]+"H"+outerTickSize);break}}if(scale1.rangeBand){var x=scale1,dx=x.rangeBand()/2;scale0=scale1=function(d){return x(d)+dx}}else if(scale0.rangeBand){scale0=scale1}else{tickExit.call(tickTransform,scale1)}tickEnter.call(tickTransform,scale0);tickUpdate.call(tickTransform,scale1)})}axis.scale=function(x){if(!arguments.length)return scale;scale=x;return axis};axis.orient=function(x){if(!arguments.length)return orient;orient=x in d3_svg_axisOrients?x+"":d3_svg_axisDefaultOrient;return axis};axis.ticks=function(){if(!arguments.length)return tickArguments_;tickArguments_=arguments;return axis};axis.tickValues=function(x){if(!arguments.length)return tickValues;tickValues=x;return axis};axis.tickFormat=function(x){if(!arguments.length)return tickFormat_;tickFormat_=x;return axis};axis.tickSize=function(x){var n=arguments.length;if(!n)return innerTickSize;innerTickSize=+x;outerTickSize=+arguments[n-1];return axis};axis.innerTickSize=function(x){if(!arguments.length)return innerTickSize;innerTickSize=+x;return axis};axis.outerTickSize=function(x){if(!arguments.length)return outerTickSize;outerTickSize=+x;return axis};axis.tickPadding=function(x){if(!arguments.length)return tickPadding;tickPadding=+x;return axis};axis.tickSubdivide=function(){return arguments.length&&axis};return axis};var d3_svg_axisDefaultOrient="bottom",d3_svg_axisOrients={top:1,right:1,bottom:1,left:1};function d3_svg_axisX(selection,x){selection.attr("transform",function(d){return"translate("+x(d)+",0)"})}function d3_svg_axisY(selection,y){selection.attr("transform",function(d){return"translate(0,"+y(d)+")"})}d3.svg.brush=function(){var event=d3_eventDispatch(brush,"brushstart","brush","brushend"),x=null,y=null,xExtent=[0,0],yExtent=[0,0],xExtentDomain,yExtentDomain,xClamp=true,yClamp=true,resizes=d3_svg_brushResizes[0];function brush(g){g.each(function(){var g=d3.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",brushstart).on("touchstart.brush",brushstart);var background=g.selectAll(".background").data([0]);background.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair");g.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var resize=g.selectAll(".resize").data(resizes,d3_identity);resize.exit().remove();resize.enter().append("g").attr("class",function(d){return"resize "+d}).style("cursor",function(d){return d3_svg_brushCursor[d]}).append("rect").attr("x",function(d){return/[ew]$/.test(d)?-3:null}).attr("y",function(d){return/^[ns]/.test(d)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden");resize.style("display",brush.empty()?"none":null);var gUpdate=d3.transition(g),backgroundUpdate=d3.transition(background),range;if(x){range=d3_scaleRange(x);backgroundUpdate.attr("x",range[0]).attr("width",range[1]-range[0]);redrawX(gUpdate)}if(y){range=d3_scaleRange(y);backgroundUpdate.attr("y",range[0]).attr("height",range[1]-range[0]);redrawY(gUpdate)}redraw(gUpdate)})}brush.event=function(g){g.each(function(){var event_=event.of(this,arguments),extent1={x:xExtent,y:yExtent,i:xExtentDomain,j:yExtentDomain},extent0=this.__chart__||extent1;this.__chart__=extent1;if(d3_transitionInheritId){d3.select(this).transition().each("start.brush",function(){xExtentDomain=extent0.i;yExtentDomain=extent0.j;xExtent=extent0.x;yExtent=extent0.y;event_({type:"brushstart"})}).tween("brush:brush",function(){var xi=d3_interpolateArray(xExtent,extent1.x),yi=d3_interpolateArray(yExtent,extent1.y);xExtentDomain=yExtentDomain=null;return function(t){xExtent=extent1.x=xi(t);yExtent=extent1.y=yi(t);event_({type:"brush",mode:"resize"})}}).each("end.brush",function(){xExtentDomain=extent1.i;yExtentDomain=extent1.j;event_({type:"brush",mode:"resize"});event_({type:"brushend"})})}else{event_({type:"brushstart"});event_({type:"brush",mode:"resize"});event_({type:"brushend"})}})};function redraw(g){g.selectAll(".resize").attr("transform",function(d){return"translate("+xExtent[+/e$/.test(d)]+","+yExtent[+/^s/.test(d)]+")"})}function redrawX(g){g.select(".extent").attr("x",xExtent[0]);g.selectAll(".extent,.n>rect,.s>rect").attr("width",xExtent[1]-xExtent[0])}function redrawY(g){g.select(".extent").attr("y",yExtent[0]);g.selectAll(".extent,.e>rect,.w>rect").attr("height",yExtent[1]-yExtent[0])}function brushstart(){var target=this,eventTarget=d3.select(d3.event.target),event_=event.of(target,arguments),g=d3.select(target),resizing=eventTarget.datum(),resizingX=!/^(n|s)$/.test(resizing)&&x,resizingY=!/^(e|w)$/.test(resizing)&&y,dragging=eventTarget.classed("extent"),dragRestore=d3_event_dragSuppress(),center,origin=d3.mouse(target),offset;var w=d3.select(d3_window).on("keydown.brush",keydown).on("keyup.brush",keyup);if(d3.event.changedTouches){w.on("touchmove.brush",brushmove).on("touchend.brush",brushend)}else{w.on("mousemove.brush",brushmove).on("mouseup.brush",brushend)}g.interrupt().selectAll("*").interrupt();if(dragging){origin[0]=xExtent[0]-origin[0];origin[1]=yExtent[0]-origin[1]}else if(resizing){var ex=+/w$/.test(resizing),ey=+/^n/.test(resizing);offset=[xExtent[1-ex]-origin[0],yExtent[1-ey]-origin[1]];origin[0]=xExtent[ex];origin[1]=yExtent[ey]}else if(d3.event.altKey)center=origin.slice();g.style("pointer-events","none").selectAll(".resize").style("display",null);d3.select("body").style("cursor",eventTarget.style("cursor"));event_({type:"brushstart"});brushmove();function keydown(){if(d3.event.keyCode==32){if(!dragging){center=null;origin[0]-=xExtent[1];origin[1]-=yExtent[1];dragging=2}d3_eventPreventDefault()}}function keyup(){if(d3.event.keyCode==32&&dragging==2){origin[0]+=xExtent[1];origin[1]+=yExtent[1];dragging=0;d3_eventPreventDefault()}}function brushmove(){var point=d3.mouse(target),moved=false;if(offset){point[0]+=offset[0];point[1]+=offset[1]}if(!dragging){if(d3.event.altKey){if(!center)center=[(xExtent[0]+xExtent[1])/2,(yExtent[0]+yExtent[1])/2];origin[0]=xExtent[+(point[0]1?{floor:function(date){while(skipped(date=interval.floor(date)))date=d3_time_scaleDate(date-1);return date},ceil:function(date){while(skipped(date=interval.ceil(date)))date=d3_time_scaleDate(+date+1);return date}}:interval))};scale.ticks=function(interval,skip){var extent=d3_scaleExtent(scale.domain()),method=interval==null?tickMethod(extent,10):typeof interval==="number"?tickMethod(extent,interval):!interval.range&&[{range:interval},skip];if(method)interval=method[0],skip=method[1];return interval.range(extent[0],d3_time_scaleDate(+extent[1]+1),skip<1?1:skip)};scale.tickFormat=function(){return format};scale.copy=function(){return d3_time_scale(linear.copy(),methods,format)};return d3_scale_linearRebind(scale,linear)}function d3_time_scaleDate(t){return new Date(t)}var d3_time_scaleSteps=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6];var d3_time_scaleLocalMethods=[[d3_time.second,1],[d3_time.second,5],[d3_time.second,15],[d3_time.second,30],[d3_time.minute,1],[d3_time.minute,5],[d3_time.minute,15],[d3_time.minute,30],[d3_time.hour,1],[d3_time.hour,3],[d3_time.hour,6],[d3_time.hour,12],[d3_time.day,1],[d3_time.day,2],[d3_time.week,1],[d3_time.month,1],[d3_time.month,3],[d3_time.year,1]];var d3_time_scaleLocalFormat=d3_time_format.multi([[".%L",function(d){return d.getMilliseconds()}],[":%S",function(d){return d.getSeconds()}],["%I:%M",function(d){return d.getMinutes()}],["%I %p",function(d){return d.getHours()}],["%a %d",function(d){return d.getDay()&&d.getDate()!=1}],["%b %d",function(d){return d.getDate()!=1}],["%B",function(d){return d.getMonth()}],["%Y",d3_true]]);var d3_time_scaleMilliseconds={range:function(start,stop,step){return d3.range(Math.ceil(start/step)*step,+stop,step).map(d3_time_scaleDate)},floor:d3_identity,ceil:d3_identity};d3_time_scaleLocalMethods.year=d3_time.year;d3_time.scale=function(){return d3_time_scale(d3.scale.linear(),d3_time_scaleLocalMethods,d3_time_scaleLocalFormat)};var d3_time_scaleUtcMethods=d3_time_scaleLocalMethods.map(function(m){return[m[0].utc,m[1]]});var d3_time_scaleUtcFormat=d3_time_formatUtc.multi([[".%L",function(d){return d.getUTCMilliseconds()}],[":%S",function(d){return d.getUTCSeconds()}],["%I:%M",function(d){return d.getUTCMinutes()}],["%I %p",function(d){return d.getUTCHours()}],["%a %d",function(d){return d.getUTCDay()&&d.getUTCDate()!=1}],["%b %d",function(d){return d.getUTCDate()!=1}],["%B",function(d){return d.getUTCMonth()}],["%Y",d3_true]]);d3_time_scaleUtcMethods.year=d3_time.year.utc;d3_time.scale.utc=function(){return d3_time_scale(d3.scale.linear(),d3_time_scaleUtcMethods,d3_time_scaleUtcFormat)};d3.text=d3_xhrType(function(request){return request.responseText});d3.json=function(url,callback){return d3_xhr(url,"application/json",d3_json,callback)};function d3_json(request){return JSON.parse(request.responseText)}d3.html=function(url,callback){return d3_xhr(url,"text/html",d3_html,callback)};function d3_html(request){var range=d3_document.createRange();range.selectNode(d3_document.body);return range.createContextualFragment(request.responseText)}d3.xml=d3_xhrType(function(request){return request.responseXML});if(typeof define==="function"&&define.amd){define(d3)}else if(typeof module==="object"&&module.exports){module.exports=d3}else{this.d3=d3}}();(function(){var dataframe={cols:function(data){var result={access:function(column){if(!(column in data))throw"dataframe doesn't have column "+column.toString();var columnv=data[column];var f=function(i){return columnv[i]};f.attrs=columnv;return f},index:function(i){return i},num_rows:function(){for(var col in data)return data[col].length},has:function(k){return k in data},records:function(){return _.range(0,this.num_rows())}};return result},rows:function(data){var result={access:function(column){var f=function(i){return data[i][column]};if("attrs"in data&&_.isObject(data.attrs))f.attrs=data.attrs[column];return f},index:function(i){return i},num_rows:function(){return data.length},has:function(k){return k in data[0]},records:function(){return _.range(0,this.num_rows())}};return result}};if(typeof define==="function"&&define.amd){define(dataframe)}else if(typeof module==="object"&&module.exports){module.exports=dataframe}else{this.dataframe=dataframe}})();(function(){function _dcplot(dc,crossfilter){dcplot.group={identity:function(dim){return dim.group()},bin:function(binwidth){var f=function(dim){return dim.group(function(x){return Math.floor(x/binwidth)*binwidth})};f.binwidth=binwidth;return f}};dcplot.reduce={count:function(group){return group.reduceCount()},countFilter:function(access,level){return dcplot.reduce.sum(function(a){return access(a)===level?1:0})},filter:function(reduce,access,level){function wrapper(acc){return function(a){return access(a)===level?acc(a):0}}return{arg:reduce.arg,fun:function(acc){return reduce.fun(wrapper(acc))}}},sum:function(access,wacc){return{arg:access,fun:function(acc2){if(wacc===undefined)return function(group){return group.reduceSum(function(item){return acc2(item)})};else return function(group){return group.reduce(function(p,v){p.sum+=acc2(v)*wacc(v);return p},function(p,v){p.sum-=acc2(v)*wacc(v);return p},function(p,v){return{sum:0,valueOf:function(){return this.sum}}})}}}},any:function(access){return{arg:access,fun:function(acc2){return function(group){return group.reduce(function(p,v){return acc2(v)},function(p,v){return p},function(p,v){return 0})}}}},avg:function(access,wacc){return{arg:access,fun:function(acc2){if(wacc===undefined)return function(group){return group.reduce(function(p,v){++p.count;p.sum+=acc2(v);p.avg=p.sum/p.count;return p},function(p,v){--p.count;p.sum-=acc2(v);p.avg=p.count?p.sum/p.count:0;return p},function(p,v){return{count:0,sum:0,avg:0,valueOf:function(){return this.avg}}})};else return function(group){return group.reduce(function(p,v){p.count+=wacc(v);p.sum+=acc2(v)*wacc(v);p.avg=p.sum/p.count;return p},function(p,v){p.count-=wacc(v);p.sum-=acc2(v)*wacc(v);p.avg=p.count?p.sum/p.count:0;return p},function(p,v){return{count:0,sum:0,avg:0,valueOf:function(){return this.avg}}})}}}},value:function(field){return function(key,value){return value[field]}}};var chart_attrs={base:{supported:true,div:{required:true},title:{required:false},dimension:{required:true},group:{required:true},ordering:{required:false},width:{required:true,"default":300},height:{required:true,"default":300},"transition.duration":{required:false},label:{required:false},tips:{required:false},more:{required:false}},color:{supported:true,color:{required:false},"color.scale":{required:false},"color.domain":{required:false},"color.range":{required:false}},stackable:{supported:true,stack:{required:false},"stack.levels":{required:false}},coordinateGrid:{supported:true,parents:["base","color"],margins:{required:false},x:{required:false},y:{required:false},"x.ordinal":{required:false},"x.scale":{required:true},"x.domain":{required:false},"x.units":{required:false},"x.round":{required:false},"x.elastic":{required:false},"x.padding":{required:false},"y.scale":{required:false},"y.domain":{required:false},"y.elastic":{required:false},"y.padding":{required:false},gridLines:{required:false},brush:{required:false}},pie:{supported:true,concrete:true,parents:["base","color"],radius:{required:false},innerRadius:{required:false},wedge:{required:false},size:{required:false}},row:{supported:false,parents:["base","color"]},bar:{supported:true,concrete:true,parents:["coordinateGrid","stackable"],width:{"default":700},height:{"default":250},centerBar:{required:false},gap:{required:false},"color.x":{"default":true},"x.units":{required:true}},line:{supported:true,concrete:true,parents:["coordinateGrid","stackable"],width:{"default":800},height:{"default":250},area:{required:false},dotRadius:{required:false}},composite:{parents:["coordinateGrid"],supported:false},abstractBubble:{supported:true,parents:["color"],r:{"default":2},"r.scale":{required:false},"r.domain":{required:false}},bubble:{concrete:true,parents:["coordinateGrid","abstractBubble"],width:{"default":400},label:{"default":null},color:{"default":0},supported:true,"r.elastic":{required:false}},bubbleOverlay:{supported:false,parents:["base","abstractBubble"]},geoCloropleth:{supported:false},dataCount:{supported:false},dataTable:{supported:true,concrete:true,parents:["base"],columns:{required:true},size:{required:false},sortBy:{required:false}}};function skip_attr(a){return a==="supported"||a==="concrete"||a==="parents"}function parents_first_traversal(map,iter,callbacks){if(!(iter in map))throw"unknown chart type "+defn.type;var curr=map[iter];if("parents"in curr)for(var i=0;i1e4||filter<-1e4)return Math.round(filter);else return filter.toPrecision(4)}else return _psv(filter)};dcplot.format_error=function(e){var tab;if(_.isArray(e)){tab=$("");$.each(e,function(i){var err=e[i],formatted_errors=$("").append($("
");if(_.isString(err.errors))formatted_errors.text(err.errors);else if(_.isArray(err.errors))$.each(err.errors,function(e){formatted_errors.append($("

").text(err.errors[e]))});else formatted_errors.text(err.errors.message.toString());var name=err.name.replace(/_\d*_\d*$/,"");tab.append($("

").text(err.type)).append($("").text(name)).append(formatted_errors))})}else tab=$("

").text(e.toString());var error_report=$("

").append($("

").text("dcplot errors!")).append(tab);return error_report};function dcplot(frame,groupname,definition){function mhas(obj){for(var i=1;i10?d3.scale.category20():d3.scale.category10()}if(!defn["color.domain"]){if(mhas(defn,"color","attrs","r_attributes","levels"))defn["color.domain"]=defn.color.attrs.r_attributes.levels}},stackable:function(){if(_.has(defn,"stack")){if(!_.has(defn,"stack.levels"))defn["stack.levels"]=get_levels(defn.stack);var levels=defn["stack.levels"];for(var s=0;s/gm,">")}function t(v){return v.nodeName.toLowerCase()}function i(w,x){var v=w&&w.exec(x);return v&&v.index==0}function d(v){return Array.prototype.map.call(v.childNodes,function(w){if(w.nodeType==3){return b.useBR?w.nodeValue.replace(/\n/g,""):w.nodeValue}if(t(w)=="br"){return"\n"}return d(w)}).join("")}function r(w){var v=(w.className+" "+(w.parentNode?w.parentNode.className:"")).split(/\s+/);v=v.map(function(x){return x.replace(/^language-/,"")});return v.filter(function(x){return j(x)||x=="no-highlight"})[0]}function o(x,y){var v={};for(var w in x){v[w]=x[w]}if(y){for(var w in y){v[w]=y[w]}}return v}function u(x){var v=[];(function w(y,z){for(var A=y.firstChild;A;A=A.nextSibling){if(A.nodeType==3){z+=A.nodeValue.length}else{if(t(A)=="br"){z+=1}else{if(A.nodeType==1){v.push({event:"start",offset:z,node:A});z=w(A,z);v.push({event:"stop",offset:z,node:A})}}}}return z})(x,0);return v}function q(w,y,C){var x=0;var F="";var z=[];function B(){if(!w.length||!y.length){return w.length?w:y}if(w[0].offset!=y[0].offset){return w[0].offset"}function E(G){F+=""}function v(G){(G.event=="start"?A:E)(G.node)}while(w.length||y.length){var D=B();F+=k(C.substr(x,D[0].offset-x));x=D[0].offset;if(D==w){z.reverse().forEach(E);do{v(D.splice(0,1)[0]);D=B()}while(D==w&&D.length&&D[0].offset==x);z.reverse().forEach(A)}else{if(D[0].event=="start"){z.push(D[0].node)}else{z.pop()}v(D.splice(0,1)[0])}}return F+k(C.substr(x))}function m(y){function v(z){return z&&z.source||z}function w(A,z){return RegExp(v(A),"m"+(y.cI?"i":"")+(z?"g":""))}function x(D,C){if(D.compiled){return}D.compiled=true;D.k=D.k||D.bK;if(D.k){var z={};function E(G,F){if(y.cI){F=F.toLowerCase()}F.split(" ").forEach(function(H){var I=H.split("|");z[I[0]]=[G,I[1]?Number(I[1]):1]})}if(typeof D.k=="string"){E("keyword",D.k)}else{Object.keys(D.k).forEach(function(F){E(F,D.k[F])})}D.k=z}D.lR=w(D.l||/\b[A-Za-z0-9_]+\b/,true);if(C){if(D.bK){D.b=D.bK.split(" ").join("|")}if(!D.b){D.b=/\B|\b/}D.bR=w(D.b);if(!D.e&&!D.eW){D.e=/\B|\b/}if(D.e){D.eR=w(D.e)}D.tE=v(D.e)||"";if(D.eW&&C.tE){D.tE+=(D.e?"|":"")+C.tE}}if(D.i){D.iR=w(D.i)}if(D.r===undefined){D.r=1}if(!D.c){D.c=[]}var B=[];D.c.forEach(function(F){if(F.v){F.v.forEach(function(G){B.push(o(F,G))})}else{B.push(F=="self"?D:F)}});D.c=B;D.c.forEach(function(F){x(F,D)});if(D.starts){x(D.starts,C)}var A=D.c.map(function(F){return F.bK?"\\.?\\b("+F.b+")\\b\\.?":F.b}).concat([D.tE]).concat([D.i]).map(v).filter(Boolean);D.t=A.length?w(A.join("|"),true):{exec:function(F){return null}};D.continuation={}}x(y)}function c(S,L,J,R){function v(U,V){for(var T=0;T";U+=Z+'">';return U+X+Y}function N(){var U=k(C);if(!I.k){return U}var T="";var X=0;I.lR.lastIndex=0;var V=I.lR.exec(U);while(V){T+=U.substr(X,V.index-X);var W=E(I,V);if(W){H+=W[1];T+=w(W[0],V[0])}else{T+=V[0]}X=I.lR.lastIndex;V=I.lR.exec(U)}return T+U.substr(X)}function F(){if(I.sL&&!f[I.sL]){return k(C)}var T=I.sL?c(I.sL,C,true,I.continuation.top):g(C);if(I.r>0){H+=T.r}if(I.subLanguageMode=="continuous"){I.continuation.top=T.top}return w(T.language,T.value,false,true)}function Q(){return I.sL!==undefined?F():N()}function P(V,U){var T=V.cN?w(V.cN,"",true):"";if(V.rB){D+=T;C=""}else{if(V.eB){D+=k(U)+T;C=""}else{D+=T;C=U}}I=Object.create(V,{parent:{value:I}})}function G(T,X){C+=T;if(X===undefined){D+=Q();return 0}var V=v(X,I);if(V){D+=Q();P(V,X);return V.rB?0:X.length}var W=z(I,X);if(W){var U=I;if(!(U.rE||U.eE)){C+=X}D+=Q();do{if(I.cN){D+=""}H+=I.r;I=I.parent}while(I!=W.parent);if(U.eE){D+=k(X)}C="";if(W.starts){P(W.starts,"")}return U.rE?0:X.length}if(A(X,I)){throw new Error('Illegal lexeme "'+X+'" for mode "'+(I.cN||"")+'"')}C+=X;return X.length||1}var M=j(S);if(!M){throw new Error('Unknown language: "'+S+'"')}m(M);var I=R||M;var D="";for(var K=I;K!=M;K=K.parent){if(K.cN){D=w(K.cN,D,true)}}var C="";var H=0;try{var B,y,x=0;while(true){I.t.lastIndex=x;B=I.t.exec(L);if(!B){break}y=G(L.substr(x,B.index-x),B[0]);x=B.index+y}G(L.substr(x));for(var K=I;K.parent;K=K.parent){if(K.cN){D+=""}}return{r:H,value:D,language:S,top:I}}catch(O){if(O.message.indexOf("Illegal")!=-1){return{r:0,value:k(L)}}else{throw O}}}function g(y,x){x=x||b.languages||Object.keys(f);var v={r:0,value:k(y)};var w=v;x.forEach(function(z){if(!j(z)){return}var A=c(z,y,false);A.language=z;if(A.r>w.r){w=A}if(A.r>v.r){w=v;v=A}});if(w.language){v.second_best=w}return v}function h(v){if(b.tabReplace){v=v.replace(/^((<[^>]+>|\t)+)/gm,function(w,z,y,x){return z.replace(/\t/g,b.tabReplace)})}if(b.useBR){v=v.replace(/\n/g,"
")}return v}function p(z){var y=d(z);var A=r(z);if(A=="no-highlight"){return}var v=A?c(A,y,true):g(y);var w=u(z);if(w.length){var x=document.createElementNS("http://www.w3.org/1999/xhtml","pre");x.innerHTML=v.value;v.value=q(w,u(x),y)}v.value=h(v.value);z.innerHTML=v.value;z.className+=" hljs "+(!A&&v.language||"");z.result={language:v.language,re:v.r};if(v.second_best){z.second_best={language:v.second_best.language,re:v.second_best.r}}}var b={classPrefix:"hljs-",tabReplace:null,useBR:false,languages:undefined};function s(v){b=o(b,v)}function l(){if(l.called){return}l.called=true;var v=document.querySelectorAll("pre code");Array.prototype.forEach.call(v,p)}function a(){addEventListener("DOMContentLoaded",l,false);addEventListener("load",l,false)}var f={};var n={};function e(v,x){var w=f[v]=x(this);if(w.aliases){w.aliases.forEach(function(y){n[y]=v})}}function j(v){return f[v]||f[n[v]]}this.highlight=c;this.highlightAuto=g;this.fixMarkup=h;this.highlightBlock=p;this.configure=s;this.initHighlighting=l;this.initHighlightingOnLoad=a;this.registerLanguage=e;this.getLanguage=j;this.inherit=o;this.IR="[a-zA-Z][a-zA-Z0-9_]*";this.UIR="[a-zA-Z_][a-zA-Z0-9_]*";this.NR="\\b\\d+(\\.\\d+)?";this.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)";this.BNR="\\b(0b[01]+)";this.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~";this.BE={b:"\\\\[\\s\\S]",r:0};this.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[this.BE]};this.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[this.BE]};this.CLCM={cN:"comment",b:"//",e:"$"};this.CBLCLM={cN:"comment",b:"/\\*",e:"\\*/"};this.HCM={cN:"comment",b:"#",e:"$"};this.NM={cN:"number",b:this.NR,r:0};this.CNM={cN:"number",b:this.CNR,r:0};this.BNM={cN:"number",b:this.BNR,r:0};this.REGEXP_MODE={cN:"regexp",b:/\//,e:/\/[gim]*/,i:/\n/,c:[this.BE,{b:/\[/,e:/\]/,r:0,c:[this.BE]}]};this.TM={cN:"title",b:this.IR,r:0};this.UTM={cN:"title",b:this.UIR,r:0}};hljs.registerLanguage("python",function(a){var f={cN:"prompt",b:/^(>>>|\.\.\.) /};var b={cN:"string",c:[a.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[f],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[f],r:10},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},a.ASM,a.QSM]};var d={cN:"number",r:0,v:[{b:a.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:a.CNR+"[lLjJ]?"}]};var e={cN:"params",b:/\(/,e:/\)/,c:["self",f,d,b]};var c={e:/:/,i:/[${=;\n]/,c:[a.UTM,e]};return{k:{keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},i:/(<\/|->|\?)/,c:[f,d,b,a.HCM,a.inherit(c,{cN:"function",bK:"def",r:10}),a.inherit(c,{cN:"class",bK:"class"}),{cN:"decorator",b:/@/,e:/$/},{b:/\b(print|exec)\(/}]}});hljs.registerLanguage("r",function(a){var b="([a-zA-Z]|\\.[a-zA-Z.])[a-zA-Z0-9._]*";return{c:[a.HCM,{b:b,l:b,k:{keyword:"function if in break next repeat else for return switch while try tryCatch|10 stop warning require library attach detach source setMethod setGeneric setGroupGeneric setClass ...|10",literal:"NULL NA TRUE FALSE T F Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10"},r:0},{cN:"number",b:"0[xX][0-9a-fA-F]+[Li]?\\b",r:0},{cN:"number",b:"\\d+(?:[eE][+\\-]?\\d*)?L\\b",r:0},{cN:"number",b:"\\d+\\.(?!\\d)(?:i\\b)?",r:0},{cN:"number",b:"\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d*)?i?\\b",r:0},{cN:"number",b:"\\.\\d+(?:[eE][+\\-]?\\d*)?i?\\b",r:0},{b:"`",e:"`",r:0},{cN:"string",c:[a.BE],v:[{b:'"',e:'"'},{b:"'",e:"'"}]}]}});(function(global,factory){if(typeof module==="object"&&typeof module.exports==="object"){module.exports=global.document?factory(global,true):function(w){if(!w.document){throw new Error("jQuery requires a window with a document")}return factory(w)}}else{factory(global)}})(typeof window!=="undefined"?window:this,function(window,noGlobal){var arr=[];var slice=arr.slice;var concat=arr.concat;var push=arr.push;var indexOf=arr.indexOf;var class2type={};var toString=class2type.toString;var hasOwn=class2type.hasOwnProperty;var support={};var document=window.document,version="2.1.1",jQuery=function(selector,context){return new jQuery.fn.init(selector,context)},rtrim=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,rmsPrefix=/^-ms-/,rdashAlpha=/-([\da-z])/gi,fcamelCase=function(all,letter){return letter.toUpperCase()};jQuery.fn=jQuery.prototype={jquery:version,constructor:jQuery,selector:"",length:0,toArray:function(){return slice.call(this)},get:function(num){return num!=null?num<0?this[num+this.length]:this[num]:slice.call(this)},pushStack:function(elems){var ret=jQuery.merge(this.constructor(),elems);ret.prevObject=this;ret.context=this.context;return ret},each:function(callback,args){return jQuery.each(this,callback,args)},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem)}))},slice:function(){return this.pushStack(slice.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(i){var len=this.length,j=+i+(i<0?len:0);return this.pushStack(j>=0&&j=0},isPlainObject:function(obj){if(jQuery.type(obj)!=="object"||obj.nodeType||jQuery.isWindow(obj)){return false}if(obj.constructor&&!hasOwn.call(obj.constructor.prototype,"isPrototypeOf")){return false}return true},isEmptyObject:function(obj){var name;for(name in obj){return false}return true},type:function(obj){if(obj==null){return obj+""}return typeof obj==="object"||typeof obj==="function"?class2type[toString.call(obj)]||"object":typeof obj},globalEval:function(code){var script,indirect=eval;code=jQuery.trim(code);if(code){if(code.indexOf("use strict")===1){script=document.createElement("script");script.text=code;document.head.appendChild(script).parentNode.removeChild(script)}else{indirect(code)}}},camelCase:function(string){return string.replace(rmsPrefix,"ms-").replace(rdashAlpha,fcamelCase)},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toLowerCase()===name.toLowerCase()},each:function(obj,callback,args){var value,i=0,length=obj.length,isArray=isArraylike(obj);if(args){if(isArray){for(;i0&&length-1 in obj}var Sizzle=function(window){var i,support,Expr,getText,isXML,tokenize,compile,select,outermostContext,sortInput,hasDuplicate,setDocument,document,docElem,documentIsHTML,rbuggyQSA,rbuggyMatches,matches,contains,expando="sizzle"+-new Date,preferredDoc=window.document,dirruns=0,done=0,classCache=createCache(),tokenCache=createCache(),compilerCache=createCache(),sortOrder=function(a,b){if(a===b){hasDuplicate=true}return 0},strundefined=typeof undefined,MAX_NEGATIVE=1<<31,hasOwn={}.hasOwnProperty,arr=[],pop=arr.pop,push_native=arr.push,push=arr.push,slice=arr.slice,indexOf=arr.indexOf||function(elem){var i=0,len=this.length;for(;i+~]|"+whitespace+")"+whitespace+"*"),rattributeQuotes=new RegExp("="+whitespace+"*([^\\]'\"]*?)"+whitespace+"*\\]","g"),rpseudo=new RegExp(pseudos),ridentifier=new RegExp("^"+identifier+"$"),matchExpr={ID:new RegExp("^#("+characterEncoding+")"),CLASS:new RegExp("^\\.("+characterEncoding+")"),TAG:new RegExp("^("+characterEncoding.replace("w","w*")+")"),ATTR:new RegExp("^"+attributes),PSEUDO:new RegExp("^"+pseudos),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+whitespace+"*(even|odd|(([+-]|)(\\d*)n|)"+whitespace+"*(?:([+-]|)"+whitespace+"*(\\d+)|))"+whitespace+"*\\)|)","i"),bool:new RegExp("^(?:"+booleans+")$","i"),needsContext:new RegExp("^"+whitespace+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+whitespace+"*((?:-\\d)?\\d*)"+whitespace+"*\\)|)(?=[^-]|$)","i")},rinputs=/^(?:input|select|textarea|button)$/i,rheader=/^h\d$/i,rnative=/^[^{]+\{\s*\[native \w/,rquickExpr=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,rsibling=/[+~]/,rescape=/'|\\/g,runescape=new RegExp("\\\\([\\da-f]{1,6}"+whitespace+"?|("+whitespace+")|.)","ig"),funescape=function(_,escaped,escapedWhitespace){var high="0x"+escaped-65536;return high!==high||escapedWhitespace?escaped:high<0?String.fromCharCode(high+65536):String.fromCharCode(high>>10|55296,high&1023|56320)};try{push.apply(arr=slice.call(preferredDoc.childNodes),preferredDoc.childNodes);arr[preferredDoc.childNodes.length].nodeType}catch(e){push={apply:arr.length?function(target,els){push_native.apply(target,slice.call(els))}:function(target,els){var j=target.length,i=0;while(target[j++]=els[i++]){}target.length=j-1}}}function Sizzle(selector,context,results,seed){var match,elem,m,nodeType,i,groups,old,nid,newContext,newSelector;if((context?context.ownerDocument||context:preferredDoc)!==document){setDocument(context)}context=context||document;results=results||[];if(!selector||typeof selector!=="string"){return results}if((nodeType=context.nodeType)!==1&&nodeType!==9){return[]}if(documentIsHTML&&!seed){if(match=rquickExpr.exec(selector)){if(m=match[1]){if(nodeType===9){elem=context.getElementById(m);if(elem&&elem.parentNode){if(elem.id===m){results.push(elem);return results}}else{return results}}else{if(context.ownerDocument&&(elem=context.ownerDocument.getElementById(m))&&contains(context,elem)&&elem.id===m){results.push(elem);return results}}}else if(match[2]){push.apply(results,context.getElementsByTagName(selector));return results}else if((m=match[3])&&support.getElementsByClassName&&context.getElementsByClassName){push.apply(results,context.getElementsByClassName(m));return results}}if(support.qsa&&(!rbuggyQSA||!rbuggyQSA.test(selector))){nid=old=expando;newContext=context;newSelector=nodeType===9&&selector;if(nodeType===1&&context.nodeName.toLowerCase()!=="object"){groups=tokenize(selector);if(old=context.getAttribute("id")){nid=old.replace(rescape,"\\$&")}else{context.setAttribute("id",nid)}nid="[id='"+nid+"'] ";i=groups.length;while(i--){groups[i]=nid+toSelector(groups[i])}newContext=rsibling.test(selector)&&testContext(context.parentNode)||context;newSelector=groups.join(",")}if(newSelector){try{push.apply(results,newContext.querySelectorAll(newSelector));return results}catch(qsaError){}finally{if(!old){context.removeAttribute("id")}}}}}return select(selector.replace(rtrim,"$1"),context,results,seed)}function createCache(){var keys=[];function cache(key,value){if(keys.push(key+" ")>Expr.cacheLength){delete cache[keys.shift()]}return cache[key+" "]=value}return cache}function markFunction(fn){fn[expando]=true;return fn}function assert(fn){var div=document.createElement("div");try{return!!fn(div)}catch(e){return false}finally{if(div.parentNode){div.parentNode.removeChild(div)}div=null}}function addHandle(attrs,handler){var arr=attrs.split("|"),i=attrs.length;while(i--){Expr.attrHandle[arr[i]]=handler}}function siblingCheck(a,b){var cur=b&&a,diff=cur&&a.nodeType===1&&b.nodeType===1&&(~b.sourceIndex||MAX_NEGATIVE)-(~a.sourceIndex||MAX_NEGATIVE);if(diff){return diff}if(cur){while(cur=cur.nextSibling){if(cur===b){return-1}}}return a?1:-1}function createInputPseudo(type){return function(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&elem.type===type}}function createButtonPseudo(type){return function(elem){var name=elem.nodeName.toLowerCase();return(name==="input"||name==="button")&&elem.type===type}}function createPositionalPseudo(fn){return markFunction(function(argument){argument=+argument;return markFunction(function(seed,matches){var j,matchIndexes=fn([],seed.length,argument),i=matchIndexes.length;while(i--){if(seed[j=matchIndexes[i]]){seed[j]=!(matches[j]=seed[j])}}})})}function testContext(context){return context&&typeof context.getElementsByTagName!==strundefined&&context}support=Sizzle.support={};isXML=Sizzle.isXML=function(elem){var documentElement=elem&&(elem.ownerDocument||elem).documentElement;return documentElement?documentElement.nodeName!=="HTML":false};setDocument=Sizzle.setDocument=function(node){var hasCompare,doc=node?node.ownerDocument||node:preferredDoc,parent=doc.defaultView;if(doc===document||doc.nodeType!==9||!doc.documentElement){return document}document=doc;docElem=doc.documentElement;documentIsHTML=!isXML(doc);if(parent&&parent!==parent.top){if(parent.addEventListener){parent.addEventListener("unload",function(){setDocument()},false)}else if(parent.attachEvent){parent.attachEvent("onunload",function(){setDocument()})}}support.attributes=assert(function(div){div.className="i";return!div.getAttribute("className")});support.getElementsByTagName=assert(function(div){div.appendChild(doc.createComment(""));return!div.getElementsByTagName("*").length});support.getElementsByClassName=rnative.test(doc.getElementsByClassName)&&assert(function(div){div.innerHTML="

";div.firstChild.className="i";return div.getElementsByClassName("i").length===2});support.getById=assert(function(div){docElem.appendChild(div).id=expando;return!doc.getElementsByName||!doc.getElementsByName(expando).length});if(support.getById){Expr.find["ID"]=function(id,context){if(typeof context.getElementById!==strundefined&&documentIsHTML){var m=context.getElementById(id);return m&&m.parentNode?[m]:[]}};Expr.filter["ID"]=function(id){var attrId=id.replace(runescape,funescape);return function(elem){return elem.getAttribute("id")===attrId}}}else{delete Expr.find["ID"];Expr.filter["ID"]=function(id){var attrId=id.replace(runescape,funescape);return function(elem){var node=typeof elem.getAttributeNode!==strundefined&&elem.getAttributeNode("id");return node&&node.value===attrId}}}Expr.find["TAG"]=support.getElementsByTagName?function(tag,context){if(typeof context.getElementsByTagName!==strundefined){return context.getElementsByTagName(tag)}}:function(tag,context){var elem,tmp=[],i=0,results=context.getElementsByTagName(tag);if(tag==="*"){while(elem=results[i++]){if(elem.nodeType===1){tmp.push(elem)}}return tmp}return results};Expr.find["CLASS"]=support.getElementsByClassName&&function(className,context){if(typeof context.getElementsByClassName!==strundefined&&documentIsHTML){return context.getElementsByClassName(className)}};rbuggyMatches=[];rbuggyQSA=[];if(support.qsa=rnative.test(doc.querySelectorAll)){assert(function(div){div.innerHTML="";if(div.querySelectorAll("[msallowclip^='']").length){rbuggyQSA.push("[*^$]="+whitespace+"*(?:''|\"\")")}if(!div.querySelectorAll("[selected]").length){rbuggyQSA.push("\\["+whitespace+"*(?:value|"+booleans+")")}if(!div.querySelectorAll(":checked").length){rbuggyQSA.push(":checked")}});assert(function(div){var input=doc.createElement("input");input.setAttribute("type","hidden");div.appendChild(input).setAttribute("name","D");if(div.querySelectorAll("[name=d]").length){rbuggyQSA.push("name"+whitespace+"*[*^$|!~]?=")}if(!div.querySelectorAll(":enabled").length){rbuggyQSA.push(":enabled",":disabled")}div.querySelectorAll("*,:x");rbuggyQSA.push(",.*:")})}if(support.matchesSelector=rnative.test(matches=docElem.matches||docElem.webkitMatchesSelector||docElem.mozMatchesSelector||docElem.oMatchesSelector||docElem.msMatchesSelector)){assert(function(div){support.disconnectedMatch=matches.call(div,"div");matches.call(div,"[s!='']:x");rbuggyMatches.push("!=",pseudos)})}rbuggyQSA=rbuggyQSA.length&&new RegExp(rbuggyQSA.join("|"));rbuggyMatches=rbuggyMatches.length&&new RegExp(rbuggyMatches.join("|"));hasCompare=rnative.test(docElem.compareDocumentPosition);contains=hasCompare||rnative.test(docElem.contains)?function(a,b){var adown=a.nodeType===9?a.documentElement:a,bup=b&&b.parentNode;return a===bup||!!(bup&&bup.nodeType===1&&(adown.contains?adown.contains(bup):a.compareDocumentPosition&&a.compareDocumentPosition(bup)&16))}:function(a,b){if(b){while(b=b.parentNode){if(b===a){return true}}}return false};sortOrder=hasCompare?function(a,b){if(a===b){hasDuplicate=true;return 0}var compare=!a.compareDocumentPosition-!b.compareDocumentPosition;if(compare){return compare}compare=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1;if(compare&1||!support.sortDetached&&b.compareDocumentPosition(a)===compare){if(a===doc||a.ownerDocument===preferredDoc&&contains(preferredDoc,a)){return-1}if(b===doc||b.ownerDocument===preferredDoc&&contains(preferredDoc,b)){return 1}return sortInput?indexOf.call(sortInput,a)-indexOf.call(sortInput,b):0}return compare&4?-1:1}:function(a,b){if(a===b){hasDuplicate=true;return 0}var cur,i=0,aup=a.parentNode,bup=b.parentNode,ap=[a],bp=[b];if(!aup||!bup){return a===doc?-1:b===doc?1:aup?-1:bup?1:sortInput?indexOf.call(sortInput,a)-indexOf.call(sortInput,b):0}else if(aup===bup){return siblingCheck(a,b)}cur=a;while(cur=cur.parentNode){ap.unshift(cur)}cur=b;while(cur=cur.parentNode){bp.unshift(cur)}while(ap[i]===bp[i]){i++}return i?siblingCheck(ap[i],bp[i]):ap[i]===preferredDoc?-1:bp[i]===preferredDoc?1:0};return doc};Sizzle.matches=function(expr,elements){return Sizzle(expr,null,null,elements)};Sizzle.matchesSelector=function(elem,expr){if((elem.ownerDocument||elem)!==document){setDocument(elem)}expr=expr.replace(rattributeQuotes,"='$1']");if(support.matchesSelector&&documentIsHTML&&(!rbuggyMatches||!rbuggyMatches.test(expr))&&(!rbuggyQSA||!rbuggyQSA.test(expr))){try{var ret=matches.call(elem,expr);if(ret||support.disconnectedMatch||elem.document&&elem.document.nodeType!==11){return ret}}catch(e){}}return Sizzle(expr,document,null,[elem]).length>0};Sizzle.contains=function(context,elem){if((context.ownerDocument||context)!==document){setDocument(context)}return contains(context,elem)};Sizzle.attr=function(elem,name){if((elem.ownerDocument||elem)!==document){setDocument(elem)}var fn=Expr.attrHandle[name.toLowerCase()],val=fn&&hasOwn.call(Expr.attrHandle,name.toLowerCase())?fn(elem,name,!documentIsHTML):undefined;return val!==undefined?val:support.attributes||!documentIsHTML?elem.getAttribute(name):(val=elem.getAttributeNode(name))&&val.specified?val.value:null};Sizzle.error=function(msg){throw new Error("Syntax error, unrecognized expression: "+msg)};Sizzle.uniqueSort=function(results){var elem,duplicates=[],j=0,i=0;hasDuplicate=!support.detectDuplicates;sortInput=!support.sortStable&&results.slice(0);results.sort(sortOrder);if(hasDuplicate){while(elem=results[i++]){if(elem===results[i]){j=duplicates.push(i)}}while(j--){results.splice(duplicates[j],1)}}sortInput=null;return results};getText=Sizzle.getText=function(elem){var node,ret="",i=0,nodeType=elem.nodeType;if(!nodeType){while(node=elem[i++]){ret+=getText(node)}}else if(nodeType===1||nodeType===9||nodeType===11){if(typeof elem.textContent==="string"){return elem.textContent}else{for(elem=elem.firstChild;elem;elem=elem.nextSibling){ret+=getText(elem)}}}else if(nodeType===3||nodeType===4){return elem.nodeValue}return ret};Expr=Sizzle.selectors={cacheLength:50,createPseudo:markFunction,match:matchExpr,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(match){match[1]=match[1].replace(runescape,funescape);match[3]=(match[3]||match[4]||match[5]||"").replace(runescape,funescape);if(match[2]==="~="){match[3]=" "+match[3]+" "}return match.slice(0,4)},CHILD:function(match){match[1]=match[1].toLowerCase();if(match[1].slice(0,3)==="nth"){if(!match[3]){Sizzle.error(match[0])}match[4]=+(match[4]?match[5]+(match[6]||1):2*(match[3]==="even"||match[3]==="odd"));match[5]=+(match[7]+match[8]||match[3]==="odd")}else if(match[3]){Sizzle.error(match[0])}return match},PSEUDO:function(match){var excess,unquoted=!match[6]&&match[2];if(matchExpr["CHILD"].test(match[0])){return null}if(match[3]){match[2]=match[4]||match[5]||""}else if(unquoted&&rpseudo.test(unquoted)&&(excess=tokenize(unquoted,true))&&(excess=unquoted.indexOf(")",unquoted.length-excess)-unquoted.length)){match[0]=match[0].slice(0,excess);match[2]=unquoted.slice(0,excess)}return match.slice(0,3)}},filter:{TAG:function(nodeNameSelector){var nodeName=nodeNameSelector.replace(runescape,funescape).toLowerCase();return nodeNameSelector==="*"?function(){return true}:function(elem){return elem.nodeName&&elem.nodeName.toLowerCase()===nodeName}},CLASS:function(className){var pattern=classCache[className+" "];return pattern||(pattern=new RegExp("(^|"+whitespace+")"+className+"("+whitespace+"|$)"))&&classCache(className,function(elem){return pattern.test(typeof elem.className==="string"&&elem.className||typeof elem.getAttribute!==strundefined&&elem.getAttribute("class")||"")})},ATTR:function(name,operator,check){return function(elem){var result=Sizzle.attr(elem,name);if(result==null){return operator==="!="}if(!operator){return true}result+="";return operator==="="?result===check:operator==="!="?result!==check:operator==="^="?check&&result.indexOf(check)===0:operator==="*="?check&&result.indexOf(check)>-1:operator==="$="?check&&result.slice(-check.length)===check:operator==="~="?(" "+result+" ").indexOf(check)>-1:operator==="|="?result===check||result.slice(0,check.length+1)===check+"-":false}},CHILD:function(type,what,argument,first,last){var simple=type.slice(0,3)!=="nth",forward=type.slice(-4)!=="last",ofType=what==="of-type";return first===1&&last===0?function(elem){return!!elem.parentNode}:function(elem,context,xml){var cache,outerCache,node,diff,nodeIndex,start,dir=simple!==forward?"nextSibling":"previousSibling",parent=elem.parentNode,name=ofType&&elem.nodeName.toLowerCase(),useCache=!xml&&!ofType;if(parent){if(simple){while(dir){node=elem;while(node=node[dir]){if(ofType?node.nodeName.toLowerCase()===name:node.nodeType===1){return false}}start=dir=type==="only"&&!start&&"nextSibling"}return true}start=[forward?parent.firstChild:parent.lastChild];if(forward&&useCache){outerCache=parent[expando]||(parent[expando]={});cache=outerCache[type]||[];nodeIndex=cache[0]===dirruns&&cache[1];diff=cache[0]===dirruns&&cache[2];node=nodeIndex&&parent.childNodes[nodeIndex];while(node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop()){if(node.nodeType===1&&++diff&&node===elem){outerCache[type]=[dirruns,nodeIndex,diff];break}}}else if(useCache&&(cache=(elem[expando]||(elem[expando]={}))[type])&&cache[0]===dirruns){diff=cache[1]}else{while(node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop()){if((ofType?node.nodeName.toLowerCase()===name:node.nodeType===1)&&++diff){if(useCache){(node[expando]||(node[expando]={}))[type]=[dirruns,diff]}if(node===elem){break}}}}diff-=last;return diff===first||diff%first===0&&diff/first>=0}}},PSEUDO:function(pseudo,argument){var args,fn=Expr.pseudos[pseudo]||Expr.setFilters[pseudo.toLowerCase()]||Sizzle.error("unsupported pseudo: "+pseudo);if(fn[expando]){return fn(argument)}if(fn.length>1){args=[pseudo,pseudo,"",argument];return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase())?markFunction(function(seed,matches){var idx,matched=fn(seed,argument),i=matched.length;while(i--){idx=indexOf.call(seed,matched[i]);seed[idx]=!(matches[idx]=matched[i])}}):function(elem){return fn(elem,0,args)}}return fn}},pseudos:{not:markFunction(function(selector){var input=[],results=[],matcher=compile(selector.replace(rtrim,"$1"));return matcher[expando]?markFunction(function(seed,matches,context,xml){var elem,unmatched=matcher(seed,null,xml,[]),i=seed.length;while(i--){if(elem=unmatched[i]){seed[i]=!(matches[i]=elem)}}}):function(elem,context,xml){input[0]=elem;matcher(input,null,xml,results);return!results.pop()}}),has:markFunction(function(selector){return function(elem){return Sizzle(selector,elem).length>0}}),contains:markFunction(function(text){return function(elem){return(elem.textContent||elem.innerText||getText(elem)).indexOf(text)>-1}}),lang:markFunction(function(lang){if(!ridentifier.test(lang||"")){Sizzle.error("unsupported lang: "+lang)}lang=lang.replace(runescape,funescape).toLowerCase();return function(elem){var elemLang;do{if(elemLang=documentIsHTML?elem.lang:elem.getAttribute("xml:lang")||elem.getAttribute("lang")){elemLang=elemLang.toLowerCase();return elemLang===lang||elemLang.indexOf(lang+"-")===0}}while((elem=elem.parentNode)&&elem.nodeType===1);return false}}),target:function(elem){var hash=window.location&&window.location.hash;return hash&&hash.slice(1)===elem.id},root:function(elem){return elem===docElem},focus:function(elem){return elem===document.activeElement&&(!document.hasFocus||document.hasFocus())&&!!(elem.type||elem.href||~elem.tabIndex)},enabled:function(elem){return elem.disabled===false},disabled:function(elem){return elem.disabled===true},checked:function(elem){var nodeName=elem.nodeName.toLowerCase();return nodeName==="input"&&!!elem.checked||nodeName==="option"&&!!elem.selected},selected:function(elem){if(elem.parentNode){elem.parentNode.selectedIndex}return elem.selected===true},empty:function(elem){for(elem=elem.firstChild;elem;elem=elem.nextSibling){if(elem.nodeType<6){return false}}return true},parent:function(elem){return!Expr.pseudos["empty"](elem)},header:function(elem){return rheader.test(elem.nodeName)},input:function(elem){return rinputs.test(elem.nodeName)},button:function(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&elem.type==="button"||name==="button"},text:function(elem){var attr;return elem.nodeName.toLowerCase()==="input"&&elem.type==="text"&&((attr=elem.getAttribute("type"))==null||attr.toLowerCase()==="text")},first:createPositionalPseudo(function(){return[0]}),last:createPositionalPseudo(function(matchIndexes,length){return[length-1]}),eq:createPositionalPseudo(function(matchIndexes,length,argument){return[argument<0?argument+length:argument]}),even:createPositionalPseudo(function(matchIndexes,length){var i=0;for(;i=0;){matchIndexes.push(i)}return matchIndexes}),gt:createPositionalPseudo(function(matchIndexes,length,argument){var i=argument<0?argument+length:argument;for(;++i1?function(elem,context,xml){var i=matchers.length;while(i--){if(!matchers[i](elem,context,xml)){return false}}return true}:matchers[0]}function multipleContexts(selector,contexts,results){var i=0,len=contexts.length;for(;i-1){seed[temp]=!(results[temp]=elem)}}}}else{matcherOut=condense(matcherOut===results?matcherOut.splice(preexisting,matcherOut.length):matcherOut);if(postFinder){postFinder(null,results,matcherOut,xml)}else{push.apply(results,matcherOut)}}})}function matcherFromTokens(tokens){var checkContext,matcher,j,len=tokens.length,leadingRelative=Expr.relative[tokens[0].type],implicitRelative=leadingRelative||Expr.relative[" "],i=leadingRelative?1:0,matchContext=addCombinator(function(elem){return elem===checkContext},implicitRelative,true),matchAnyContext=addCombinator(function(elem){return indexOf.call(checkContext,elem)>-1},implicitRelative,true),matchers=[function(elem,context,xml){return!leadingRelative&&(xml||context!==outermostContext)||((checkContext=context).nodeType?matchContext(elem,context,xml):matchAnyContext(elem,context,xml))}];for(;i1&&elementMatcher(matchers),i>1&&toSelector(tokens.slice(0,i-1).concat({value:tokens[i-2].type===" "?"*":""})).replace(rtrim,"$1"),matcher,i0,byElement=elementMatchers.length>0,superMatcher=function(seed,context,xml,results,outermost){var elem,j,matcher,matchedCount=0,i="0",unmatched=seed&&[],setMatched=[],contextBackup=outermostContext,elems=seed||byElement&&Expr.find["TAG"]("*",outermost),dirrunsUnique=dirruns+=contextBackup==null?1:Math.random()||.1,len=elems.length;if(outermost){outermostContext=context!==document&&context}for(;i!==len&&(elem=elems[i])!=null;i++){if(byElement&&elem){j=0;while(matcher=elementMatchers[j++]){if(matcher(elem,context,xml)){results.push(elem);break}}if(outermost){dirruns=dirrunsUnique}}if(bySet){if(elem=!matcher&&elem){matchedCount--}if(seed){unmatched.push(elem)}}}matchedCount+=i;if(bySet&&i!==matchedCount){j=0;while(matcher=setMatchers[j++]){matcher(unmatched,setMatched,context,xml)}if(seed){if(matchedCount>0){while(i--){if(!(unmatched[i]||setMatched[i])){setMatched[i]=pop.call(results)}}}setMatched=condense(setMatched)}push.apply(results,setMatched);if(outermost&&!seed&&setMatched.length>0&&matchedCount+setMatchers.length>1){Sizzle.uniqueSort(results)}}if(outermost){dirruns=dirrunsUnique;outermostContext=contextBackup}return unmatched};return bySet?markFunction(superMatcher):superMatcher}compile=Sizzle.compile=function(selector,match){var i,setMatchers=[],elementMatchers=[],cached=compilerCache[selector+" "];if(!cached){if(!match){match=tokenize(selector)}i=match.length;while(i--){cached=matcherFromTokens(match[i]);if(cached[expando]){setMatchers.push(cached)}else{elementMatchers.push(cached)}}cached=compilerCache(selector,matcherFromGroupMatchers(elementMatchers,setMatchers));cached.selector=selector}return cached};select=Sizzle.select=function(selector,context,results,seed){var i,tokens,token,type,find,compiled=typeof selector==="function"&&selector,match=!seed&&tokenize(selector=compiled.selector||selector);results=results||[];if(match.length===1){tokens=match[0]=match[0].slice(0);if(tokens.length>2&&(token=tokens[0]).type==="ID"&&support.getById&&context.nodeType===9&&documentIsHTML&&Expr.relative[tokens[1].type]){context=(Expr.find["ID"](token.matches[0].replace(runescape,funescape),context)||[])[0];if(!context){return results}else if(compiled){context=context.parentNode}selector=selector.slice(tokens.shift().value.length)}i=matchExpr["needsContext"].test(selector)?0:tokens.length;while(i--){token=tokens[i];if(Expr.relative[type=token.type]){break}if(find=Expr.find[type]){if(seed=find(token.matches[0].replace(runescape,funescape),rsibling.test(tokens[0].type)&&testContext(context.parentNode)||context)){tokens.splice(i,1);selector=seed.length&&toSelector(tokens);if(!selector){push.apply(results,seed);return results}break}}}}(compiled||compile(selector,match))(seed,context,!documentIsHTML,results,rsibling.test(selector)&&testContext(context.parentNode)||context);return results};support.sortStable=expando.split("").sort(sortOrder).join("")===expando;support.detectDuplicates=!!hasDuplicate;setDocument();support.sortDetached=assert(function(div1){return div1.compareDocumentPosition(document.createElement("div"))&1});if(!assert(function(div){div.innerHTML="";return div.firstChild.getAttribute("href")==="#"})){addHandle("type|href|height|width",function(elem,name,isXML){if(!isXML){return elem.getAttribute(name,name.toLowerCase()==="type"?1:2)}})}if(!support.attributes||!assert(function(div){div.innerHTML="";div.firstChild.setAttribute("value","");return div.firstChild.getAttribute("value")===""})){addHandle("value",function(elem,name,isXML){if(!isXML&&elem.nodeName.toLowerCase()==="input"){return elem.defaultValue}})}if(!assert(function(div){return div.getAttribute("disabled")==null})){addHandle(booleans,function(elem,name,isXML){var val;if(!isXML){return elem[name]===true?name.toLowerCase():(val=elem.getAttributeNode(name))&&val.specified?val.value:null}})}return Sizzle}(window);jQuery.find=Sizzle;jQuery.expr=Sizzle.selectors;jQuery.expr[":"]=jQuery.expr.pseudos;jQuery.unique=Sizzle.uniqueSort;jQuery.text=Sizzle.getText;jQuery.isXMLDoc=Sizzle.isXML;jQuery.contains=Sizzle.contains;var rneedsContext=jQuery.expr.match.needsContext;var rsingleTag=/^<(\w+)\s*\/?>(?:<\/\1>|)$/;var risSimple=/^.[^:#\[\.,]*$/;function winnow(elements,qualifier,not){if(jQuery.isFunction(qualifier)){return jQuery.grep(elements,function(elem,i){return!!qualifier.call(elem,i,elem)!==not})}if(qualifier.nodeType){return jQuery.grep(elements,function(elem){return elem===qualifier!==not})}if(typeof qualifier==="string"){if(risSimple.test(qualifier)){return jQuery.filter(qualifier,elements,not)}qualifier=jQuery.filter(qualifier,elements)}return jQuery.grep(elements,function(elem){return indexOf.call(qualifier,elem)>=0!==not})}jQuery.filter=function(expr,elems,not){var elem=elems[0];if(not){expr=":not("+expr+")"}return elems.length===1&&elem.nodeType===1?jQuery.find.matchesSelector(elem,expr)?[elem]:[]:jQuery.find.matches(expr,jQuery.grep(elems,function(elem){return elem.nodeType===1}))};jQuery.fn.extend({find:function(selector){var i,len=this.length,ret=[],self=this;if(typeof selector!=="string"){return this.pushStack(jQuery(selector).filter(function(){for(i=0;i1?jQuery.unique(ret):ret);ret.selector=this.selector?this.selector+" "+selector:selector;return ret},filter:function(selector){return this.pushStack(winnow(this,selector||[],false))},not:function(selector){return this.pushStack(winnow(this,selector||[],true))},is:function(selector){return!!winnow(this,typeof selector==="string"&&rneedsContext.test(selector)?jQuery(selector):selector||[],false).length}});var rootjQuery,rquickExpr=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,init=jQuery.fn.init=function(selector,context){var match,elem;if(!selector){return this}if(typeof selector==="string"){if(selector[0]==="<"&&selector[selector.length-1]===">"&&selector.length>=3){match=[null,selector,null]}else{match=rquickExpr.exec(selector)}if(match&&(match[1]||!context)){if(match[1]){context=context instanceof jQuery?context[0]:context;jQuery.merge(this,jQuery.parseHTML(match[1],context&&context.nodeType?context.ownerDocument||context:document,true));if(rsingleTag.test(match[1])&&jQuery.isPlainObject(context)){for(match in context){if(jQuery.isFunction(this[match])){this[match](context[match])}else{this.attr(match,context[match])}}}return this}else{elem=document.getElementById(match[2]);if(elem&&elem.parentNode){this.length=1;this[0]=elem}this.context=document;this.selector=selector;return this}}else if(!context||context.jquery){return(context||rootjQuery).find(selector)}else{return this.constructor(context).find(selector)}}else if(selector.nodeType){this.context=this[0]=selector;this.length=1;return this}else if(jQuery.isFunction(selector)){return typeof rootjQuery.ready!=="undefined"?rootjQuery.ready(selector):selector(jQuery)}if(selector.selector!==undefined){this.selector=selector.selector;this.context=selector.context}return jQuery.makeArray(selector,this)};init.prototype=jQuery.fn;rootjQuery=jQuery(document);var rparentsprev=/^(?:parents|prev(?:Until|All))/,guaranteedUnique={children:true,contents:true,next:true,prev:true};jQuery.extend({dir:function(elem,dir,until){var matched=[],truncate=until!==undefined;while((elem=elem[dir])&&elem.nodeType!==9){if(elem.nodeType===1){if(truncate&&jQuery(elem).is(until)){break}matched.push(elem)}}return matched},sibling:function(n,elem){var matched=[];for(;n;n=n.nextSibling){if(n.nodeType===1&&n!==elem){matched.push(n)}}return matched}});jQuery.fn.extend({has:function(target){var targets=jQuery(target,this),l=targets.length;return this.filter(function(){var i=0;for(;i-1:cur.nodeType===1&&jQuery.find.matchesSelector(cur,selectors))){matched.push(cur);break}}}return this.pushStack(matched.length>1?jQuery.unique(matched):matched)},index:function(elem){if(!elem){return this[0]&&this[0].parentNode?this.first().prevAll().length:-1}if(typeof elem==="string"){return indexOf.call(jQuery(elem),this[0])}return indexOf.call(this,elem.jquery?elem[0]:elem)},add:function(selector,context){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),jQuery(selector,context))))},addBack:function(selector){return this.add(selector==null?this.prevObject:this.prevObject.filter(selector))}});function sibling(cur,dir){while((cur=cur[dir])&&cur.nodeType!==1){}return cur}jQuery.each({parent:function(elem){var parent=elem.parentNode;return parent&&parent.nodeType!==11?parent:null},parents:function(elem){return jQuery.dir(elem,"parentNode")},parentsUntil:function(elem,i,until){return jQuery.dir(elem,"parentNode",until)},next:function(elem){return sibling(elem,"nextSibling")},prev:function(elem){return sibling(elem,"previousSibling")},nextAll:function(elem){return jQuery.dir(elem,"nextSibling")},prevAll:function(elem){return jQuery.dir(elem,"previousSibling")},nextUntil:function(elem,i,until){return jQuery.dir(elem,"nextSibling",until)},prevUntil:function(elem,i,until){return jQuery.dir(elem,"previousSibling",until)},siblings:function(elem){return jQuery.sibling((elem.parentNode||{}).firstChild,elem)},children:function(elem){return jQuery.sibling(elem.firstChild)},contents:function(elem){return elem.contentDocument||jQuery.merge([],elem.childNodes)}},function(name,fn){jQuery.fn[name]=function(until,selector){var matched=jQuery.map(this,fn,until);if(name.slice(-5)!=="Until"){selector=until}if(selector&&typeof selector==="string"){matched=jQuery.filter(selector,matched)}if(this.length>1){if(!guaranteedUnique[name]){jQuery.unique(matched)}if(rparentsprev.test(name)){matched.reverse()}}return this.pushStack(matched)}});var rnotwhite=/\S+/g;var optionsCache={};function createOptions(options){var object=optionsCache[options]={};jQuery.each(options.match(rnotwhite)||[],function(_,flag){object[flag]=true});return object}jQuery.Callbacks=function(options){options=typeof options==="string"?optionsCache[options]||createOptions(options):jQuery.extend({},options);var memory,fired,firing,firingStart,firingLength,firingIndex,list=[],stack=!options.once&&[],fire=function(data){memory=options.memory&&data;fired=true;firingIndex=firingStart||0;firingStart=0;firingLength=list.length;firing=true;for(;list&&firingIndex-1){list.splice(index,1);if(firing){if(index<=firingLength){firingLength--}if(index<=firingIndex){firingIndex--}}}})}return this},has:function(fn){return fn?jQuery.inArray(fn,list)>-1:!!(list&&list.length)},empty:function(){list=[];firingLength=0;return this},disable:function(){list=stack=memory=undefined;return this},disabled:function(){return!list},lock:function(){stack=undefined;if(!memory){self.disable()}return this},locked:function(){return!stack},fireWith:function(context,args){if(list&&(!fired||stack)){args=args||[];args=[context,args.slice?args.slice():args];if(firing){stack.push(args)}else{fire(args)}}return this},fire:function(){self.fireWith(this,arguments);return this},fired:function(){return!!fired}};return self};jQuery.extend({Deferred:function(func){var tuples=[["resolve","done",jQuery.Callbacks("once memory"),"resolved"],["reject","fail",jQuery.Callbacks("once memory"),"rejected"],["notify","progress",jQuery.Callbacks("memory")]],state="pending",promise={state:function(){return state},always:function(){deferred.done(arguments).fail(arguments);return this},then:function(){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var fn=jQuery.isFunction(fns[i])&&fns[i];deferred[tuple[1]](function(){var returned=fn&&fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().done(newDefer.resolve).fail(newDefer.reject).progress(newDefer.notify)}else{newDefer[tuple[0]+"With"](this===promise?newDefer.promise():this,fn?[returned]:arguments)}})});fns=null}).promise()},promise:function(obj){return obj!=null?jQuery.extend(obj,promise):promise}},deferred={};promise.pipe=promise.then;jQuery.each(tuples,function(i,tuple){var list=tuple[2],stateString=tuple[3];promise[tuple[1]]=list.add;if(stateString){list.add(function(){state=stateString},tuples[i^1][2].disable,tuples[2][2].lock)}deferred[tuple[0]]=function(){deferred[tuple[0]+"With"](this===deferred?promise:this,arguments);return this};deferred[tuple[0]+"With"]=list.fireWith});promise.promise(deferred);if(func){func.call(deferred,deferred)}return deferred},when:function(subordinate){var i=0,resolveValues=slice.call(arguments),length=resolveValues.length,remaining=length!==1||subordinate&&jQuery.isFunction(subordinate.promise)?length:0,deferred=remaining===1?subordinate:jQuery.Deferred(),updateFunc=function(i,contexts,values){return function(value){contexts[i]=this;values[i]=arguments.length>1?slice.call(arguments):value;if(values===progressValues){deferred.notifyWith(contexts,values)}else if(!--remaining){deferred.resolveWith(contexts,values)}}},progressValues,progressContexts,resolveContexts;if(length>1){progressValues=new Array(length);progressContexts=new Array(length);resolveContexts=new Array(length);for(;i0){return}readyList.resolveWith(document,[jQuery]);if(jQuery.fn.triggerHandler){jQuery(document).triggerHandler("ready");jQuery(document).off("ready")}}});function completed(){document.removeEventListener("DOMContentLoaded",completed,false);window.removeEventListener("load",completed,false);jQuery.ready()}jQuery.ready.promise=function(obj){if(!readyList){readyList=jQuery.Deferred();if(document.readyState==="complete"){setTimeout(jQuery.ready)}else{document.addEventListener("DOMContentLoaded",completed,false);window.addEventListener("load",completed,false)}}return readyList.promise(obj)};jQuery.ready.promise();var access=jQuery.access=function(elems,fn,key,value,chainable,emptyGet,raw){var i=0,len=elems.length,bulk=key==null;if(jQuery.type(key)==="object"){chainable=true;for(i in key){jQuery.access(elems,fn,i,key[i],true,emptyGet,raw)}}else if(value!==undefined){chainable=true;if(!jQuery.isFunction(value)){raw=true}if(bulk){if(raw){fn.call(elems,value);fn=null}else{bulk=fn;fn=function(elem,key,value){return bulk.call(jQuery(elem),value)}}}if(fn){for(;i1,null,true)},removeData:function(key){return this.each(function(){data_user.remove(this,key)})}});jQuery.extend({queue:function(elem,type,data){var queue;if(elem){type=(type||"fx")+"queue";queue=data_priv.get(elem,type);if(data){if(!queue||jQuery.isArray(data)){queue=data_priv.access(elem,type,jQuery.makeArray(data))}else{queue.push(data)}}return queue||[]}},dequeue:function(elem,type){type=type||"fx";var queue=jQuery.queue(elem,type),startLength=queue.length,fn=queue.shift(),hooks=jQuery._queueHooks(elem,type),next=function(){jQuery.dequeue(elem,type)};if(fn==="inprogress"){fn=queue.shift();startLength--}if(fn){if(type==="fx"){queue.unshift("inprogress")}delete hooks.stop;fn.call(elem,next,hooks)}if(!startLength&&hooks){hooks.empty.fire()}},_queueHooks:function(elem,type){var key=type+"queueHooks";return data_priv.get(elem,key)||data_priv.access(elem,key,{empty:jQuery.Callbacks("once memory").add(function(){data_priv.remove(elem,[type+"queue",key])})})}});jQuery.fn.extend({queue:function(type,data){var setter=2;if(typeof type!=="string"){data=type;type="fx";setter--}if(arguments.lengthx";support.noCloneChecked=!!div.cloneNode(true).lastChild.defaultValue})();var strundefined=typeof undefined;support.focusinBubbles="onfocusin"in window;var rkeyEvent=/^key/,rmouseEvent=/^(?:mouse|pointer|contextmenu)|click/,rfocusMorph=/^(?:focusinfocus|focusoutblur)$/,rtypenamespace=/^([^.]*)(?:\.(.+)|)$/;function returnTrue(){return true}function returnFalse(){return false}function safeActiveElement(){try{return document.activeElement}catch(err){}}jQuery.event={global:{},add:function(elem,types,handler,data,selector){var handleObjIn,eventHandle,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=data_priv.get(elem);if(!elemData){return}if(handler.handler){handleObjIn=handler;handler=handleObjIn.handler;selector=handleObjIn.selector}if(!handler.guid){handler.guid=jQuery.guid++}if(!(events=elemData.events)){events=elemData.events={}}if(!(eventHandle=elemData.handle)){eventHandle=elemData.handle=function(e){return typeof jQuery!==strundefined&&jQuery.event.triggered!==e.type?jQuery.event.dispatch.apply(elem,arguments):undefined}}types=(types||"").match(rnotwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){continue}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;special=jQuery.event.special[type]||{};handleObj=jQuery.extend({type:type,origType:origType,data:data,handler:handler,guid:handler.guid,selector:selector,needsContext:selector&&jQuery.expr.match.needsContext.test(selector),namespace:namespaces.join(".")},handleObjIn);if(!(handlers=events[type])){handlers=events[type]=[];handlers.delegateCount=0;if(!special.setup||special.setup.call(elem,data,namespaces,eventHandle)===false){if(elem.addEventListener){elem.addEventListener(type,eventHandle,false)}}}if(special.add){special.add.call(elem,handleObj);if(!handleObj.handler.guid){handleObj.handler.guid=handler.guid}}if(selector){handlers.splice(handlers.delegateCount++,0,handleObj)}else{handlers.push(handleObj)}jQuery.event.global[type]=true}},remove:function(elem,types,handler,selector,mappedTypes){var j,origCount,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=data_priv.hasData(elem)&&data_priv.get(elem);if(!elemData||!(events=elemData.events)){return}types=(types||"").match(rnotwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){for(type in events){jQuery.event.remove(elem,type+types[t],handler,selector,true)}continue}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;handlers=events[type]||[];tmp=tmp[2]&&new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)");origCount=j=handlers.length;while(j--){handleObj=handlers[j];if((mappedTypes||origType===handleObj.origType)&&(!handler||handler.guid===handleObj.guid)&&(!tmp||tmp.test(handleObj.namespace))&&(!selector||selector===handleObj.selector||selector==="**"&&handleObj.selector)){handlers.splice(j,1);if(handleObj.selector){handlers.delegateCount--}if(special.remove){special.remove.call(elem,handleObj)}}}if(origCount&&!handlers.length){if(!special.teardown||special.teardown.call(elem,namespaces,elemData.handle)===false){jQuery.removeEvent(elem,type,elemData.handle)}delete events[type]}}if(jQuery.isEmptyObject(events)){delete elemData.handle;data_priv.remove(elem,"events")}},trigger:function(event,data,elem,onlyHandlers){var i,cur,tmp,bubbleType,ontype,handle,special,eventPath=[elem||document],type=hasOwn.call(event,"type")?event.type:event,namespaces=hasOwn.call(event,"namespace")?event.namespace.split("."):[];cur=tmp=elem=elem||document;if(elem.nodeType===3||elem.nodeType===8){return}if(rfocusMorph.test(type+jQuery.event.triggered)){return}if(type.indexOf(".")>=0){namespaces=type.split(".");type=namespaces.shift(); -namespaces.sort()}ontype=type.indexOf(":")<0&&"on"+type;event=event[jQuery.expando]?event:new jQuery.Event(type,typeof event==="object"&&event);event.isTrigger=onlyHandlers?2:3;event.namespace=namespaces.join(".");event.namespace_re=event.namespace?new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;event.result=undefined;if(!event.target){event.target=elem}data=data==null?[event]:jQuery.makeArray(data,[event]);special=jQuery.event.special[type]||{};if(!onlyHandlers&&special.trigger&&special.trigger.apply(elem,data)===false){return}if(!onlyHandlers&&!special.noBubble&&!jQuery.isWindow(elem)){bubbleType=special.delegateType||type;if(!rfocusMorph.test(bubbleType+type)){cur=cur.parentNode}for(;cur;cur=cur.parentNode){eventPath.push(cur);tmp=cur}if(tmp===(elem.ownerDocument||document)){eventPath.push(tmp.defaultView||tmp.parentWindow||window)}}i=0;while((cur=eventPath[i++])&&!event.isPropagationStopped()){event.type=i>1?bubbleType:special.bindType||type;handle=(data_priv.get(cur,"events")||{})[event.type]&&data_priv.get(cur,"handle");if(handle){handle.apply(cur,data)}handle=ontype&&cur[ontype];if(handle&&handle.apply&&jQuery.acceptData(cur)){event.result=handle.apply(cur,data);if(event.result===false){event.preventDefault()}}}event.type=type;if(!onlyHandlers&&!event.isDefaultPrevented()){if((!special._default||special._default.apply(eventPath.pop(),data)===false)&&jQuery.acceptData(elem)){if(ontype&&jQuery.isFunction(elem[type])&&!jQuery.isWindow(elem)){tmp=elem[ontype];if(tmp){elem[ontype]=null}jQuery.event.triggered=type;elem[type]();jQuery.event.triggered=undefined;if(tmp){elem[ontype]=tmp}}}}return event.result},dispatch:function(event){event=jQuery.event.fix(event);var i,j,ret,matched,handleObj,handlerQueue=[],args=slice.call(arguments),handlers=(data_priv.get(this,"events")||{})[event.type]||[],special=jQuery.event.special[event.type]||{};args[0]=event;event.delegateTarget=this;if(special.preDispatch&&special.preDispatch.call(this,event)===false){return}handlerQueue=jQuery.event.handlers.call(this,event,handlers);i=0;while((matched=handlerQueue[i++])&&!event.isPropagationStopped()){event.currentTarget=matched.elem;j=0;while((handleObj=matched.handlers[j++])&&!event.isImmediatePropagationStopped()){if(!event.namespace_re||event.namespace_re.test(handleObj.namespace)){event.handleObj=handleObj;event.data=handleObj.data;ret=((jQuery.event.special[handleObj.origType]||{}).handle||handleObj.handler).apply(matched.elem,args);if(ret!==undefined){if((event.result=ret)===false){event.preventDefault();event.stopPropagation()}}}}}if(special.postDispatch){special.postDispatch.call(this,event)}return event.result},handlers:function(event,handlers){var i,matches,sel,handleObj,handlerQueue=[],delegateCount=handlers.delegateCount,cur=event.target;if(delegateCount&&cur.nodeType&&(!event.button||event.type!=="click")){for(;cur!==this;cur=cur.parentNode||this){if(cur.disabled!==true||event.type!=="click"){matches=[];for(i=0;i=0:jQuery.find(sel,this,null,[cur]).length}if(matches[sel]){matches.push(handleObj)}}if(matches.length){handlerQueue.push({elem:cur,handlers:matches})}}}}if(delegateCount]*)\/>/gi,rtagName=/<([\w:]+)/,rhtml=/<|&#?\w+;/,rnoInnerhtml=/<(?:script|style|link)/i,rchecked=/checked\s*(?:[^=]|=\s*.checked.)/i,rscriptType=/^$|\/(?:java|ecma)script/i,rscriptTypeMasked=/^true\/(.*)/,rcleanScript=/^\s*\s*$/g,wrapMap={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};wrapMap.optgroup=wrapMap.option;wrapMap.tbody=wrapMap.tfoot=wrapMap.colgroup=wrapMap.caption=wrapMap.thead;wrapMap.th=wrapMap.td;function manipulationTarget(elem,content){return jQuery.nodeName(elem,"table")&&jQuery.nodeName(content.nodeType!==11?content:content.firstChild,"tr")?elem.getElementsByTagName("tbody")[0]||elem.appendChild(elem.ownerDocument.createElement("tbody")):elem}function disableScript(elem){elem.type=(elem.getAttribute("type")!==null)+"/"+elem.type;return elem}function restoreScript(elem){var match=rscriptTypeMasked.exec(elem.type);if(match){elem.type=match[1]}else{elem.removeAttribute("type")}return elem}function setGlobalEval(elems,refElements){var i=0,l=elems.length;for(;i0){setGlobalEval(destElements,!inPage&&getAll(elem,"script"))}return clone},buildFragment:function(elems,context,scripts,selection){var elem,tmp,tag,wrap,contains,j,fragment=context.createDocumentFragment(),nodes=[],i=0,l=elems.length;for(;i")+wrap[2];j=wrap[0];while(j--){tmp=tmp.lastChild}jQuery.merge(nodes,tmp.childNodes);tmp=fragment.firstChild;tmp.textContent=""}}}fragment.textContent="";i=0;while(elem=nodes[i++]){if(selection&&jQuery.inArray(elem,selection)!==-1){continue}contains=jQuery.contains(elem.ownerDocument,elem);tmp=getAll(fragment.appendChild(elem),"script");if(contains){setGlobalEval(tmp)}if(scripts){j=0;while(elem=tmp[j++]){if(rscriptType.test(elem.type||"")){scripts.push(elem)}}}}return fragment},cleanData:function(elems){var data,elem,type,key,special=jQuery.event.special,i=0;for(;(elem=elems[i])!==undefined;i++){if(jQuery.acceptData(elem)){key=elem[data_priv.expando];if(key&&(data=data_priv.cache[key])){if(data.events){for(type in data.events){if(special[type]){jQuery.event.remove(elem,type)}else{jQuery.removeEvent(elem,type,data.handle)}}}if(data_priv.cache[key]){delete data_priv.cache[key]}}}delete data_user.cache[elem[data_user.expando]]}}});jQuery.fn.extend({text:function(value){return access(this,function(value){return value===undefined?jQuery.text(this):this.empty().each(function(){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){this.textContent=value}})},null,value,arguments.length)},append:function(){return this.domManip(arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.appendChild(elem)}})},prepend:function(){return this.domManip(arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.insertBefore(elem,target.firstChild)}})},before:function(){return this.domManip(arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this)}})},after:function(){return this.domManip(arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this.nextSibling)}})},remove:function(selector,keepData){var elem,elems=selector?jQuery.filter(selector,this):this,i=0;for(;(elem=elems[i])!=null;i++){if(!keepData&&elem.nodeType===1){jQuery.cleanData(getAll(elem))}if(elem.parentNode){if(keepData&&jQuery.contains(elem.ownerDocument,elem)){setGlobalEval(getAll(elem,"script"))}elem.parentNode.removeChild(elem)}}return this},empty:function(){var elem,i=0;for(;(elem=this[i])!=null;i++){if(elem.nodeType===1){jQuery.cleanData(getAll(elem,false));elem.textContent=""}}return this},clone:function(dataAndEvents,deepDataAndEvents){dataAndEvents=dataAndEvents==null?false:dataAndEvents;deepDataAndEvents=deepDataAndEvents==null?dataAndEvents:deepDataAndEvents;return this.map(function(){return jQuery.clone(this,dataAndEvents,deepDataAndEvents)})},html:function(value){return access(this,function(value){var elem=this[0]||{},i=0,l=this.length;if(value===undefined&&elem.nodeType===1){return elem.innerHTML}if(typeof value==="string"&&!rnoInnerhtml.test(value)&&!wrapMap[(rtagName.exec(value)||["",""])[1].toLowerCase()]){value=value.replace(rxhtmlTag,"<$1>");try{for(;i1&&typeof value==="string"&&!support.checkClone&&rchecked.test(value)){return this.each(function(index){var self=set.eq(index);if(isFunction){args[0]=value.call(this,index,self.html())}self.domManip(args,callback)})}if(l){fragment=jQuery.buildFragment(args,this[0].ownerDocument,false,this);first=fragment.firstChild;if(fragment.childNodes.length===1){fragment=first}if(first){scripts=jQuery.map(getAll(fragment,"script"),disableScript);hasScripts=scripts.length;for(;i")).appendTo(doc.documentElement);doc=iframe[0].contentDocument;doc.write();doc.close();display=actualDisplay(nodeName,doc);iframe.detach()}elemdisplay[nodeName]=display}return display}var rmargin=/^margin/;var rnumnonpx=new RegExp("^("+pnum+")(?!px)[a-z%]+$","i");var getStyles=function(elem){return elem.ownerDocument.defaultView.getComputedStyle(elem,null)};function curCSS(elem,name,computed){var width,minWidth,maxWidth,ret,style=elem.style;computed=computed||getStyles(elem);if(computed){ret=computed.getPropertyValue(name)||computed[name]}if(computed){if(ret===""&&!jQuery.contains(elem.ownerDocument,elem)){ret=jQuery.style(elem,name)}if(rnumnonpx.test(ret)&&rmargin.test(name)){width=style.width;minWidth=style.minWidth;maxWidth=style.maxWidth;style.minWidth=style.maxWidth=style.width=ret;ret=computed.width;style.width=width;style.minWidth=minWidth;style.maxWidth=maxWidth}}return ret!==undefined?ret+"":ret}function addGetHookIf(conditionFn,hookFn){return{get:function(){if(conditionFn()){delete this.get;return}return(this.get=hookFn).apply(this,arguments)}}}(function(){var pixelPositionVal,boxSizingReliableVal,docElem=document.documentElement,container=document.createElement("div"),div=document.createElement("div");if(!div.style){return}div.style.backgroundClip="content-box";div.cloneNode(true).style.backgroundClip="";support.clearCloneStyle=div.style.backgroundClip==="content-box";container.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;"+"position:absolute";container.appendChild(div);function computePixelPositionAndBoxSizingReliable(){div.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;"+"box-sizing:border-box;display:block;margin-top:1%;top:1%;"+"border:1px;padding:1px;width:4px;position:absolute";div.innerHTML="";docElem.appendChild(container);var divStyle=window.getComputedStyle(div,null);pixelPositionVal=divStyle.top!=="1%";boxSizingReliableVal=divStyle.width==="4px";docElem.removeChild(container)}if(window.getComputedStyle){jQuery.extend(support,{pixelPosition:function(){computePixelPositionAndBoxSizingReliable();return pixelPositionVal},boxSizingReliable:function(){if(boxSizingReliableVal==null){computePixelPositionAndBoxSizingReliable()}return boxSizingReliableVal},reliableMarginRight:function(){var ret,marginDiv=div.appendChild(document.createElement("div"));marginDiv.style.cssText=div.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;"+"box-sizing:content-box;display:block;margin:0;border:0;padding:0";marginDiv.style.marginRight=marginDiv.style.width="0";div.style.width="1px";docElem.appendChild(container);ret=!parseFloat(window.getComputedStyle(marginDiv,null).marginRight);docElem.removeChild(container);return ret}})}})();jQuery.swap=function(elem,options,callback,args){var ret,name,old={};for(name in options){old[name]=elem.style[name];elem.style[name]=options[name]}ret=callback.apply(elem,args||[]);for(name in options){elem.style[name]=old[name]}return ret};var rdisplayswap=/^(none|table(?!-c[ea]).+)/,rnumsplit=new RegExp("^("+pnum+")(.*)$","i"),rrelNum=new RegExp("^([+-])=("+pnum+")","i"),cssShow={position:"absolute",visibility:"hidden",display:"block"},cssNormalTransform={letterSpacing:"0",fontWeight:"400"},cssPrefixes=["Webkit","O","Moz","ms"];function vendorPropName(style,name){if(name in style){return name}var capName=name[0].toUpperCase()+name.slice(1),origName=name,i=cssPrefixes.length;while(i--){name=cssPrefixes[i]+capName;if(name in style){return name}}return origName}function setPositiveNumber(elem,value,subtract){var matches=rnumsplit.exec(value);return matches?Math.max(0,matches[1]-(subtract||0))+(matches[2]||"px"):value}function augmentWidthOrHeight(elem,name,extra,isBorderBox,styles){var i=extra===(isBorderBox?"border":"content")?4:name==="width"?1:0,val=0;for(;i<4;i+=2){if(extra==="margin"){val+=jQuery.css(elem,extra+cssExpand[i],true,styles)}if(isBorderBox){if(extra==="content"){val-=jQuery.css(elem,"padding"+cssExpand[i],true,styles)}if(extra!=="margin"){val-=jQuery.css(elem,"border"+cssExpand[i]+"Width",true,styles)}}else{val+=jQuery.css(elem,"padding"+cssExpand[i],true,styles);if(extra!=="padding"){val+=jQuery.css(elem,"border"+cssExpand[i]+"Width",true,styles)}}}return val}function getWidthOrHeight(elem,name,extra){var valueIsBorderBox=true,val=name==="width"?elem.offsetWidth:elem.offsetHeight,styles=getStyles(elem),isBorderBox=jQuery.css(elem,"boxSizing",false,styles)==="border-box";if(val<=0||val==null){val=curCSS(elem,name,styles);if(val<0||val==null){val=elem.style[name]}if(rnumnonpx.test(val)){return val}valueIsBorderBox=isBorderBox&&(support.boxSizingReliable()||val===elem.style[name]);val=parseFloat(val)||0}return val+augmentWidthOrHeight(elem,name,extra||(isBorderBox?"border":"content"),valueIsBorderBox,styles)+"px"}function showHide(elements,show){var display,elem,hidden,values=[],index=0,length=elements.length;for(;index1)},show:function(){return showHide(this,true)},hide:function(){return showHide(this)},toggle:function(state){if(typeof state==="boolean"){return state?this.show():this.hide()}return this.each(function(){if(isHidden(this)){jQuery(this).show()}else{jQuery(this).hide()}})}});function Tween(elem,options,prop,end,easing){return new Tween.prototype.init(elem,options,prop,end,easing)}jQuery.Tween=Tween;Tween.prototype={constructor:Tween,init:function(elem,options,prop,end,easing,unit){this.elem=elem;this.prop=prop;this.easing=easing||"swing";this.options=options;this.start=this.now=this.cur();this.end=end;this.unit=unit||(jQuery.cssNumber[prop]?"":"px")},cur:function(){var hooks=Tween.propHooks[this.prop];return hooks&&hooks.get?hooks.get(this):Tween.propHooks._default.get(this)},run:function(percent){var eased,hooks=Tween.propHooks[this.prop];if(this.options.duration){this.pos=eased=jQuery.easing[this.easing](percent,this.options.duration*percent,0,1,this.options.duration)}else{this.pos=eased=percent}this.now=(this.end-this.start)*eased+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this)}if(hooks&&hooks.set){hooks.set(this)}else{Tween.propHooks._default.set(this)}return this}};Tween.prototype.init.prototype=Tween.prototype;Tween.propHooks={_default:{get:function(tween){var result;if(tween.elem[tween.prop]!=null&&(!tween.elem.style||tween.elem.style[tween.prop]==null)){return tween.elem[tween.prop]}result=jQuery.css(tween.elem,tween.prop,"");return!result||result==="auto"?0:result},set:function(tween){if(jQuery.fx.step[tween.prop]){jQuery.fx.step[tween.prop](tween)}else if(tween.elem.style&&(tween.elem.style[jQuery.cssProps[tween.prop]]!=null||jQuery.cssHooks[tween.prop])){jQuery.style(tween.elem,tween.prop,tween.now+tween.unit)}else{tween.elem[tween.prop]=tween.now}}}};Tween.propHooks.scrollTop=Tween.propHooks.scrollLeft={set:function(tween){if(tween.elem.nodeType&&tween.elem.parentNode){tween.elem[tween.prop]=tween.now}}};jQuery.easing={linear:function(p){return p},swing:function(p){return.5-Math.cos(p*Math.PI)/2}};jQuery.fx=Tween.prototype.init;jQuery.fx.step={};var fxNow,timerId,rfxtypes=/^(?:toggle|show|hide)$/,rfxnum=new RegExp("^(?:([+-])=|)("+pnum+")([a-z%]*)$","i"),rrun=/queueHooks$/,animationPrefilters=[defaultPrefilter],tweeners={"*":[function(prop,value){var tween=this.createTween(prop,value),target=tween.cur(),parts=rfxnum.exec(value),unit=parts&&parts[3]||(jQuery.cssNumber[prop]?"":"px"),start=(jQuery.cssNumber[prop]||unit!=="px"&&+target)&&rfxnum.exec(jQuery.css(tween.elem,prop)),scale=1,maxIterations=20;if(start&&start[3]!==unit){unit=unit||start[3];parts=parts||[];start=+target||1;do{scale=scale||".5";start=start/scale;jQuery.style(tween.elem,prop,start+unit)}while(scale!==(scale=tween.cur()/target)&&scale!==1&&--maxIterations)}if(parts){start=tween.start=+start||+target||0;tween.unit=unit;tween.end=parts[1]?start+(parts[1]+1)*parts[2]:+parts[2]}return tween}]};function createFxNow(){setTimeout(function(){fxNow=undefined});return fxNow=jQuery.now()}function genFx(type,includeWidth){var which,i=0,attrs={height:type};includeWidth=includeWidth?1:0;for(;i<4;i+=2-includeWidth){which=cssExpand[i];attrs["margin"+which]=attrs["padding"+which]=type}if(includeWidth){attrs.opacity=attrs.width=type}return attrs}function createTween(value,prop,animation){var tween,collection=(tweeners[prop]||[]).concat(tweeners["*"]),index=0,length=collection.length;for(;index1)},removeAttr:function(name){return this.each(function(){jQuery.removeAttr(this,name)})}});jQuery.extend({attr:function(elem,name,value){var hooks,ret,nType=elem.nodeType;if(!elem||nType===3||nType===8||nType===2){return}if(typeof elem.getAttribute===strundefined){return jQuery.prop(elem,name,value)}if(nType!==1||!jQuery.isXMLDoc(elem)){name=name.toLowerCase();hooks=jQuery.attrHooks[name]||(jQuery.expr.match.bool.test(name)?boolHook:nodeHook)}if(value!==undefined){if(value===null){jQuery.removeAttr(elem,name)}else if(hooks&&"set"in hooks&&(ret=hooks.set(elem,value,name))!==undefined){return ret}else{elem.setAttribute(name,value+"");return value}}else if(hooks&&"get"in hooks&&(ret=hooks.get(elem,name))!==null){return ret}else{ret=jQuery.find.attr(elem,name);return ret==null?undefined:ret}},removeAttr:function(elem,value){var name,propName,i=0,attrNames=value&&value.match(rnotwhite);if(attrNames&&elem.nodeType===1){while(name=attrNames[i++]){propName=jQuery.propFix[name]||name;if(jQuery.expr.match.bool.test(name)){elem[propName]=false}elem.removeAttribute(name)}}},attrHooks:{type:{set:function(elem,value){if(!support.radioValue&&value==="radio"&&jQuery.nodeName(elem,"input")){var val=elem.value;elem.setAttribute("type",value);if(val){elem.value=val}return value}}}}});boolHook={set:function(elem,value,name){if(value===false){jQuery.removeAttr(elem,name)}else{elem.setAttribute(name,name)}return name}};jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g),function(i,name){var getter=attrHandle[name]||jQuery.find.attr;attrHandle[name]=function(elem,name,isXML){var ret,handle;if(!isXML){handle=attrHandle[name];attrHandle[name]=ret;ret=getter(elem,name,isXML)!=null?name.toLowerCase():null;attrHandle[name]=handle}return ret}});var rfocusable=/^(?:input|select|textarea|button)$/i;jQuery.fn.extend({prop:function(name,value){return access(this,jQuery.prop,name,value,arguments.length>1)},removeProp:function(name){return this.each(function(){delete this[jQuery.propFix[name]||name]})}});jQuery.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(elem,name,value){var ret,hooks,notxml,nType=elem.nodeType;if(!elem||nType===3||nType===8||nType===2){return}notxml=nType!==1||!jQuery.isXMLDoc(elem);if(notxml){name=jQuery.propFix[name]||name;hooks=jQuery.propHooks[name]}if(value!==undefined){return hooks&&"set"in hooks&&(ret=hooks.set(elem,value,name))!==undefined?ret:elem[name]=value}else{return hooks&&"get"in hooks&&(ret=hooks.get(elem,name))!==null?ret:elem[name]}},propHooks:{tabIndex:{get:function(elem){return elem.hasAttribute("tabindex")||rfocusable.test(elem.nodeName)||elem.href?elem.tabIndex:-1}}}});if(!support.optSelected){jQuery.propHooks.selected={get:function(elem){var parent=elem.parentNode;if(parent&&parent.parentNode){parent.parentNode.selectedIndex}return null}}}jQuery.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){jQuery.propFix[this.toLowerCase()]=this});var rclass=/[\t\r\n\f]/g;jQuery.fn.extend({addClass:function(value){var classes,elem,cur,clazz,j,finalValue,proceed=typeof value==="string"&&value,i=0,len=this.length;if(jQuery.isFunction(value)){return this.each(function(j){jQuery(this).addClass(value.call(this,j,this.className))})}if(proceed){classes=(value||"").match(rnotwhite)||[];for(;i=0){cur=cur.replace(" "+clazz+" "," ")}}finalValue=value?jQuery.trim(cur):"";if(elem.className!==finalValue){elem.className=finalValue}}}}return this},toggleClass:function(value,stateVal){var type=typeof value;if(typeof stateVal==="boolean"&&type==="string"){return stateVal?this.addClass(value):this.removeClass(value)}if(jQuery.isFunction(value)){return this.each(function(i){jQuery(this).toggleClass(value.call(this,i,this.className,stateVal),stateVal)})}return this.each(function(){if(type==="string"){var className,i=0,self=jQuery(this),classNames=value.match(rnotwhite)||[];while(className=classNames[i++]){if(self.hasClass(className)){self.removeClass(className)}else{self.addClass(className)}}}else if(type===strundefined||type==="boolean"){if(this.className){data_priv.set(this,"__className__",this.className)}this.className=this.className||value===false?"":data_priv.get(this,"__className__")||""}})},hasClass:function(selector){var className=" "+selector+" ",i=0,l=this.length;for(;i=0){return true}}return false}});var rreturn=/\r/g;jQuery.fn.extend({val:function(value){var hooks,ret,isFunction,elem=this[0];if(!arguments.length){if(elem){hooks=jQuery.valHooks[elem.type]||jQuery.valHooks[elem.nodeName.toLowerCase()];if(hooks&&"get"in hooks&&(ret=hooks.get(elem,"value"))!==undefined){return ret}ret=elem.value;return typeof ret==="string"?ret.replace(rreturn,""):ret==null?"":ret}return}isFunction=jQuery.isFunction(value);return this.each(function(i){var val;if(this.nodeType!==1){return}if(isFunction){val=value.call(this,i,jQuery(this).val())}else{val=value}if(val==null){val=""}else if(typeof val==="number"){val+=""}else if(jQuery.isArray(val)){val=jQuery.map(val,function(value){return value==null?"":value+""})}hooks=jQuery.valHooks[this.type]||jQuery.valHooks[this.nodeName.toLowerCase()];if(!hooks||!("set"in hooks)||hooks.set(this,val,"value")===undefined){this.value=val}})}});jQuery.extend({valHooks:{option:{get:function(elem){var val=jQuery.find.attr(elem,"value");return val!=null?val:jQuery.trim(jQuery.text(elem))}},select:{get:function(elem){var value,option,options=elem.options,index=elem.selectedIndex,one=elem.type==="select-one"||index<0,values=one?null:[],max=one?index+1:options.length,i=index<0?max:one?index:0;for(;i=0){optionSet=true}}if(!optionSet){elem.selectedIndex=-1}return values}}}});jQuery.each(["radio","checkbox"],function(){jQuery.valHooks[this]={set:function(elem,value){if(jQuery.isArray(value)){return elem.checked=jQuery.inArray(jQuery(elem).val(),value)>=0}}};if(!support.checkOn){jQuery.valHooks[this].get=function(elem){return elem.getAttribute("value")===null?"on":elem.value}}});jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick "+"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave "+"change select submit keydown keypress keyup error contextmenu").split(" "),function(i,name){jQuery.fn[name]=function(data,fn){return arguments.length>0?this.on(name,null,data,fn):this.trigger(name)}});jQuery.fn.extend({hover:function(fnOver,fnOut){return this.mouseenter(fnOver).mouseleave(fnOut||fnOver)},bind:function(types,data,fn){return this.on(types,null,data,fn)},unbind:function(types,fn){return this.off(types,null,fn)},delegate:function(selector,types,data,fn){return this.on(types,selector,data,fn)},undelegate:function(selector,types,fn){return arguments.length===1?this.off(selector,"**"):this.off(types,selector||"**",fn)}});var nonce=jQuery.now();var rquery=/\?/;jQuery.parseJSON=function(data){return JSON.parse(data+"")};jQuery.parseXML=function(data){var xml,tmp;if(!data||typeof data!=="string"){return null}try{tmp=new DOMParser;xml=tmp.parseFromString(data,"text/xml")}catch(e){xml=undefined}if(!xml||xml.getElementsByTagName("parsererror").length){jQuery.error("Invalid XML: "+data)}return xml};var ajaxLocParts,ajaxLocation,rhash=/#.*$/,rts=/([?&])_=[^&]*/,rheaders=/^(.*?):[ \t]*([^\r\n]*)$/gm,rlocalProtocol=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,rnoContent=/^(?:GET|HEAD)$/,rprotocol=/^\/\//,rurl=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,prefilters={},transports={},allTypes="*/".concat("*");try{ajaxLocation=location.href}catch(e){ajaxLocation=document.createElement("a");ajaxLocation.href="";ajaxLocation=ajaxLocation.href}ajaxLocParts=rurl.exec(ajaxLocation.toLowerCase())||[];function addToPrefiltersOrTransports(structure){return function(dataTypeExpression,func){if(typeof dataTypeExpression!=="string"){func=dataTypeExpression;dataTypeExpression="*"}var dataType,i=0,dataTypes=dataTypeExpression.toLowerCase().match(rnotwhite)||[];if(jQuery.isFunction(func)){while(dataType=dataTypes[i++]){if(dataType[0]==="+"){dataType=dataType.slice(1)||"*";(structure[dataType]=structure[dataType]||[]).unshift(func)}else{(structure[dataType]=structure[dataType]||[]).push(func)}}}}}function inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR){var inspected={},seekingTransport=structure===transports;function inspect(dataType){var selected;inspected[dataType]=true;jQuery.each(structure[dataType]||[],function(_,prefilterOrFactory){var dataTypeOrTransport=prefilterOrFactory(options,originalOptions,jqXHR);if(typeof dataTypeOrTransport==="string"&&!seekingTransport&&!inspected[dataTypeOrTransport]){options.dataTypes.unshift(dataTypeOrTransport);inspect(dataTypeOrTransport);return false}else if(seekingTransport){return!(selected=dataTypeOrTransport)}});return selected}return inspect(options.dataTypes[0])||!inspected["*"]&&inspect("*")}function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key]}}if(deep){jQuery.extend(true,target,deep)}return target}function ajaxHandleResponses(s,jqXHR,responses){var ct,type,finalDataType,firstDataType,contents=s.contents,dataTypes=s.dataTypes;while(dataTypes[0]==="*"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader("Content-Type")}}if(ct){for(type in contents){if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break}}}if(dataTypes[0]in responses){finalDataType=dataTypes[0]}else{for(type in responses){if(!dataTypes[0]||s.converters[type+" "+dataTypes[0]]){finalDataType=type;break}if(!firstDataType){firstDataType=type}}finalDataType=finalDataType||firstDataType}if(finalDataType){if(finalDataType!==dataTypes[0]){dataTypes.unshift(finalDataType)}return responses[finalDataType]}}function ajaxConvert(s,response,jqXHR,isSuccess){var conv2,current,conv,tmp,prev,converters={},dataTypes=s.dataTypes.slice();if(dataTypes[1]){for(conv in s.converters){converters[conv.toLowerCase()]=s.converters[conv]}}current=dataTypes.shift();while(current){if(s.responseFields[current]){jqXHR[s.responseFields[current]]=response}if(!prev&&isSuccess&&s.dataFilter){response=s.dataFilter(response,s.dataType)}prev=current;current=dataTypes.shift();if(current){if(current==="*"){current=prev}else if(prev!=="*"&&prev!==current){conv=converters[prev+" "+current]||converters["* "+current];if(!conv){for(conv2 in converters){tmp=conv2.split(" ");if(tmp[1]===current){conv=converters[prev+" "+tmp[0]]||converters["* "+tmp[0]];if(conv){if(conv===true){conv=converters[conv2]}else if(converters[conv2]!==true){current=tmp[0];dataTypes.unshift(tmp[1])}break}}}}if(conv!==true){if(conv&&s["throws"]){response=conv(response)}else{try{response=conv(response)}catch(e){return{state:"parsererror",error:conv?e:"No conversion from "+prev+" to "+current}}}}}}}return{state:"success",data:response}}jQuery.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ajaxLocation,type:"GET",isLocal:rlocalProtocol.test(ajaxLocParts[1]),global:true,processData:true,async:true,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":allTypes,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":true,"text json":jQuery.parseJSON,"text xml":jQuery.parseXML},flatOptions:{url:true,context:true}},ajaxSetup:function(target,settings){return settings?ajaxExtend(ajaxExtend(target,jQuery.ajaxSettings),settings):ajaxExtend(jQuery.ajaxSettings,target)},ajaxPrefilter:addToPrefiltersOrTransports(prefilters),ajaxTransport:addToPrefiltersOrTransports(transports),ajax:function(url,options){if(typeof url==="object"){options=url;url=undefined}options=options||{};var transport,cacheURL,responseHeadersString,responseHeaders,timeoutTimer,parts,fireGlobals,i,s=jQuery.ajaxSetup({},options),callbackContext=s.context||s,globalEventContext=s.context&&(callbackContext.nodeType||callbackContext.jquery)?jQuery(callbackContext):jQuery.event,deferred=jQuery.Deferred(),completeDeferred=jQuery.Callbacks("once memory"),statusCode=s.statusCode||{},requestHeaders={},requestHeadersNames={},state=0,strAbort="canceled",jqXHR={readyState:0,getResponseHeader:function(key){var match;if(state===2){if(!responseHeaders){responseHeaders={};while(match=rheaders.exec(responseHeadersString)){responseHeaders[match[1].toLowerCase()]=match[2]}}match=responseHeaders[key.toLowerCase()]}return match==null?null:match},getAllResponseHeaders:function(){return state===2?responseHeadersString:null},setRequestHeader:function(name,value){var lname=name.toLowerCase();if(!state){name=requestHeadersNames[lname]=requestHeadersNames[lname]||name;requestHeaders[name]=value}return this},overrideMimeType:function(type){if(!state){s.mimeType=type}return this},statusCode:function(map){var code;if(map){if(state<2){for(code in map){statusCode[code]=[statusCode[code],map[code]]}}else{jqXHR.always(map[jqXHR.status])}}return this},abort:function(statusText){var finalText=statusText||strAbort;if(transport){transport.abort(finalText)}done(0,finalText);return this}};deferred.promise(jqXHR).complete=completeDeferred.add;jqXHR.success=jqXHR.done;jqXHR.error=jqXHR.fail;s.url=((url||s.url||ajaxLocation)+"").replace(rhash,"").replace(rprotocol,ajaxLocParts[1]+"//");s.type=options.method||options.type||s.method||s.type;s.dataTypes=jQuery.trim(s.dataType||"*").toLowerCase().match(rnotwhite)||[""];if(s.crossDomain==null){parts=rurl.exec(s.url.toLowerCase());s.crossDomain=!!(parts&&(parts[1]!==ajaxLocParts[1]||parts[2]!==ajaxLocParts[2]||(parts[3]||(parts[1]==="http:"?"80":"443"))!==(ajaxLocParts[3]||(ajaxLocParts[1]==="http:"?"80":"443"))))}if(s.data&&s.processData&&typeof s.data!=="string"){s.data=jQuery.param(s.data,s.traditional)}inspectPrefiltersOrTransports(prefilters,s,options,jqXHR);if(state===2){return jqXHR}fireGlobals=s.global;if(fireGlobals&&jQuery.active++===0){jQuery.event.trigger("ajaxStart")}s.type=s.type.toUpperCase();s.hasContent=!rnoContent.test(s.type);cacheURL=s.url;if(!s.hasContent){if(s.data){cacheURL=s.url+=(rquery.test(cacheURL)?"&":"?")+s.data;delete s.data}if(s.cache===false){s.url=rts.test(cacheURL)?cacheURL.replace(rts,"$1_="+nonce++):cacheURL+(rquery.test(cacheURL)?"&":"?")+"_="+nonce++}}if(s.ifModified){if(jQuery.lastModified[cacheURL]){jqXHR.setRequestHeader("If-Modified-Since",jQuery.lastModified[cacheURL])}if(jQuery.etag[cacheURL]){jqXHR.setRequestHeader("If-None-Match",jQuery.etag[cacheURL])}}if(s.data&&s.hasContent&&s.contentType!==false||options.contentType){jqXHR.setRequestHeader("Content-Type",s.contentType)}jqXHR.setRequestHeader("Accept",s.dataTypes[0]&&s.accepts[s.dataTypes[0]]?s.accepts[s.dataTypes[0]]+(s.dataTypes[0]!=="*"?", "+allTypes+"; q=0.01":""):s.accepts["*"]);for(i in s.headers){jqXHR.setRequestHeader(i,s.headers[i])}if(s.beforeSend&&(s.beforeSend.call(callbackContext,jqXHR,s)===false||state===2)){return jqXHR.abort()}strAbort="abort";for(i in{success:1,error:1,complete:1}){jqXHR[i](s[i])}transport=inspectPrefiltersOrTransports(transports,s,options,jqXHR);if(!transport){done(-1,"No Transport")}else{jqXHR.readyState=1;if(fireGlobals){globalEventContext.trigger("ajaxSend",[jqXHR,s])}if(s.async&&s.timeout>0){timeoutTimer=setTimeout(function(){jqXHR.abort("timeout")},s.timeout)}try{state=1;transport.send(requestHeaders,done)}catch(e){if(state<2){done(-1,e)}else{throw e}}}function done(status,nativeStatusText,responses,headers){var isSuccess,success,error,response,modified,statusText=nativeStatusText;if(state===2){return}state=2;if(timeoutTimer){clearTimeout(timeoutTimer)}transport=undefined;responseHeadersString=headers||"";jqXHR.readyState=status>0?4:0;isSuccess=status>=200&&status<300||status===304;if(responses){response=ajaxHandleResponses(s,jqXHR,responses)}response=ajaxConvert(s,response,jqXHR,isSuccess);if(isSuccess){if(s.ifModified){modified=jqXHR.getResponseHeader("Last-Modified");if(modified){jQuery.lastModified[cacheURL]=modified}modified=jqXHR.getResponseHeader("etag");if(modified){jQuery.etag[cacheURL]=modified}}if(status===204||s.type==="HEAD"){statusText="nocontent"}else if(status===304){statusText="notmodified"}else{statusText=response.state;success=response.data;error=response.error;isSuccess=!error}}else{error=statusText;if(status||!statusText){statusText="error";if(status<0){status=0}}}jqXHR.status=status;jqXHR.statusText=(nativeStatusText||statusText)+"";if(isSuccess){deferred.resolveWith(callbackContext,[success,statusText,jqXHR])}else{deferred.rejectWith(callbackContext,[jqXHR,statusText,error])}jqXHR.statusCode(statusCode);statusCode=undefined;if(fireGlobals){globalEventContext.trigger(isSuccess?"ajaxSuccess":"ajaxError",[jqXHR,s,isSuccess?success:error])}completeDeferred.fireWith(callbackContext,[jqXHR,statusText]);if(fireGlobals){globalEventContext.trigger("ajaxComplete",[jqXHR,s]);if(!--jQuery.active){jQuery.event.trigger("ajaxStop")}}}return jqXHR},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json")},getScript:function(url,callback){return jQuery.get(url,undefined,callback,"script")}});jQuery.each(["get","post"],function(i,method){jQuery[method]=function(url,data,callback,type){if(jQuery.isFunction(data)){type=type||callback;callback=data;data=undefined}return jQuery.ajax({url:url,type:method,dataType:type,data:data,success:callback})}});jQuery.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(i,type){jQuery.fn[type]=function(fn){return this.on(type,fn)}});jQuery._evalUrl=function(url){return jQuery.ajax({url:url,type:"GET",dataType:"script",async:false,global:false,"throws":true})};jQuery.fn.extend({wrapAll:function(html){var wrap;if(jQuery.isFunction(html)){return this.each(function(i){jQuery(this).wrapAll(html.call(this,i))})}if(this[0]){wrap=jQuery(html,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){wrap.insertBefore(this[0])}wrap.map(function(){var elem=this;while(elem.firstElementChild){elem=elem.firstElementChild}return elem}).append(this)}return this},wrapInner:function(html){if(jQuery.isFunction(html)){return this.each(function(i){jQuery(this).wrapInner(html.call(this,i))})}return this.each(function(){var self=jQuery(this),contents=self.contents();if(contents.length){contents.wrapAll(html)}else{self.append(html)}})},wrap:function(html){var isFunction=jQuery.isFunction(html);return this.each(function(i){jQuery(this).wrapAll(isFunction?html.call(this,i):html)})},unwrap:function(){return this.parent().each(function(){if(!jQuery.nodeName(this,"body")){jQuery(this).replaceWith(this.childNodes)}}).end()}});jQuery.expr.filters.hidden=function(elem){return elem.offsetWidth<=0&&elem.offsetHeight<=0};jQuery.expr.filters.visible=function(elem){return!jQuery.expr.filters.hidden(elem)};var r20=/%20/g,rbracket=/\[\]$/,rCRLF=/\r?\n/g,rsubmitterTypes=/^(?:submit|button|image|reset|file)$/i,rsubmittable=/^(?:input|select|textarea|keygen)/i;function buildParams(prefix,obj,traditional,add){var name;if(jQuery.isArray(obj)){jQuery.each(obj,function(i,v){if(traditional||rbracket.test(prefix)){add(prefix,v)}else{buildParams(prefix+"["+(typeof v==="object"?i:"")+"]",v,traditional,add)}})}else if(!traditional&&jQuery.type(obj)==="object"){for(name in obj){buildParams(prefix+"["+name+"]",obj[name],traditional,add)}}else{add(prefix,obj)}}jQuery.param=function(a,traditional){var prefix,s=[],add=function(key,value){value=jQuery.isFunction(value)?value():value==null?"":value;s[s.length]=encodeURIComponent(key)+"="+encodeURIComponent(value)};if(traditional===undefined){traditional=jQuery.ajaxSettings&&jQuery.ajaxSettings.traditional}if(jQuery.isArray(a)||a.jquery&&!jQuery.isPlainObject(a)){jQuery.each(a,function(){add(this.name,this.value)})}else{for(prefix in a){buildParams(prefix,a[prefix],traditional,add)}}return s.join("&").replace(r20,"+")};jQuery.fn.extend({serialize:function(){return jQuery.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var elements=jQuery.prop(this,"elements");return elements?jQuery.makeArray(elements):this}).filter(function(){var type=this.type;return this.name&&!jQuery(this).is(":disabled")&&rsubmittable.test(this.nodeName)&&!rsubmitterTypes.test(type)&&(this.checked||!rcheckableType.test(type))}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:jQuery.isArray(val)?jQuery.map(val,function(val){return{name:elem.name,value:val.replace(rCRLF,"\r\n")}}):{name:elem.name,value:val.replace(rCRLF,"\r\n")}}).get()}});jQuery.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(e){}};var xhrId=0,xhrCallbacks={},xhrSuccessStatus={0:200,1223:204},xhrSupported=jQuery.ajaxSettings.xhr();if(window.ActiveXObject){jQuery(window).on("unload",function(){for(var key in xhrCallbacks){xhrCallbacks[key]()}})}support.cors=!!xhrSupported&&"withCredentials"in xhrSupported;support.ajax=xhrSupported=!!xhrSupported;jQuery.ajaxTransport(function(options){var callback;if(support.cors||xhrSupported&&!options.crossDomain){return{send:function(headers,complete){var i,xhr=options.xhr(),id=++xhrId;xhr.open(options.type,options.url,options.async,options.username,options.password);if(options.xhrFields){for(i in options.xhrFields){xhr[i]=options.xhrFields[i]}}if(options.mimeType&&xhr.overrideMimeType){xhr.overrideMimeType(options.mimeType)}if(!options.crossDomain&&!headers["X-Requested-With"]){headers["X-Requested-With"]="XMLHttpRequest"}for(i in headers){xhr.setRequestHeader(i,headers[i])}callback=function(type){return function(){if(callback){delete xhrCallbacks[id];callback=xhr.onload=xhr.onerror=null;if(type==="abort"){xhr.abort()}else if(type==="error"){complete(xhr.status,xhr.statusText) -}else{complete(xhrSuccessStatus[xhr.status]||xhr.status,xhr.statusText,typeof xhr.responseText==="string"?{text:xhr.responseText}:undefined,xhr.getAllResponseHeaders())}}}};xhr.onload=callback();xhr.onerror=callback("error");callback=xhrCallbacks[id]=callback("abort");try{xhr.send(options.hasContent&&options.data||null)}catch(e){if(callback){throw e}}},abort:function(){if(callback){callback()}}}}});jQuery.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(text){jQuery.globalEval(text);return text}}});jQuery.ajaxPrefilter("script",function(s){if(s.cache===undefined){s.cache=false}if(s.crossDomain){s.type="GET"}});jQuery.ajaxTransport("script",function(s){if(s.crossDomain){var script,callback;return{send:function(_,complete){script=jQuery("