Repository: themadcreator/gifler Branch: master Commit: ce36440633f5 Files: 33 Total size: 457.8 KB Directory structure: gitextract_7a1xagvw/ ├── .gitignore ├── README.md ├── gh-pages/ │ ├── assets/ │ │ ├── gifler.js │ │ └── lib/ │ │ ├── highlight.pack.js │ │ └── monokai_sublime.css │ ├── docs.css │ ├── docs.html │ ├── examples.css │ ├── examples.html │ ├── index.css │ ├── index.html │ └── theme.css ├── gifler.bare.js ├── gifler.bundle.js ├── metalsmith.json ├── package.json ├── site/ │ ├── _constants.less │ ├── _examples/ │ │ ├── control.js │ │ ├── rainbow.js │ │ └── simple.js │ ├── _layout.jade │ ├── _nav.jade │ ├── assets/ │ │ ├── gifler.js │ │ └── lib/ │ │ ├── highlight.pack.js │ │ └── monokai_sublime.css │ ├── docs.jade │ ├── docs.less │ ├── examples.jade │ ├── examples.less │ ├── index.jade │ ├── index.less │ └── theme.less └── src/ └── gifler.coffee ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .DS_Store node_modules npm-debug.log # Built gh-pages site # site-dist ================================================ FILE: README.md ================================================ # Gifler Animate GIFs in canvas. - Loads GIF contents with XHR - Decodes GIF frames and pixels with omggif - Prepares canvas buffer for fast rendering - Animates each frame and compensates for render delays - API enables fully custom canvas rendering ### Examples & Docs ### Usage ```html ``` ### License Apache-2.0 ================================================ FILE: gh-pages/assets/gifler.js ================================================ /** gifler.js | github.com/themadcreator/gifler | @license: Apache-2.0 */ !function t(e,n,r){function i(s,a){if(!n[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[s]={exports:{}};e[s][0].call(l.exports,function(t){var n=e[s][1][t];return i(n?n:t)},l,l.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s=0?r>t:t>r;r>=0?t++:t--)n.push(t);return n}.apply(this).map(function(n){return t.decodeFrame(e,n)})},t.decodeFramesAsync=function(e){var n,r;return a.map(function(){r=[];for(var t=0,n=e.numFrames();n>=0?n>t:t>n;n>=0?t++:t--)r.push(t);return r}.apply(this),function(n){return t.decodeFrame(e,n)},n=1)},t.decodeFrame=function(t,e){var n;return n=t.frameInfo(e),n.pixels=new Uint8ClampedArray(t.width*t.height*4),t.decodeAndBlitFrameRGBA(e,n.pixels),n},t}(),r=function(){function t(t,e){var n;this._reader=t,this._frames=e,this._advanceFrame=c(this._advanceFrame,this),this._nextFrameRender=c(this._nextFrameRender,this),this._nextFrame=c(this._nextFrame,this),n=this._reader,this.width=n.width,this.height=n.height,this._loopCount=this._reader.loopCount(),this._loops=0,this._frameIndex=0,this._running=!1}return t.createBufferCanvas=function(t,e,n){var r,i,o;return r=document.createElement("canvas"),i=r.getContext("2d"),r.width=t.width,r.height=t.height,o=i.createImageData(e,n),o.data.set(t.pixels),i.putImageData(o,-t.x,-t.y),r},t.prototype.start=function(){return this._lastTime=(new Date).valueOf(),this._delayCompensation=0,this._running=!0,setTimeout(this._nextFrame,0),this},t.prototype.stop=function(){return this._running=!1,this},t.prototype.reset=function(){return this._frameIndex=0,this._loops=0,this},t.prototype.running=function(){return this._running},t.prototype._nextFrame=function(){requestAnimationFrame(this._nextFrameRender)},t.prototype._nextFrameRender=function(){var t,e;if(this._running)return t=this._frames[this._frameIndex],null!=(e=this.onFrame)&&e.apply(this,[t,this._frameIndex]),this._enqueueNextFrame()},t.prototype._advanceFrame=function(){this._frameIndex+=1,this._frameIndex>=this._frames.length&&(0!==this._loopCount&&this._loopCount===this._loops?this.stop():(this._frameIndex=0,this._loops+=1))},t.prototype._enqueueNextFrame=function(){var t,e,n,r;for(this._advanceFrame();this._running;){if(n=this._frames[this._frameIndex],e=(new Date).valueOf()-this._lastTime,this._lastTime+=e,this._delayCompensation+=e,r=10*n.delay,t=r-this._delayCompensation,this._delayCompensation-=r,!(0>t)){setTimeout(this._nextFrame,t);break}this._advanceFrame()}},t.prototype.animateInCanvas=function(e,n){var r;return null==n&&(n=!0),n&&(e.width=this.width,e.height=this.height),r=e.getContext("2d"),null==this.onDrawFrame&&(this.onDrawFrame=function(t,e,n){return t.drawImage(e.buffer,e.x,e.y)}),null==this.onFrame&&(this.onFrame=function(n){return function(i,o){var s,a;switch(null==i.buffer&&(i.buffer=t.createBufferCanvas(i,n.width,n.height)),"function"==typeof n.disposeFrame&&n.disposeFrame(),i.disposal){case 2:n.disposeFrame=function(){return r.clearRect(0,0,e.width,e.height)};break;case 3:a=r.getImageData(0,0,e.width,e.height),n.disposeFrame=function(){return r.putImageData(a,0,0)};break;default:n.disposeFrame=null}return null!=(s=n.onDrawFrame)?s.apply(n,[r,i,o]):void 0}}(this)),this.start(),this},t}(),u.Gif=o,u.Decoder=i,u.Animator=r,"undefined"!=typeof window&&null!==window&&(window.gifler=u),"undefined"!=typeof e&&null!==e&&(e.exports=u)},{bluebird:2,omggif:4}],2:[function(t,e,n){(function(t,r){!function(t){if("object"==typeof n&&"undefined"!=typeof e)e.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i;"undefined"!=typeof window?i=window:"undefined"!=typeof r?i=r:"undefined"!=typeof self&&(i=self),i.Promise=t()}}(function(){var e,n,i;return function t(e,n,r){function i(s,a){if(!n[s]){if(!e[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[s]={exports:{}};e[s][0].call(l.exports,function(t){var n=e[s][1][t];return i(n?n:t)},l,l.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},i.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},i.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},i.prototype._reset=function(){this._isTickUsed=!1},n.exports=i,n.exports.firstLineError=u},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},u=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var c=n(o),l=new t(e);l._propagateFrom(this,1);var h=this._target();if(l._setBoundTo(c),c instanceof t){var f={promiseRejectionQueued:!1,promise:l,target:h,bindingPromise:c};h._then(e,s,void 0,l,f),c._then(a,u,void 0,l,f),l._setOnCancel(c)}else l._resolveCallback(h);return l},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":22}],5:[function(t,e,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}var s,a=t("./util"),u=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(u){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,u=e._async;e.prototype.break=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t.isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n.isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this.isCancellable()&&(this._setCancelled(),u.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return 0},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promisesCreated=0,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promisesCreated;return t._promisesCreated=0,e}return 0},e.CapturedTrace=null,e.create=n,e.activateLongStackTraces=function(){i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&t._promisesCreated++}},e}},{}],9:[function(e,n,r){"use strict";n.exports=function(n,r){function i(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+H.toString(t));r._attachCancellationCallback(t)})}catch(t){return t}}function o(t){if(!this.isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function s(){return this._onCancelField}function a(t){this._onCancelField=t}function u(){this._cancellationParent=void 0,this._onCancelField=void 0}function c(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function l(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof n?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new R(this._peekContext())}function p(t,e){if(L(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=C(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function _(t,e,n,r){if(void 0===t&&e>0&&Y.longStackTraces&&Y.warnings){var i="a promise was created in a "+n+" handler but was not returned from it";r._warn(i)}}function d(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),v(n)}function v(t,e,r){if(Y.warnings){var i,o=new V(t);if(e)r._attachExtraTrace(o);else if(Y.longStackTraces&&(i=n._peekContext()))i.attachExtraTrace(o);else{var s=C(o);o.stack=s.message+"\n"+s.stack.join("\n")}j(o,"",!0)}}function y(t,e){for(var n=0;n=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=r[a];if(e[i]!==u)break;e.pop(),i--}e=r}}function b(t){for(var e=[],n=0;n0&&(e=e.slice(n)),e}function C(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?w(t):[" (No stack trace)"],{message:n,stack:b(e)}}function j(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+B(i,t)}else r=e+String(t);"function"==typeof S?S(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function F(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(t){D.throwLater(t)}var o=!1;try{o=J(t,n,r)}catch(t){o=!0,D.throwLater(t)}var s=!1;if(X)try{s=X(t.toLowerCase(),{reason:n,promise:r})}catch(t){s=!0,D.throwLater(t)}o||i||s||"unhandledRejection"!==t||j(n,"Unhandled rejection ")}function k(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(t){}0===e.length&&(e="(empty array)")}return"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.lengths||0>a||!n||!r||n!==r||s>=a||(z=function(t){if(N.test(t))return!0;var e=T(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function R(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);K(this,R),e>32&&this.uncycle()}var A,O,S,I=n._getDomain,D=n._async,V=e("./errors").Warning,H=e("./util"),L=H.canAttachTrace,N=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,U=null,B=null,M=!1,q=!0,Q=!(0==H.env("BLUEBIRD_WARNINGS")||!q&&!H.env("BLUEBIRD_WARNINGS")),$=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!q&&!H.env("BLUEBIRD_LONG_STACK_TRACES"));n.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|2097152},n.prototype._ensurePossibleRejectionHandled=function(){0===(2097152&this._bitField)&&(this._setRejectionIsUnhandled(),D.invokeLater(this._notifyUnhandledRejection,this,void 0))},n.prototype._notifyUnhandledRejectionIsHandled=function(){F("rejectionHandled",A,void 0,this)},n.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),F("unhandledRejection",O,t,this)}},n.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},n.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},n.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},n.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},n.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},n.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},n.prototype._warn=function(t,e){return v(t,e,this)},n.onPossiblyUnhandledRejection=function(t){var e=I();O="function"==typeof t?null===e?t:e.bind(t):void 0},n.onUnhandledRejectionHandled=function(t){var e=I();A="function"==typeof t?null===e?t:e.bind(t):void 0},n.longStackTraces=function(){if(D.haveItemsQueued()&&!Y.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");!Y.longStackTraces&&E()&&(Y.longStackTraces=!0,n.prototype._captureStackTrace=f,n.prototype._attachExtraTrace=p,r.activateLongStackTraces(),D.disableTrampolineIfNecessary())},n.hasLongStackTraces=function(){return Y.longStackTraces&&E()},n.config=function(t){if(t=Object(t),"longStackTraces"in t&&t.longStackTraces&&n.longStackTraces(),"warnings"in t&&(Y.warnings=!!t.warnings),"cancellation"in t&&t.cancellation&&!Y.cancellation){if(D.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");n.prototype._clearCancellationData=u,n.prototype._propagateFrom=c,n.prototype._onCancel=s,n.prototype._setOnCancel=a,n.prototype._attachCancellationCallback=o,n.prototype._execute=i,G=c,Y.cancellation=!0}},n.prototype._execute=function(t,e,n){try{t(e,n)}catch(t){return t}},n.prototype._onCancel=function(){},n.prototype._setOnCancel=function(t){},n.prototype._attachCancellationCallback=function(t){},n.prototype._captureStackTrace=function(){},n.prototype._attachExtraTrace=function(){},n.prototype._clearCancellationData=function(){},n.prototype._propagateFrom=function(t,e){};var G=l,z=function(){return!1},W=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(R,Error),r.CapturedTrace=R,R.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var u=r>0?e[r-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,l=r-2;l>=0;--l)e[l]._length=c,c++;return}}}},R.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=C(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(b(i.stack.split("\n"))),i=i._parent;g(r),m(r),H.notEnumerableProp(t,"stack",y(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var X,K=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():k(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,U=t,B=e;var n=Error.captureStackTrace;return z=function(t){return N.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return U=/@/,B=e,M=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(t){i="stack"in t}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(B=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?k(e):e.toString()},null):(U=t,B=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]),J=function(){if(H.isNode)return function(e,n,r){return"rejectionHandled"===e?t.emit(e,r):t.emit(e,n,r)};var e=!1,n=!0;try{var r=new self.CustomEvent("test");e=r instanceof CustomEvent}catch(t){}if(!e)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(t){n=!1}n&&(X=function(t,n){var r;return e?r=new self.CustomEvent(t,{detail:n,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(r=document.createEvent("CustomEvent"),r.initCustomEvent(t,!1,!0,n)),r?!self.dispatchEvent(r):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,n){var r=o[t],i=self[r];return i?("rejectionHandled"===t?i.call(self,n):i.call(self,e,n),!0):!1}}();"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(S=function(t){console.warn(t)},H.isNode&&t.stderr.isTTY?S=function(e,n){var r=n?"":"";t.stderr.write(r+e+"\n")}:H.isNode||"string"!=typeof(new Error).stack||(S=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var Y={warnings:Q,longStackTraces:!1,cancellation:!1};return $&&n.longStackTraces(),{longStackTraces:function(){return Y.longStackTraces},warnings:function(){return Y.warnings},cancellation:function(){return Y.cancellation},propagateFromFunction:function(){return G},boundValueFunction:function(){return h},checkForgottenReturns:_,setBounds:P,warn:v,deprecated:d,CapturedTrace:R}}},{"./errors":12,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype.return=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype.throw=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return this.mapSeries(t)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,e){return r(t,e)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(h(this,"message","string"==typeof r?r:e),h(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return l(n,Error),n}function i(t){return this instanceof i?(h(this,"name","OperationalError"),h(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(h(this,"message",t.message),h(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5"),u=a.freeze,c=t("./util"),l=c.inherits,h=c.notEnumerableProp,f=r("Warning","warning"),p=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(t){o=r("TypeError","type error"),s=r("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function o(){return a.call(this,this.promise._target()._settledValue())}function s(t){return i(this,t)?void 0:(l.e=t,l)}function a(t){var a=this.promise,u=this.handler;if(!this.called){this.called=!0;var h=0===this.type?u.call(a._boundValue()):u.call(a._boundValue(),t);if(void 0!==h){var f=n(h,a);if(f instanceof e){if(null!=this.cancelPromise){if(f.isCancelled()){var p=new c("late cancellation observer");return a._attachExtraTrace(p),l.e=p,l}f.isPending()&&f._attachCancellationCallback(new r(this))}return f._then(o,s,void 0,this,void 0)}}}return a.isRejected()?(i(this),l.e=t,l):(i(this),t)}var u=t("./util"),c=e.CancellationError,l=u.errorObj;return r.prototype._resultCancelled=function(){i(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,{promise:this,handler:t,called:!1,cancelPromise:null,type:e},void 0)},e.prototype.lastly=e.prototype.finally=function(t){return this._passThrough(t,0,a,a)},e.prototype.tap=function(t){return this._passThrough(t,1,a)},a}},{"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=c();this._callback=null===i?e:i.bind(e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=n>=1?[]:p,this._init$(void 0,-2)}function u(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+l.classString(e));var o="object"==typeof n&&null!==n?n.concurrency:0;return o="number"==typeof o&&isFinite(o)&&o>=1?o:0,new a(t,e,o,i).promise()}var c=e._getDomain,l=t("./util"),h=l.tryCatch,f=l.errorObj,p=[];l.inherits(a,n),a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){var r=this._values,o=this.length(),a=this._preservedValues,u=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,u>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(u>=1&&this._inFlight>=u)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var c=this._promise,l=this._callback,p=c._boundValue();c._pushContext();var _=h(l).call(p,t,n,o),d=c._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",c),_===f)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return u>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var m=++this._totalResolved;return m>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return u(this,t,e,null)},e.map=function(t,e,n,r){return u(t,e,n,r)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments);return r._popContext(),r._resolveFromSyncValue(i),r}},e.attempt=e.try=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var u;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],l=arguments[2];u=s.isArray(c)?a(t).apply(l,c):a(t).call(l,c)}else u=a(t)();return r._popContext(),r._resolveFromSyncValue(u),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&l.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new c(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=l.keys(t),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!p.isObject(o))return h("expecting an object but got "+p.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(l,l,void 0,this,void 0)},i.prototype.then=function(t,e){if(E.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+p.classString(t);arguments.length>1&&(n+=", "+p.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?h("expecting a function but got "+p.classString(t)):this.all()._then(t,void 0,void 0,w,void 0)},i.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new F(this).promise()},i.prototype.error=function(t){return this.caught(p.originatesFromRejection,t)},i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b),n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=O(t)(R(e,n));return r===A&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new F(t).promise()},i.cast=function(t){var e=j(t);return e instanceof i||(e=new i(b),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+p.classString(t));var e=v._schedule;return v._schedule=t,e},i.prototype._then=function(t,e,n,r,o){var s=void 0!==o,a=s?o:new i(b),c=this._target(),l=c._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&l)?this._boundValue():c===this?void 0:this._boundTo));var h=u();if(0!==(50397184&l)){var f,p,_=c._settlePromiseCtx;0!==(33554432&l)?(p=c._rejectionHandler0,f=t):0!==(16777216&l)?(p=c._fulfillmentHandler0,f=e,c._unsetRejectionIsUnhandled()):(_=c._settlePromiseLateCancellationObserver,p=new g("late cancellation observer"),c._attachExtraTrace(p),f=e),v.invoke(_,c,{handler:null===h?f:"function"==typeof f&&h.bind(f),promise:a,receiver:r,value:p})}else c._addCallbacks(t,e,a,r,h);return a},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField},i.prototype._setAsyncGuaranteed=function(){this._bitField=134217728|this._bitField},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===f?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=f),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=f),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:i.bind(t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:i.bind(e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:i.bind(t)),"function"==typeof e&&(this[s+1]=null===i?e:i.bind(e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(c(),!1);var n=j(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target(),o=r._bitField;if(0===(50397184&o)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;s>a;++a)r._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var u=new g("late cancellation observer");r._attachExtraTrace(u),this._reject(u)}}},i.prototype._rejectCallback=function(t,e){var n=p.ensureErrorObject(t),r=n===t;if(!r&&E.warnings()){var i="a promise was rejected with a non-error: "+p.classString(t);this._warn(i,!0)}this._attachExtraTrace(n,e?r:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===w?n&&"number"==typeof n.length?o=O(t).apply(this._boundValue(),n):(o=A,o.e=new m("cannot .spread() a non-array: "+p.classString(n))):o=O(t).call(e,n);var s=r._popContext();if(i=r._bitField,0===(65536&i))if(o===C)r._reject(n);else if(o===A||o===r){var a=o===r?c():o.e;r._rejectCallback(a,!1)}else void 0===o&&s>0&&E.longStackTraces()&&E.warnings()&&r._warn("a promise was created in a handler but none were returned from it",!0),r._resolveCallback(o)}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var s=t instanceof i,a=this._bitField,u=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),e===T?(r.cancelPromise=t,O(e).call(r,o)===A&&t._reject(A.e)):e===l?t._fulfill(l.call(r)):r instanceof n?r._promiseCancelled(t):s||t instanceof F?t._cancel():r.cancel()):"function"==typeof e?s?(u&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&a)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):s&&(u&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=c();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,p.isNode):void((65535&e)>0?0!==(134217728&e)?this._settlePromises():v.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){E.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:s}},p.notEnumerableProp(i,"_makeSelfResolutionError",c),e("./method")(i,b,j,h,E),e("./bind")(i,b,j,E),e("./cancel")(i,F,h,E),e("./direct_resolve")(i),e("./synchronous_inspection")(i),e("./join")(i,F,j,b,E),i.Promise=i,e("./map.js")(i,F,h,j,b,E),e("./using.js")(i,h,j,x,b,E),e("./timers.js")(i,b),e("./generators.js")(i,h,b,j,n,E),e("./nodeify.js")(i),e("./call_get.js")(i),e("./props.js")(i,F,j,h),e("./race.js")(i,b,j,h),e("./reduce.js")(i,F,h,j,b,E),e("./settle.js")(i,F,E),e("./some.js")(i,F,h),e("./promisify.js")(i,b),e("./any.js")(i),e("./each.js")(i,b),e("./filter.js")(i,b),p.toFastProperties(i),p.toFastProperties(i.prototype),a({a:1}),a({b:2}),a({c:3}),a(1),a(function(){}),a(void 0),a(!1),a(new i(b)),E.setBounds(d.firstLineError,p.lastLineError),i}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{}}}function a(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var u=t("./util");u.isArray;return u.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function t(n,o){var a=r(this._values,this._promise);if(a instanceof e){a=a._target();var c=a._bitField;if(this._values=a,0===(50397184&c))return this._promise._setAsyncGuaranteed(),a._then(t,this._reject,void 0,this,o);if(0===(33554432&c))return 0!==(16777216&c)?this._reject(a._reason()):this._cancel();a=a._value()}if(a=u.asArray(a),null===a){var l=i("expecting an array or an iterable object but got "+u.classString(a)).reason();return void this._promise._rejectCallback(l,!1)}return 0===a.length?void(-5===o?this._resolveEmptyArray():this._resolve(s(o))):void this._iterate(a)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var u=r(t[a],i);u instanceof e?(u=u._target(),s=u._bitField):s=null,o?null!==s&&u.suppressUnhandledRejections():null!==s?0===(50397184&s)?(u._proxy(this,a),this._values[a]=u):o=0!==(33554432&s)?this._promiseFulfilled(u._value(),a):0!==(16777216&s)?this._promiseRejected(u._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(u,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise.isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;nu;u+=2){var l=s[u],h=s[u+1],_=l+e;if(r===k)t[_]=k(l,f,l,h,e,i);else{var d=r(h,function(){return k(l,f,l,h,e,i)});p.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return p.toFastProperties(t),t}function l(t,e,n){return k(t,e,void 0,t,null,n)}var h,f={},p=t("./util"),_=t("./nodeback"),d=p.withAppended,v=p.maybeWrapAsError,y=p.canEvaluate,m=t("./errors").TypeError,g="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return p.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},F=function(t){return t.replace(/([$])/,"\\$")},k=y?h:u;e.promisify=function(t,e){if("function"!=typeof t)throw new m("expecting a function but got "+p.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?f:e.context,o=!!e.multiArgs,s=l(t,n,o);return p.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new m("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=g);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=k),!p.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=p.inheritedDataKeys(t),a=0;ao;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,-3)}function s(t){var n,s=r(t);return c(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}var a,u=t("./util"),c=u.isObject,l=t("./es5");"function"==typeof Map&&(a=Map);var h=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),f=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};u.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=f(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacityf;++f){var _=t[f];(void 0!==_||f in t)&&e.cast(_)._then(l,h,void 0,c,null)}return c}var s=t("./util"),a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=f();this._fn=null===s?n:s.bind(n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,this._eachValues=i===o?[]:void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function u(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function c(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+p.classString(e));var o=new a(t,e,n,i);return o.promise()}function l(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(h,void 0,void 0,this,void 0)):h.call(this,n)}function h(t){var n=this.array,r=n._promise,i=_(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var f=e._getDomain,p=t("./util"),_=p.tryCatch;p.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(l,void 0,void 0,o,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(u,u,void 0,n,this)},e.prototype.reduce=function(t,e){return c(this,t,e,null)},e.reduce=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],29:[function(e,n,i){"use strict";var o,s=e("./util"),a=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")};if(s.isNode&&"undefined"==typeof MutationObserver){var u=r.setImmediate,c=t.nextTick;o=s.isRecentNode?function(t){u.call(r,t)}:function(e){c.call(t,e)}}else"undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&window.navigator.standalone?o="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:a:(o=function(t){var e=document.createElement("div"),n=new MutationObserver(t);return n.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},o.isStatic=!0);n.exports=o},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n"); var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,u=t("./errors").AggregateError,c=s.isArray,l={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()?(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(l),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new u,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=t.prototype._isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype.isCancelled=function(){return this._target()._isCancelled()},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(l(t)){if(t instanceof e)return t;var i=o(t);if(i===c){r&&r._pushContext();var u=e.reject(i.e);return r&&r._popContext(),u}if("function"==typeof i){if(s(t)){var u=new e(n);return t._then(u._fulfill,u._reject,void 0,u,null),u}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(t){return c.e=t,c}}function s(t){return h.call(t,"_promise0")}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,h),a=null)}var a=new e(n),l=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var h=!0,f=u.tryCatch(r).call(t,o,s);return h=!1,a&&f===c&&(a._rejectCallback(f.e,!0),a=null),l}var u=t("./util"),c=u.errorObj,l=u.isObject,h={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){var n;n="string"!=typeof e?e instanceof Error?e:new s("operation timed out"):new s(e),o.markAsOriginatingFromRejection(n),t._attachExtraTrace(n),t._reject(n)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,r){var i;return void 0!==r?i=e.resolve(r)._then(u,null,null,t,void 0):(i=new e(n),setTimeout(function(){i._fulfill()},+t)),i._setAsyncGuaranteed(),i};e.prototype.delay=function(t){return c(t,this)},e.prototype.timeout=function(t,e){t=+t;var n=this.then(),o=setTimeout(function(){a(n,e)},t);return n._then(r,i,void 0,o,void 0)}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function u(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function c(t,n){function i(){if(s>=c)return l._fulfill();var o=u(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(t){return a(t)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,c=t.length,l=new e(o);return i(),l}function l(t,e,n){this._data=t,this._promise=e,this._context=n}function h(t,e,n){this.constructor$(t,e,n)}function f(t){return l.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function p(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,m=_.tryCatch;l.prototype.data=function(){return this._data},l.prototype.promise=function(){return this._promise},l.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},l.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=null!==e?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},l.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(h,l),h.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},p.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var u=new p(t),h=0;t>h;++h){var d=o[h];if(l.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var g=r(d);g instanceof e&&(d=g._then(f,null,null,{resources:u,index:h},void 0))}u[h]=d}for(var b=new Array(u.length),h=0;h0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new h(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(e,n,r){"use strict";function i(){try{var t=E;return E=null,t.apply(this,arguments)}catch(t){return x.e=t,x}}function o(t){return E=t,i}function s(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function a(t){return"function"==typeof t||"object"==typeof t&&null!==t}function u(t){return s(t)?new Error(y(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function h(t,e,n){if(s(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function f(t){throw t}function p(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=R.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(t){return!1}}function _(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function d(t){return A.test(t)}function v(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function y(t){try{return t+""}catch(t){return"[no string representation]"}}function m(t){try{h(t,"isOperational",!0)}catch(t){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return t instanceof Error&&F.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function C(t,e,n){for(var r=F.names(t),i=0;i10||e[0]>0}(),V.isNode&&V.toFastProperties(t);try{throw new Error}catch(t){V.lastLineError=t}n.exports=V},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:3}],3:[function(t,e,n){function r(){l=!1,a.length?c=a.concat(c):h=-1,c.length&&i()}function i(){if(!l){var t=setTimeout(r);l=!0;for(var e=c.length;e;){for(a=c,c=[];++h1)for(var n=1;ne||e>256||e&e-1)throw"Invalid code/color length, must be power of 2 and 2 .. 256.";return e}var s=0,r=void 0===r?{}:r,a=void 0===r.loop?null:r.loop,u=void 0===r.palette?null:r.palette;if(0>=e||0>=n||e>65535||n>65535)throw"Width/Height invalid.";t[s++]=71,t[s++]=73,t[s++]=70,t[s++]=56,t[s++]=57,t[s++]=97;var c=0,l=0;if(null!==u){for(var h=o(u);h>>=1;)++c;if(h=1<=h)throw"Background index out of range.";if(0===l)throw"Background index explicitly passed as 0."}}if(t[s++]=255&e,t[s++]=e>>8&255,t[s++]=255&n,t[s++]=n>>8&255,t[s++]=(null!==u?128:0)|c,t[s++]=l,t[s++]=0,null!==u)for(var f=0,p=u.length;p>f;++f){var _=u[f];t[s++]=_>>16&255,t[s++]=_>>8&255,t[s++]=255&_}if(null!==a){if(0>a||a>65535)throw"Loop count invalid.";t[s++]=33,t[s++]=255,t[s++]=11,t[s++]=78,t[s++]=69,t[s++]=84,t[s++]=83,t[s++]=67,t[s++]=65,t[s++]=80,t[s++]=69,t[s++]=50,t[s++]=46,t[s++]=48,t[s++]=3,t[s++]=1,t[s++]=255&a,t[s++]=a>>8&255,t[s++]=0}var d=!1;this.addFrame=function(e,n,r,a,c,l){if(d===!0&&(--s,d=!1),l=void 0===l?{}:l,0>e||0>n||e>65535||n>65535)throw"x/y invalid.";if(0>=r||0>=a||r>65535||a>65535)throw"Width/Height invalid.";if(c.length>=1;)++_;p=1<<_;var v=void 0===l.delay?0:l.delay,y=void 0===l.disposal?0:l.disposal;if(0>y||y>3)throw"Disposal out of range.";var m=!1,g=0;if(void 0!==l.transparent&&null!==l.transparent&&(m=!0,g=l.transparent,0>g||g>=p))throw"Transparent color index.";if((0!==y||m||0!==v)&&(t[s++]=33,t[s++]=249,t[s++]=4,t[s++]=y<<2|(m===!0?1:0),t[s++]=255&v,t[s++]=v>>8&255,t[s++]=g,t[s++]=0),t[s++]=44,t[s++]=255&e,t[s++]=e>>8&255,t[s++]=255&n,t[s++]=n>>8&255,t[s++]=255&r,t[s++]=r>>8&255,t[s++]=255&a,t[s++]=a>>8&255,t[s++]=h===!0?128|_-1:0,h===!0)for(var b=0,w=f.length;w>b;++b){var C=f[b];t[s++]=C>>16&255,t[s++]=C>>8&255,t[s++]=255&C}s=i(t,s,2>_?2:_,c)},this.end=function(){return d===!1&&(t[s++]=59,d=!0),s}}function i(t,e,n,r){function i(n){for(;f>=n;)t[e++]=255&p,p>>=8,f-=8,e===s+256&&(t[s]=255,s=e++)}function o(t){p|=t<v;++v){var m=r[v]&u,g=_<<8|m,b=d[g];if(void 0===b){for(p|=_<=8;)t[e++]=255&p,p>>=8,f-=8,e===s+256&&(t[s]=255,s=e++);4096===l?(o(a),l=c+1,h=n+1,d={}):(l>=1<>7,a=7&i,u=1<>2&7,e++;break;case 254:for(;;){var v=t[e++];if(0===v)break;e+=v}break;default:throw"Unknown graphic control label: 0x"+t[e-1].toString(16)}break;case 44:var m=t[e++]|t[e++]<<8,g=t[e++]|t[e++]<<8,b=t[e++]|t[e++]<<8,w=t[e++]|t[e++]<<8,C=t[e++],j=C>>7,F=C>>6&1,k=7&C,x=1<t||t>=h.length)throw"Frame index out of range.";return h[t]},this.decodeAndBlitFrameBGRA=function(e,r){var i=this.frameInfo(e),o=i.width*i.height,a=new Uint8Array(o);s(t,i.data_offset,a,o);var u=i.palette_offset,c=i.transparent_index;null===c&&(c=256);var l=i.width,h=n-l,f=l,p=4*(i.y*n+i.x),_=4*((i.y+i.height)*n+i.x),d=p,v=4*h;i.interlaced===!0&&(v+=4*n*7);for(var y=8,m=0,g=a.length;g>m;++m){var b=a[m];if(0===f&&(d+=v,f=l,d>=_&&(v=4*h+4*n*(y-1),d=p+(l+h)*(y<<1),y>>=1)),b===c)d+=4;else{var w=t[u+3*b],C=t[u+3*b+1],j=t[u+3*b+2];r[d++]=j,r[d++]=C,r[d++]=w,r[d++]=255}--f}},this.decodeAndBlitFrameRGBA=function(e,r){var i=this.frameInfo(e),o=i.width*i.height,a=new Uint8Array(o);s(t,i.data_offset,a,o);var u=i.palette_offset,c=i.transparent_index;null===c&&(c=256);var l=i.width,h=n-l,f=l,p=4*(i.y*n+i.x),_=4*((i.y+i.height)*n+i.x),d=p,v=4*h;i.interlaced===!0&&(v+=4*n*7);for(var y=8,m=0,g=a.length;g>m;++m){var b=a[m];if(0===f&&(d+=v,f=l,d>=_&&(v=4*h+4*n*(y-1),d=p+(l+h)*(y<<1),y>>=1)),b===c)d+=4;else{var w=t[u+3*b],C=t[u+3*b+1],j=t[u+3*b+2];r[d++]=w,r[d++]=C,r[d++]=j,r[d++]=255}--f}}}function s(t,e,n,r){for(var i=t[e++],o=1<l&&0!==p;)h|=t[e++]<l)break;var v=h&c;if(h>>=u,l-=u,v!==o){if(v===s)break;for(var y=a>v?v:d,m=0,g=y;g>o;)g=_[g]>>8,++m;var b=g,w=f+m+(y!==v?1:0);if(w>r)return void console.log("Warning, gif stream longer than expected.");n[f++]=b,f+=m;var C=f;for(y!==v&&(n[f++]=b),g=y;m--;)g=_[g],n[--C]=255&g,g>>=8;null!==d&&4096>a&&(_[a++]=d<<8|b,a>=c+1&&12>u&&(++u,c=c<<1|1)),d=v}else a=s+1,u=i+1,c=(1</gm,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0==t.index}function a(e){return/^(no-?highlight|plain|text)$/i.test(e)}function i(e){var n,t,r,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=/\blang(?:uage)?-([\w-]+)\b/i.exec(i))return w(t[1])?t[1]:"no-highlight";for(i=i.split(/\s+/),n=0,r=i.length;r>n;n++)if(w(i[n])||a(i[n]))return i[n]}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3==i.nodeType?a+=i.nodeValue.length:1==i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!=r[0].offset?e[0].offset"}function u(e){f+=""}function c(e){("start"==e.event?o:u)(e.node)}for(var s=0,f="",l=[];e.length||r.length;){var g=i();if(f+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g==e){l.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g==e&&g.length&&g[0].offset==s);l.reverse().forEach(o)}else"start"==g[0].event?l.push(g[0].node):l.pop(),c(g.splice(0,1)[0])}return f+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):Object.keys(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\b\w+\b/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),void 0===a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"==e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var f=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=f.length?t(f.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){for(var t=0;t";return i+=e+'">',i+n+o}function p(){if(!L.k)return n(y);var e="",t=0;L.lR.lastIndex=0;for(var r=L.lR.exec(y);r;){e+=n(y.substr(t,r.index-t));var a=g(L,r);a?(B+=a[1],e+=h(a[0],n(r[0]))):e+=n(r[0]),t=L.lR.lastIndex,r=L.lR.exec(y)}return e+n(y.substr(t))}function d(){var e="string"==typeof L.sL;if(e&&!x[L.sL])return n(y);var t=e?f(L.sL,y,!0,M[L.sL]):l(y,L.sL.length?L.sL:void 0);return L.r>0&&(B+=t.r),e&&(M[L.sL]=t.top),h(t.language,t.value,!1,!0)}function b(){return void 0!==L.sL?d():p()}function v(e,t){var r=e.cN?h(e.cN,"",!0):"";e.rB?(k+=r,y=""):e.eB?(k+=n(t)+r,y=""):(k+=r,y=t),L=Object.create(e,{parent:{value:L}})}function m(e,t){if(y+=e,void 0===t)return k+=b(),0;var r=o(t,L);if(r)return k+=b(),v(r,t),r.rB?0:t.length;var a=u(L,t);if(a){var i=L;i.rE||i.eE||(y+=t),k+=b();do L.cN&&(k+=""),B+=L.r,L=L.parent;while(L!=a.parent);return i.eE&&(k+=n(t)),y="",a.starts&&v(a.starts,""),i.rE?0:t.length}if(c(t,L))throw new Error('Illegal lexeme "'+t+'" for mode "'+(L.cN||"")+'"');return y+=t,t.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var R,L=i||N,M={},k="";for(R=L;R!=N;R=R.parent)R.cN&&(k=h(R.cN,"",!0)+k);var y="",B=0;try{for(var C,j,I=0;;){if(L.t.lastIndex=I,C=L.t.exec(t),!C)break;j=m(t.substr(I,C.index-I),C[0]),I=C.index+j}for(m(t.substr(I)),R=L;R.parent;R=R.parent)R.cN&&(k+="");return{r:B,value:k,language:e,top:L}}catch(O){if(-1!=O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function l(e,t){t=t||E.languages||Object.keys(x);var r={r:0,value:n(e)},a=r;return t.forEach(function(n){if(w(n)){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}}),a.language&&(r.second_best=a),r}function g(e){return E.tabReplace&&(e=e.replace(/^((<[^>]+>|\t)+)/gm,function(e,n){return n.replace(/\t/g,E.tabReplace)})),E.useBR&&(e=e.replace(/\n/g,"
")),e}function h(e,n,t){var r=n?R[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function p(e){var n=i(e);if(!a(n)){var t;E.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):t=e;var r=t.textContent,o=n?f(n,r,!0):l(r),s=u(t);if(s.length){var p=document.createElementNS("http://www.w3.org/1999/xhtml","div");p.innerHTML=o.value,o.value=c(s,u(p),r)}o.value=g(o.value),e.innerHTML=o.value,e.className=h(e.className,n,o.language),e.result={language:o.language,re:o.r},o.second_best&&(e.second_best={language:o.second_best.language,re:o.second_best.r})}}function d(e){E=o(E,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");Array.prototype.forEach.call(e,p)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=x[n]=t(e);r.aliases&&r.aliases.forEach(function(e){R[e]=n})}function N(){return Object.keys(x)}function w(e){return e=e.toLowerCase(),x[e]||x[R[e]]}var E={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},x={},R={};return e.highlight=f,e.highlightAuto=l,e.fixMarkup=g,e.highlightBlock=p,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/-?[a-z\.]+/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",operator:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"shebang",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,e.NM,s,a,t]}});hljs.registerLanguage("css",function(e){var c="[a-zA-Z-][a-zA-Z0-9_-]*",a={cN:"function",b:c+"\\(",rB:!0,eE:!0,e:"\\("},r={cN:"rule",b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{cN:"value",eW:!0,eE:!0,c:[a,e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"hexcolor",b:"#[0-9A-Fa-f]+"},{cN:"important",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,r,{cN:"id",b:/\#[A-Za-z0-9_-]+/},{cN:"class",b:/\.[A-Za-z0-9_-]+/},{cN:"attr_selector",b:/\[/,e:/\]/,i:"$"},{cN:"pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"']+/},{cN:"at_rule",b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{cN:"at_rule",b:"@",e:"[{;]",c:[{cN:"keyword",b:/\S+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[a,e.ASM,e.QSM,e.CSSNM]}]},{cN:"tag",b:c,r:0},{cN:"rules",b:"{",e:"}",i:/\S/,c:[e.CBCM,r]}]}});hljs.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"header",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"blockquote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{cN:"horizontal_rule",b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"link_label",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link_url",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"link_reference",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:"^\\[.+\\]:",rB:!0,c:[{cN:"link_reference",b:"\\[",e:"\\]:",eB:!0,eE:!0,starts:{cN:"link_url",e:"$"}}]}]}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"chunk",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"header",v:[{b:/Index: /,e:/$/},{b:/=====/,e:/=====$/},{b:/^\-\-\-/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+\+\+/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"change",b:"^\\!",e:"$"}]}});hljs.registerLanguage("json",function(e){var t={literal:"true false null"},i=[e.QSM,e.CNM],l={cN:"value",e:",",eW:!0,eE:!0,c:i,k:t},c={b:"{",e:"}",c:[{cN:"attribute",b:'\\s*"',e:'"\\s*:\\s*',eB:!0,eE:!0,c:[e.BE],i:"\\n",starts:l}],i:"\\S"},n={b:"\\[",e:"\\]",c:[e.inherit(l,{cN:null})],i:"\\S"};return i.splice(i.length,0,c,n),{c:i,k:t,i:"\\S"}});hljs.registerLanguage("coffeescript",function(e){var c={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},n="[A-Za-z$_][0-9A-Za-z$_]*",r={cN:"subst",b:/#\{/,e:/}/,k:c},t=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,r]},{b:/"/,e:/"/,c:[e.BE,r]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[r,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{cN:"property",b:"@"+n},{b:"`",e:"`",eB:!0,eE:!0,sL:"javascript"}];r.c=t;var s=e.inherit(e.TM,{b:n}),i="(\\(.*\\))?\\s*\\B[-=]>",o={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:c,c:["self"].concat(t)}]};return{aliases:["coffee","cson","iced"],k:c,i:/\/\*/,c:t.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+n+"\\s*=\\s*"+i,e:"[-=]>",rB:!0,c:[s,o]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:i,e:"[-=]>",rB:!0,c:[o]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[s]},s]},{cN:"attribute",b:n+":",e:":",rB:!0,rE:!0,r:0}])}});hljs.registerLanguage("javascript",function(e){return{aliases:["js"],k:{keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},c:[{cN:"pi",r:10,b:/^\s*['"]use (strict|asm)['"]/},e.ASM,e.QSM,{cN:"string",b:"`",e:"`",c:[e.BE,{cN:"subst",b:"\\$\\{",e:"\\}"}]},e.CLCM,e.CBCM,{cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{b:/\s*[);\]]/,r:0,sL:"xml"}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:[e.CLCM,e.CBCM]}],i:/\[|%/},{b:/\$[(.]/},{b:"\\."+e.IR,r:0},{bK:"import",e:"[;$]",k:"import from as",c:[e.ASM,e.QSM]},{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]}],i:/#/}});hljs.registerLanguage("xml",function(t){var s="[A-Za-z0-9\\._:-]+",c={b:/<\?(php)?(?!\w)/,e:/\?>/,sL:"php"},e={eW:!0,i:/]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xsl","plist"],cI:!0,c:[{cN:"doctype",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},t.C("",{r:10}),{cN:"cdata",b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"|$)",e:">",k:{title:"style"},c:[e],starts:{e:"",rE:!0,sL:"css"}},{cN:"tag",b:"|$)",e:">",k:{title:"script"},c:[e],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars"]}},c,{cN:"pi",b:/<\?\w+/,e:/\?>/,r:10},{cN:"tag",b:"",c:[{cN:"title",b:/[^ \/><\n\t]+/,r:0},e]}]}}); ================================================ FILE: gh-pages/assets/lib/monokai_sublime.css ================================================ /* Monokai Sublime style. Derived from Monokai by noformnocontent http://nn.mit-license.org/ */ .hljs { display: block; overflow-x: auto; padding: 0.5em; background: #23241f; -webkit-text-size-adjust: none; } .hljs, .hljs-tag, .css .hljs-rule, .css .hljs-value, .aspectj .hljs-function, .css .hljs-function .hljs-preprocessor, .hljs-pragma { color: #f8f8f2; } .hljs-strongemphasis, .hljs-strong, .hljs-emphasis { color: #a8a8a2; } .hljs-bullet, .hljs-blockquote, .hljs-horizontal_rule, .hljs-number, .hljs-regexp, .alias .hljs-keyword, .hljs-literal, .hljs-hexcolor { color: #ae81ff; } .hljs-tag .hljs-value, .hljs-code, .hljs-title, .css .hljs-class, .hljs-class .hljs-title:last-child { color: #a6e22e; } .hljs-link_url { font-size: 80%; } .hljs-strong, .hljs-strongemphasis { font-weight: bold; } .hljs-emphasis, .hljs-strongemphasis, .hljs-class .hljs-title:last-child, .hljs-typename { font-style: italic; } .hljs-keyword, .ruby .hljs-class .hljs-keyword:first-child, .ruby .hljs-function .hljs-keyword, .hljs-function, .hljs-change, .hljs-winutils, .hljs-flow, .nginx .hljs-title, .tex .hljs-special, .hljs-header, .hljs-attribute, .hljs-symbol, .hljs-symbol .hljs-string, .hljs-tag .hljs-title, .hljs-value, .alias .hljs-keyword:first-child, .css .hljs-tag, .css .unit, .css .hljs-important { color: #f92672; } .hljs-function .hljs-keyword, .hljs-class .hljs-keyword:first-child, .hljs-aspect .hljs-keyword:first-child, .hljs-constant, .hljs-typename, .hljs-name, .css .hljs-attribute { color: #66d9ef; } .hljs-variable, .hljs-params, .hljs-class .hljs-title, .hljs-aspect .hljs-title { color: #f8f8f2; } .hljs-string, .css .hljs-id, .hljs-subst, .hljs-type, .ruby .hljs-class .hljs-parent, .hljs-built_in, .django .hljs-template_tag, .django .hljs-variable, .smalltalk .hljs-class, .django .hljs-filter .hljs-argument, .smalltalk .hljs-localvars, .smalltalk .hljs-array, .hljs-attr_selector, .hljs-pseudo, .hljs-addition, .hljs-stream, .hljs-envvar, .apache .hljs-tag, .apache .hljs-cbracket, .tex .hljs-command, .hljs-prompt, .hljs-link_label, .hljs-link_url { color: #e6db74; } .hljs-comment, .hljs-annotation, .hljs-decorator, .hljs-pi, .hljs-doctype, .hljs-deletion, .hljs-shebang, .apache .hljs-sqbracket, .tex .hljs-formula { color: #75715e; } .coffeescript .javascript, .javascript .xml, .tex .hljs-formula, .xml .javascript, .xml .vbscript, .xml .css, .xml .hljs-cdata, .xml .php, .php .xml { opacity: 0.5; } ================================================ FILE: gh-pages/docs.css ================================================ h2 { font-weight: 100; color: #BD1550; font-size: 30px; line-height: 30px; margin-top: 20px; margin-bottom: 10px; } h4 { font-weight: 700; margin-top: 30px; margin-bottom: 20px; } p.text { line-height: 1.2em; } table.arguments { width: 100%; border-collapse: collapse; table-layout: fixed; } table.arguments td { padding: 10px 15px; border: 1px solid #DDD; vertical-align: top; } table.arguments td.name { width: 110px; } ================================================ FILE: gh-pages/docs.html ================================================

gifler()

This is the main entrypoint to the library.

Prepares and sends an XHR request to load the GIF file.

Returns a Gif instance for interacting with the library.

Arguments

url URL to .gif file

Returns

a Gif instance object

gif.animate()

Animates the loaded GIF, drawing each frame into the canvas. This matches the look of an <img> tag.

Arguments

selector A <canvas> element or query selector for a <canvas> element.

gif.frames()

Runs the animation on the loaded GIF, but passes the canvas context and GIF frame to the onDrawFrame callback for rendering.

This gives you complete control of how the frame is drawn into the canvas context.

Arguments

selector A <canvas> element or query selector for a <canvas> element.
onDrawFrame A callback that will be invoked when each frame should be drawn into the canvas. see Animator.onDrawFrame.
setDimesions OPTIONAL. If true, the canvas's width/height will be set to the dimension of the loaded GIF. default: false.

gif.get()

To get even more control, and for your convenience, this method returns a promise that will be fulfilled with an Animator instance. The animator will be in an unstarted state, but can be started with a call to animator.animateInCanvas()

animator::createBufferCanvas()

Creates a buffer canvas element since it is much faster to call .putImage() than .putImageData().

The omggif library decodes the pixels into the full gif dimensions. We only need to store the frame dimensions, so we offset the putImageData call.

Arguments

frame A frame of the GIF (from the omggif library)
width width of the GIF (not the frame)
height height of the GIF

Returns

A <canvas> element containing the frame's image.

animator.start()

Starts running the GIF animation loop.

animator.stop()

Stops running the GIF animation loop.

animator.reset()

Resets the animation loop to the first frame.

Does not stop the animation from running.

animator.running()

Returns

A boolean indicating whether or not the animation is running.

animator.animateInCanvas()

This method prepares the canvas to be drawn into and sets up the callbacks for each frame while the animation is running.

To change how each frame is drawn into the canvas, override animator.onDrawFrame() before calling this method. If animator.onDrawFrame() is not set, we simply draw the frame directly into the canvas as is.

You may also override animator.onFrame() before calling this method. onFrame handles the lazy construction of canvas buffers for each frame as well as the disposal method for each frame.

Arguments

canvas A canvas element.
setDimensions OPTIONAL. If true, the canvas width/height will be set to match the GIF. default: true.
================================================ FILE: gh-pages/examples.css ================================================ h3 { font-size: 30px; line-height: 40px; } table.comparisons { width: 100%; table-layout: fixed; text-align: center; } table.comparisons td img { width: 300px; height: 300px; } table.comparisons td canvas { width: 300px; height: 300px; } @media only screen and (max-device-width: 480px) { table.comparisons td img { width: 150px; height: 150px; } table.comparisons td canvas { width: 150px; height: 150px; } } .source { font-size: 14px; color: #AAA; float: right; margin-right: 20px; margin-bottom: 20px; clear: both; } ================================================ FILE: gh-pages/examples.html ================================================

<img>

<canvas>

Source: http://www.wired.co.uk/
Source: Florian de Looij
Source: http://www.weshootfood.net/
Source: David Ope
================================================ FILE: gh-pages/index.css ================================================ .hero { width: 100vw; height: 66vh; background-color: #490A3D; display: table-cell; text-align: center; vertical-align: middle; } .hero h1 { color: white; font-size: 140px; line-height: 150px; font-weight: 100; margin-top: 15px; } .hero h2 { color: rgba(255, 255, 255, 0.5); font-size: 20px; font-weight: normal; } .hero .download { margin-top: 50px; margin-bottom: 15px; padding: 0px 0px; width: 200px; height: 60px; line-height: 60px; font-size: 24px; } .canvas-wrapper { max-width: 100vw; padding: 15px 15px; } .canvas-wrapper canvas { max-width: 100%; } .canvas-wrapper canvas.rainbow-pikachus { width: 100%; height: 100px; } pre code { padding: 15px 15px !important; box-sizing: border-box; overflow-x: scroll !important; -webkit-touch-callout: text; -webkit-user-select: text; -khtml-user-select: text; -moz-user-select: text; -ms-user-select: text; user-select: text; } .tech-icons { font-size: 50px; text-align: center; margin: 30px 0px; color: #AAA; } .tech-icons span { margin: 0px 15px; } ================================================ FILE: gh-pages/index.html ================================================

Gifler

Render GIF frames to <canvas>

Download

Hello, Gifler!

Getting started is easy! Just call the gifler function to load a GIF. Then run the animation in a canvas using the .animate() method. The method .animate() accepts a canvas DOM element or a string selector to a canvas element.
gifler('assets/gif/run.gif').animate('canvas.running-pikachu')

Custom Rendering

Gifler makes it easy to manipulate the underlying frames from the GIF. Just call the .frames() method with a canvas selector and a callback that will be called when each frame should be renderd. Gifler handles all the timing calculations and GIF transition logic. Just put the pixels you want to see into the canvas.
var frames = 0;

function onDrawFrame(ctx, frame) {
  // Match width/height to remove distortion
  ctx.canvas.width  = ctx.canvas.offsetWidth;
  ctx.canvas.height = ctx.canvas.offsetHeight;

  // Determine how many pikachus will fit on screen
  var n = Math.floor((ctx.canvas.width)/150)

  for(var x = 0; x < n; x++) {
    // Draw a pikachu
    var left = x * 150;
    ctx.globalCompositeOperation = 'source-over';
    ctx.drawImage(frame.buffer, frame.x + left, frame.y, 150, 100);

    // Composite a color
    var hue = (frames * 10 + x * 50) % 360;
    ctx.globalCompositeOperation = 'source-atop';
    ctx.fillStyle = 'hsla(' + hue + ', 100%, 50%, 0.5)';
    ctx.fillRect(left, 0, 150, this.height);
  }
  frames++;
}

// Load the GIF, set custom frame render function
gifler('assets/gif/run.gif')
  .frames('canvas.rainbow-pikachus', onDrawFrame);

Play/Pause Control

With access to Gifler''s animator, you can stop and start the animation with ease. When running, the animator will automatically compensate for canvas render time when computing when to draw the next GIF frame.

Try clicking the animation below to start/stop it.
gifler('assets/gif/run.gif')
  .animate('canvas.play-pause')
  .then(function(animator) {
    $('canvas.play-pause').click(function(){
      if(animator.running()){
        animator.stop();
      } else {
        animator.start();
      }
    });
  });
================================================ FILE: gh-pages/theme.css ================================================ a, div { box-sizing: border-box; } a { text-decoration: none; } h1, h2, h3, h4 { color: black; box-sizing: border-box; font-weight: 700; padding: 0px 0px; margin: 0px 0px; } body { font-family: "Roboto"; text-align: center; background: #490A3D; color: #555; margin: 0; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } body > div { font-size: 16px; line-height: 1em; } .nav-top { width: 100%; height: 60px; background-color: #BD1550; } .nav-top .nav-left { float: left; margin-left: 20px; } @media only screen and (max-device-width: 400px) { .nav-top .nav-left { margin-left: 0px; } } .nav-top .nav-right { float: right; margin-right: 20px; } @media only screen and (max-device-width: 400px) { .nav-top .nav-right { display: none; } } .nav-top .devicons { font-size: 50px; line-height: 60px; } .nav-top a { display: inline-block; color: white; line-height: 60px; height: 60px; border-bottom: 5px solid transparent; padding: 0px 15px; } .nav-top a:hover { border-bottom-color: #eb4d84; } .content-row { text-align: center; background: white; } .content { display: inline-block; text-align: left; padding: 15px 0px; width: 700px; max-width: 100vw; } .content h2 { font-size: 40px; line-height: 40px; padding: 30px 0px 15px 0px; } .content .flavor { font-weight: 300; line-height: 1.2em; margin-bottom: 2em; } .block { padding-left: 15px; padding-right: 15px; } .button { padding: 15px 30px; background: #BD1550; color: white; cursor: pointer; display: inline-block; } .button:hover { background: #eb4d84; } .footer { margin: 30px 0px; color: #BD1550; } .footer a { color: #BD1550; } ================================================ FILE: gifler.bare.js ================================================ // Generated by CoffeeScript 1.10.0 var Animator, Decoder, Gif, GifReader, Promise, gifler, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; GifReader = require('omggif').GifReader; Promise = require('bluebird'); /*--- head : 'gifler()' text : - This is the main entrypoint to the library. - Prepares and sends an XHR request to load the GIF file. - Returns a Gif instance for interacting with the library. args : url : 'URL to .gif file' return : 'a Gif instance object' */ gifler = function(url) { var aync, promise, xhr; xhr = new XMLHttpRequest(); xhr.open('GET', url, aync = true); xhr.responseType = 'arraybuffer'; promise = new Promise(function(resolve, reject) { return xhr.onload = function(e) { return resolve(this.response); }; }); xhr.send(); return new Gif(promise); }; Gif = (function() { Gif.getCanvasElement = function(selector) { var element, ref; if (typeof selector === 'string' && ((ref = (element = document.querySelector(selector))) != null ? ref.tagName : void 0) === 'CANVAS') { return element; } else if ((selector != null ? selector.tagName : void 0) === 'CANVAS') { return selector; } else { throw new Error('Unexpected selector type. Valid types are query-selector-string/canvas-element'); } }; function Gif(dataPromise) { this._animatorPromise = dataPromise.then(function(data) { var reader; reader = new GifReader(new Uint8Array(data)); return Decoder.decodeFramesAsync(reader).then(function(frames) { return new Animator(reader, frames); }); }); } /*--- head : 'gif.animate()' text : - > Animates the loaded GIF, drawing each frame into the canvas. This matches the look of an <img> tag. args : selector : 'A element or query selector for a element.' */ Gif.prototype.animate = function(selector) { var canvas; canvas = Gif.getCanvasElement(selector); return this._animatorPromise.then(function(animator) { return animator.animateInCanvas(canvas); }); }; /*--- head : 'gif.frames()' text : - > Runs the animation on the loaded GIF, but passes the canvas context and GIF frame to the onDrawFrame callback for rendering. - > This gives you complete control of how the frame is drawn into the canvas context. args : selector : 'A element or query selector for a element.' onDrawFrame : 'A callback that will be invoked when each frame should be drawn into the canvas. see Animator.onDrawFrame.' setDimesions : 'OPTIONAL. If true, the canvas''s width/height will be set to the dimension of the loaded GIF. default: false.' */ Gif.prototype.frames = function(selector, onDrawFrame, setCanvasDimesions) { var canvas; if (setCanvasDimesions == null) { setCanvasDimesions = false; } canvas = Gif.getCanvasElement(selector); return this._animatorPromise.then(function(animator) { animator.onDrawFrame = onDrawFrame; return animator.animateInCanvas(canvas, setCanvasDimesions); }); }; /*--- head : 'gif.get()' text : - > To get even more control, and for your convenience, this method returns a promise that will be fulfilled with an Animator instance. The animator will be in an unstarted state, but can be started with a call to animator.animateInCanvas() */ Gif.prototype.get = function(callback) { return this._animatorPromise; }; return Gif; })(); /* These methods decode the pixels for each frame (decompressing and de-interlacing) into a Uint8ClampedArray, which is suitable for canvas ImageData. */ Decoder = (function() { function Decoder() {} Decoder.decodeFramesSync = function(reader) { var j, ref, results; return (function() { results = []; for (var j = 0, ref = reader.numFrames(); 0 <= ref ? j < ref : j > ref; 0 <= ref ? j++ : j--){ results.push(j); } return results; }).apply(this).map(function(frameIndex) { return Decoder.decodeFrame(reader, frameIndex); }); }; Decoder.decodeFramesAsync = function(reader) { var concurrency, j, ref, results; return Promise.map((function() { results = []; for (var j = 0, ref = reader.numFrames(); 0 <= ref ? j < ref : j > ref; 0 <= ref ? j++ : j--){ results.push(j); } return results; }).apply(this), (function(i) { return Decoder.decodeFrame(reader, i); }), concurrency = 1); }; Decoder.decodeFrame = function(reader, frameIndex) { var frameInfo; frameInfo = reader.frameInfo(frameIndex); frameInfo.pixels = new Uint8ClampedArray(reader.width * reader.height * 4); reader.decodeAndBlitFrameRGBA(frameIndex, frameInfo.pixels); return frameInfo; }; return Decoder; })(); Animator = (function() { /*--- head : 'animator::createBufferCanvas()' text : - > Creates a buffer canvas element since it is much faster to call .putImage() than .putImageData(). - > The omggif library decodes the pixels into the full gif dimensions. We only need to store the frame dimensions, so we offset the putImageData call. args : frame : A frame of the GIF (from the omggif library) width : width of the GIF (not the frame) height : height of the GIF return : A element containing the frame's image. */ Animator.createBufferCanvas = function(frame, width, height) { var bufferCanvas, bufferContext, imageData; bufferCanvas = document.createElement('canvas'); bufferContext = bufferCanvas.getContext('2d'); bufferCanvas.width = frame.width; bufferCanvas.height = frame.height; imageData = bufferContext.createImageData(width, height); imageData.data.set(frame.pixels); bufferContext.putImageData(imageData, -frame.x, -frame.y); return bufferCanvas; }; function Animator(_reader, _frames) { var ref; this._reader = _reader; this._frames = _frames; this._advanceFrame = bind(this._advanceFrame, this); this._nextFrameRender = bind(this._nextFrameRender, this); this._nextFrame = bind(this._nextFrame, this); ref = this._reader, this.width = ref.width, this.height = ref.height; this._loopCount = this._reader.loopCount(); this._loops = 0; this._frameIndex = 0; this._running = false; } /*--- head : 'animator.start()' text : - Starts running the GIF animation loop. */ Animator.prototype.start = function() { this._lastTime = new Date().valueOf(); this._delayCompensation = 0; this._running = true; setTimeout(this._nextFrame, 0); return this; }; /*--- head : 'animator.stop()' text : - Stops running the GIF animation loop. */ Animator.prototype.stop = function() { this._running = false; return this; }; /*--- head : 'animator.reset()' text : - Resets the animation loop to the first frame. - Does not stop the animation from running. */ Animator.prototype.reset = function() { this._frameIndex = 0; this._loops = 0; return this; }; /*--- head : 'animator.running()' return : A boolean indicating whether or not the animation is running. */ Animator.prototype.running = function() { return this._running; }; Animator.prototype._nextFrame = function() { requestAnimationFrame(this._nextFrameRender); }; Animator.prototype._nextFrameRender = function() { var frame, ref; if (!this._running) { return; } frame = this._frames[this._frameIndex]; if ((ref = this.onFrame) != null) { ref.apply(this, [frame, this._frameIndex]); } return this._enqueueNextFrame(); }; Animator.prototype._advanceFrame = function() { this._frameIndex += 1; if (this._frameIndex >= this._frames.length) { if (this._loopCount !== 0 && this._loopCount === this._loops) { this.stop(); } else { this._frameIndex = 0; this._loops += 1; } } }; Animator.prototype._enqueueNextFrame = function() { var actualDelay, delta, frame, frameDelay; this._advanceFrame(); while (this._running) { frame = this._frames[this._frameIndex]; delta = new Date().valueOf() - this._lastTime; this._lastTime += delta; this._delayCompensation += delta; frameDelay = frame.delay * 10; actualDelay = frameDelay - this._delayCompensation; this._delayCompensation -= frameDelay; if (actualDelay < 0) { this._advanceFrame(); continue; } else { setTimeout(this._nextFrame, actualDelay); break; } } }; /*--- head : 'animator.animateInCanvas()' text : - > This method prepares the canvas to be drawn into and sets up the callbacks for each frame while the animation is running. - > To change how each frame is drawn into the canvas, override animator.onDrawFrame() before calling this method. If animator.onDrawFrame() is not set, we simply draw the frame directly into the canvas as is. - > You may also override animator.onFrame() before calling this method. onFrame handles the lazy construction of canvas buffers for each frame as well as the disposal method for each frame. args : canvas : A canvas element. setDimensions : 'OPTIONAL. If true, the canvas width/height will be set to match the GIF. default: true.' */ Animator.prototype.animateInCanvas = function(canvas, setDimensions) { var ctx; if (setDimensions == null) { setDimensions = true; } if (setDimensions) { canvas.width = this.width; canvas.height = this.height; } ctx = canvas.getContext('2d'); if (this.onDrawFrame == null) { this.onDrawFrame = function(ctx, frame, i) { return ctx.drawImage(frame.buffer, frame.x, frame.y); }; } if (this.onFrame == null) { this.onFrame = (function(_this) { return function(frame, i) { var ref, saved; if (frame.buffer == null) { frame.buffer = Animator.createBufferCanvas(frame, _this.width, _this.height); } if (typeof _this.disposeFrame === "function") { _this.disposeFrame(); } switch (frame.disposal) { case 2: _this.disposeFrame = function() { return ctx.clearRect(0, 0, canvas.width, canvas.height); }; break; case 3: saved = ctx.getImageData(0, 0, canvas.width, canvas.height); _this.disposeFrame = function() { return ctx.putImageData(saved, 0, 0); }; break; default: _this.disposeFrame = null; } return (ref = _this.onDrawFrame) != null ? ref.apply(_this, [ctx, frame, i]) : void 0; }; })(this); } this.start(); return this; }; return Animator; })(); gifler.Gif = Gif; gifler.Decoder = Decoder; gifler.Animator = Animator; if (typeof window !== "undefined" && window !== null) { window.gifler = gifler; } if (typeof module !== "undefined" && module !== null) { module.exports = gifler; } ================================================ FILE: gifler.bundle.js ================================================ (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);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;oGif instance for interacting with the library. args : url : 'URL to .gif file' return : 'a Gif instance object' */ gifler = function(url) { var aync, promise, xhr; xhr = new XMLHttpRequest(); xhr.open('GET', url, aync = true); xhr.responseType = 'arraybuffer'; promise = new Promise(function(resolve, reject) { return xhr.onload = function(e) { return resolve(this.response); }; }); xhr.send(); return new Gif(promise); }; Gif = (function() { Gif.getCanvasElement = function(selector) { var element, ref; if (typeof selector === 'string' && ((ref = (element = document.querySelector(selector))) != null ? ref.tagName : void 0) === 'CANVAS') { return element; } else if ((selector != null ? selector.tagName : void 0) === 'CANVAS') { return selector; } else { throw new Error('Unexpected selector type. Valid types are query-selector-string/canvas-element'); } }; function Gif(dataPromise) { this._animatorPromise = dataPromise.then(function(data) { var reader; reader = new GifReader(new Uint8Array(data)); return Decoder.decodeFramesAsync(reader).then(function(frames) { return new Animator(reader, frames); }); }); } /*--- head : 'gif.animate()' text : - > Animates the loaded GIF, drawing each frame into the canvas. This matches the look of an <img> tag. args : selector : 'A element or query selector for a element.' */ Gif.prototype.animate = function(selector) { var canvas; canvas = Gif.getCanvasElement(selector); return this._animatorPromise.then(function(animator) { return animator.animateInCanvas(canvas); }); }; /*--- head : 'gif.frames()' text : - > Runs the animation on the loaded GIF, but passes the canvas context and GIF frame to the onDrawFrame callback for rendering. - > This gives you complete control of how the frame is drawn into the canvas context. args : selector : 'A element or query selector for a element.' onDrawFrame : 'A callback that will be invoked when each frame should be drawn into the canvas. see Animator.onDrawFrame.' setDimesions : 'OPTIONAL. If true, the canvas''s width/height will be set to the dimension of the loaded GIF. default: false.' */ Gif.prototype.frames = function(selector, onDrawFrame, setCanvasDimesions) { var canvas; if (setCanvasDimesions == null) { setCanvasDimesions = false; } canvas = Gif.getCanvasElement(selector); return this._animatorPromise.then(function(animator) { animator.onDrawFrame = onDrawFrame; return animator.animateInCanvas(canvas, setCanvasDimesions); }); }; /*--- head : 'gif.get()' text : - > To get even more control, and for your convenience, this method returns a promise that will be fulfilled with an Animator instance. The animator will be in an unstarted state, but can be started with a call to animator.animateInCanvas() */ Gif.prototype.get = function(callback) { return this._animatorPromise; }; return Gif; })(); /* These methods decode the pixels for each frame (decompressing and de-interlacing) into a Uint8ClampedArray, which is suitable for canvas ImageData. */ Decoder = (function() { function Decoder() {} Decoder.decodeFramesSync = function(reader) { var j, ref, results; return (function() { results = []; for (var j = 0, ref = reader.numFrames(); 0 <= ref ? j < ref : j > ref; 0 <= ref ? j++ : j--){ results.push(j); } return results; }).apply(this).map(function(frameIndex) { return Decoder.decodeFrame(reader, frameIndex); }); }; Decoder.decodeFramesAsync = function(reader) { var concurrency, j, ref, results; return Promise.map((function() { results = []; for (var j = 0, ref = reader.numFrames(); 0 <= ref ? j < ref : j > ref; 0 <= ref ? j++ : j--){ results.push(j); } return results; }).apply(this), (function(i) { return Decoder.decodeFrame(reader, i); }), concurrency = 1); }; Decoder.decodeFrame = function(reader, frameIndex) { var frameInfo; frameInfo = reader.frameInfo(frameIndex); frameInfo.pixels = new Uint8ClampedArray(reader.width * reader.height * 4); reader.decodeAndBlitFrameRGBA(frameIndex, frameInfo.pixels); return frameInfo; }; return Decoder; })(); Animator = (function() { /*--- head : 'animator::createBufferCanvas()' text : - > Creates a buffer canvas element since it is much faster to call .putImage() than .putImageData(). - > The omggif library decodes the pixels into the full gif dimensions. We only need to store the frame dimensions, so we offset the putImageData call. args : frame : A frame of the GIF (from the omggif library) width : width of the GIF (not the frame) height : height of the GIF return : A element containing the frame's image. */ Animator.createBufferCanvas = function(frame, width, height) { var bufferCanvas, bufferContext, imageData; bufferCanvas = document.createElement('canvas'); bufferContext = bufferCanvas.getContext('2d'); bufferCanvas.width = frame.width; bufferCanvas.height = frame.height; imageData = bufferContext.createImageData(width, height); imageData.data.set(frame.pixels); bufferContext.putImageData(imageData, -frame.x, -frame.y); return bufferCanvas; }; function Animator(_reader, _frames) { var ref; this._reader = _reader; this._frames = _frames; this._advanceFrame = bind(this._advanceFrame, this); this._nextFrameRender = bind(this._nextFrameRender, this); this._nextFrame = bind(this._nextFrame, this); ref = this._reader, this.width = ref.width, this.height = ref.height; this._loopCount = this._reader.loopCount(); this._loops = 0; this._frameIndex = 0; this._running = false; } /*--- head : 'animator.start()' text : - Starts running the GIF animation loop. */ Animator.prototype.start = function() { this._lastTime = new Date().valueOf(); this._delayCompensation = 0; this._running = true; setTimeout(this._nextFrame, 0); return this; }; /*--- head : 'animator.stop()' text : - Stops running the GIF animation loop. */ Animator.prototype.stop = function() { this._running = false; return this; }; /*--- head : 'animator.reset()' text : - Resets the animation loop to the first frame. - Does not stop the animation from running. */ Animator.prototype.reset = function() { this._frameIndex = 0; this._loops = 0; return this; }; /*--- head : 'animator.running()' return : A boolean indicating whether or not the animation is running. */ Animator.prototype.running = function() { return this._running; }; Animator.prototype._nextFrame = function() { requestAnimationFrame(this._nextFrameRender); }; Animator.prototype._nextFrameRender = function() { var frame, ref; if (!this._running) { return; } frame = this._frames[this._frameIndex]; if ((ref = this.onFrame) != null) { ref.apply(this, [frame, this._frameIndex]); } return this._enqueueNextFrame(); }; Animator.prototype._advanceFrame = function() { this._frameIndex += 1; if (this._frameIndex >= this._frames.length) { if (this._loopCount !== 0 && this._loopCount === this._loops) { this.stop(); } else { this._frameIndex = 0; this._loops += 1; } } }; Animator.prototype._enqueueNextFrame = function() { var actualDelay, delta, frame, frameDelay; this._advanceFrame(); while (this._running) { frame = this._frames[this._frameIndex]; delta = new Date().valueOf() - this._lastTime; this._lastTime += delta; this._delayCompensation += delta; frameDelay = frame.delay * 10; actualDelay = frameDelay - this._delayCompensation; this._delayCompensation -= frameDelay; if (actualDelay < 0) { this._advanceFrame(); continue; } else { setTimeout(this._nextFrame, actualDelay); break; } } }; /*--- head : 'animator.animateInCanvas()' text : - > This method prepares the canvas to be drawn into and sets up the callbacks for each frame while the animation is running. - > To change how each frame is drawn into the canvas, override animator.onDrawFrame() before calling this method. If animator.onDrawFrame() is not set, we simply draw the frame directly into the canvas as is. - > You may also override animator.onFrame() before calling this method. onFrame handles the lazy construction of canvas buffers for each frame as well as the disposal method for each frame. args : canvas : A canvas element. setDimensions : 'OPTIONAL. If true, the canvas width/height will be set to match the GIF. default: true.' */ Animator.prototype.animateInCanvas = function(canvas, setDimensions) { var ctx; if (setDimensions == null) { setDimensions = true; } if (setDimensions) { canvas.width = this.width; canvas.height = this.height; } ctx = canvas.getContext('2d'); if (this.onDrawFrame == null) { this.onDrawFrame = function(ctx, frame, i) { return ctx.drawImage(frame.buffer, frame.x, frame.y); }; } if (this.onFrame == null) { this.onFrame = (function(_this) { return function(frame, i) { var ref, saved; if (frame.buffer == null) { frame.buffer = Animator.createBufferCanvas(frame, _this.width, _this.height); } if (typeof _this.disposeFrame === "function") { _this.disposeFrame(); } switch (frame.disposal) { case 2: _this.disposeFrame = function() { return ctx.clearRect(0, 0, canvas.width, canvas.height); }; break; case 3: saved = ctx.getImageData(0, 0, canvas.width, canvas.height); _this.disposeFrame = function() { return ctx.putImageData(saved, 0, 0); }; break; default: _this.disposeFrame = null; } return (ref = _this.onDrawFrame) != null ? ref.apply(_this, [ctx, frame, i]) : void 0; }; })(this); } this.start(); return this; }; return Animator; })(); gifler.Gif = Gif; gifler.Decoder = Decoder; gifler.Animator = Animator; if (typeof window !== "undefined" && window !== null) { window.gifler = gifler; } if (typeof module !== "undefined" && module !== null) { module.exports = gifler; } },{"bluebird":2,"omggif":4}],2:[function(require,module,exports){ (function (process,global){ /* @preserve * The MIT License (MIT) * * Copyright (c) 2013-2015 Petka Antonov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ /** * bluebird build version 3.0.2 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o 0) { var fn = queue.shift(); if (typeof fn !== "function") { fn._settlePromises(); continue; } var receiver = queue.shift(); var arg = queue.shift(); fn.call(receiver, arg); } }; Async.prototype._drainQueues = function () { this._drainQueue(this._normalQueue); this._reset(); this._haveDrainedQueues = true; this._drainQueue(this._lateQueue); }; Async.prototype._queueTick = function () { if (!this._isTickUsed) { this._isTickUsed = true; this._schedule(this.drainQueues); } }; Async.prototype._reset = function () { this._isTickUsed = false; }; module.exports = Async; module.exports.firstLineError = firstLineError; },{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { var calledBind = false; var rejectThis = function(_, e) { this._reject(e); }; var targetRejected = function(e, context) { context.promiseRejectionQueued = true; context.bindingPromise._then(rejectThis, rejectThis, null, this, e); }; var bindingResolved = function(thisArg, context) { if (((this._bitField & 50397184) === 0)) { this._resolveCallback(context.target); } }; var bindingRejected = function(e, context) { if (!context.promiseRejectionQueued) this._reject(e); }; Promise.prototype.bind = function (thisArg) { if (!calledBind) { calledBind = true; Promise.prototype._propagateFrom = debug.propagateFromFunction(); Promise.prototype._boundValue = debug.boundValueFunction(); } var maybePromise = tryConvertToPromise(thisArg); var ret = new Promise(INTERNAL); ret._propagateFrom(this, 1); var target = this._target(); ret._setBoundTo(maybePromise); if (maybePromise instanceof Promise) { var context = { promiseRejectionQueued: false, promise: ret, target: target, bindingPromise: maybePromise }; target._then(INTERNAL, targetRejected, undefined, ret, context); maybePromise._then( bindingResolved, bindingRejected, undefined, ret, context); ret._setOnCancel(maybePromise); } else { ret._resolveCallback(target); } return ret; }; Promise.prototype._setBoundTo = function (obj) { if (obj !== undefined) { this._bitField = this._bitField | 2097152; this._boundTo = obj; } else { this._bitField = this._bitField & (~2097152); } }; Promise.prototype._isBound = function () { return (this._bitField & 2097152) === 2097152; }; Promise.bind = function (thisArg, value) { return Promise.resolve(value).bind(thisArg); }; }; },{}],4:[function(_dereq_,module,exports){ "use strict"; var old; if (typeof Promise !== "undefined") old = Promise; function noConflict() { try { if (Promise === bluebird) Promise = old; } catch (e) {} return bluebird; } var bluebird = _dereq_("./promise")(); bluebird.noConflict = noConflict; module.exports = bluebird; },{"./promise":22}],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"); 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; } ret = compiler(name); cache[name] = ret; cache[" size"]++; if (cache[" size"] > 512) { var keys = Object.keys(cache); for (var i = 0; i < 256; ++i) delete cache[keys[i]]; cache[" size"] = keys.length - 256; } } return ret; }; getMethodCaller = function(name) { return getCompiled(name, makeMethodCaller, callerCache); }; getGetter = function(name) { return getCompiled(name, makeGetter, getterCache); }; } function ensureMethod(obj, methodName) { var fn; if (obj != null) fn = obj[methodName]; if (typeof fn !== "function") { var message = "Object " + util.classString(obj) + " has no method '" + util.toString(methodName) + "'"; throw new Promise.TypeError(message); } return fn; } function caller(obj) { var methodName = this.pop(); var fn = ensureMethod(obj, methodName); return fn.apply(obj, this); } Promise.prototype.call = function (methodName) { var args = [].slice.call(arguments, 1);; if (!true) { if (canEvaluate) { var maybeCaller = getMethodCaller(methodName); if (maybeCaller !== null) { return this._then( maybeCaller, undefined, undefined, args, undefined); } } } args.push(methodName); return this._then(caller, undefined, undefined, args, undefined); }; function namedGetter(obj) { return obj[this]; } function indexedGetter(obj) { var index = +this; if (index < 0) index = Math.max(0, index + obj.length); return obj[index]; } Promise.prototype.get = function (propertyName) { var isIndex = (typeof propertyName === "number"); var getter; if (!isIndex) { if (canEvaluate) { var maybeGetter = getGetter(propertyName); getter = maybeGetter !== null ? maybeGetter : namedGetter; } else { getter = namedGetter; } } else { getter = indexedGetter; } return this._then(getter, undefined, undefined, propertyName, undefined); }; }; },{"./util":36}],6:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var async = Promise._async; Promise.prototype["break"] = Promise.prototype.cancel = function() { if (!debug.cancellation()) return this._warn("cancellation is disabled"); var promise = this; var child = promise; while (promise.isCancellable()) { if (!promise._cancelBy(child)) { if (child._isFollowing()) { child._followee().cancel(); } else { child._cancelBranched(); } break; } var parent = promise._cancellationParent; if (parent == null || !parent.isCancellable()) { if (promise._isFollowing()) { promise._followee().cancel(); } else { promise._cancelBranched(); } break; } else { if (promise._isFollowing()) promise._followee().cancel(); child = promise; promise = parent; } } }; Promise.prototype._branchHasCancelled = function() { this._branchesRemainingToCancel--; }; Promise.prototype._enoughBranchesHaveCancelled = function() { return this._branchesRemainingToCancel === undefined || this._branchesRemainingToCancel <= 0; }; Promise.prototype._cancelBy = function(canceller) { if (canceller === this) { this._branchesRemainingToCancel = 0; this._invokeOnCancel(); return true; } else { this._branchHasCancelled(); if (this._enoughBranchesHaveCancelled()) { this._invokeOnCancel(); return true; } } return false; }; Promise.prototype._cancelBranched = function() { if (this._enoughBranchesHaveCancelled()) { this._cancel(); } }; Promise.prototype._cancel = function() { if (!this.isCancellable()) return; this._setCancelled(); async.invoke(this._cancelPromises, this, undefined); }; Promise.prototype._cancelPromises = function() { if (this._length() > 0) this._settlePromises(); }; Promise.prototype._unsetOnCancel = function() { this._onCancelField = undefined; }; Promise.prototype.isCancellable = function() { return this.isPending() && !this.isCancelled(); }; Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { if (util.isArray(onCancelCallback)) { for (var i = 0; i < onCancelCallback.length; ++i) { this._doInvokeOnCancel(onCancelCallback[i], internalOnly); } } else if (onCancelCallback !== undefined) { if (typeof onCancelCallback === "function") { if (!internalOnly) { var e = tryCatch(onCancelCallback).call(this._boundValue()); if (e === errorObj) { this._attachExtraTrace(e.e); async.throwLater(e.e); } } } else { onCancelCallback._resultCancelled(this); } } }; Promise.prototype._invokeOnCancel = function() { var onCancelCallback = this._onCancel(); this._unsetOnCancel(); async.invoke(this._doInvokeOnCancel, this, onCancelCallback); }; Promise.prototype._invokeInternalOnCancel = function() { if (this.isCancellable()) { this._doInvokeOnCancel(this._onCancel(), true); this._unsetOnCancel(); } }; Promise.prototype._resultCancelled = function() { this.cancel(); }; }; },{"./util":36}],7:[function(_dereq_,module,exports){ "use strict"; module.exports = function(NEXT_FILTER) { var util = _dereq_("./util"); var getKeys = _dereq_("./es5").keys; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function catchFilter(instances, cb, promise) { return function(e) { var boundTo = promise._boundValue(); predicateLoop: for (var i = 0; i < instances.length; ++i) { var item = instances[i]; if (item === Error || (item != null && item.prototype instanceof Error)) { if (e instanceof item) { return tryCatch(cb).call(boundTo, e); } } else if (typeof item === "function") { var matchesPredicate = tryCatch(item).call(boundTo, e); if (matchesPredicate === errorObj) { return matchesPredicate; } else if (matchesPredicate) { return tryCatch(cb).call(boundTo, e); } } else if (util.isObject(e)) { var keys = getKeys(item); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; if (item[key] != e[key]) { continue predicateLoop; } } return tryCatch(cb).call(boundTo, e); } } return NEXT_FILTER; }; } return catchFilter; }; },{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var longStackTraces = false; var contextStack = []; Promise.prototype._promiseCreated = function() {}; Promise.prototype._pushContext = function() {}; Promise.prototype._popContext = function() {return 0;}; Promise._peekContext = Promise.prototype._peekContext = function() {}; function Context() { this._trace = new Context.CapturedTrace(peekContext()); } Context.prototype._pushContext = function () { if (this._trace !== undefined) { this._trace._promisesCreated = 0; contextStack.push(this._trace); } }; Context.prototype._popContext = function () { if (this._trace !== undefined) { var trace = contextStack.pop(); var ret = trace._promisesCreated; trace._promisesCreated = 0; return ret; } return 0; }; function createContext() { if (longStackTraces) return new Context(); } function peekContext() { var lastIndex = contextStack.length - 1; if (lastIndex >= 0) { return contextStack[lastIndex]; } return undefined; } Context.CapturedTrace = null; Context.create = createContext; Context.activateLongStackTraces = function() { longStackTraces = true; Promise.prototype._pushContext = Context.prototype._pushContext; Promise.prototype._popContext = Context.prototype._popContext; Promise._peekContext = Promise.prototype._peekContext = peekContext; Promise.prototype._promiseCreated = function() { var ctx = this._peekContext(); if (ctx) ctx._promisesCreated++; }; }; return Context; }; },{}],9:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, Context) { var getDomain = Promise._getDomain; var async = Promise._async; var Warning = _dereq_("./errors").Warning; var util = _dereq_("./util"); var canAttachTrace = util.canAttachTrace; var unhandledRejectionHandled; var possiblyUnhandledRejection; var bluebirdFramePattern = /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; var stackFramePattern = null; var formatStack = null; var indentStackFrames = false; var printWarning; var debugging =!!(true || util.env("BLUEBIRD_DEBUG") || util.env("NODE_ENV") === "development"); var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && (debugging || util.env("BLUEBIRD_WARNINGS"))); var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); Promise.prototype.suppressUnhandledRejections = function() { var target = this._target(); target._bitField = ((target._bitField & (~1048576)) | 2097152); }; Promise.prototype._ensurePossibleRejectionHandled = function () { if ((this._bitField & 2097152) !== 0) return; this._setRejectionIsUnhandled(); async.invokeLater(this._notifyUnhandledRejection, this, undefined); }; Promise.prototype._notifyUnhandledRejectionIsHandled = function () { fireRejectionEvent("rejectionHandled", unhandledRejectionHandled, undefined, this); }; Promise.prototype._notifyUnhandledRejection = function () { if (this._isRejectionUnhandled()) { var reason = this._settledValue(); this._setUnhandledRejectionIsNotified(); fireRejectionEvent("unhandledRejection", possiblyUnhandledRejection, reason, this); } }; Promise.prototype._setUnhandledRejectionIsNotified = function () { this._bitField = this._bitField | 262144; }; Promise.prototype._unsetUnhandledRejectionIsNotified = function () { this._bitField = this._bitField & (~262144); }; Promise.prototype._isUnhandledRejectionNotified = function () { return (this._bitField & 262144) > 0; }; Promise.prototype._setRejectionIsUnhandled = function () { this._bitField = this._bitField | 1048576; }; Promise.prototype._unsetRejectionIsUnhandled = function () { this._bitField = this._bitField & (~1048576); if (this._isUnhandledRejectionNotified()) { this._unsetUnhandledRejectionIsNotified(); this._notifyUnhandledRejectionIsHandled(); } }; Promise.prototype._isRejectionUnhandled = function () { return (this._bitField & 1048576) > 0; }; Promise.prototype._warn = function(message, shouldUseOwnTrace) { return warn(message, shouldUseOwnTrace, this); }; Promise.onPossiblyUnhandledRejection = function (fn) { var domain = getDomain(); possiblyUnhandledRejection = typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) : undefined; }; Promise.onUnhandledRejectionHandled = function (fn) { var domain = getDomain(); unhandledRejectionHandled = typeof fn === "function" ? (domain === null ? fn : domain.bind(fn)) : undefined; }; Promise.longStackTraces = function () { if (async.haveItemsQueued() && !config.longStackTraces) { throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (!config.longStackTraces && longStackTracesIsSupported()) { config.longStackTraces = true; Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; Context.activateLongStackTraces(); async.disableTrampolineIfNecessary(); } }; Promise.hasLongStackTraces = function () { return config.longStackTraces && longStackTracesIsSupported(); }; Promise.config = function(opts) { opts = Object(opts); if ("longStackTraces" in opts && opts.longStackTraces) { Promise.longStackTraces(); } if ("warnings" in opts) { config.warnings = !!opts.warnings; } if ("cancellation" in opts && opts.cancellation && !config.cancellation) { if (async.haveItemsQueued()) { throw new Error( "cannot enable cancellation after promises are in use"); } Promise.prototype._clearCancellationData = cancellationClearCancellationData; Promise.prototype._propagateFrom = cancellationPropagateFrom; Promise.prototype._onCancel = cancellationOnCancel; Promise.prototype._setOnCancel = cancellationSetOnCancel; Promise.prototype._attachCancellationCallback = cancellationAttachCancellationCallback; Promise.prototype._execute = cancellationExecute; propagateFromFunction = cancellationPropagateFrom; config.cancellation = true; } }; Promise.prototype._execute = function(executor, resolve, reject) { try { executor(resolve, reject); } catch (e) { return e; } }; Promise.prototype._onCancel = function () {}; Promise.prototype._setOnCancel = function (handler) { ; }; Promise.prototype._attachCancellationCallback = function(onCancel) { ; }; Promise.prototype._captureStackTrace = function () {}; Promise.prototype._attachExtraTrace = function () {}; Promise.prototype._clearCancellationData = function() {}; Promise.prototype._propagateFrom = function (parent, flags) { ; ; }; function cancellationExecute(executor, resolve, reject) { var promise = this; try { executor(resolve, reject, function(onCancel) { if (typeof onCancel !== "function") { throw new TypeError("onCancel must be a function, got: " + util.toString(onCancel)); } promise._attachCancellationCallback(onCancel); }); } catch (e) { return e; } } function cancellationAttachCancellationCallback(onCancel) { if (!this.isCancellable()) return this; var previousOnCancel = this._onCancel(); if (previousOnCancel !== undefined) { if (util.isArray(previousOnCancel)) { previousOnCancel.push(onCancel); } else { this._setOnCancel([previousOnCancel, onCancel]); } } else { this._setOnCancel(onCancel); } } function cancellationOnCancel() { return this._onCancelField; } function cancellationSetOnCancel(onCancel) { this._onCancelField = onCancel; } function cancellationClearCancellationData() { this._cancellationParent = undefined; this._onCancelField = undefined; } function cancellationPropagateFrom(parent, flags) { if ((flags & 1) !== 0) { this._cancellationParent = parent; var branchesRemainingToCancel = parent._branchesRemainingToCancel; if (branchesRemainingToCancel === undefined) { branchesRemainingToCancel = 0; } parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; } if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } function bindingPropagateFrom(parent, flags) { if ((flags & 2) !== 0 && parent._isBound()) { this._setBoundTo(parent._boundTo); } } var propagateFromFunction = bindingPropagateFrom; function boundValueFunction() { var ret = this._boundTo; if (ret !== undefined) { if (ret instanceof Promise) { if (ret.isFulfilled()) { return ret.value(); } else { return undefined; } } } return ret; } function longStackTracesCaptureStackTrace() { this._trace = new CapturedTrace(this._peekContext()); } function longStackTracesAttachExtraTrace(error, ignoreSelf) { if (canAttachTrace(error)) { var trace = this._trace; if (trace !== undefined) { if (ignoreSelf) trace = trace._parent; } if (trace !== undefined) { trace.attachExtraTrace(error); } else if (!error.__stackCleaned__) { var parsed = parseStackAndMessage(error); util.notEnumerableProp(error, "stack", parsed.message + "\n" + parsed.stack.join("\n")); util.notEnumerableProp(error, "__stackCleaned__", true); } } } function checkForgottenReturns(returnValue, promisesCreated, name, promise) { if (returnValue === undefined && promisesCreated > 0 && config.longStackTraces && config.warnings) { var msg = "a promise was created in a " + name + " handler but was not returned from it"; promise._warn(msg); } } function deprecated(name, replacement) { var message = name + " is deprecated and will be removed in a future version."; if (replacement) message += " Use " + replacement + " instead."; return warn(message); } function warn(message, shouldUseOwnTrace, promise) { if (!config.warnings) return; var warning = new Warning(message); var ctx; if (shouldUseOwnTrace) { promise._attachExtraTrace(warning); } else if (config.longStackTraces && (ctx = Promise._peekContext())) { ctx.attachExtraTrace(warning); } else { var parsed = parseStackAndMessage(warning); warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); } formatAndLogError(warning, "", true); } function reconstructStack(message, stacks) { for (var i = 0; i < stacks.length - 1; ++i) { stacks[i].push("From previous event:"); stacks[i] = stacks[i].join("\n"); } if (i < stacks.length) { stacks[i] = stacks[i].join("\n"); } return message + "\n" + stacks.join("\n"); } function removeDuplicateOrEmptyJumps(stacks) { for (var i = 0; i < stacks.length; ++i) { if (stacks[i].length === 0 || ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { stacks.splice(i, 1); i--; } } } function removeCommonRoots(stacks) { var current = stacks[0]; for (var i = 1; i < stacks.length; ++i) { var prev = stacks[i]; var currentLastIndex = current.length - 1; var currentLastLine = current[currentLastIndex]; var commonRootMeetPoint = -1; for (var j = prev.length - 1; j >= 0; --j) { if (prev[j] === currentLastLine) { commonRootMeetPoint = j; break; } } for (var j = commonRootMeetPoint; j >= 0; --j) { var line = prev[j]; if (current[currentLastIndex] === line) { current.pop(); currentLastIndex--; } else { break; } } current = prev; } } function cleanStack(stack) { var ret = []; for (var i = 0; i < stack.length; ++i) { var line = stack[i]; var isTraceLine = " (No stack trace)" === line || stackFramePattern.test(line); var isInternalFrame = isTraceLine && shouldIgnore(line); if (isTraceLine && !isInternalFrame) { if (indentStackFrames && line.charAt(0) !== " ") { line = " " + line; } ret.push(line); } } return ret; } function stackFramesAsArray(error) { var stack = error.stack.replace(/\s+$/g, "").split("\n"); for (var i = 0; i < stack.length; ++i) { var line = stack[i]; if (" (No stack trace)" === line || stackFramePattern.test(line)) { break; } } if (i > 0) { stack = stack.slice(i); } return stack; } function parseStackAndMessage(error) { var stack = error.stack; var message = error.toString(); stack = typeof stack === "string" && stack.length > 0 ? stackFramesAsArray(error) : [" (No stack trace)"]; return { message: message, stack: cleanStack(stack) }; } function formatAndLogError(error, title, isSoft) { if (typeof console !== "undefined") { var message; if (util.isObject(error)) { var stack = error.stack; message = title + formatStack(stack, error); } else { message = title + String(error); } if (typeof printWarning === "function") { printWarning(message, isSoft); } else if (typeof console.log === "function" || typeof console.log === "object") { console.log(message); } } } function fireRejectionEvent(name, localHandler, reason, promise) { var localEventFired = false; try { if (typeof localHandler === "function") { localEventFired = true; if (name === "rejectionHandled") { localHandler(promise); } else { localHandler(reason, promise); } } } catch (e) { async.throwLater(e); } var globalEventFired = false; try { globalEventFired = fireGlobalEvent(name, reason, promise); } catch (e) { globalEventFired = true; async.throwLater(e); } var domEventFired = false; if (fireDomEvent) { try { domEventFired = fireDomEvent(name.toLowerCase(), { reason: reason, promise: promise }); } catch (e) { domEventFired = true; async.throwLater(e); } } if (!globalEventFired && !localEventFired && !domEventFired && name === "unhandledRejection") { formatAndLogError(reason, "Unhandled rejection "); } } function formatNonError(obj) { var str; if (typeof obj === "function") { str = "[function " + (obj.name || "anonymous") + "]"; } else { str = obj && typeof obj.toString === "function" ? obj.toString() : util.toString(obj); var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; if (ruselessToString.test(str)) { try { var newStr = JSON.stringify(obj); str = newStr; } catch(e) { } } if (str.length === 0) { str = "(empty array)"; } } return ("(<" + snip(str) + ">, no stack trace)"); } function snip(str) { var maxChars = 41; if (str.length < maxChars) { return str; } return str.substr(0, maxChars - 3) + "..."; } function longStackTracesIsSupported() { return typeof captureStackTrace === "function"; } var shouldIgnore = function() { return false; }; var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; function parseLineInfo(line) { var matches = line.match(parseLineInfoRegex); if (matches) { return { fileName: matches[1], line: parseInt(matches[2], 10) }; } } function setBounds(firstLineError, lastLineError) { if (!longStackTracesIsSupported()) return; var firstStackLines = firstLineError.stack.split("\n"); var lastStackLines = lastLineError.stack.split("\n"); var firstIndex = -1; var lastIndex = -1; var firstFileName; var lastFileName; for (var i = 0; i < firstStackLines.length; ++i) { var result = parseLineInfo(firstStackLines[i]); if (result) { firstFileName = result.fileName; firstIndex = result.line; break; } } for (var i = 0; i < lastStackLines.length; ++i) { var result = parseLineInfo(lastStackLines[i]); if (result) { lastFileName = result.fileName; lastIndex = result.line; break; } } if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || firstFileName !== lastFileName || firstIndex >= lastIndex) { return; } shouldIgnore = function(line) { if (bluebirdFramePattern.test(line)) return true; var info = parseLineInfo(line); if (info) { if (info.fileName === firstFileName && (firstIndex <= info.line && info.line <= lastIndex)) { return true; } } return false; }; } function CapturedTrace(parent) { this._parent = parent; this._promisesCreated = 0; var length = this._length = 1 + (parent === undefined ? 0 : parent._length); captureStackTrace(this, CapturedTrace); if (length > 32) this.uncycle(); } util.inherits(CapturedTrace, Error); Context.CapturedTrace = CapturedTrace; CapturedTrace.prototype.uncycle = function() { var length = this._length; if (length < 2) return; var nodes = []; var stackToIndex = {}; for (var i = 0, node = this; node !== undefined; ++i) { nodes.push(node); node = node._parent; } length = this._length = i; for (var i = length - 1; i >= 0; --i) { var stack = nodes[i].stack; if (stackToIndex[stack] === undefined) { stackToIndex[stack] = i; } } for (var i = 0; i < length; ++i) { var currentStack = nodes[i].stack; var index = stackToIndex[currentStack]; if (index !== undefined && index !== i) { if (index > 0) { nodes[index - 1]._parent = undefined; nodes[index - 1]._length = 1; } nodes[i]._parent = undefined; nodes[i]._length = 1; var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; if (index < length - 1) { cycleEdgeNode._parent = nodes[index + 1]; cycleEdgeNode._parent.uncycle(); cycleEdgeNode._length = cycleEdgeNode._parent._length + 1; } else { cycleEdgeNode._parent = undefined; cycleEdgeNode._length = 1; } var currentChildLength = cycleEdgeNode._length + 1; for (var j = i - 2; j >= 0; --j) { nodes[j]._length = currentChildLength; currentChildLength++; } return; } } }; CapturedTrace.prototype.attachExtraTrace = function(error) { if (error.__stackCleaned__) return; this.uncycle(); var parsed = parseStackAndMessage(error); var message = parsed.message; var stacks = [parsed.stack]; var trace = this; while (trace !== undefined) { stacks.push(cleanStack(trace.stack.split("\n"))); trace = trace._parent; } removeCommonRoots(stacks); removeDuplicateOrEmptyJumps(stacks); util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); util.notEnumerableProp(error, "__stackCleaned__", true); }; var captureStackTrace = (function stackDetection() { var v8stackFramePattern = /^\s*at\s*/; var v8stackFormatter = function(stack, error) { if (typeof stack === "string") return stack; if (error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; if (typeof Error.stackTraceLimit === "number" && typeof Error.captureStackTrace === "function") { Error.stackTraceLimit += 6; stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; var captureStackTrace = Error.captureStackTrace; shouldIgnore = function(line) { return bluebirdFramePattern.test(line); }; return function(receiver, ignoreUntil) { Error.stackTraceLimit += 6; captureStackTrace(receiver, ignoreUntil); Error.stackTraceLimit -= 6; }; } var err = new Error(); if (typeof err.stack === "string" && err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { stackFramePattern = /@/; formatStack = v8stackFormatter; indentStackFrames = true; return function captureStackTrace(o) { o.stack = new Error().stack; }; } var hasStackAfterThrow; try { throw new Error(); } catch(e) { hasStackAfterThrow = ("stack" in e); } if (!("stack" in err) && hasStackAfterThrow && typeof Error.stackTraceLimit === "number") { stackFramePattern = v8stackFramePattern; formatStack = v8stackFormatter; return function captureStackTrace(o) { Error.stackTraceLimit += 6; try { throw new Error(); } catch(e) { o.stack = e.stack; } Error.stackTraceLimit -= 6; }; } formatStack = function(stack, error) { if (typeof stack === "string") return stack; if ((typeof error === "object" || typeof error === "function") && error.name !== undefined && error.message !== undefined) { return error.toString(); } return formatNonError(error); }; return null; })([]); var fireDomEvent; var fireGlobalEvent = (function() { if (util.isNode) { return function(name, reason, promise) { if (name === "rejectionHandled") { return process.emit(name, promise); } else { return process.emit(name, reason, promise); } }; } else { var customEventWorks = false; var anyEventWorks = true; try { var ev = new self.CustomEvent("test"); customEventWorks = ev instanceof CustomEvent; } catch (e) {} if (!customEventWorks) { try { var event = document.createEvent("CustomEvent"); event.initCustomEvent("testingtheevent", false, true, {}); self.dispatchEvent(event); } catch (e) { anyEventWorks = false; } } if (anyEventWorks) { fireDomEvent = function(type, detail) { var event; if (customEventWorks) { event = new self.CustomEvent(type, { detail: detail, bubbles: false, cancelable: true }); } else if (self.dispatchEvent) { event = document.createEvent("CustomEvent"); event.initCustomEvent(type, false, true, detail); } return event ? !self.dispatchEvent(event) : false; }; } var toWindowMethodNameMap = {}; toWindowMethodNameMap["unhandledRejection"] = ("on" + "unhandledRejection").toLowerCase(); toWindowMethodNameMap["rejectionHandled"] = ("on" + "rejectionHandled").toLowerCase(); return function(name, reason, promise) { var methodName = toWindowMethodNameMap[name]; var method = self[methodName]; if (!method) return false; if (name === "rejectionHandled") { method.call(self, promise); } else { method.call(self, reason, promise); } return true; }; } })(); if (typeof console !== "undefined" && typeof console.warn !== "undefined") { printWarning = function (message) { console.warn(message); }; if (util.isNode && process.stderr.isTTY) { printWarning = function(message, isSoft) { var color = isSoft ? "\u001b[33m" : "\u001b[31m"; process.stderr.write(color + message + "\u001b[0m\n"); }; } else if (!util.isNode && typeof (new Error().stack) === "string") { printWarning = function(message, isSoft) { console.warn("%c" + message, isSoft ? "color: darkorange" : "color: red"); }; } } var config = { warnings: warnings, longStackTraces: false, cancellation: false }; if (longStackTraces) Promise.longStackTraces(); return { longStackTraces: function() { return config.longStackTraces; }, warnings: function() { return config.warnings; }, cancellation: function() { return config.cancellation; }, propagateFromFunction: function() { return propagateFromFunction; }, boundValueFunction: function() { return boundValueFunction; }, checkForgottenReturns: checkForgottenReturns, setBounds: setBounds, warn: warn, deprecated: deprecated, CapturedTrace: CapturedTrace }; }; },{"./errors":12,"./util":36}],10:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function returner() { return this.value; } function thrower() { throw this.reason; } Promise.prototype["return"] = Promise.prototype.thenReturn = function (value) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( returner, undefined, undefined, {value: value}, undefined); }; Promise.prototype["throw"] = Promise.prototype.thenThrow = function (reason) { return this._then( thrower, undefined, undefined, {reason: reason}, undefined); }; Promise.prototype.catchThrow = function (reason) { if (arguments.length <= 1) { return this._then( undefined, thrower, undefined, {reason: reason}, undefined); } else { var _reason = arguments[1]; var handler = function() {throw _reason;}; return this.caught(reason, handler); } }; Promise.prototype.catchReturn = function (value) { if (arguments.length <= 1) { if (value instanceof Promise) value.suppressUnhandledRejections(); return this._then( undefined, returner, undefined, {value: value}, undefined); } else { var _value = arguments[1]; if (_value instanceof Promise) _value.suppressUnhandledRejections(); var handler = function() {return _value;}; return this.caught(value, handler); } }; }; },{}],11:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseReduce = Promise.reduce; var PromiseAll = Promise.all; function promiseAllThis() { return PromiseAll(this); } function PromiseMapSeries(promises, fn) { return PromiseReduce(promises, fn, INTERNAL, INTERNAL); } Promise.prototype.each = function (fn) { return this.mapSeries(fn) ._then(promiseAllThis, undefined, undefined, this, undefined); }; Promise.prototype.mapSeries = function (fn) { return PromiseReduce(this, fn, INTERNAL, INTERNAL); }; Promise.each = function (promises, fn) { return PromiseMapSeries(promises, fn) ._then(promiseAllThis, undefined, undefined, promises, undefined); }; Promise.mapSeries = PromiseMapSeries; }; },{}],12:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var Objectfreeze = es5.freeze; var util = _dereq_("./util"); var inherits = util.inherits; var notEnumerableProp = util.notEnumerableProp; function subError(nameProperty, defaultMessage) { function SubError(message) { if (!(this instanceof SubError)) return new SubError(message); notEnumerableProp(this, "message", typeof message === "string" ? message : defaultMessage); notEnumerableProp(this, "name", nameProperty); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { Error.call(this); } } inherits(SubError, Error); return SubError; } var _TypeError, _RangeError; var Warning = subError("Warning", "warning"); var CancellationError = subError("CancellationError", "cancellation error"); var TimeoutError = subError("TimeoutError", "timeout error"); var AggregateError = subError("AggregateError", "aggregate error"); try { _TypeError = TypeError; _RangeError = RangeError; } catch(e) { _TypeError = subError("TypeError", "type error"); _RangeError = subError("RangeError", "range error"); } var methods = ("join pop push shift unshift slice filter forEach some " + "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); for (var i = 0; i < methods.length; ++i) { if (typeof Array.prototype[methods[i]] === "function") { AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; } } es5.defineProperty(AggregateError.prototype, "length", { value: 0, configurable: false, writable: true, enumerable: true }); AggregateError.prototype["isOperational"] = true; var level = 0; AggregateError.prototype.toString = function() { var indent = Array(level * 4 + 1).join(" "); var ret = "\n" + indent + "AggregateError of:" + "\n"; level++; indent = Array(level * 4 + 1).join(" "); for (var i = 0; i < this.length; ++i) { var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; var lines = str.split("\n"); for (var j = 0; j < lines.length; ++j) { lines[j] = indent + lines[j]; } str = lines.join("\n"); ret += str + "\n"; } level--; return ret; }; function OperationalError(message) { if (!(this instanceof OperationalError)) return new OperationalError(message); notEnumerableProp(this, "name", "OperationalError"); notEnumerableProp(this, "message", message); this.cause = message; this["isOperational"] = true; if (message instanceof Error) { notEnumerableProp(this, "message", message.message); notEnumerableProp(this, "stack", message.stack); } else if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } inherits(OperationalError, Error); var errorTypes = Error["__BluebirdErrorTypes__"]; if (!errorTypes) { errorTypes = Objectfreeze({ CancellationError: CancellationError, TimeoutError: TimeoutError, OperationalError: OperationalError, RejectionError: OperationalError, AggregateError: AggregateError }); notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes); } module.exports = { Error: Error, TypeError: _TypeError, RangeError: _RangeError, CancellationError: errorTypes.CancellationError, OperationalError: errorTypes.OperationalError, TimeoutError: errorTypes.TimeoutError, AggregateError: errorTypes.AggregateError, Warning: Warning }; },{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){ var isES5 = (function(){ "use strict"; return this === undefined; })(); if (isES5) { module.exports = { freeze: Object.freeze, defineProperty: Object.defineProperty, getDescriptor: Object.getOwnPropertyDescriptor, keys: Object.keys, names: Object.getOwnPropertyNames, getPrototypeOf: Object.getPrototypeOf, isArray: Array.isArray, isES5: isES5, propertyIsWritable: function(obj, prop) { var descriptor = Object.getOwnPropertyDescriptor(obj, prop); return !!(!descriptor || descriptor.writable || descriptor.set); } }; } else { var has = {}.hasOwnProperty; var str = {}.toString; var proto = {}.constructor.prototype; var ObjectKeys = function (o) { var ret = []; for (var key in o) { if (has.call(o, key)) { ret.push(key); } } return ret; }; var ObjectGetDescriptor = function(o, key) { return {value: o[key]}; }; var ObjectDefineProperty = function (o, key, desc) { o[key] = desc.value; return o; }; var ObjectFreeze = function (obj) { return obj; }; var ObjectGetPrototypeOf = function (obj) { try { return Object(obj).constructor.prototype; } catch (e) { return proto; } }; var ArrayIsArray = function (obj) { try { return str.call(obj) === "[object Array]"; } catch(e) { return false; } }; module.exports = { isArray: ArrayIsArray, keys: ObjectKeys, names: ObjectKeys, defineProperty: ObjectDefineProperty, getDescriptor: ObjectGetDescriptor, freeze: ObjectFreeze, getPrototypeOf: ObjectGetPrototypeOf, isES5: isES5, propertyIsWritable: function() { return true; } }; } },{}],14:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var PromiseMap = Promise.map; Promise.prototype.filter = function (fn, options) { return PromiseMap(this, fn, options, INTERNAL); }; Promise.filter = function (promises, fn, options) { return PromiseMap(promises, fn, options, INTERNAL); }; }; },{}],15:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, tryConvertToPromise) { var util = _dereq_("./util"); var CancellationError = Promise.CancellationError; var errorObj = util.errorObj; function FinallyHandlerCancelReaction(finallyHandler) { this.finallyHandler = finallyHandler; } FinallyHandlerCancelReaction.prototype._resultCancelled = function() { checkCancel(this.finallyHandler); }; function checkCancel(ctx, reason) { if (ctx.cancelPromise != null) { if (arguments.length > 1) { ctx.cancelPromise._reject(reason); } else { ctx.cancelPromise._cancel(); } ctx.cancelPromise = null; return true; } return false; } function succeed() { return finallyHandler.call(this, this.promise._target()._settledValue()); } function fail(reason) { if (checkCancel(this, reason)) return; errorObj.e = reason; return errorObj; } function finallyHandler(reasonOrValue) { var promise = this.promise; var handler = this.handler; if (!this.called) { this.called = true; var ret = this.type === 0 ? handler.call(promise._boundValue()) : handler.call(promise._boundValue(), reasonOrValue); if (ret !== undefined) { var maybePromise = tryConvertToPromise(ret, promise); if (maybePromise instanceof Promise) { if (this.cancelPromise != null) { if (maybePromise.isCancelled()) { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); errorObj.e = reason; return errorObj; } else if (maybePromise.isPending()) { maybePromise._attachCancellationCallback( new FinallyHandlerCancelReaction(this)); } } return maybePromise._then( succeed, fail, undefined, this, undefined); } } } if (promise.isRejected()) { checkCancel(this); errorObj.e = reasonOrValue; return errorObj; } else { checkCancel(this); return reasonOrValue; } } Promise.prototype._passThrough = function(handler, type, success, fail) { if (typeof handler !== "function") return this.then(); return this._then(success, fail, undefined, { promise: this, handler: handler, called: false, cancelPromise: null, type: type }, undefined); }; Promise.prototype.lastly = Promise.prototype["finally"] = function (handler) { return this._passThrough(handler, 0, finallyHandler, finallyHandler); }; Promise.prototype.tap = function (handler) { return this._passThrough(handler, 1, finallyHandler); }; return finallyHandler; }; },{"./util":36}],16:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug) { var errors = _dereq_("./errors"); var TypeError = errors.TypeError; var util = _dereq_("./util"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; var yieldHandlers = []; function promiseFromYieldHandler(value, yieldHandlers, traceParent) { for (var i = 0; i < yieldHandlers.length; ++i) { traceParent._pushContext(); var result = tryCatch(yieldHandlers[i])(value); traceParent._popContext(); if (result === errorObj) { traceParent._pushContext(); var ret = Promise.reject(errorObj.e); traceParent._popContext(); return ret; } var maybePromise = tryConvertToPromise(result, traceParent); if (maybePromise instanceof Promise) return maybePromise; } return null; } function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { var promise = this._promise = new Promise(INTERNAL); promise._captureStackTrace(); promise._setOnCancel(this); this._stack = stack; this._generatorFunction = generatorFunction; this._receiver = receiver; this._generator = undefined; this._yieldHandlers = typeof yieldHandler === "function" ? [yieldHandler].concat(yieldHandlers) : yieldHandlers; this._yieldedPromise = null; } util.inherits(PromiseSpawn, Proxyable); PromiseSpawn.prototype._isResolved = function() { return this.promise === null; }; PromiseSpawn.prototype._cleanup = function() { this._promise = this._generator = null; }; PromiseSpawn.prototype._promiseCancelled = function() { if (this._isResolved()) return; var implementsReturn = typeof this._generator["return"] !== "undefined"; var result; if (!implementsReturn) { var reason = new Promise.CancellationError( "generator .return() sentinel"); Promise.coroutine.returnSentinel = reason; this._promise._attachExtraTrace(reason); this._promise._pushContext(); result = tryCatch(this._generator["throw"]).call(this._generator, reason); this._promise._popContext(); if (result === errorObj && result.e === reason) { result = null; } } else { this._promise._pushContext(); result = tryCatch(this._generator["return"]).call(this._generator, undefined); this._promise._popContext(); } var promise = this._promise; this._cleanup(); if (result === errorObj) { promise._rejectCallback(result.e, false); } else { promise.cancel(); } }; PromiseSpawn.prototype._promiseFulfilled = function(value) { this._yieldedPromise = null; this._promise._pushContext(); var result = tryCatch(this._generator.next).call(this._generator, value); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._promiseRejected = function(reason) { this._yieldedPromise = null; this._promise._attachExtraTrace(reason); this._promise._pushContext(); var result = tryCatch(this._generator["throw"]) .call(this._generator, reason); this._promise._popContext(); this._continue(result); }; PromiseSpawn.prototype._resultCancelled = function() { if (this._yieldedPromise instanceof Promise) { var promise = this._yieldedPromise; this._yieldedPromise = null; promise.cancel(); } }; PromiseSpawn.prototype.promise = function () { return this._promise; }; PromiseSpawn.prototype._run = function () { this._generator = this._generatorFunction.call(this._receiver); this._receiver = this._generatorFunction = undefined; this._promiseFulfilled(undefined); }; PromiseSpawn.prototype._continue = function (result) { var promise = this._promise; if (result === errorObj) { this._cleanup(); return promise._rejectCallback(result.e, false); } var value = result.value; if (result.done === true) { this._cleanup(); return promise._resolveCallback(value); } else { var maybePromise = tryConvertToPromise(value, this._promise); if (!(maybePromise instanceof Promise)) { maybePromise = promiseFromYieldHandler(maybePromise, this._yieldHandlers, this._promise); if (maybePromise === null) { this._promiseRejected( new TypeError( "A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", value) + "From coroutine:\u000a" + this._stack.split("\n").slice(1, -7).join("\n") ) ); return; } } maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { this._yieldedPromise = maybePromise; maybePromise._proxy(this, null); } else if (((bitField & 33554432) !== 0)) { this._promiseFulfilled(maybePromise._value()); } else if (((bitField & 16777216) !== 0)) { this._promiseRejected(maybePromise._reason()); } else { this._promiseCancelled(); } } }; Promise.coroutine = function (generatorFunction, options) { if (typeof generatorFunction !== "function") { throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var yieldHandler = Object(options).yieldHandler; var PromiseSpawn$ = PromiseSpawn; var stack = new Error().stack; return function () { var generator = generatorFunction.apply(this, arguments); var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, stack); var ret = spawn.promise(); spawn._generator = generator; spawn._promiseFulfilled(undefined); return ret; }; }; Promise.coroutine.addYieldHandler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } yieldHandlers.push(fn); }; Promise.spawn = function (generatorFunction) { debug.deprecated("Promise.spawn()", "Promise.coroutine()"); if (typeof generatorFunction !== "function") { return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var spawn = new PromiseSpawn(generatorFunction, this); var ret = spawn.promise(); spawn._run(Promise.spawn); return ret; }; }; },{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) { var util = _dereq_("./util"); 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 promiseSetter = function(i) { return new Function("promise", "holder", " \n\ 'use strict'; \n\ holder.pIndex = promise; \n\ ".replace(/Index/g, i)); }; var generateHolderClass = function(total) { var props = new Array(total); for (var i = 0; i < props.length; ++i) { props[i] = "this.p" + (i+1); } var assignment = props.join(" = ") + " = null;"; var cancellationCode= "var promise;\n" + props.map(function(prop) { return " \n\ promise = " + prop + "; \n\ if (promise instanceof Promise) { \n\ promise.cancel(); \n\ } \n\ "; }).join("\n"); var passedArguments = props.join(", "); var name = "Holder$" + total; var code = "return function(tryCatch, errorObj, Promise) { \n\ 'use strict'; \n\ function [TheName](fn) { \n\ [TheProperties] \n\ this.fn = fn; \n\ this.now = 0; \n\ } \n\ [TheName].prototype.checkFulfillment = function(promise) { \n\ var now = ++this.now; \n\ if (now === [TheTotal]) { \n\ promise._pushContext(); \n\ var callback = this.fn; \n\ var ret = tryCatch(callback)([ThePassedArguments]); \n\ promise._popContext(); \n\ if (ret === errorObj) { \n\ promise._rejectCallback(ret.e, false); \n\ } else { \n\ promise._resolveCallback(ret); \n\ } \n\ } \n\ }; \n\ \n\ [TheName].prototype._resultCancelled = function() { \n\ [CancellationCode] \n\ }; \n\ \n\ return [TheName]; \n\ }(tryCatch, errorObj, Promise); \n\ "; code = code.replace(/\[TheName\]/g, name) .replace(/\[TheTotal\]/g, total) .replace(/\[ThePassedArguments\]/g, passedArguments) .replace(/\[TheProperties\]/g, assignment) .replace(/\[CancellationCode\]/g, cancellationCode); return new Function("tryCatch", "errorObj", "Promise", code) (tryCatch, errorObj, Promise); }; var holderClasses = []; var thenCallbacks = []; var promiseSetters = []; for (var i = 0; i < 8; ++i) { holderClasses.push(generateHolderClass(i + 1)); thenCallbacks.push(thenCallback(i + 1)); promiseSetters.push(promiseSetter(i + 1)); } reject = function (reason) { this._reject(reason); }; }} Promise.join = function () { var last = arguments.length - 1; var fn; if (last > 0 && typeof arguments[last] === "function") { fn = arguments[last]; if (!true) { if (last <= 8 && canEvaluate) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var HolderClass = holderClasses[last - 1]; var holder = new HolderClass(fn); var callbacks = thenCallbacks; for (var i = 0; i < last; ++i) { var maybePromise = tryConvertToPromise(arguments[i], ret); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { maybePromise._then(callbacks[i], reject, undefined, ret, holder); promiseSetters[i](maybePromise, holder); } else if (((bitField & 33554432) !== 0)) { callbacks[i].call(ret, maybePromise._value(), holder); } else if (((bitField & 16777216) !== 0)) { ret._reject(maybePromise._reason()); } else { ret._cancel(); } } else { callbacks[i].call(ret, maybePromise, holder); } } if (!ret._isFateSealed()) { ret._setAsyncGuaranteed(); ret._setOnCancel(holder); } return ret; } } } var args = [].slice.call(arguments);; if (fn) args.pop(); var ret = new PromiseArray(args).promise(); return fn !== undefined ? ret.spread(fn) : ret; }; }; },{"./util":36}],18:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; var errorObj = util.errorObj; var EMPTY_ARRAY = []; function MappingPromiseArray(promises, fn, limit, _filter) { this.constructor$(promises); this._promise._captureStackTrace(); var domain = getDomain(); this._callback = domain === null ? fn : domain.bind(fn); this._preservedValues = _filter === INTERNAL ? new Array(this.length()) : null; this._limit = limit; this._inFlight = 0; this._queue = limit >= 1 ? [] : EMPTY_ARRAY; this._init$(undefined, -2); } util.inherits(MappingPromiseArray, PromiseArray); MappingPromiseArray.prototype._init = function () {}; MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { var values = this._values; var length = this.length(); var preservedValues = this._preservedValues; var limit = this._limit; if (index < 0) { index = (index * -1) - 1; values[index] = value; if (limit >= 1) { this._inFlight--; this._drainQueue(); if (this._isResolved()) return true; } } else { if (limit >= 1 && this._inFlight >= limit) { values[index] = value; this._queue.push(index); return false; } if (preservedValues !== null) preservedValues[index] = value; var promise = this._promise; var callback = this._callback; var receiver = promise._boundValue(); promise._pushContext(); var ret = tryCatch(callback).call(receiver, value, index, length); var promisesCreated = promise._popContext(); debug.checkForgottenReturns( ret, promisesCreated, preservedValues !== null ? "Promise.filter" : "Promise.map", promise ); if (ret === errorObj) { this._reject(ret.e); return true; } var maybePromise = tryConvertToPromise(ret, this._promise); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); var bitField = maybePromise._bitField; ; if (((bitField & 50397184) === 0)) { if (limit >= 1) this._inFlight++; values[index] = maybePromise; maybePromise._proxy(this, (index + 1) * -1); return false; } else if (((bitField & 33554432) !== 0)) { ret = maybePromise._value(); } else if (((bitField & 16777216) !== 0)) { this._reject(maybePromise._reason()); return true; } else { this._cancel(); return true; } } values[index] = ret; } var totalResolved = ++this._totalResolved; if (totalResolved >= length) { if (preservedValues !== null) { this._filter(values, preservedValues); } else { this._resolve(values); } return true; } return false; }; MappingPromiseArray.prototype._drainQueue = function () { var queue = this._queue; var limit = this._limit; var values = this._values; while (queue.length > 0 && this._inFlight < limit) { if (this._isResolved()) return; var index = queue.pop(); this._promiseFulfilled(values[index], index); } }; MappingPromiseArray.prototype._filter = function (booleans, values) { var len = values.length; var ret = new Array(len); var j = 0; for (var i = 0; i < len; ++i) { if (booleans[i]) ret[j++] = values[i]; } ret.length = j; this._resolve(ret); }; MappingPromiseArray.prototype.preservedValues = function () { return this._preservedValues; }; function map(promises, fn, options, _filter) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var limit = typeof options === "object" && options !== null ? options.concurrency : 0; limit = typeof limit === "number" && isFinite(limit) && limit >= 1 ? limit : 0; return new MappingPromiseArray(promises, fn, limit, _filter).promise(); } Promise.prototype.map = function (fn, options) { return map(this, fn, options, null); }; Promise.map = function (promises, fn, options, _filter) { return map(promises, fn, options, _filter); }; }; },{"./util":36}],19:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { var util = _dereq_("./util"); var tryCatch = util.tryCatch; Promise.method = function (fn) { if (typeof fn !== "function") { throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); } return function () { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value = tryCatch(fn).apply(this, arguments); ret._popContext(); ret._resolveFromSyncValue(value); return ret; }; }; Promise.attempt = Promise["try"] = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._pushContext(); var value; if (arguments.length > 1) { debug.deprecated("calling Promise.try with more than 1 argument"); var arg = arguments[1]; var ctx = arguments[2]; value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) : tryCatch(fn).call(ctx, arg); } else { value = tryCatch(fn)(); } ret._popContext(); ret._resolveFromSyncValue(value); return ret; }; Promise.prototype._resolveFromSyncValue = function (value) { if (value === util.errorObj) { this._rejectCallback(value.e, false); } else { this._resolveCallback(value, true); } }; }; },{"./util":36}],20:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var maybeWrapAsError = util.maybeWrapAsError; var errors = _dereq_("./errors"); var OperationalError = errors.OperationalError; var es5 = _dereq_("./es5"); function isUntypedError(obj) { return obj instanceof Error && es5.getPrototypeOf(obj) === Error.prototype; } var rErrorKey = /^(?:name|message|stack|cause)$/; function wrapAsOperationalError(obj) { var ret; if (isUntypedError(obj)) { ret = new OperationalError(obj); ret.name = obj.name; ret.message = obj.message; ret.stack = obj.stack; var keys = es5.keys(obj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (!rErrorKey.test(key)) { ret[key] = obj[key]; } } return ret; } util.markAsOriginatingFromRejection(obj); return obj; } function nodebackForPromise(promise, multiArgs) { return function(err, value) { if (promise === null) return; if (err) { var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); promise._attachExtraTrace(wrapped); promise._reject(wrapped); } else if (!multiArgs) { promise._fulfill(value); } else { var args = [].slice.call(arguments, 1);; promise._fulfill(args); } promise = null; }; } module.exports = nodebackForPromise; },{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { var util = _dereq_("./util"); var async = Promise._async; var tryCatch = util.tryCatch; var errorObj = util.errorObj; function spreadAdapter(val, nodeback) { var promise = this; if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); var ret = tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); if (ret === errorObj) { async.throwLater(ret.e); } } function successAdapter(val, nodeback) { var promise = this; var receiver = promise._boundValue(); var ret = val === undefined ? tryCatch(nodeback).call(receiver, null) : tryCatch(nodeback).call(receiver, null, val); if (ret === errorObj) { async.throwLater(ret.e); } } function errorAdapter(reason, nodeback) { var promise = this; if (!reason) { var newReason = new Error(reason + ""); newReason.cause = reason; reason = newReason; } var ret = tryCatch(nodeback).call(promise._boundValue(), reason); if (ret === errorObj) { async.throwLater(ret.e); } } Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, options) { if (typeof nodeback == "function") { var adapter = successAdapter; if (options !== undefined && Object(options).spread) { adapter = spreadAdapter; } this._then( adapter, errorAdapter, undefined, this, nodeback ); } return this; }; }; },{"./util":36}],22:[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/MqrFmX\u000a"); }; var reflectHandler = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; function Proxyable() {} var UNDEFINED_BINDING = {}; var util = _dereq_("./util"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var es5 = _dereq_("./es5"); var Async = _dereq_("./async"); var async = new Async(); es5.defineProperty(Promise, "_async", {value: async}); var errors = _dereq_("./errors"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL); var PromiseArray = _dereq_("./promise_array")(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); var Context = _dereq_("./context")(Promise); /*jshint unused:false*/ var createContext = Context.create; var debug = _dereq_("./debuggability")(Promise, Context); var CapturedTrace = debug.CapturedTrace; var finallyHandler = _dereq_("./finally")(Promise, tryConvertToPromise); var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER); var nodebackForPromise = _dereq_("./nodeback"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; function check(self, executor) { if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util.classString(executor)); } if (self.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } } function Promise(executor) { this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; if (executor !== INTERNAL) { check(this, executor); this._resolveFromExecutor(executor); } this._promiseCreated(); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return apiRejection("expecting an object but got " + util.classString(item)); } } catchInstances.length = j; fn = arguments[i]; return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); }; Promise.prototype.reflect = function () { return this._then(reflectHandler, reflectHandler, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject) { if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, undefined, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject) { var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { if (arguments.length > 0) { this._warn(".all() was passed arguments but it does not take any"); } return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } var prev = async._schedule; async._schedule = fn; return prev; }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && domain.bind(handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; }; Promise.prototype._setAsyncGuaranteed = function() { this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : domain.bind(reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : domain.bind(fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : domain.bind(reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous) { var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promisesCreatedDuringHandlerInvocation = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj || x === promise) { var err = x === promise ? makeSelfResolutionError() : x.e; promise._rejectCallback(err, false); } else { if (x === undefined && promisesCreatedDuringHandlerInvocation > 0 && debug.longStackTraces() && debug.warnings()) { promise._warn("a promise was created in a handler but " + "none were returned from it", true); } promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (handler === finallyHandler) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util.isNode); } if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); _dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); _dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); _dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug); _dereq_("./direct_resolve")(Promise); _dereq_("./synchronous_inspection")(Promise); _dereq_("./join")( Promise, PromiseArray, tryConvertToPromise, INTERNAL, debug); Promise.Promise = Promise; _dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); _dereq_('./timers.js')(Promise, INTERNAL); _dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); _dereq_('./nodeify.js')(Promise); _dereq_('./call_get.js')(Promise); _dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); _dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); _dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); _dereq_('./settle.js')(Promise, PromiseArray, debug); _dereq_('./some.js')(Promise, PromiseArray, apiRejection); _dereq_('./promisify.js')(Promise, INTERNAL); _dereq_('./any.js')(Promise); _dereq_('./each.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._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util.lastLineError); return Promise; }; },{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable) { var util = _dereq_("./util"); var isArray = util.isArray; function toResolutionValue(val) { switch(val) { case -2: return []; case -3: return {}; } } function PromiseArray(values) { var promise = this._promise = new Promise(INTERNAL); if (values instanceof Promise) { promise._propagateFrom(values, 3); } promise._setOnCancel(this); this._values = values; this._length = 0; this._totalResolved = 0; this._init(undefined, -2); } util.inherits(PromiseArray, Proxyable); PromiseArray.prototype.length = function () { return this._length; }; PromiseArray.prototype.promise = function () { return this._promise; }; PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { var values = tryConvertToPromise(this._values, this._promise); if (values instanceof Promise) { values = values._target(); var bitField = values._bitField; ; this._values = values; if (((bitField & 50397184) === 0)) { this._promise._setAsyncGuaranteed(); return values._then( init, this._reject, undefined, this, resolveValueIfEmpty ); } else if (((bitField & 33554432) !== 0)) { values = values._value(); } else if (((bitField & 16777216) !== 0)) { return this._reject(values._reason()); } else { return this._cancel(); } } values = util.asArray(values); if (values === null) { var err = apiRejection( "expecting an array or an iterable object but got " + util.classString(values)).reason(); this._promise._rejectCallback(err, false); return; } if (values.length === 0) { if (resolveValueIfEmpty === -5) { this._resolveEmptyArray(); } else { this._resolve(toResolutionValue(resolveValueIfEmpty)); } return; } this._iterate(values); }; PromiseArray.prototype._iterate = function(values) { var len = this.getActualLength(values.length); this._length = len; this._values = this.shouldCopyValues() ? new Array(len) : this._values; var result = this._promise; var isResolved = false; var bitField = null; for (var i = 0; i < len; ++i) { var maybePromise = tryConvertToPromise(values[i], result); if (maybePromise instanceof Promise) { maybePromise = maybePromise._target(); bitField = maybePromise._bitField; } else { bitField = null; } if (isResolved) { if (bitField !== null) { maybePromise.suppressUnhandledRejections(); } } else if (bitField !== null) { if (((bitField & 50397184) === 0)) { maybePromise._proxy(this, i); this._values[i] = maybePromise; } else if (((bitField & 33554432) !== 0)) { isResolved = this._promiseFulfilled(maybePromise._value(), i); } else if (((bitField & 16777216) !== 0)) { isResolved = this._promiseRejected(maybePromise._reason(), i); } else { isResolved = this._promiseCancelled(i); } } else { isResolved = this._promiseFulfilled(maybePromise, i); } } if (!isResolved) result._setAsyncGuaranteed(); }; PromiseArray.prototype._isResolved = function () { return this._values === null; }; PromiseArray.prototype._resolve = function (value) { this._values = null; this._promise._fulfill(value); }; PromiseArray.prototype._cancel = function() { if (this._isResolved() || !this._promise.isCancellable()) return; this._values = null; this._promise._cancel(); }; PromiseArray.prototype._reject = function (reason) { this._values = null; this._promise._rejectCallback(reason, false); }; PromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; PromiseArray.prototype._promiseCancelled = function() { this._cancel(); return true; }; PromiseArray.prototype._promiseRejected = function (reason) { this._totalResolved++; this._reject(reason); return true; }; PromiseArray.prototype._resultCancelled = function() { if (this._isResolved()) return; var values = this._values; this._cancel(); if (values instanceof Promise) { values.cancel(); } else { for (var i = 0; i < values.length; ++i) { if (values[i] instanceof Promise) { values[i].cancel(); } } } }; PromiseArray.prototype.shouldCopyValues = function () { return true; }; PromiseArray.prototype.getActualLength = function (len) { return len; }; return PromiseArray; }; },{"./util":36}],24:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var THIS = {}; var util = _dereq_("./util"); var nodebackForPromise = _dereq_("./nodeback"); 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 noCopyProps = [ "arity", "length", "name", "arguments", "caller", "callee", "prototype", "__isPromisified__" ]; var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); var defaultFilter = function(name) { return util.isIdentifier(name) && name.charAt(0) !== "_" && name !== "constructor"; }; function propsFilter(key) { return !noCopyPropsPattern.test(key); } function isPromisified(fn) { try { return fn.__isPromisified__ === true; } catch (e) { return false; } } function hasPromisified(obj, key, suffix) { var val = util.getDataPropertyOrDefault(obj, key + suffix, defaultPromisified); return val ? isPromisified(val) : false; } function checkValid(ret, suffix, suffixRegexp) { for (var i = 0; i < ret.length; i += 2) { var key = ret[i]; if (suffixRegexp.test(key)) { var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); for (var j = 0; j < ret.length; j += 2) { if (ret[j] === keyWithoutAsyncSuffix) { throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" .replace("%s", suffix)); } } } } } function promisifiableMethods(obj, suffix, suffixRegexp, filter) { var keys = util.inheritedDataKeys(obj); var ret = []; for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var value = obj[key]; var passesDefaultFilter = filter === defaultFilter ? true : defaultFilter(key, value, obj); if (typeof value === "function" && !isPromisified(value) && !hasPromisified(obj, key, suffix) && filter(key, value, obj, passesDefaultFilter)) { ret.push(key, value); } } checkValid(ret, suffix, suffixRegexp); return ret; } var escapeIdentRegex = function(str) { return str.replace(/([$])/, "\\$"); }; var makeNodePromisifiedEval; if (!true) { var switchCaseArgumentOrder = function(likelyArgumentCount) { var ret = [likelyArgumentCount]; var min = Math.max(0, likelyArgumentCount - 1 - 3); for(var i = likelyArgumentCount - 1; i >= min; --i) { ret.push(i); } for(var i = likelyArgumentCount + 1; i <= 3; ++i) { ret.push(i); } return ret; }; var argumentSequence = function(argumentCount) { return util.filledRange(argumentCount, "_arg", ""); }; var parameterDeclaration = function(parameterCount) { return util.filledRange( Math.max(parameterCount, 3), "_arg", ""); }; var parameterCount = function(fn) { if (typeof fn.length === "number") { return Math.max(Math.min(fn.length, 1023 + 1), 0); } return 0; }; makeNodePromisifiedEval = function(callback, receiver, originalName, fn, _, multiArgs) { var newParameterCount = Math.max(0, parameterCount(fn) - 1); var argumentOrder = switchCaseArgumentOrder(newParameterCount); var shouldProxyThis = typeof callback === "string" || receiver === THIS; function generateCallForArgumentCount(count) { var args = argumentSequence(count).join(", "); var comma = count > 0 ? ", " : ""; var ret; if (shouldProxyThis) { ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; } else { ret = receiver === undefined ? "ret = callback({{args}}, nodeback); break;\n" : "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; } return ret.replace("{{args}}", args).replace(", ", comma); } function generateArgumentSwitchCase() { var ret = ""; for (var i = 0; i < argumentOrder.length; ++i) { ret += "case " + argumentOrder[i] +":" + generateCallForArgumentCount(argumentOrder[i]); } ret += " \n\ default: \n\ var args = new Array(len + 1); \n\ var i = 0; \n\ for (var i = 0; i < len; ++i) { \n\ args[i] = arguments[i]; \n\ } \n\ args[i] = nodeback; \n\ [CodeForCall] \n\ break; \n\ ".replace("[CodeForCall]", (shouldProxyThis ? "ret = callback.apply(this, args);\n" : "ret = callback.apply(receiver, args);\n")); return ret; } var getFunctionCode = typeof callback === "string" ? ("this != null ? this['"+callback+"'] : fn") : "fn"; var body = "'use strict'; \n\ var ret = function (Parameters) { \n\ 'use strict'; \n\ var len = arguments.length; \n\ var promise = new Promise(INTERNAL); \n\ promise._captureStackTrace(); \n\ var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ var ret; \n\ var callback = tryCatch([GetFunctionCode]); \n\ switch(len) { \n\ [CodeForSwitchCase] \n\ } \n\ if (ret === errorObj) { \n\ promise._rejectCallback(maybeWrapAsError(ret.e), true); \n\ } \n\ if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ return promise; \n\ }; \n\ notEnumerableProp(ret, '__isPromisified__', true); \n\ return ret; \n\ ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) .replace("[GetFunctionCode]", getFunctionCode); body = body.replace("Parameters", parameterDeclaration(newParameterCount)); return new Function("Promise", "fn", "receiver", "withAppended", "maybeWrapAsError", "nodebackForPromise", "tryCatch", "errorObj", "notEnumerableProp", "INTERNAL", body)( Promise, fn, receiver, withAppended, maybeWrapAsError, nodebackForPromise, util.tryCatch, util.errorObj, util.notEnumerableProp, INTERNAL); }; } function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { var defaultThis = (function() {return this;})(); var method = callback; if (typeof method === "string") { callback = fn; } function promisified() { var _receiver = receiver; if (receiver === THIS) _receiver = this; var promise = new Promise(INTERNAL); promise._captureStackTrace(); var cb = typeof method === "string" && this !== defaultThis ? this[method] : callback; var fn = nodebackForPromise(promise, multiArgs); try { cb.apply(_receiver, withAppended(arguments, fn)); } catch(e) { promise._rejectCallback(maybeWrapAsError(e), true); } if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); return promise; } util.notEnumerableProp(promisified, "__isPromisified__", true); return promisified; } var makeNodePromisified = canEvaluate ? makeNodePromisifiedEval : makeNodePromisifiedClosure; function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); var methods = promisifiableMethods(obj, suffix, suffixRegexp, filter); for (var i = 0, len = methods.length; i < len; i+= 2) { var key = methods[i]; var fn = methods[i+1]; var promisifiedKey = key + suffix; if (promisifier === makeNodePromisified) { obj[promisifiedKey] = makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); } else { var promisified = promisifier(fn, function() { return makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); }); util.notEnumerableProp(promisified, "__isPromisified__", true); obj[promisifiedKey] = promisified; } } util.toFastProperties(obj); return obj; } function promisify(callback, receiver, multiArgs) { return makeNodePromisified(callback, receiver, undefined, callback, null, multiArgs); } Promise.promisify = function (fn, options) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } if (isPromisified(fn)) { return fn; } options = Object(options); var receiver = options.context === undefined ? THIS : options.context; var multiArgs = !!options.multiArgs; var ret = promisify(fn, receiver, multiArgs); util.copyDescriptors(fn, ret, propsFilter); return ret; }; Promise.promisifyAll = function (target, options) { if (typeof target !== "function" && typeof target !== "object") { throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } options = Object(options); var multiArgs = !!options.multiArgs; var suffix = options.suffix; if (typeof suffix !== "string") suffix = defaultSuffix; var filter = options.filter; if (typeof filter !== "function") filter = defaultFilter; var promisifier = options.promisifier; if (typeof promisifier !== "function") promisifier = makeNodePromisified; if (!util.isIdentifier(suffix)) { throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var keys = util.inheritedDataKeys(target); for (var i = 0; i < keys.length; ++i) { var value = target[keys[i]]; if (keys[i] !== "constructor" && util.isClass(value)) { promisifyAll(value.prototype, suffix, filter, promisifier, multiArgs); promisifyAll(value, suffix, filter, promisifier, multiArgs); } } return promisifyAll(target, suffix, filter, promisifier, multiArgs); }; }; },{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, PromiseArray, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var isObject = util.isObject; var es5 = _dereq_("./es5"); var Es6Map; if (typeof Map === "function") Es6Map = Map; var mapToEntries = (function() { var index = 0; var size = 0; function extractEntry(value, key) { this[index] = value; this[index + size] = key; index++; } return function mapToEntries(map) { size = map.size; index = 0; var ret = new Array(map.size * 2); map.forEach(extractEntry, ret); return ret; }; })(); var entriesToMap = function(entries) { var ret = new Es6Map(); var length = entries.length / 2 | 0; for (var i = 0; i < length; ++i) { var key = entries[length + i]; var value = entries[i]; ret.set(key, value); } return ret; }; function PropertiesPromiseArray(obj) { var isMap = false; var entries; if (Es6Map !== undefined && obj instanceof Es6Map) { entries = mapToEntries(obj); isMap = true; } else { var keys = es5.keys(obj); var len = keys.length; entries = new Array(len * 2); for (var i = 0; i < len; ++i) { var key = keys[i]; entries[i] = obj[key]; entries[i + len] = key; } } this.constructor$(entries); this._isMap = isMap; this._init$(undefined, -3); } util.inherits(PropertiesPromiseArray, PromiseArray); PropertiesPromiseArray.prototype._init = function () {}; PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { this._values[index] = value; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { var val; if (this._isMap) { val = entriesToMap(this._values); } else { val = {}; var keyOffset = this.length(); for (var i = 0, len = this.length(); i < len; ++i) { val[this._values[i + keyOffset]] = this._values[i]; } } this._resolve(val); return true; } return false; }; PropertiesPromiseArray.prototype.shouldCopyValues = function () { return false; }; PropertiesPromiseArray.prototype.getActualLength = function (len) { return len >> 1; }; function props(promises) { var ret; var castValue = tryConvertToPromise(promises); if (!isObject(castValue)) { return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } else if (castValue instanceof Promise) { ret = castValue._then( Promise.props, undefined, undefined, undefined, undefined); } else { ret = new PropertiesPromiseArray(castValue).promise(); } if (castValue instanceof Promise) { ret._propagateFrom(castValue, 2); } return ret; } Promise.prototype.props = function () { return props(this); }; Promise.props = function (promises) { return props(promises); }; }; },{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){ "use strict"; 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 Queue(capacity) { this._capacity = capacity; this._length = 0; this._front = 0; } Queue.prototype._willBeOverCapacity = function (size) { return this._capacity < size; }; Queue.prototype._pushOne = function (arg) { var length = this.length(); this._checkCapacity(length + 1); var i = (this._front + length) & (this._capacity - 1); this[i] = arg; this._length = length + 1; }; 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); this._pushOne(receiver); this._pushOne(arg); return; } var j = this._front + length - 3; this._checkCapacity(length); var wrapMask = this._capacity - 1; this[(j + 0) & wrapMask] = fn; this[(j + 1) & wrapMask] = receiver; this[(j + 2) & wrapMask] = arg; this._length = length; }; Queue.prototype.shift = function () { var front = this._front, ret = this[front]; this[front] = undefined; this._front = (front + 1) & (this._capacity - 1); this._length--; return ret; }; Queue.prototype.length = function () { return this._length; }; Queue.prototype._checkCapacity = function (size) { if (this._capacity < size) { this._resizeTo(this._capacity << 1); } }; Queue.prototype._resizeTo = function (capacity) { var oldCapacity = this._capacity; this._capacity = capacity; var front = this._front; var length = this._length; var moveItemsCount = (front + length) & (oldCapacity - 1); arrayMove(this, 0, this, oldCapacity, moveItemsCount); }; module.exports = Queue; },{}],27:[function(_dereq_,module,exports){ "use strict"; module.exports = function( Promise, INTERNAL, tryConvertToPromise, apiRejection) { var util = _dereq_("./util"); var raceLater = function (promise) { return promise.then(function(array) { return race(array, promise); }); }; function race(promises, parent) { var maybePromise = tryConvertToPromise(promises); if (maybePromise instanceof Promise) { return raceLater(maybePromise); } else { promises = util.asArray(promises); if (promises === null) return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); } var ret = new Promise(INTERNAL); if (parent !== undefined) { ret._propagateFrom(parent, 3); } var fulfill = ret._fulfill; var reject = ret._reject; for (var i = 0, len = promises.length; i < len; ++i) { var val = promises[i]; if (val === undefined && !(i in promises)) { continue; } Promise.cast(val)._then(fulfill, reject, undefined, ret, null); } return ret; } Promise.race = function (promises) { return race(promises, undefined); }; Promise.prototype.race = function () { return race(this, undefined); }; }; },{"./util":36}],28:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug) { var getDomain = Promise._getDomain; var util = _dereq_("./util"); var tryCatch = util.tryCatch; function ReductionPromiseArray(promises, fn, initialValue, _each) { this.constructor$(promises); var domain = getDomain(); this._fn = domain === null ? fn : domain.bind(fn); if (initialValue !== undefined) { initialValue = Promise.resolve(initialValue); initialValue._attachCancellationCallback(this); } this._initialValue = initialValue; this._currentCancellable = null; this._eachValues = _each === INTERNAL ? [] : undefined; this._promise._captureStackTrace(); this._init$(undefined, -5); } util.inherits(ReductionPromiseArray, PromiseArray); ReductionPromiseArray.prototype._gotAccum = function(accum) { if (this._eachValues !== undefined && accum !== INTERNAL) { this._eachValues.push(accum); } }; ReductionPromiseArray.prototype._eachComplete = function(value) { this._eachValues.push(value); return this._eachValues; }; ReductionPromiseArray.prototype._init = function() {}; ReductionPromiseArray.prototype._resolveEmptyArray = function() { this._resolve(this._eachValues !== undefined ? this._eachValues : this._initialValue); }; ReductionPromiseArray.prototype.shouldCopyValues = function () { return false; }; ReductionPromiseArray.prototype._resolve = function(value) { this._promise._resolveCallback(value); this._values = null; }; ReductionPromiseArray.prototype._resultCancelled = function(sender) { if (sender === this._initialValue) return this._cancel(); if (this._isResolved()) return; this._resultCancelled$(); if (this._currentCancellable instanceof Promise) { this._currentCancellable.cancel(); } if (this._initialValue instanceof Promise) { this._initialValue.cancel(); } }; ReductionPromiseArray.prototype._iterate = function (values) { this._values = values; var value; var i; var length = values.length; if (this._initialValue !== undefined) { value = this._initialValue; i = 0; } else { value = Promise.resolve(values[0]); i = 1; } this._currentCancellable = value; if (!value.isRejected()) { for (; i < length; ++i) { var ctx = { accum: null, value: values[i], index: i, length: length, array: this }; value = value._then(gotAccum, undefined, undefined, ctx, undefined); } } if (this._eachValues !== undefined) { value = value ._then(this._eachComplete, undefined, undefined, this, undefined); } value._then(completed, completed, undefined, value, this); }; Promise.prototype.reduce = function (fn, initialValue) { return reduce(this, fn, initialValue, null); }; Promise.reduce = function (promises, fn, initialValue, _each) { return reduce(promises, fn, initialValue, _each); }; function completed(valueOrReason, array) { if (this.isFulfilled()) { array._resolve(valueOrReason); } else { array._reject(valueOrReason); } } function reduce(promises, fn, initialValue, _each) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var array = new ReductionPromiseArray(promises, fn, initialValue, _each); return array.promise(); } function gotAccum(accum) { this.accum = accum; this.array._gotAccum(accum); var value = tryConvertToPromise(this.value, this.array._promise); if (value instanceof Promise) { this.array._currentCancellable = value; return value._then(gotValue, undefined, undefined, this, undefined); } else { return gotValue.call(this, value); } } function gotValue(value) { var array = this.array; var promise = array._promise; var fn = tryCatch(array._fn); promise._pushContext(); var ret; if (array._eachValues !== undefined) { ret = fn.call(promise._boundValue(), value, this.index, this.length); } else { ret = fn.call(promise._boundValue(), this.accum, value, this.index, this.length); } if (ret instanceof Promise) { array._currentCancellable = ret; } var promisesCreated = promise._popContext(); debug.checkForgottenReturns( ret, promisesCreated, array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", promise ); return ret; } }; },{"./util":36}],29:[function(_dereq_,module,exports){ "use strict"; var util = _dereq_("./util"); var schedule; var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; if (util.isNode && typeof MutationObserver === "undefined") { var GlobalSetImmediate = global.setImmediate; var ProcessNextTick = process.nextTick; schedule = util.isRecentNode ? function(fn) { GlobalSetImmediate.call(global, fn); } : function(fn) { ProcessNextTick.call(process, fn); }; } else if ((typeof MutationObserver !== "undefined") && !(typeof window !== "undefined" && window.navigator && window.navigator.standalone)) { schedule = function(fn) { var div = document.createElement("div"); var observer = new MutationObserver(fn); observer.observe(div, {attributes: true}); return function() { div.classList.toggle("foo"); }; }; schedule.isStatic = true; } else if (typeof setImmediate !== "undefined") { schedule = function (fn) { setImmediate(fn); }; } else if (typeof setTimeout !== "undefined") { schedule = function (fn) { setTimeout(fn, 0); }; } else { schedule = noAsyncScheduler; } module.exports = schedule; },{"./util":36}],30:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, debug) { var PromiseInspection = Promise.PromiseInspection; var util = _dereq_("./util"); function SettledPromiseArray(values) { this.constructor$(values); } util.inherits(SettledPromiseArray, PromiseArray); SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { this._values[index] = inspection; var totalResolved = ++this._totalResolved; if (totalResolved >= this._length) { this._resolve(this._values); return true; } return false; }; SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { var ret = new PromiseInspection(); ret._bitField = 33554432; ret._settledValueField = value; return this._promiseResolved(index, ret); }; SettledPromiseArray.prototype._promiseRejected = function (reason, index) { var ret = new PromiseInspection(); ret._bitField = 16777216; ret._settledValueField = reason; return this._promiseResolved(index, ret); }; Promise.settle = function (promises) { debug.deprecated(".settle()", ".reflect()"); return new SettledPromiseArray(promises).promise(); }; Promise.prototype.settle = function () { return Promise.settle(this); }; }; },{"./util":36}],31:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, PromiseArray, apiRejection) { var util = _dereq_("./util"); var RangeError = _dereq_("./errors").RangeError; var AggregateError = _dereq_("./errors").AggregateError; var isArray = util.isArray; var CANCELLATION = {}; function SomePromiseArray(values) { this.constructor$(values); this._howMany = 0; this._unwrap = false; this._initialized = false; } util.inherits(SomePromiseArray, PromiseArray); SomePromiseArray.prototype._init = function () { if (!this._initialized) { return; } if (this._howMany === 0) { this._resolve([]); return; } this._init$(undefined, -5); var isArrayResolved = isArray(this._values); if (!this._isResolved() && isArrayResolved && this._howMany > this._canPossiblyFulfill()) { this._reject(this._getRangeError(this.length())); } }; SomePromiseArray.prototype.init = function () { this._initialized = true; this._init(); }; SomePromiseArray.prototype.setUnwrap = function () { this._unwrap = true; }; SomePromiseArray.prototype.howMany = function () { return this._howMany; }; SomePromiseArray.prototype.setHowMany = function (count) { this._howMany = count; }; SomePromiseArray.prototype._promiseFulfilled = function (value) { this._addFulfilled(value); if (this._fulfilled() === this.howMany()) { this._values.length = this.howMany(); if (this.howMany() === 1 && this._unwrap) { this._resolve(this._values[0]); } else { this._resolve(this._values); } return true; } return false; }; SomePromiseArray.prototype._promiseRejected = function (reason) { this._addRejected(reason); return this._checkOutcome(); }; SomePromiseArray.prototype._promiseCancelled = function () { if (this._values instanceof Promise || this._values == null) { return this._cancel(); } this._addRejected(CANCELLATION); return this._checkOutcome(); }; SomePromiseArray.prototype._checkOutcome = function() { if (this.howMany() > this._canPossiblyFulfill()) { var e = new AggregateError(); for (var i = this.length(); i < this._values.length; ++i) { if (this._values[i] !== CANCELLATION) { e.push(this._values[i]); } } if (e.length > 0) { this._reject(e); } else { this._cancel(); } return true; } return false; }; SomePromiseArray.prototype._fulfilled = function () { return this._totalResolved; }; SomePromiseArray.prototype._rejected = function () { return this._values.length - this.length(); }; SomePromiseArray.prototype._addRejected = function (reason) { this._values.push(reason); }; SomePromiseArray.prototype._addFulfilled = function (value) { this._values[this._totalResolved++] = value; }; SomePromiseArray.prototype._canPossiblyFulfill = function () { return this.length() - this._rejected(); }; SomePromiseArray.prototype._getRangeError = function (count) { var message = "Input array must contain at least " + this._howMany + " items but contains only " + count + " items"; return new RangeError(message); }; SomePromiseArray.prototype._resolveEmptyArray = function () { this._reject(this._getRangeError(0)); }; function some(promises, howMany) { if ((howMany | 0) !== howMany || howMany < 0) { return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } var ret = new SomePromiseArray(promises); var promise = ret.promise(); ret.setHowMany(howMany); ret.init(); return promise; } Promise.some = function (promises, howMany) { return some(promises, howMany); }; Promise.prototype.some = function (howMany) { return some(this, howMany); }; Promise._SomePromiseArray = SomePromiseArray; }; },{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise) { function PromiseInspection(promise) { if (promise !== undefined) { promise = promise._target(); this._bitField = promise._bitField; this._settledValueField = promise._isFateSealed() ? promise._settledValue() : undefined; } else { this._bitField = 0; this._settledValueField = undefined; } } PromiseInspection.prototype._settledValue = function() { return this._settledValueField; }; var value = PromiseInspection.prototype.value = function () { if (!this.isFulfilled()) { throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var reason = PromiseInspection.prototype.error = PromiseInspection.prototype.reason = function () { if (!this.isRejected()) { throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } return this._settledValue(); }; var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { return (this._bitField & 33554432) !== 0; }; var isRejected = PromiseInspection.prototype.isRejected = function () { return (this._bitField & 16777216) !== 0; }; var isPending = PromiseInspection.prototype.isPending = function () { return (this._bitField & 50397184) === 0; }; var isResolved = PromiseInspection.prototype.isResolved = function () { return (this._bitField & 50331648) !== 0; }; PromiseInspection.prototype.isCancelled = Promise.prototype._isCancelled = function() { return (this._bitField & 65536) === 65536; }; Promise.prototype.isCancelled = function() { return this._target()._isCancelled(); }; Promise.prototype.isPending = function() { return isPending.call(this._target()); }; Promise.prototype.isRejected = function() { return isRejected.call(this._target()); }; Promise.prototype.isFulfilled = function() { return isFulfilled.call(this._target()); }; Promise.prototype.isResolved = function() { return isResolved.call(this._target()); }; Promise.prototype.value = function() { return value.call(this._target()); }; Promise.prototype.reason = function() { var target = this._target(); target._unsetRejectionIsUnhandled(); return reason.call(target); }; Promise.prototype._value = function() { return this._settledValue(); }; Promise.prototype._reason = function() { this._unsetRejectionIsUnhandled(); return this._settledValue(); }; Promise.PromiseInspection = PromiseInspection; }; },{}],33:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util"); var errorObj = util.errorObj; var isObject = util.isObject; function tryConvertToPromise(obj, context) { if (isObject(obj)) { if (obj instanceof Promise) return obj; var then = getThen(obj); if (then === errorObj) { if (context) context._pushContext(); var ret = Promise.reject(then.e); if (context) context._popContext(); return ret; } else if (typeof then === "function") { if (isAnyBluebirdPromise(obj)) { var ret = new Promise(INTERNAL); obj._then( ret._fulfill, ret._reject, undefined, ret, null ); return ret; } return doThenable(obj, then, context); } } return obj; } function doGetThen(obj) { return obj.then; } function getThen(obj) { try { return doGetThen(obj); } catch (e) { errorObj.e = e; return errorObj; } } var hasProp = {}.hasOwnProperty; function isAnyBluebirdPromise(obj) { return hasProp.call(obj, "_promise0"); } function doThenable(x, then, context) { var promise = new Promise(INTERNAL); var ret = promise; if (context) context._pushContext(); promise._captureStackTrace(); if (context) context._popContext(); var synchronous = true; var result = util.tryCatch(then).call(x, resolve, reject); synchronous = false; if (promise && result === errorObj) { promise._rejectCallback(result.e, true); promise = null; } function resolve(value) { if (!promise) return; promise._resolveCallback(value); promise = null; } function reject(reason) { if (!promise) return; promise._rejectCallback(reason, synchronous); promise = null; } return ret; } return tryConvertToPromise; }; },{"./util":36}],34:[function(_dereq_,module,exports){ "use strict"; module.exports = function(Promise, INTERNAL) { var util = _dereq_("./util"); var TimeoutError = Promise.TimeoutError; var afterTimeout = function (promise, message) { if (!promise.isPending()) return; var err; if (typeof message !== "string") { if (message instanceof Error) { err = message; } else { err = new TimeoutError("operation timed out"); } } else { err = new TimeoutError(message); } util.markAsOriginatingFromRejection(err); promise._attachExtraTrace(err); promise._reject(err); }; var afterValue = function(value) { return delay(+this).thenReturn(value); }; var delay = Promise.delay = function (ms, value) { var ret; if (value !== undefined) { ret = Promise.resolve(value) ._then(afterValue, null, null, ms, undefined); } else { ret = new Promise(INTERNAL); setTimeout(function() { ret._fulfill(); }, +ms); } ret._setAsyncGuaranteed(); return ret; }; Promise.prototype.delay = function (ms) { return delay(ms, this); }; function successClear(value) { var handle = this; if (handle instanceof Number) handle = +handle; clearTimeout(handle); return value; } function failureClear(reason) { var handle = this; if (handle instanceof Number) handle = +handle; clearTimeout(handle); throw reason; } Promise.prototype.timeout = function (ms, message) { ms = +ms; var ret = this.then(); var handle = setTimeout(function timeoutTimeout() { afterTimeout(ret, message); }, ms); return ret._then(successClear, failureClear, undefined, handle, undefined); }; }; },{"./util":36}],35:[function(_dereq_,module,exports){ "use strict"; module.exports = function (Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug) { var util = _dereq_("./util"); var TypeError = _dereq_("./errors").TypeError; var inherits = _dereq_("./util").inherits; var errorObj = util.errorObj; var tryCatch = util.tryCatch; function thrower(e) { setTimeout(function(){throw e;}, 0); } function castPreservingDisposable(thenable) { var maybePromise = tryConvertToPromise(thenable); if (maybePromise !== thenable && typeof thenable._isDisposable === "function" && typeof thenable._getDisposer === "function" && thenable._isDisposable()) { maybePromise._setDisposable(thenable._getDisposer()); } return maybePromise; } function dispose(resources, inspection) { var i = 0; var len = resources.length; var ret = new Promise(INTERNAL); function iterator() { if (i >= len) return ret._fulfill(); var maybePromise = castPreservingDisposable(resources[i++]); if (maybePromise instanceof Promise && maybePromise._isDisposable()) { try { maybePromise = tryConvertToPromise( maybePromise._getDisposer().tryDispose(inspection), resources.promise); } catch (e) { return thrower(e); } if (maybePromise instanceof Promise) { return maybePromise._then(iterator, thrower, null, null, null); } } iterator(); } iterator(); return ret; } function Disposer(data, promise, context) { this._data = data; this._promise = promise; this._context = context; } Disposer.prototype.data = function () { return this._data; }; Disposer.prototype.promise = function () { return this._promise; }; Disposer.prototype.resource = function () { if (this.promise().isFulfilled()) { return this.promise().value(); } return null; }; Disposer.prototype.tryDispose = function(inspection) { var resource = this.resource(); var context = this._context; if (context !== undefined) context._pushContext(); var ret = resource !== null ? this.doDispose(resource, inspection) : null; if (context !== undefined) context._popContext(); this._promise._unsetDisposable(); this._data = null; return ret; }; Disposer.isDisposer = function (d) { return (d != null && typeof d.resource === "function" && typeof d.tryDispose === "function"); }; function FunctionDisposer(fn, promise, context) { this.constructor$(fn, promise, context); } inherits(FunctionDisposer, Disposer); FunctionDisposer.prototype.doDispose = function (resource, inspection) { var fn = this.data(); return fn.call(resource, resource, inspection); }; function maybeUnwrapDisposer(value) { if (Disposer.isDisposer(value)) { this.resources[this.index]._setDisposable(value); return value.promise(); } return value; } function ResourceList(length) { this.length = length; this.promise = null; this[length-1] = null; } ResourceList.prototype._resultCancelled = function() { var len = this.length; for (var i = 0; i < len; ++i) { var item = this[i]; if (item instanceof Promise) { item.cancel(); } } }; Promise.using = function () { var len = arguments.length; if (len < 2) return apiRejection( "you must pass at least 2 arguments to Promise.using"); var fn = arguments[len - 1]; if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } var input; var spreadArgs = true; if (len === 2 && Array.isArray(arguments[0])) { input = arguments[0]; len = input.length; spreadArgs = false; } else { input = arguments; len--; } var resources = new ResourceList(len); for (var i = 0; i < len; ++i) { var resource = input[i]; if (Disposer.isDisposer(resource)) { var disposer = resource; resource = resource.promise(); resource._setDisposable(disposer); } else { var maybePromise = tryConvertToPromise(resource); if (maybePromise instanceof Promise) { resource = maybePromise._then(maybeUnwrapDisposer, null, null, { resources: resources, index: i }, undefined); } } resources[i] = resource; } var reflectedResources = new Array(resources.length); for (var i = 0; i < reflectedResources.length; ++i) { reflectedResources[i] = Promise.resolve(resources[i]).reflect(); } var resultPromise = Promise.all(reflectedResources) .then(function(inspections) { for (var i = 0; i < inspections.length; ++i) { var inspection = inspections[i]; if (inspection.isRejected()) { errorObj.e = inspection.error(); return errorObj; } else if (!inspection.isFulfilled()) { resultPromise.cancel(); return; } inspections[i] = inspection.value(); } promise._pushContext(); fn = tryCatch(fn); var ret = spreadArgs ? fn.apply(undefined, inspections) : fn(inspections); var promisesCreated = promise._popContext(); debug.checkForgottenReturns( ret, promisesCreated, "Promise.using", promise); return ret; }); var promise = resultPromise.lastly(function() { var inspection = new Promise.PromiseInspection(resultPromise); return dispose(resources, inspection); }); resources.promise = promise; promise._setOnCancel(resources); return promise; }; Promise.prototype._setDisposable = function (disposer) { this._bitField = this._bitField | 131072; this._disposer = disposer; }; Promise.prototype._isDisposable = function () { return (this._bitField & 131072) > 0; }; Promise.prototype._getDisposer = function () { return this._disposer; }; Promise.prototype._unsetDisposable = function () { this._bitField = this._bitField & (~131072); this._disposer = undefined; }; Promise.prototype.disposer = function (fn) { if (typeof fn === "function") { return new FunctionDisposer(fn, this, createContext()); } throw new TypeError(); }; }; },{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){ "use strict"; var es5 = _dereq_("./es5"); var canEvaluate = typeof navigator == "undefined"; var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { var target = tryCatchTarget; tryCatchTarget = null; return target.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { tryCatchTarget = fn; return tryCatcher; } var inherits = function(Child, Parent) { var hasProp = {}.hasOwnProperty; function T() { this.constructor = Child; this.constructor$ = Parent; for (var propertyName in Parent.prototype) { if (hasProp.call(Parent.prototype, propertyName) && propertyName.charAt(propertyName.length-1) !== "$" ) { this[propertyName + "$"] = Parent.prototype[propertyName]; } } } T.prototype = Parent.prototype; Child.prototype = new T(); return Child.prototype; }; function isPrimitive(val) { return val == null || val === true || val === false || typeof val === "string" || typeof val === "number"; } function isObject(value) { return typeof value === "function" || typeof value === "object" && value !== null; } function maybeWrapAsError(maybeError) { if (!isPrimitive(maybeError)) return maybeError; return new Error(safeToString(maybeError)); } function withAppended(target, appendee) { var len = target.length; var ret = new Array(len + 1); var i; for (i = 0; i < len; ++i) { ret[i] = target[i]; } ret[i] = appendee; return ret; } function getDataPropertyOrDefault(obj, key, defaultValue) { if (es5.isES5) { var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null) { return desc.get == null && desc.set == null ? desc.value : defaultValue; } } else { return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; } } function notEnumerableProp(obj, name, value) { if (isPrimitive(obj)) return obj; var descriptor = { value: value, configurable: true, enumerable: false, writable: true }; es5.defineProperty(obj, name, descriptor); return obj; } function thrower(r) { throw r; } var inheritedDataKeys = (function() { var excludedPrototypes = [ Array.prototype, Object.prototype, Function.prototype ]; var isExcludedProto = function(val) { for (var i = 0; i < excludedPrototypes.length; ++i) { if (excludedPrototypes[i] === val) { return true; } } return false; }; if (es5.isES5) { var getKeys = Object.getOwnPropertyNames; return function(obj) { var ret = []; var visitedKeys = Object.create(null); while (obj != null && !isExcludedProto(obj)) { var keys; try { keys = getKeys(obj); } catch (e) { return ret; } for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (visitedKeys[key]) continue; visitedKeys[key] = true; var desc = Object.getOwnPropertyDescriptor(obj, key); if (desc != null && desc.get == null && desc.set == null) { ret.push(key); } } obj = es5.getPrototypeOf(obj); } return ret; }; } else { var hasProp = {}.hasOwnProperty; return function(obj) { if (isExcludedProto(obj)) return []; var ret = []; /*jshint forin:false */ enumeration: for (var key in obj) { if (hasProp.call(obj, key)) { ret.push(key); } else { for (var i = 0; i < excludedPrototypes.length; ++i) { if (hasProp.call(excludedPrototypes[i], key)) { continue enumeration; } } ret.push(key); } } return ret; }; } })(); var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; function isClass(fn) { try { if (typeof fn === "function") { var keys = es5.names(fn.prototype); var hasMethods = es5.isES5 && keys.length > 1; var hasMethodsOtherThanConstructor = keys.length > 0 && !(keys.length === 1 && keys[0] === "constructor"); var hasThisAssignmentAndStaticMethods = thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; if (hasMethods || hasMethodsOtherThanConstructor || hasThisAssignmentAndStaticMethods) { return true; } } return false; } catch (e) { return false; } } function toFastProperties(obj) { /*jshint -W027,-W055,-W031*/ function FakeConstructor() {} FakeConstructor.prototype = obj; var l = 8; while (l--) new FakeConstructor(); return obj; eval(obj); } var rident = /^[a-z$_][a-z$_0-9]*$/i; function isIdentifier(str) { return rident.test(str); } function filledRange(count, prefix, suffix) { var ret = new Array(count); for(var i = 0; i < count; ++i) { ret[i] = prefix + i + suffix; } return ret; } function safeToString(obj) { try { return obj + ""; } catch (e) { return "[no string representation]"; } } function markAsOriginatingFromRejection(e) { try { notEnumerableProp(e, "isOperational", true); } catch(ignore) {} } function originatesFromRejection(e) { if (e == null) return false; return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || e["isOperational"] === true); } function canAttachTrace(obj) { return obj instanceof Error && es5.propertyIsWritable(obj, "stack"); } var ensureErrorObject = (function() { if (!("stack" in new Error())) { return function(value) { if (canAttachTrace(value)) return value; try {throw new Error(safeToString(value));} catch(err) {return err;} }; } else { return function(value) { if (canAttachTrace(value)) return value; return new Error(safeToString(value)); }; } })(); function classString(obj) { return {}.toString.call(obj); } function copyDescriptors(from, to, filter) { var keys = es5.names(from); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; if (filter(key)) { try { es5.defineProperty(to, key, es5.getDescriptor(from, key)); } catch (ignore) {} } } } var asArray = function(v) { if (es5.isArray(v)) { return v; } return null; }; if (typeof Symbol !== "undefined" && Symbol.iterator) { var ArrayFrom = typeof Array.from === "function" ? function(v) { return Array.from(v); } : function(v) { var ret = []; var it = v[Symbol.iterator](); var itResult; while (!((itResult = it.next()).done)) { ret.push(itResult.value); } return ret; }; asArray = function(v) { if (es5.isArray(v)) { return v; } else if (v != null && typeof v[Symbol.iterator] === "function") { return ArrayFrom(v); } return null; }; } var isNode = typeof process !== "undefined" && classString(process).toLowerCase() === "[object process]"; function env(key, def) { return isNode ? process.env[key] : def; } var ret = { isClass: isClass, isIdentifier: isIdentifier, inheritedDataKeys: inheritedDataKeys, getDataPropertyOrDefault: getDataPropertyOrDefault, thrower: thrower, isArray: es5.isArray, asArray: asArray, notEnumerableProp: notEnumerableProp, isPrimitive: isPrimitive, isObject: isObject, canEvaluate: canEvaluate, errorObj: errorObj, tryCatch: tryCatch, inherits: inherits, withAppended: withAppended, maybeWrapAsError: maybeWrapAsError, toFastProperties: toFastProperties, filledRange: filledRange, toString: safeToString, canAttachTrace: canAttachTrace, ensureErrorObject: ensureErrorObject, originatesFromRejection: originatesFromRejection, markAsOriginatingFromRejection: markAsOriginatingFromRejection, classString: classString, copyDescriptors: copyDescriptors, hasDevTools: typeof chrome !== "undefined" && chrome && typeof chrome.loadTimes === "function", isNode: isNode, env: env }; ret.isRecentNode = ret.isNode && (function() { var version = process.versions.node.split(".").map(Number); return (version[0] === 0 && version[1] > 10) || (version[0] > 0); })(); if (ret.isNode) ret.toFastProperties(process); try {throw new Error(); } catch (e) {ret.lastLineError = e;} module.exports = ret; },{"./es5":13}]},{},[4])(4) }); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":3}],3:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],4:[function(require,module,exports){ // (c) Dean McNamee , 2013. // // https://github.com/deanm/omggif // // 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. // // omggif is a JavaScript implementation of a GIF 89a encoder and decoder, // including animation and compression. It does not rely on any specific // underlying system, so should run in the browser, Node, or Plask. function GifWriter(buf, width, height, gopts) { var p = 0; var gopts = gopts === undefined ? { } : gopts; var loop_count = gopts.loop === undefined ? null : gopts.loop; var global_palette = gopts.palette === undefined ? null : gopts.palette; if (width <= 0 || height <= 0 || width > 65535 || height > 65535) throw "Width/Height invalid." function check_palette_and_num_colors(palette) { var num_colors = palette.length; if (num_colors < 2 || num_colors > 256 || num_colors & (num_colors-1)) throw "Invalid code/color length, must be power of 2 and 2 .. 256."; return num_colors; } // - Header. buf[p++] = 0x47; buf[p++] = 0x49; buf[p++] = 0x46; // GIF buf[p++] = 0x38; buf[p++] = 0x39; buf[p++] = 0x61; // 89a // Handling of Global Color Table (palette) and background index. var gp_num_colors_pow2 = 0; var background = 0; if (global_palette !== null) { var gp_num_colors = check_palette_and_num_colors(global_palette); while (gp_num_colors >>= 1) ++gp_num_colors_pow2; gp_num_colors = 1 << gp_num_colors_pow2; --gp_num_colors_pow2; if (gopts.background !== undefined) { background = gopts.background; if (background >= gp_num_colors) throw "Background index out of range."; // The GIF spec states that a background index of 0 should be ignored, so // this is probably a mistake and you really want to set it to another // slot in the palette. But actually in the end most browsers, etc end // up ignoring this almost completely (including for dispose background). if (background === 0) throw "Background index explicitly passed as 0."; } } // - Logical Screen Descriptor. // NOTE(deanm): w/h apparently ignored by implementations, but set anyway. buf[p++] = width & 0xff; buf[p++] = width >> 8 & 0xff; buf[p++] = height & 0xff; buf[p++] = height >> 8 & 0xff; // NOTE: Indicates 0-bpp original color resolution (unused?). buf[p++] = (global_palette !== null ? 0x80 : 0) | // Global Color Table Flag. gp_num_colors_pow2; // NOTE: No sort flag (unused?). buf[p++] = background; // Background Color Index. buf[p++] = 0; // Pixel aspect ratio (unused?). // - Global Color Table if (global_palette !== null) { for (var i = 0, il = global_palette.length; i < il; ++i) { var rgb = global_palette[i]; buf[p++] = rgb >> 16 & 0xff; buf[p++] = rgb >> 8 & 0xff; buf[p++] = rgb & 0xff; } } if (loop_count !== null) { // Netscape block for looping. if (loop_count < 0 || loop_count > 65535) throw "Loop count invalid." // Extension code, label, and length. buf[p++] = 0x21; buf[p++] = 0xff; buf[p++] = 0x0b; // NETSCAPE2.0 buf[p++] = 0x4e; buf[p++] = 0x45; buf[p++] = 0x54; buf[p++] = 0x53; buf[p++] = 0x43; buf[p++] = 0x41; buf[p++] = 0x50; buf[p++] = 0x45; buf[p++] = 0x32; buf[p++] = 0x2e; buf[p++] = 0x30; // Sub-block buf[p++] = 0x03; buf[p++] = 0x01; buf[p++] = loop_count & 0xff; buf[p++] = loop_count >> 8 & 0xff; buf[p++] = 0x00; // Terminator. } var ended = false; this.addFrame = function(x, y, w, h, indexed_pixels, opts) { if (ended === true) { --p; ended = false; } // Un-end. opts = opts === undefined ? { } : opts; // TODO(deanm): Bounds check x, y. Do they need to be within the virtual // canvas width/height, I imagine? if (x < 0 || y < 0 || x > 65535 || y > 65535) throw "x/y invalid." if (w <= 0 || h <= 0 || w > 65535 || h > 65535) throw "Width/Height invalid." if (indexed_pixels.length < w * h) throw "Not enough pixels for the frame size."; var using_local_palette = true; var palette = opts.palette; if (palette === undefined || palette === null) { using_local_palette = false; palette = global_palette; } if (palette === undefined || palette === null) throw "Must supply either a local or global palette."; var num_colors = check_palette_and_num_colors(palette); // Compute the min_code_size (power of 2), destroying num_colors. var min_code_size = 0; while (num_colors >>= 1) ++min_code_size; num_colors = 1 << min_code_size; // Now we can easily get it back. var delay = opts.delay === undefined ? 0 : opts.delay; // From the spec: // 0 - No disposal specified. The decoder is // not required to take any action. // 1 - Do not dispose. The graphic is to be left // in place. // 2 - Restore to background color. The area used by the // graphic must be restored to the background color. // 3 - Restore to previous. The decoder is required to // restore the area overwritten by the graphic with // what was there prior to rendering the graphic. // 4-7 - To be defined. // NOTE(deanm): Dispose background doesn't really work, apparently most // browsers ignore the background palette index and clear to transparency. var disposal = opts.disposal === undefined ? 0 : opts.disposal; if (disposal < 0 || disposal > 3) // 4-7 is reserved. throw "Disposal out of range."; var use_transparency = false; var transparent_index = 0; if (opts.transparent !== undefined && opts.transparent !== null) { use_transparency = true; transparent_index = opts.transparent; if (transparent_index < 0 || transparent_index >= num_colors) throw "Transparent color index."; } if (disposal !== 0 || use_transparency || delay !== 0) { // - Graphics Control Extension buf[p++] = 0x21; buf[p++] = 0xf9; // Extension / Label. buf[p++] = 4; // Byte size. buf[p++] = disposal << 2 | (use_transparency === true ? 1 : 0); buf[p++] = delay & 0xff; buf[p++] = delay >> 8 & 0xff; buf[p++] = transparent_index; // Transparent color index. buf[p++] = 0; // Block Terminator. } // - Image Descriptor buf[p++] = 0x2c; // Image Seperator. buf[p++] = x & 0xff; buf[p++] = x >> 8 & 0xff; // Left. buf[p++] = y & 0xff; buf[p++] = y >> 8 & 0xff; // Top. buf[p++] = w & 0xff; buf[p++] = w >> 8 & 0xff; buf[p++] = h & 0xff; buf[p++] = h >> 8 & 0xff; // NOTE: No sort flag (unused?). // TODO(deanm): Support interlace. buf[p++] = using_local_palette === true ? (0x80 | (min_code_size-1)) : 0; // - Local Color Table if (using_local_palette === true) { for (var i = 0, il = palette.length; i < il; ++i) { var rgb = palette[i]; buf[p++] = rgb >> 16 & 0xff; buf[p++] = rgb >> 8 & 0xff; buf[p++] = rgb & 0xff; } } p = GifWriterOutputLZWCodeStream( buf, p, min_code_size < 2 ? 2 : min_code_size, indexed_pixels); }; this.end = function() { if (ended === false) { buf[p++] = 0x3b; // Trailer. ended = true; } return p; }; } // Main compression routine, palette indexes -> LZW code stream. // |index_stream| must have at least one entry. function GifWriterOutputLZWCodeStream(buf, p, min_code_size, index_stream) { buf[p++] = min_code_size; var cur_subblock = p++; // Pointing at the length field. var clear_code = 1 << min_code_size; var code_mask = clear_code - 1; var eoi_code = clear_code + 1; var next_code = eoi_code + 1; var cur_code_size = min_code_size + 1; // Number of bits per code. var cur_shift = 0; // We have at most 12-bit codes, so we should have to hold a max of 19 // bits here (and then we would write out). var cur = 0; function emit_bytes_to_buffer(bit_block_size) { while (cur_shift >= bit_block_size) { buf[p++] = cur & 0xff; cur >>= 8; cur_shift -= 8; if (p === cur_subblock + 256) { // Finished a subblock. buf[cur_subblock] = 255; cur_subblock = p++; } } } function emit_code(c) { cur |= c << cur_shift; cur_shift += cur_code_size; emit_bytes_to_buffer(8); } // I am not an expert on the topic, and I don't want to write a thesis. // However, it is good to outline here the basic algorithm and the few data // structures and optimizations here that make this implementation fast. // The basic idea behind LZW is to build a table of previously seen runs // addressed by a short id (herein called output code). All data is // referenced by a code, which represents one or more values from the // original input stream. All input bytes can be referenced as the same // value as an output code. So if you didn't want any compression, you // could more or less just output the original bytes as codes (there are // some details to this, but it is the idea). In order to achieve // compression, values greater then the input range (codes can be up to // 12-bit while input only 8-bit) represent a sequence of previously seen // inputs. The decompressor is able to build the same mapping while // decoding, so there is always a shared common knowledge between the // encoding and decoder, which is also important for "timing" aspects like // how to handle variable bit width code encoding. // // One obvious but very important consequence of the table system is there // is always a unique id (at most 12-bits) to map the runs. 'A' might be // 4, then 'AA' might be 10, 'AAA' 11, 'AAAA' 12, etc. This relationship // can be used for an effecient lookup strategy for the code mapping. We // need to know if a run has been seen before, and be able to map that run // to the output code. Since we start with known unique ids (input bytes), // and then from those build more unique ids (table entries), we can // continue this chain (almost like a linked list) to always have small // integer values that represent the current byte chains in the encoder. // This means instead of tracking the input bytes (AAAABCD) to know our // current state, we can track the table entry for AAAABC (it is guaranteed // to exist by the nature of the algorithm) and the next character D. // Therefor the tuple of (table_entry, byte) is guaranteed to also be // unique. This allows us to create a simple lookup key for mapping input // sequences to codes (table indices) without having to store or search // any of the code sequences. So if 'AAAA' has a table entry of 12, the // tuple of ('AAAA', K) for any input byte K will be unique, and can be our // key. This leads to a integer value at most 20-bits, which can always // fit in an SMI value and be used as a fast sparse array / object key. // Output code for the current contents of the index buffer. var ib_code = index_stream[0] & code_mask; // Load first input index. var code_table = { }; // Key'd on our 20-bit "tuple". emit_code(clear_code); // Spec says first code should be a clear code. // First index already loaded, process the rest of the stream. for (var i = 1, il = index_stream.length; i < il; ++i) { var k = index_stream[i] & code_mask; var cur_key = ib_code << 8 | k; // (prev, k) unique tuple. var cur_code = code_table[cur_key]; // buffer + k. // Check if we have to create a new code table entry. if (cur_code === undefined) { // We don't have buffer + k. // Emit index buffer (without k). // This is an inline version of emit_code, because this is the core // writing routine of the compressor (and V8 cannot inline emit_code // because it is a closure here in a different context). Additionally // we can call emit_byte_to_buffer less often, because we can have // 30-bits (from our 31-bit signed SMI), and we know our codes will only // be 12-bits, so can safely have 18-bits there without overflow. // emit_code(ib_code); cur |= ib_code << cur_shift; cur_shift += cur_code_size; while (cur_shift >= 8) { buf[p++] = cur & 0xff; cur >>= 8; cur_shift -= 8; if (p === cur_subblock + 256) { // Finished a subblock. buf[cur_subblock] = 255; cur_subblock = p++; } } if (next_code === 4096) { // Table full, need a clear. emit_code(clear_code); next_code = eoi_code + 1; cur_code_size = min_code_size + 1; code_table = { }; } else { // Table not full, insert a new entry. // Increase our variable bit code sizes if necessary. This is a bit // tricky as it is based on "timing" between the encoding and // decoder. From the encoders perspective this should happen after // we've already emitted the index buffer and are about to create the // first table entry that would overflow our current code bit size. if (next_code >= (1 << cur_code_size)) ++cur_code_size; code_table[cur_key] = next_code++; // Insert into code table. } ib_code = k; // Index buffer to single input k. } else { ib_code = cur_code; // Index buffer to sequence in code table. } } emit_code(ib_code); // There will still be something in the index buffer. emit_code(eoi_code); // End Of Information. // Flush / finalize the sub-blocks stream to the buffer. emit_bytes_to_buffer(1); // Finish the sub-blocks, writing out any unfinished lengths and // terminating with a sub-block of length 0. If we have already started // but not yet used a sub-block it can just become the terminator. if (cur_subblock + 1 === p) { // Started but unused. buf[cur_subblock] = 0; } else { // Started and used, write length and additional terminator block. buf[cur_subblock] = p - cur_subblock - 1; buf[p++] = 0; } return p; } function GifReader(buf) { var p = 0; // - Header (GIF87a or GIF89a). if (buf[p++] !== 0x47 || buf[p++] !== 0x49 || buf[p++] !== 0x46 || buf[p++] !== 0x38 || (buf[p++]+1 & 0xfd) !== 0x38 || buf[p++] !== 0x61) { throw "Invalid GIF 87a/89a header."; } // - Logical Screen Descriptor. var width = buf[p++] | buf[p++] << 8; var height = buf[p++] | buf[p++] << 8; var pf0 = buf[p++]; // . var global_palette_flag = pf0 >> 7; var num_global_colors_pow2 = pf0 & 0x7; var num_global_colors = 1 << (num_global_colors_pow2 + 1); var background = buf[p++]; buf[p++]; // Pixel aspect ratio (unused?). var global_palette_offset = null; if (global_palette_flag) { global_palette_offset = p; p += num_global_colors * 3; // Seek past palette. } var no_eof = true; var frames = [ ]; var delay = 0; var transparent_index = null; var disposal = 0; // 0 - No disposal specified. var loop_count = null; this.width = width; this.height = height; while (no_eof && p < buf.length) { switch (buf[p++]) { case 0x21: // Graphics Control Extension Block switch (buf[p++]) { case 0xff: // Application specific block // Try if it's a Netscape block (with animation loop counter). if (buf[p ] !== 0x0b || // 21 FF already read, check block size. // NETSCAPE2.0 buf[p+1 ] == 0x4e && buf[p+2 ] == 0x45 && buf[p+3 ] == 0x54 && buf[p+4 ] == 0x53 && buf[p+5 ] == 0x43 && buf[p+6 ] == 0x41 && buf[p+7 ] == 0x50 && buf[p+8 ] == 0x45 && buf[p+9 ] == 0x32 && buf[p+10] == 0x2e && buf[p+11] == 0x30 && // Sub-block buf[p+12] == 0x03 && buf[p+13] == 0x01 && buf[p+16] == 0) { p += 14; loop_count = buf[p++] | buf[p++] << 8; p++; // Skip terminator. } else { // We don't know what it is, just try to get past it. p += 12; while (true) { // Seek through subblocks. var block_size = buf[p++]; if (block_size === 0) break; p += block_size; } } break; case 0xf9: // Graphics Control Extension if (buf[p++] !== 0x4 || buf[p+4] !== 0) throw "Invalid graphics extension block."; var pf1 = buf[p++]; delay = buf[p++] | buf[p++] << 8; transparent_index = buf[p++]; if ((pf1 & 1) === 0) transparent_index = null; disposal = pf1 >> 2 & 0x7; p++; // Skip terminator. break; case 0xfe: // Comment Extension. while (true) { // Seek through subblocks. var block_size = buf[p++]; if (block_size === 0) break; // console.log(buf.slice(p, p+block_size).toString('ascii')); p += block_size; } break; default: throw "Unknown graphic control label: 0x" + buf[p-1].toString(16); } break; case 0x2c: // Image Descriptor. var x = buf[p++] | buf[p++] << 8; var y = buf[p++] | buf[p++] << 8; var w = buf[p++] | buf[p++] << 8; var h = buf[p++] | buf[p++] << 8; var pf2 = buf[p++]; var local_palette_flag = pf2 >> 7; var interlace_flag = pf2 >> 6 & 1; var num_local_colors_pow2 = pf2 & 0x7; var num_local_colors = 1 << (num_local_colors_pow2 + 1); var palette_offset = global_palette_offset; var has_local_palette = false; if (local_palette_flag) { var has_local_palette = true; palette_offset = p; // Override with local palette. p += num_local_colors * 3; // Seek past palette. } var data_offset = p; p++; // codesize while (true) { var block_size = buf[p++]; if (block_size === 0) break; p += block_size; } frames.push({x: x, y: y, width: w, height: h, has_local_palette: has_local_palette, palette_offset: palette_offset, data_offset: data_offset, data_length: p - data_offset, transparent_index: transparent_index, interlaced: !!interlace_flag, delay: delay, disposal: disposal}); break; case 0x3b: // Trailer Marker (end of file). no_eof = false; break; default: throw "Unknown gif block: 0x" + buf[p-1].toString(16); break; } } this.numFrames = function() { return frames.length; }; this.loopCount = function() { return loop_count; }; this.frameInfo = function(frame_num) { if (frame_num < 0 || frame_num >= frames.length) throw "Frame index out of range."; return frames[frame_num]; } this.decodeAndBlitFrameBGRA = function(frame_num, pixels) { var frame = this.frameInfo(frame_num); var num_pixels = frame.width * frame.height; var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. GifReaderLZWOutputIndexStream( buf, frame.data_offset, index_stream, num_pixels); var palette_offset = frame.palette_offset; // NOTE(deanm): It seems to be much faster to compare index to 256 than // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in // the profile, not sure if it's related to using a Uint8Array. var trans = frame.transparent_index; if (trans === null) trans = 256; // We are possibly just blitting to a portion of the entire frame. // That is a subrect within the framerect, so the additional pixels // must be skipped over after we finished a scanline. var framewidth = frame.width; var framestride = width - framewidth; var xleft = framewidth; // Number of subrect pixels left in scanline. // Output indicies of the top left and bottom right corners of the subrect. var opbeg = ((frame.y * width) + frame.x) * 4; var opend = ((frame.y + frame.height) * width + frame.x) * 4; var op = opbeg; var scanstride = framestride * 4; // Use scanstride to skip past the rows when interlacing. This is skipping // 7 rows for the first two passes, then 3 then 1. if (frame.interlaced === true) { scanstride += width * 4 * 7; // Pass 1. } var interlaceskip = 8; // Tracking the row interval in the current pass. for (var i = 0, il = index_stream.length; i < il; ++i) { var index = index_stream[i]; if (xleft === 0) { // Beginning of new scan line op += scanstride; xleft = framewidth; if (op >= opend) { // Catch the wrap to switch passes when interlacing. scanstride = framestride * 4 + width * 4 * (interlaceskip-1); // interlaceskip / 2 * 4 is interlaceskip << 1. op = opbeg + (framewidth + framestride) * (interlaceskip << 1); interlaceskip >>= 1; } } if (index === trans) { op += 4; } else { var r = buf[palette_offset + index * 3]; var g = buf[palette_offset + index * 3 + 1]; var b = buf[palette_offset + index * 3 + 2]; pixels[op++] = b; pixels[op++] = g; pixels[op++] = r; pixels[op++] = 255; } --xleft; } }; // I will go to copy and paste hell one day... this.decodeAndBlitFrameRGBA = function(frame_num, pixels) { var frame = this.frameInfo(frame_num); var num_pixels = frame.width * frame.height; var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices. GifReaderLZWOutputIndexStream( buf, frame.data_offset, index_stream, num_pixels); var palette_offset = frame.palette_offset; // NOTE(deanm): It seems to be much faster to compare index to 256 than // to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in // the profile, not sure if it's related to using a Uint8Array. var trans = frame.transparent_index; if (trans === null) trans = 256; // We are possibly just blitting to a portion of the entire frame. // That is a subrect within the framerect, so the additional pixels // must be skipped over after we finished a scanline. var framewidth = frame.width; var framestride = width - framewidth; var xleft = framewidth; // Number of subrect pixels left in scanline. // Output indicies of the top left and bottom right corners of the subrect. var opbeg = ((frame.y * width) + frame.x) * 4; var opend = ((frame.y + frame.height) * width + frame.x) * 4; var op = opbeg; var scanstride = framestride * 4; // Use scanstride to skip past the rows when interlacing. This is skipping // 7 rows for the first two passes, then 3 then 1. if (frame.interlaced === true) { scanstride += width * 4 * 7; // Pass 1. } var interlaceskip = 8; // Tracking the row interval in the current pass. for (var i = 0, il = index_stream.length; i < il; ++i) { var index = index_stream[i]; if (xleft === 0) { // Beginning of new scan line op += scanstride; xleft = framewidth; if (op >= opend) { // Catch the wrap to switch passes when interlacing. scanstride = framestride * 4 + width * 4 * (interlaceskip-1); // interlaceskip / 2 * 4 is interlaceskip << 1. op = opbeg + (framewidth + framestride) * (interlaceskip << 1); interlaceskip >>= 1; } } if (index === trans) { op += 4; } else { var r = buf[palette_offset + index * 3]; var g = buf[palette_offset + index * 3 + 1]; var b = buf[palette_offset + index * 3 + 2]; pixels[op++] = r; pixels[op++] = g; pixels[op++] = b; pixels[op++] = 255; } --xleft; } }; } function GifReaderLZWOutputIndexStream(code_stream, p, output, output_length) { var min_code_size = code_stream[p++]; var clear_code = 1 << min_code_size; var eoi_code = clear_code + 1; var next_code = eoi_code + 1; var cur_code_size = min_code_size + 1; // Number of bits per code. // NOTE: This shares the same name as the encoder, but has a different // meaning here. Here this masks each code coming from the code stream. var code_mask = (1 << cur_code_size) - 1; var cur_shift = 0; var cur = 0; var op = 0; // Output pointer. var subblock_size = code_stream[p++]; // TODO(deanm): Would using a TypedArray be any faster? At least it would // solve the fast mode / backing store uncertainty. // var code_table = Array(4096); var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits. var prev_code = null; // Track code-1. while (true) { // Read up to two bytes, making sure we always 12-bits for max sized code. while (cur_shift < 16) { if (subblock_size === 0) break; // No more data to be read. cur |= code_stream[p++] << cur_shift; cur_shift += 8; if (subblock_size === 1) { // Never let it get to 0 to hold logic above. subblock_size = code_stream[p++]; // Next subblock. } else { --subblock_size; } } // TODO(deanm): We should never really get here, we should have received // and EOI. if (cur_shift < cur_code_size) break; var code = cur & code_mask; cur >>= cur_code_size; cur_shift -= cur_code_size; // TODO(deanm): Maybe should check that the first code was a clear code, // at least this is what you're supposed to do. But actually our encoder // now doesn't emit a clear code first anyway. if (code === clear_code) { // We don't actually have to clear the table. This could be a good idea // for greater error checking, but we don't really do any anyway. We // will just track it with next_code and overwrite old entries. next_code = eoi_code + 1; cur_code_size = min_code_size + 1; code_mask = (1 << cur_code_size) - 1; // Don't update prev_code ? prev_code = null; continue; } else if (code === eoi_code) { break; } // We have a similar situation as the decoder, where we want to store // variable length entries (code table entries), but we want to do in a // faster manner than an array of arrays. The code below stores sort of a // linked list within the code table, and then "chases" through it to // construct the dictionary entries. When a new entry is created, just the // last byte is stored, and the rest (prefix) of the entry is only // referenced by its table entry. Then the code chases through the // prefixes until it reaches a single byte code. We have to chase twice, // first to compute the length, and then to actually copy the data to the // output (backwards, since we know the length). The alternative would be // storing something in an intermediate stack, but that doesn't make any // more sense. I implemented an approach where it also stored the length // in the code table, although it's a bit tricky because you run out of // bits (12 + 12 + 8), but I didn't measure much improvements (the table // entries are generally not the long). Even when I created benchmarks for // very long table entries the complexity did not seem worth it. // The code table stores the prefix entry in 12 bits and then the suffix // byte in 8 bits, so each entry is 20 bits. var chase_code = code < next_code ? code : prev_code; // Chase what we will output, either {CODE} or {CODE-1}. var chase_length = 0; var chase = chase_code; while (chase > clear_code) { chase = code_table[chase] >> 8; ++chase_length; } var k = chase; var op_end = op + chase_length + (chase_code !== code ? 1 : 0); if (op_end > output_length) { console.log("Warning, gif stream longer than expected."); return; } // Already have the first byte from the chase, might as well write it fast. output[op++] = k; op += chase_length; var b = op; // Track pointer, writing backwards. if (chase_code !== code) // The case of emitting {CODE-1} + k. output[op++] = k; chase = chase_code; while (chase_length--) { chase = code_table[chase]; output[--b] = chase & 0xff; // Write backwards. chase >>= 8; // Pull down to the prefix code. } if (prev_code !== null && next_code < 4096) { code_table[next_code++] = prev_code << 8 | k; // TODO(deanm): Figure out this clearing vs code growth logic better. I // have an feeling that it should just happen somewhere else, for now it // is awkward between when we grow past the max and then hit a clear code. // For now just check if we hit the max 12-bits (then a clear code should // follow, also of course encoded in 12-bits). if (next_code >= code_mask+1 && cur_code_size < 12) { ++cur_code_size; code_mask = code_mask << 1 | 1; } } prev_code = code; } if (op !== output_length) { console.log("Warning, gif stream shorter than expected."); } return output; } try { exports.GifWriter = GifWriter; exports.GifReader = GifReader } catch(e) { } // CommonJS. },{}]},{},[1]); ================================================ FILE: metalsmith.json ================================================ { "source" : "site", "destination" : "gh-pages", "plugins" : { "metalsmith-less" : { "render" : { "paths" : ["site"] } }, "metalsmith-ignore" : [ "**/_*", "**/_*/**/*", "**/*.less" ], "metalsmith-assets" : { "source" : "site/assets", "destination" : "assets" }, "metalsmith-raw" : true, "metalsmith-comment-yaml" : { "docs" : "./gifler.bare.js" }, "metalsmith-jade" : { "pretty" : true, "useMetadata" : true }, "metalsmith-serve" : { "port" : 9000 }, "metalsmith-watch" : { "paths" : { "${source}/**/*" : "**/*" } } } } ================================================ FILE: package.json ================================================ { "name" : "gifler", "version" : "0.3.0", "description" : "Render GIF frames to ", "author" : "themadcreator@github", "license" : "Apache-2.0", "main" : "gifler.bare.js", "scripts" : { "compile" : "./node_modules/.bin/coffee --compile --bare --print src/gifler.coffee > gifler.bare.js", "postcompile" : "./node_modules/.bin/browserify gifler.bare.js > gifler.bundle.js", "build" : "npm run compile && ./node_modules/.bin/uglifyjs --compress --mangle --screw-ie8 --preamble '/** gifler.js | github.com/themadcreator/gifler | @license: Apache-2.0 */' -- gifler.bundle.js > gifler.min.js", "postbuild" : "cp gifler.min.js site/assets/gifler.js", "site-prep" : "npm run build && rm -rf gh-pages", "site" : "npm run site-prep && ./node_modules/.bin/metalsmith", "site-deploy" : "git subtree push --prefix gh-pages origin gh-pages", "deploy" : "npm version minor -m \"Update version to %s\" ", "postdeploy" : "git push && git push --tags" }, "dependencies" : { "bluebird" : "3.0.2", "omggif" : "1.0.x" }, "devDependencies": { "browserify" : "11.x.x", "coffee-script" : "1.10.0", "uglify-js" : "2.x.x", "metalsmith" : "2.1.0", "metalsmith-assets" : "0.1.0", "metalsmith-comment-yaml" : "0.1.0", "metalsmith-ignore" : "0.1.2", "metalsmith-jade" : "2.0.2", "metalsmith-less" : "2.0.0", "metalsmith-raw" : "0.2.0", "metalsmith-serve" : "0.0.4", "metalsmith-watch" : "1.0.1" } } ================================================ FILE: site/_constants.less ================================================ @color-bg : @color-hero-bg; @color-content : white; @color-text : #555; @color-header : #45ADA8; @color-highlight : black; //#0D7693; @color-nav : #BD1550; @color-hero-bg : #490A3D; @color-hero-fg : white; @min-size : 40px; @med-size : 60px; @pad : 15px; @content-width : 700px; .user-select(@value){ -webkit-touch-callout : @value; -webkit-user-select : @value; -khtml-user-select : @value; -moz-user-select : @value; -ms-user-select : @value; user-select : @value; } .table-center(){ display : table-cell; text-align : center; vertical-align : middle; } ================================================ FILE: site/_examples/control.js ================================================ gifler('assets/gif/run.gif') .animate('canvas.play-pause') .then(function(animator) { $('canvas.play-pause').click(function(){ if(animator.running()){ animator.stop(); } else { animator.start(); } }); }); ================================================ FILE: site/_examples/rainbow.js ================================================ var frames = 0; function onDrawFrame(ctx, frame) { // Match width/height to remove distortion ctx.canvas.width = ctx.canvas.offsetWidth; ctx.canvas.height = ctx.canvas.offsetHeight; // Determine how many pikachus will fit on screen var n = Math.floor((ctx.canvas.width)/150) for(var x = 0; x < n; x++) { // Draw a pikachu var left = x * 150; ctx.globalCompositeOperation = 'source-over'; ctx.drawImage(frame.buffer, frame.x + left, frame.y, 150, 100); // Composite a color var hue = (frames * 10 + x * 50) % 360; ctx.globalCompositeOperation = 'source-atop'; ctx.fillStyle = 'hsla(' + hue + ', 100%, 50%, 0.5)'; ctx.fillRect(left, 0, 150, this.height); } frames++; } // Load the GIF, set custom frame render function gifler('assets/gif/run.gif') .frames('canvas.rainbow-pikachus', onDrawFrame); ================================================ FILE: site/_examples/simple.js ================================================ gifler('assets/gif/run.gif').animate('canvas.running-pikachu') ================================================ FILE: site/_layout.jade ================================================ doctype html head meta(name='viewport', content='width=device-width') meta(name='viewport', content='initial-scale=1.0, maximum-scale=1.0') link(rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:100,300,400,700,900") link(rel="stylesheet" href="//cdn.jsdelivr.net/devicons/1.8.0/css/devicons.min.css") link(rel="stylesheet" href="assets/lib/monokai_sublime.css") link(rel="stylesheet" href="theme.css") block style script(type="text/javascript" src="assets/gifler.js") script(type="text/javascript" src="assets/lib/highlight.pack.js") script(type="text/javascript") hljs.initHighlightingOnLoad(); body include _nav.jade block hero .content-row.row: .content: block content .footer made by #[a(href="https://github.com/themadcreator/") themadcreator@github] ================================================ FILE: site/_nav.jade ================================================ .nav-top.row .nav-left a(href="./") Gifler a(href="examples.html") examples a(href="docs.html") docs .nav-right a(href="https://github.com/themadcreator/gifler"): span.devicons.devicons-github_full a(href="https://www.npmjs.com/package/gifler"): span.devicons.devicons-npm ================================================ FILE: site/assets/gifler.js ================================================ /** gifler.js | github.com/themadcreator/gifler | @license: Apache-2.0 */ !function t(e,n,r){function i(s,a){if(!n[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[s]={exports:{}};e[s][0].call(l.exports,function(t){var n=e[s][1][t];return i(n?n:t)},l,l.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s=0?r>t:t>r;r>=0?t++:t--)n.push(t);return n}.apply(this).map(function(n){return t.decodeFrame(e,n)})},t.decodeFramesAsync=function(e){var n,r;return a.map(function(){r=[];for(var t=0,n=e.numFrames();n>=0?n>t:t>n;n>=0?t++:t--)r.push(t);return r}.apply(this),function(n){return t.decodeFrame(e,n)},n=1)},t.decodeFrame=function(t,e){var n;return n=t.frameInfo(e),n.pixels=new Uint8ClampedArray(t.width*t.height*4),t.decodeAndBlitFrameRGBA(e,n.pixels),n},t}(),r=function(){function t(t,e){var n;this._reader=t,this._frames=e,this._advanceFrame=c(this._advanceFrame,this),this._nextFrameRender=c(this._nextFrameRender,this),this._nextFrame=c(this._nextFrame,this),n=this._reader,this.width=n.width,this.height=n.height,this._loopCount=this._reader.loopCount(),this._loops=0,this._frameIndex=0,this._running=!1}return t.createBufferCanvas=function(t,e,n){var r,i,o;return r=document.createElement("canvas"),i=r.getContext("2d"),r.width=t.width,r.height=t.height,o=i.createImageData(e,n),o.data.set(t.pixels),i.putImageData(o,-t.x,-t.y),r},t.prototype.start=function(){return this._lastTime=(new Date).valueOf(),this._delayCompensation=0,this._running=!0,setTimeout(this._nextFrame,0),this},t.prototype.stop=function(){return this._running=!1,this},t.prototype.reset=function(){return this._frameIndex=0,this._loops=0,this},t.prototype.running=function(){return this._running},t.prototype._nextFrame=function(){requestAnimationFrame(this._nextFrameRender)},t.prototype._nextFrameRender=function(){var t,e;if(this._running)return t=this._frames[this._frameIndex],null!=(e=this.onFrame)&&e.apply(this,[t,this._frameIndex]),this._enqueueNextFrame()},t.prototype._advanceFrame=function(){this._frameIndex+=1,this._frameIndex>=this._frames.length&&(0!==this._loopCount&&this._loopCount===this._loops?this.stop():(this._frameIndex=0,this._loops+=1))},t.prototype._enqueueNextFrame=function(){var t,e,n,r;for(this._advanceFrame();this._running;){if(n=this._frames[this._frameIndex],e=(new Date).valueOf()-this._lastTime,this._lastTime+=e,this._delayCompensation+=e,r=10*n.delay,t=r-this._delayCompensation,this._delayCompensation-=r,!(0>t)){setTimeout(this._nextFrame,t);break}this._advanceFrame()}},t.prototype.animateInCanvas=function(e,n){var r;return null==n&&(n=!0),n&&(e.width=this.width,e.height=this.height),r=e.getContext("2d"),null==this.onDrawFrame&&(this.onDrawFrame=function(t,e,n){return t.drawImage(e.buffer,e.x,e.y)}),null==this.onFrame&&(this.onFrame=function(n){return function(i,o){var s,a;switch(null==i.buffer&&(i.buffer=t.createBufferCanvas(i,n.width,n.height)),"function"==typeof n.disposeFrame&&n.disposeFrame(),i.disposal){case 2:n.disposeFrame=function(){return r.clearRect(0,0,e.width,e.height)};break;case 3:a=r.getImageData(0,0,e.width,e.height),n.disposeFrame=function(){return r.putImageData(a,0,0)};break;default:n.disposeFrame=null}return null!=(s=n.onDrawFrame)?s.apply(n,[r,i,o]):void 0}}(this)),this.start(),this},t}(),u.Gif=o,u.Decoder=i,u.Animator=r,"undefined"!=typeof window&&null!==window&&(window.gifler=u),"undefined"!=typeof e&&null!==e&&(e.exports=u)},{bluebird:2,omggif:4}],2:[function(t,e,n){(function(t,r){!function(t){if("object"==typeof n&&"undefined"!=typeof e)e.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i;"undefined"!=typeof window?i=window:"undefined"!=typeof r?i=r:"undefined"!=typeof self&&(i=self),i.Promise=t()}}(function(){var e,n,i;return function t(e,n,r){function i(s,a){if(!n[s]){if(!e[s]){var u="function"==typeof _dereq_&&_dereq_;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var l=n[s]={exports:{}};e[s][0].call(l.exports,function(t){var n=e[s][1][t];return i(n?n:t)},l,l.exports,t,e,n,r)}return n[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var e=t.shift();if("function"==typeof e){var n=t.shift(),r=t.shift();e.call(n,r)}else e._settlePromises()}},i.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},i.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},i.prototype._reset=function(){this._isTickUsed=!1},n.exports=i,n.exports.firstLineError=u},{"./queue":26,"./schedule":29,"./util":36}],3:[function(t,e,n){"use strict";e.exports=function(t,e,n,r){var i=!1,o=function(t,e){this._reject(e)},s=function(t,e){e.promiseRejectionQueued=!0,e.bindingPromise._then(o,o,null,this,t)},a=function(t,e){0===(50397184&this._bitField)&&this._resolveCallback(e.target)},u=function(t,e){e.promiseRejectionQueued||this._reject(t)};t.prototype.bind=function(o){i||(i=!0,t.prototype._propagateFrom=r.propagateFromFunction(),t.prototype._boundValue=r.boundValueFunction());var c=n(o),l=new t(e);l._propagateFrom(this,1);var h=this._target();if(l._setBoundTo(c),c instanceof t){var f={promiseRejectionQueued:!1,promise:l,target:h,bindingPromise:c};h._then(e,s,void 0,l,f),c._then(a,u,void 0,l,f),l._setOnCancel(c)}else l._resolveCallback(h);return l},t.prototype._setBoundTo=function(t){void 0!==t?(this._bitField=2097152|this._bitField,this._boundTo=t):this._bitField=-2097153&this._bitField},t.prototype._isBound=function(){return 2097152===(2097152&this._bitField)},t.bind=function(e,n){return t.resolve(n).bind(e)}}},{}],4:[function(t,e,n){"use strict";function r(){try{Promise===o&&(Promise=i)}catch(t){}return o}var i;"undefined"!=typeof Promise&&(i=Promise);var o=t("./promise")();o.noConflict=r,e.exports=o},{"./promise":22}],5:[function(t,e,n){"use strict";var r=Object.create;if(r){var i=r(null),o=r(null);i[" size"]=o[" size"]=0}e.exports=function(e){function n(t,n){var r;if(null!=t&&(r=t[n]),"function"!=typeof r){var i="Object "+a.classString(t)+" has no method '"+a.toString(n)+"'";throw new e.TypeError(i)}return r}function r(t){var e=this.pop(),r=n(t,e);return r.apply(t,this)}function i(t){return t[this]}function o(t){var e=+this;return 0>e&&(e=Math.max(0,e+t.length)),t[e]}var s,a=t("./util"),u=a.canEvaluate;a.isIdentifier;e.prototype.call=function(t){var e=[].slice.call(arguments,1);return e.push(t),this._then(r,void 0,void 0,e,void 0)},e.prototype.get=function(t){var e,n="number"==typeof t;if(n)e=o;else if(u){var r=s(t);e=null!==r?r:i}else e=i;return this._then(e,void 0,void 0,t,void 0)}}},{"./util":36}],6:[function(t,e,n){"use strict";e.exports=function(e,n,r,i){var o=t("./util"),s=o.tryCatch,a=o.errorObj,u=e._async;e.prototype.break=e.prototype.cancel=function(){if(!i.cancellation())return this._warn("cancellation is disabled");for(var t=this,e=t;t.isCancellable();){if(!t._cancelBy(e)){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}var n=t._cancellationParent;if(null==n||!n.isCancellable()){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}t._isFollowing()&&t._followee().cancel(),e=t,t=n}},e.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},e.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},e.prototype._cancelBy=function(t){return t===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),this._enoughBranchesHaveCancelled()?(this._invokeOnCancel(),!0):!1)},e.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},e.prototype._cancel=function(){this.isCancellable()&&(this._setCancelled(),u.invoke(this._cancelPromises,this,void 0))},e.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},e.prototype._unsetOnCancel=function(){this._onCancelField=void 0},e.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},e.prototype._doInvokeOnCancel=function(t,e){if(o.isArray(t))for(var n=0;n=0?o[t]:void 0}var i=!1,o=[];return t.prototype._promiseCreated=function(){},t.prototype._pushContext=function(){},t.prototype._popContext=function(){return 0},t._peekContext=t.prototype._peekContext=function(){},e.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promisesCreated=0,o.push(this._trace))},e.prototype._popContext=function(){if(void 0!==this._trace){var t=o.pop(),e=t._promisesCreated;return t._promisesCreated=0,e}return 0},e.CapturedTrace=null,e.create=n,e.activateLongStackTraces=function(){i=!0,t.prototype._pushContext=e.prototype._pushContext,t.prototype._popContext=e.prototype._popContext,t._peekContext=t.prototype._peekContext=r,t.prototype._promiseCreated=function(){var t=this._peekContext();t&&t._promisesCreated++}},e}},{}],9:[function(e,n,r){"use strict";n.exports=function(n,r){function i(t,e,n){var r=this;try{t(e,n,function(t){if("function"!=typeof t)throw new TypeError("onCancel must be a function, got: "+H.toString(t));r._attachCancellationCallback(t)})}catch(t){return t}}function o(t){if(!this.isCancellable())return this;var e=this._onCancel();void 0!==e?H.isArray(e)?e.push(t):this._setOnCancel([e,t]):this._setOnCancel(t)}function s(){return this._onCancelField}function a(t){this._onCancelField=t}function u(){this._cancellationParent=void 0,this._onCancelField=void 0}function c(t,e){if(0!==(1&e)){this._cancellationParent=t;var n=t._branchesRemainingToCancel;void 0===n&&(n=0),t._branchesRemainingToCancel=n+1}0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function l(t,e){0!==(2&e)&&t._isBound()&&this._setBoundTo(t._boundTo)}function h(){var t=this._boundTo;return void 0!==t&&t instanceof n?t.isFulfilled()?t.value():void 0:t}function f(){this._trace=new R(this._peekContext())}function p(t,e){if(L(t)){var n=this._trace;if(void 0!==n&&e&&(n=n._parent),void 0!==n)n.attachExtraTrace(t);else if(!t.__stackCleaned__){var r=C(t);H.notEnumerableProp(t,"stack",r.message+"\n"+r.stack.join("\n")),H.notEnumerableProp(t,"__stackCleaned__",!0)}}}function _(t,e,n,r){if(void 0===t&&e>0&&Y.longStackTraces&&Y.warnings){var i="a promise was created in a "+n+" handler but was not returned from it";r._warn(i)}}function d(t,e){var n=t+" is deprecated and will be removed in a future version.";return e&&(n+=" Use "+e+" instead."),v(n)}function v(t,e,r){if(Y.warnings){var i,o=new V(t);if(e)r._attachExtraTrace(o);else if(Y.longStackTraces&&(i=n._peekContext()))i.attachExtraTrace(o);else{var s=C(o);o.stack=s.message+"\n"+s.stack.join("\n")}j(o,"",!0)}}function y(t,e){for(var n=0;n=0;--a)if(r[a]===o){s=a;break}for(var a=s;a>=0;--a){var u=r[a];if(e[i]!==u)break;e.pop(),i--}e=r}}function b(t){for(var e=[],n=0;n0&&(e=e.slice(n)),e}function C(t){var e=t.stack,n=t.toString();return e="string"==typeof e&&e.length>0?w(t):[" (No stack trace)"],{message:n,stack:b(e)}}function j(t,e,n){if("undefined"!=typeof console){var r;if(H.isObject(t)){var i=t.stack;r=e+B(i,t)}else r=e+String(t);"function"==typeof S?S(r,n):("function"==typeof console.log||"object"==typeof console.log)&&console.log(r)}}function F(t,e,n,r){var i=!1;try{"function"==typeof e&&(i=!0,"rejectionHandled"===t?e(r):e(n,r))}catch(t){D.throwLater(t)}var o=!1;try{o=J(t,n,r)}catch(t){o=!0,D.throwLater(t)}var s=!1;if(X)try{s=X(t.toLowerCase(),{reason:n,promise:r})}catch(t){s=!0,D.throwLater(t)}o||i||s||"unhandledRejection"!==t||j(n,"Unhandled rejection ")}function k(t){var e;if("function"==typeof t)e="[function "+(t.name||"anonymous")+"]";else{e=t&&"function"==typeof t.toString?t.toString():H.toString(t);var n=/\[object [a-zA-Z0-9$_]+\]/;if(n.test(e))try{var r=JSON.stringify(t);e=r}catch(t){}0===e.length&&(e="(empty array)")}return"(<"+x(e)+">, no stack trace)"}function x(t){var e=41;return t.lengths||0>a||!n||!r||n!==r||s>=a||(z=function(t){if(N.test(t))return!0;var e=T(t);return e&&e.fileName===n&&s<=e.line&&e.line<=a?!0:!1})}}function R(t){this._parent=t,this._promisesCreated=0;var e=this._length=1+(void 0===t?0:t._length);K(this,R),e>32&&this.uncycle()}var A,O,S,I=n._getDomain,D=n._async,V=e("./errors").Warning,H=e("./util"),L=H.canAttachTrace,N=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,U=null,B=null,M=!1,q=!0,Q=!(0==H.env("BLUEBIRD_WARNINGS")||!q&&!H.env("BLUEBIRD_WARNINGS")),$=!(0==H.env("BLUEBIRD_LONG_STACK_TRACES")||!q&&!H.env("BLUEBIRD_LONG_STACK_TRACES"));n.prototype.suppressUnhandledRejections=function(){var t=this._target();t._bitField=-1048577&t._bitField|2097152},n.prototype._ensurePossibleRejectionHandled=function(){0===(2097152&this._bitField)&&(this._setRejectionIsUnhandled(),D.invokeLater(this._notifyUnhandledRejection,this,void 0))},n.prototype._notifyUnhandledRejectionIsHandled=function(){F("rejectionHandled",A,void 0,this)},n.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var t=this._settledValue();this._setUnhandledRejectionIsNotified(),F("unhandledRejection",O,t,this)}},n.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},n.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},n.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},n.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},n.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},n.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},n.prototype._warn=function(t,e){return v(t,e,this)},n.onPossiblyUnhandledRejection=function(t){var e=I();O="function"==typeof t?null===e?t:e.bind(t):void 0},n.onUnhandledRejectionHandled=function(t){var e=I();A="function"==typeof t?null===e?t:e.bind(t):void 0},n.longStackTraces=function(){if(D.haveItemsQueued()&&!Y.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");!Y.longStackTraces&&E()&&(Y.longStackTraces=!0,n.prototype._captureStackTrace=f,n.prototype._attachExtraTrace=p,r.activateLongStackTraces(),D.disableTrampolineIfNecessary())},n.hasLongStackTraces=function(){return Y.longStackTraces&&E()},n.config=function(t){if(t=Object(t),"longStackTraces"in t&&t.longStackTraces&&n.longStackTraces(),"warnings"in t&&(Y.warnings=!!t.warnings),"cancellation"in t&&t.cancellation&&!Y.cancellation){if(D.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");n.prototype._clearCancellationData=u,n.prototype._propagateFrom=c,n.prototype._onCancel=s,n.prototype._setOnCancel=a,n.prototype._attachCancellationCallback=o,n.prototype._execute=i,G=c,Y.cancellation=!0}},n.prototype._execute=function(t,e,n){try{t(e,n)}catch(t){return t}},n.prototype._onCancel=function(){},n.prototype._setOnCancel=function(t){},n.prototype._attachCancellationCallback=function(t){},n.prototype._captureStackTrace=function(){},n.prototype._attachExtraTrace=function(){},n.prototype._clearCancellationData=function(){},n.prototype._propagateFrom=function(t,e){};var G=l,z=function(){return!1},W=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;H.inherits(R,Error),r.CapturedTrace=R,R.prototype.uncycle=function(){var t=this._length;if(!(2>t)){for(var e=[],n={},r=0,i=this;void 0!==i;++r)e.push(i),i=i._parent;t=this._length=r;for(var r=t-1;r>=0;--r){var o=e[r].stack;void 0===n[o]&&(n[o]=r)}for(var r=0;t>r;++r){var s=e[r].stack,a=n[s];if(void 0!==a&&a!==r){a>0&&(e[a-1]._parent=void 0,e[a-1]._length=1),e[r]._parent=void 0,e[r]._length=1;var u=r>0?e[r-1]:this;t-1>a?(u._parent=e[a+1],u._parent.uncycle(),u._length=u._parent._length+1):(u._parent=void 0,u._length=1);for(var c=u._length+1,l=r-2;l>=0;--l)e[l]._length=c,c++;return}}}},R.prototype.attachExtraTrace=function(t){if(!t.__stackCleaned__){this.uncycle();for(var e=C(t),n=e.message,r=[e.stack],i=this;void 0!==i;)r.push(b(i.stack.split("\n"))),i=i._parent;g(r),m(r),H.notEnumerableProp(t,"stack",y(n,r)),H.notEnumerableProp(t,"__stackCleaned__",!0)}};var X,K=function(){var t=/^\s*at\s*/,e=function(t,e){return"string"==typeof t?t:void 0!==e.name&&void 0!==e.message?e.toString():k(e)};if("number"==typeof Error.stackTraceLimit&&"function"==typeof Error.captureStackTrace){Error.stackTraceLimit+=6,U=t,B=e;var n=Error.captureStackTrace;return z=function(t){return N.test(t)},function(t,e){Error.stackTraceLimit+=6,n(t,e),Error.stackTraceLimit-=6}}var r=new Error;if("string"==typeof r.stack&&r.stack.split("\n")[0].indexOf("stackDetection@")>=0)return U=/@/,B=e,M=!0,function(t){t.stack=(new Error).stack};var i;try{throw new Error}catch(t){i="stack"in t}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(B=function(t,e){return"string"==typeof t?t:"object"!=typeof e&&"function"!=typeof e||void 0===e.name||void 0===e.message?k(e):e.toString()},null):(U=t,B=e,function(t){Error.stackTraceLimit+=6;try{throw new Error}catch(e){t.stack=e.stack}Error.stackTraceLimit-=6})}([]),J=function(){if(H.isNode)return function(e,n,r){return"rejectionHandled"===e?t.emit(e,r):t.emit(e,n,r)};var e=!1,n=!0;try{var r=new self.CustomEvent("test");e=r instanceof CustomEvent}catch(t){}if(!e)try{var i=document.createEvent("CustomEvent");i.initCustomEvent("testingtheevent",!1,!0,{}),self.dispatchEvent(i)}catch(t){n=!1}n&&(X=function(t,n){var r;return e?r=new self.CustomEvent(t,{detail:n,bubbles:!1,cancelable:!0}):self.dispatchEvent&&(r=document.createEvent("CustomEvent"),r.initCustomEvent(t,!1,!0,n)),r?!self.dispatchEvent(r):!1});var o={};return o.unhandledRejection="onunhandledRejection".toLowerCase(),o.rejectionHandled="onrejectionHandled".toLowerCase(),function(t,e,n){var r=o[t],i=self[r];return i?("rejectionHandled"===t?i.call(self,n):i.call(self,e,n),!0):!1}}();"undefined"!=typeof console&&"undefined"!=typeof console.warn&&(S=function(t){console.warn(t)},H.isNode&&t.stderr.isTTY?S=function(e,n){var r=n?"":"";t.stderr.write(r+e+"\n")}:H.isNode||"string"!=typeof(new Error).stack||(S=function(t,e){console.warn("%c"+t,e?"color: darkorange":"color: red")}));var Y={warnings:Q,longStackTraces:!1,cancellation:!1};return $&&n.longStackTraces(),{longStackTraces:function(){return Y.longStackTraces},warnings:function(){return Y.warnings},cancellation:function(){return Y.cancellation},propagateFromFunction:function(){return G},boundValueFunction:function(){return h},checkForgottenReturns:_,setBounds:P,warn:v,deprecated:d,CapturedTrace:R}}},{"./errors":12,"./util":36}],10:[function(t,e,n){"use strict";e.exports=function(t){function e(){return this.value}function n(){throw this.reason}t.prototype.return=t.prototype.thenReturn=function(n){return n instanceof t&&n.suppressUnhandledRejections(),this._then(e,void 0,void 0,{value:n},void 0)},t.prototype.throw=t.prototype.thenThrow=function(t){return this._then(n,void 0,void 0,{reason:t},void 0)},t.prototype.catchThrow=function(t){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:t},void 0);var e=arguments[1],r=function(){throw e};return this.caught(t,r)},t.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof t&&n.suppressUnhandledRejections(),this._then(void 0,e,void 0,{value:n},void 0);var r=arguments[1];r instanceof t&&r.suppressUnhandledRejections();var i=function(){return r};return this.caught(n,i)}}},{}],11:[function(t,e,n){"use strict";e.exports=function(t,e){function n(){return o(this)}function r(t,n){return i(t,n,e,e)}var i=t.reduce,o=t.all;t.prototype.each=function(t){return this.mapSeries(t)._then(n,void 0,void 0,this,void 0)},t.prototype.mapSeries=function(t){return i(this,t,e,e)},t.each=function(t,e){return r(t,e)._then(n,void 0,void 0,t,void 0)},t.mapSeries=r}},{}],12:[function(t,e,n){"use strict";function r(t,e){function n(r){return this instanceof n?(h(this,"message","string"==typeof r?r:e),h(this,"name",t),void(Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this))):new n(r)}return l(n,Error),n}function i(t){return this instanceof i?(h(this,"name","OperationalError"),h(this,"message",t),this.cause=t,this.isOperational=!0,void(t instanceof Error?(h(this,"message",t.message),h(this,"stack",t.stack)):Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor))):new i(t)}var o,s,a=t("./es5"),u=a.freeze,c=t("./util"),l=c.inherits,h=c.notEnumerableProp,f=r("Warning","warning"),p=r("CancellationError","cancellation error"),_=r("TimeoutError","timeout error"),d=r("AggregateError","aggregate error");try{o=TypeError,s=RangeError}catch(t){o=r("TypeError","type error"),s=r("RangeError","range error")}for(var v="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),y=0;y1?t.cancelPromise._reject(e):t.cancelPromise._cancel(),t.cancelPromise=null,!0):!1}function o(){return a.call(this,this.promise._target()._settledValue())}function s(t){return i(this,t)?void 0:(l.e=t,l)}function a(t){var a=this.promise,u=this.handler;if(!this.called){this.called=!0;var h=0===this.type?u.call(a._boundValue()):u.call(a._boundValue(),t);if(void 0!==h){var f=n(h,a);if(f instanceof e){if(null!=this.cancelPromise){if(f.isCancelled()){var p=new c("late cancellation observer");return a._attachExtraTrace(p),l.e=p,l}f.isPending()&&f._attachCancellationCallback(new r(this))}return f._then(o,s,void 0,this,void 0)}}}return a.isRejected()?(i(this),l.e=t,l):(i(this),t)}var u=t("./util"),c=e.CancellationError,l=u.errorObj;return r.prototype._resultCancelled=function(){i(this.finallyHandler)},e.prototype._passThrough=function(t,e,n,r){return"function"!=typeof t?this.then():this._then(n,r,void 0,{promise:this,handler:t,called:!1,cancelPromise:null,type:e},void 0)},e.prototype.lastly=e.prototype.finally=function(t){return this._passThrough(t,0,a,a)},e.prototype.tap=function(t){return this._passThrough(t,1,a)},a}},{"./util":36}],16:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r){for(var o=0;o0&&"function"==typeof arguments[e]){t=arguments[e];var r}var i=[].slice.call(arguments);t&&i.pop();var r=new n(i).promise();return void 0!==t?r.spread(t):r}}},{"./util":36}],18:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,e,n,r){this.constructor$(t),this._promise._captureStackTrace();var i=c();this._callback=null===i?e:i.bind(e),this._preservedValues=r===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=n>=1?[]:p,this._init$(void 0,-2)}function u(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+l.classString(e));var o="object"==typeof n&&null!==n?n.concurrency:0;return o="number"==typeof o&&isFinite(o)&&o>=1?o:0,new a(t,e,o,i).promise()}var c=e._getDomain,l=t("./util"),h=l.tryCatch,f=l.errorObj,p=[];l.inherits(a,n),a.prototype._init=function(){},a.prototype._promiseFulfilled=function(t,n){var r=this._values,o=this.length(),a=this._preservedValues,u=this._limit;if(0>n){if(n=-1*n-1,r[n]=t,u>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(u>=1&&this._inFlight>=u)return r[n]=t,this._queue.push(n),!1;null!==a&&(a[n]=t);var c=this._promise,l=this._callback,p=c._boundValue();c._pushContext();var _=h(l).call(p,t,n,o),d=c._popContext();if(s.checkForgottenReturns(_,d,null!==a?"Promise.filter":"Promise.map",c),_===f)return this._reject(_.e),!0;var v=i(_,this._promise);if(v instanceof e){v=v._target();var y=v._bitField;if(0===(50397184&y))return u>=1&&this._inFlight++,r[n]=v,v._proxy(this,-1*(n+1)),!1;if(0===(33554432&y))return 0!==(16777216&y)?(this._reject(v._reason()),!0):(this._cancel(),!0);_=v._value()}r[n]=_}var m=++this._totalResolved;return m>=o?(null!==a?this._filter(r,a):this._resolve(r),!0):!1},a.prototype._drainQueue=function(){for(var t=this._queue,e=this._limit,n=this._values;t.length>0&&this._inFlighto;++o)t[o]&&(r[i++]=e[o]);r.length=i,this._resolve(r)},a.prototype.preservedValues=function(){return this._preservedValues},e.prototype.map=function(t,e){return u(this,t,e,null)},e.map=function(t,e,n,r){return u(t,e,n,r)}}},{"./util":36}],19:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){var s=t("./util"),a=s.tryCatch;e.method=function(t){if("function"!=typeof t)throw new e.TypeError("expecting a function but got "+s.classString(t));return function(){var r=new e(n);r._captureStackTrace(),r._pushContext();var i=a(t).apply(this,arguments);return r._popContext(),r._resolveFromSyncValue(i),r}},e.attempt=e.try=function(t){if("function"!=typeof t)return i("expecting a function but got "+s.classString(t));var r=new e(n);r._captureStackTrace(),r._pushContext();var u;if(arguments.length>1){o.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],l=arguments[2];u=s.isArray(c)?a(t).apply(l,c):a(t).call(l,c)}else u=a(t)();return r._popContext(),r._resolveFromSyncValue(u),r},e.prototype._resolveFromSyncValue=function(t){t===s.errorObj?this._rejectCallback(t.e,!1):this._resolveCallback(t,!0)}}},{"./util":36}],20:[function(t,e,n){"use strict";function r(t){return t instanceof Error&&l.getPrototypeOf(t)===Error.prototype}function i(t){var e;if(r(t)){e=new c(t),e.name=t.name,e.message=t.message,e.stack=t.stack;for(var n=l.keys(t),i=0;i1){var n,r=new Array(e-1),i=0;for(n=0;e-1>n;++n){var o=arguments[n];if(!p.isObject(o))return h("expecting an object but got "+p.classString(o));r[i++]=o}return r.length=i,t=arguments[n],this.then(void 0,P(r,t,this))}return this.then(void 0,t)},i.prototype.reflect=function(){return this._then(l,l,void 0,this,void 0)},i.prototype.then=function(t,e){if(E.warnings()&&arguments.length>0&&"function"!=typeof t&&"function"!=typeof e){var n=".then() only accepts functions but was passed: "+p.classString(t);arguments.length>1&&(n+=", "+p.classString(e)),this._warn(n)}return this._then(t,e,void 0,void 0,void 0)},i.prototype.done=function(t,e){var n=this._then(t,e,void 0,void 0,void 0);n._setIsFinal()},i.prototype.spread=function(t){return"function"!=typeof t?h("expecting a function but got "+p.classString(t)):this.all()._then(t,void 0,void 0,w,void 0)},i.prototype.toJSON=function(){var t={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(t.fulfillmentValue=this.value(),t.isFulfilled=!0):this.isRejected()&&(t.rejectionReason=this.reason(),t.isRejected=!0),t},i.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new F(this).promise()},i.prototype.error=function(t){return this.caught(p.originatesFromRejection,t)},i.is=function(t){return t instanceof i},i.fromNode=i.fromCallback=function(t){var e=new i(b),n=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,r=O(t)(R(e,n));return r===A&&e._rejectCallback(r.e,!0),e._isFateSealed()||e._setAsyncGuaranteed(),e},i.all=function(t){return new F(t).promise()},i.cast=function(t){var e=j(t);return e instanceof i||(e=new i(b),e._setFulfilled(),e._rejectionHandler0=t),e},i.resolve=i.fulfilled=i.cast,i.reject=i.rejected=function(t){var e=new i(b);return e._captureStackTrace(),e._rejectCallback(t,!0),e},i.setScheduler=function(t){if("function"!=typeof t)throw new m("expecting a function but got "+p.classString(t));var e=v._schedule;return v._schedule=t,e},i.prototype._then=function(t,e,n,r,o){var s=void 0!==o,a=s?o:new i(b),c=this._target(),l=c._bitField;s||(a._propagateFrom(this,3),a._captureStackTrace(),void 0===r&&0!==(2097152&this._bitField)&&(r=0!==(50397184&l)?this._boundValue():c===this?void 0:this._boundTo));var h=u();if(0!==(50397184&l)){var f,p,_=c._settlePromiseCtx;0!==(33554432&l)?(p=c._rejectionHandler0,f=t):0!==(16777216&l)?(p=c._fulfillmentHandler0,f=e,c._unsetRejectionIsUnhandled()):(_=c._settlePromiseLateCancellationObserver,p=new g("late cancellation observer"),c._attachExtraTrace(p),f=e),v.invoke(_,c,{handler:null===h?f:"function"==typeof f&&h.bind(f),promise:a,receiver:r,value:p})}else c._addCallbacks(t,e,a,r,h);return a},i.prototype._length=function(){return 65535&this._bitField},i.prototype._isFateSealed=function(){return 0!==(117506048&this._bitField)},i.prototype._isFollowing=function(){return 67108864===(67108864&this._bitField)},i.prototype._setLength=function(t){this._bitField=-65536&this._bitField|65535&t},i.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField},i.prototype._setRejected=function(){this._bitField=16777216|this._bitField},i.prototype._setFollowing=function(){this._bitField=67108864|this._bitField},i.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},i.prototype._isFinal=function(){return(4194304&this._bitField)>0},i.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},i.prototype._setCancelled=function(){this._bitField=65536|this._bitField},i.prototype._setAsyncGuaranteed=function(){this._bitField=134217728|this._bitField},i.prototype._receiverAt=function(t){var e=0===t?this._receiver0:this[4*t-4+3];return e===f?void 0:void 0===e&&this._isBound()?this._boundValue():e},i.prototype._promiseAt=function(t){return this[4*t-4+2]},i.prototype._fulfillmentHandlerAt=function(t){return this[4*t-4+0]},i.prototype._rejectionHandlerAt=function(t){return this[4*t-4+1]},i.prototype._boundValue=function(){},i.prototype._migrateCallback0=function(t){var e=(t._bitField,t._fulfillmentHandler0),n=t._rejectionHandler0,r=t._promise0,i=t._receiverAt(0);void 0===i&&(i=f),this._addCallbacks(e,n,r,i,null)},i.prototype._migrateCallbackAt=function(t,e){var n=t._fulfillmentHandlerAt(e),r=t._rejectionHandlerAt(e),i=t._promiseAt(e),o=t._receiverAt(e);void 0===o&&(o=f),this._addCallbacks(n,r,i,o,null)},i.prototype._addCallbacks=function(t,e,n,r,i){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=r,"function"==typeof t&&(this._fulfillmentHandler0=null===i?t:i.bind(t)),"function"==typeof e&&(this._rejectionHandler0=null===i?e:i.bind(e));else{var s=4*o-4;this[s+2]=n,this[s+3]=r,"function"==typeof t&&(this[s+0]=null===i?t:i.bind(t)),"function"==typeof e&&(this[s+1]=null===i?e:i.bind(e))}return this._setLength(o+1),o},i.prototype._proxy=function(t,e){this._addCallbacks(void 0,void 0,e,t,null)},i.prototype._resolveCallback=function(t,e){if(0===(117506048&this._bitField)){if(t===this)return this._rejectCallback(c(),!1);var n=j(t,this);if(!(n instanceof i))return this._fulfill(t);e&&this._propagateFrom(n,2);var r=n._target(),o=r._bitField;if(0===(50397184&o)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;s>a;++a)r._migrateCallbackAt(this,a);this._setFollowing(),this._setLength(0),this._setFollowee(r)}else if(0!==(33554432&o))this._fulfill(r._value());else if(0!==(16777216&o))this._reject(r._reason());else{var u=new g("late cancellation observer");r._attachExtraTrace(u),this._reject(u)}}},i.prototype._rejectCallback=function(t,e){var n=p.ensureErrorObject(t),r=n===t;if(!r&&E.warnings()){var i="a promise was rejected with a non-error: "+p.classString(t);this._warn(i,!0)}this._attachExtraTrace(n,e?r:!1),this._reject(t)},i.prototype._resolveFromExecutor=function(t){var e=this;this._captureStackTrace(),this._pushContext();var n=!0,r=this._execute(t,function(t){e._resolveCallback(t)},function(t){e._rejectCallback(t,n)});n=!1,this._popContext(),void 0!==r&&e._rejectCallback(r,!0)},i.prototype._settlePromiseFromHandler=function(t,e,n,r){var i=r._bitField;if(0===(65536&i)){r._pushContext();var o;e===w?n&&"number"==typeof n.length?o=O(t).apply(this._boundValue(),n):(o=A,o.e=new m("cannot .spread() a non-array: "+p.classString(n))):o=O(t).call(e,n);var s=r._popContext();if(i=r._bitField,0===(65536&i))if(o===C)r._reject(n);else if(o===A||o===r){var a=o===r?c():o.e;r._rejectCallback(a,!1)}else void 0===o&&s>0&&E.longStackTraces()&&E.warnings()&&r._warn("a promise was created in a handler but none were returned from it",!0),r._resolveCallback(o)}},i.prototype._target=function(){for(var t=this;t._isFollowing();)t=t._followee();return t},i.prototype._followee=function(){return this._rejectionHandler0},i.prototype._setFollowee=function(t){this._rejectionHandler0=t},i.prototype._settlePromise=function(t,e,r,o){var s=t instanceof i,a=this._bitField,u=0!==(134217728&a);0!==(65536&a)?(s&&t._invokeInternalOnCancel(),e===T?(r.cancelPromise=t,O(e).call(r,o)===A&&t._reject(A.e)):e===l?t._fulfill(l.call(r)):r instanceof n?r._promiseCancelled(t):s||t instanceof F?t._cancel():r.cancel()):"function"==typeof e?s?(u&&t._setAsyncGuaranteed(),this._settlePromiseFromHandler(e,r,o,t)):e.call(r,o,t):r instanceof n?r._isResolved()||(0!==(33554432&a)?r._promiseFulfilled(o,t):r._promiseRejected(o,t)):s&&(u&&t._setAsyncGuaranteed(),0!==(33554432&a)?t._fulfill(o):t._reject(o))},i.prototype._settlePromiseLateCancellationObserver=function(t){var e=t.handler,n=t.promise,r=t.receiver,o=t.value;"function"==typeof e?n instanceof i?this._settlePromiseFromHandler(e,r,o,n):e.call(r,o,n):n instanceof i&&n._reject(o)},i.prototype._settlePromiseCtx=function(t){this._settlePromise(t.promise,t.handler,t.receiver,t.value)},i.prototype._settlePromise0=function(t,e,n){var r=this._promise0,i=this._receiverAt(0);this._promise0=void 0,this._receiver0=void 0,this._settlePromise(r,t,i,e)},i.prototype._clearCallbackDataAtIndex=function(t){var e=4*t-4;this[e+2]=this[e+3]=this[e+0]=this[e+1]=void 0},i.prototype._fulfill=function(t){var e=this._bitField;if(!((117506048&e)>>>16)){if(t===this){var n=c();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=t,(65535&e)>0&&(0!==(134217728&e)?this._settlePromises():v.settlePromises(this))}},i.prototype._reject=function(t){var e=this._bitField;if(!((117506048&e)>>>16))return this._setRejected(),this._fulfillmentHandler0=t,this._isFinal()?v.fatalError(t,p.isNode):void((65535&e)>0?0!==(134217728&e)?this._settlePromises():v.settlePromises(this):this._ensurePossibleRejectionHandled())},i.prototype._fulfillPromises=function(t,e){for(var n=1;t>n;n++){var r=this._fulfillmentHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._rejectPromises=function(t,e){for(var n=1;t>n;n++){var r=this._rejectionHandlerAt(n),i=this._promiseAt(n),o=this._receiverAt(n);this._clearCallbackDataAtIndex(n),this._settlePromise(i,r,o,e)}},i.prototype._settlePromises=function(){var t=this._bitField,e=65535&t;if(e>0){if(0!==(16842752&t)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,t),this._rejectPromises(e,n)}else{var r=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,r,t),this._fulfillPromises(e,r)}this._setLength(0)}this._clearCancellationData()},i.prototype._settledValue=function(){var t=this._bitField;return 0!==(33554432&t)?this._rejectionHandler0:0!==(16777216&t)?this._fulfillmentHandler0:void 0},i.defer=i.pending=function(){E.deprecated("Promise.defer","new Promise");var t=new i(b);return{promise:t,resolve:o,reject:s}},p.notEnumerableProp(i,"_makeSelfResolutionError",c),e("./method")(i,b,j,h,E),e("./bind")(i,b,j,E),e("./cancel")(i,F,h,E),e("./direct_resolve")(i),e("./synchronous_inspection")(i),e("./join")(i,F,j,b,E),i.Promise=i,e("./map.js")(i,F,h,j,b,E),e("./using.js")(i,h,j,x,b,E),e("./timers.js")(i,b),e("./generators.js")(i,h,b,j,n,E),e("./nodeify.js")(i),e("./call_get.js")(i),e("./props.js")(i,F,j,h),e("./race.js")(i,b,j,h),e("./reduce.js")(i,F,h,j,b,E),e("./settle.js")(i,F,E),e("./some.js")(i,F,h),e("./promisify.js")(i,b),e("./any.js")(i),e("./each.js")(i,b),e("./filter.js")(i,b),p.toFastProperties(i),p.toFastProperties(i.prototype),a({a:1}),a({b:2}),a({c:3}),a(1),a(function(){}),a(void 0),a(!1),a(new i(b)),E.setBounds(d.firstLineError,p.lastLineError),i}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o){function s(t){switch(t){case-2:return[];case-3:return{}}}function a(t){var r=this._promise=new e(n);t instanceof e&&r._propagateFrom(t,3),r._setOnCancel(this),this._values=t,this._length=0,this._totalResolved=0,this._init(void 0,-2)}var u=t("./util");u.isArray;return u.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function t(n,o){var a=r(this._values,this._promise);if(a instanceof e){a=a._target();var c=a._bitField;if(this._values=a,0===(50397184&c))return this._promise._setAsyncGuaranteed(),a._then(t,this._reject,void 0,this,o);if(0===(33554432&c))return 0!==(16777216&c)?this._reject(a._reason()):this._cancel();a=a._value()}if(a=u.asArray(a),null===a){var l=i("expecting an array or an iterable object but got "+u.classString(a)).reason();return void this._promise._rejectCallback(l,!1)}return 0===a.length?void(-5===o?this._resolveEmptyArray():this._resolve(s(o))):void this._iterate(a)},a.prototype._iterate=function(t){var n=this.getActualLength(t.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var i=this._promise,o=!1,s=null,a=0;n>a;++a){var u=r(t[a],i);u instanceof e?(u=u._target(),s=u._bitField):s=null,o?null!==s&&u.suppressUnhandledRejections():null!==s?0===(50397184&s)?(u._proxy(this,a),this._values[a]=u):o=0!==(33554432&s)?this._promiseFulfilled(u._value(),a):0!==(16777216&s)?this._promiseRejected(u._reason(),a):this._promiseCancelled(a):o=this._promiseFulfilled(u,a)}o||i._setAsyncGuaranteed()},a.prototype._isResolved=function(){return null===this._values},a.prototype._resolve=function(t){this._values=null,this._promise._fulfill(t)},a.prototype._cancel=function(){!this._isResolved()&&this._promise.isCancellable()&&(this._values=null,this._promise._cancel())},a.prototype._reject=function(t){this._values=null,this._promise._rejectCallback(t,!1)},a.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(t){return this._totalResolved++,this._reject(t),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var t=this._values;if(this._cancel(),t instanceof e)t.cancel();else for(var n=0;nu;u+=2){var l=s[u],h=s[u+1],_=l+e;if(r===k)t[_]=k(l,f,l,h,e,i);else{var d=r(h,function(){return k(l,f,l,h,e,i)});p.notEnumerableProp(d,"__isPromisified__",!0),t[_]=d}}return p.toFastProperties(t),t}function l(t,e,n){return k(t,e,void 0,t,null,n)}var h,f={},p=t("./util"),_=t("./nodeback"),d=p.withAppended,v=p.maybeWrapAsError,y=p.canEvaluate,m=t("./errors").TypeError,g="Async",b={__isPromisified__:!0},w=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],C=new RegExp("^(?:"+w.join("|")+")$"),j=function(t){return p.isIdentifier(t)&&"_"!==t.charAt(0)&&"constructor"!==t},F=function(t){return t.replace(/([$])/,"\\$")},k=y?h:u;e.promisify=function(t,e){if("function"!=typeof t)throw new m("expecting a function but got "+p.classString(t));if(i(t))return t;e=Object(e);var n=void 0===e.context?f:e.context,o=!!e.multiArgs,s=l(t,n,o);return p.copyDescriptors(t,s,r),s},e.promisifyAll=function(t,e){if("function"!=typeof t&&"object"!=typeof t)throw new m("the target of promisifyAll must be an object or a function\n\n See http://goo.gl/MqrFmX\n");e=Object(e);var n=!!e.multiArgs,r=e.suffix;"string"!=typeof r&&(r=g);var i=e.filter;"function"!=typeof i&&(i=j);var o=e.promisifier;if("function"!=typeof o&&(o=k),!p.isIdentifier(r))throw new RangeError("suffix must be a valid identifier\n\n See http://goo.gl/MqrFmX\n");for(var s=p.inheritedDataKeys(t),a=0;ao;++o){var s=r[o];e[o]=t[s],e[o+i]=s}}this.constructor$(e),this._isMap=n,this._init$(void 0,-3)}function s(t){var n,s=r(t);return c(s)?(n=s instanceof e?s._then(e.props,void 0,void 0,void 0,void 0):new o(s).promise(),s instanceof e&&n._propagateFrom(s,2),n):i("cannot await properties of a non-object\n\n See http://goo.gl/MqrFmX\n")}var a,u=t("./util"),c=u.isObject,l=t("./es5");"function"==typeof Map&&(a=Map);var h=function(){function t(t,r){this[e]=t,this[e+n]=r,e++}var e=0,n=0;return function(r){n=r.size,e=0;var i=new Array(2*r.size);return r.forEach(t,i),i}}(),f=function(t){for(var e=new a,n=t.length/2|0,r=0;n>r;++r){var i=t[n+r],o=t[r];e.set(i,o)}return e};u.inherits(o,n),o.prototype._init=function(){},o.prototype._promiseFulfilled=function(t,e){this._values[e]=t;var n=++this._totalResolved;if(n>=this._length){var r;if(this._isMap)r=f(this._values);else{r={};for(var i=this.length(),o=0,s=this.length();s>o;++o)r[this._values[o+i]]=this._values[o]}return this._resolve(r),!0}return!1},o.prototype.shouldCopyValues=function(){return!1},o.prototype.getActualLength=function(t){return t>>1},e.prototype.props=function(){return s(this)},e.props=function(t){return s(t)}}},{"./es5":13,"./util":36}],26:[function(t,e,n){"use strict";function r(t,e,n,r,i){for(var o=0;i>o;++o)n[o+r]=t[o+e],t[o+e]=void 0}function i(t){this._capacity=t,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(t){return this._capacityf;++f){var _=t[f];(void 0!==_||f in t)&&e.cast(_)._then(l,h,void 0,c,null)}return c}var s=t("./util"),a=function(t){return t.then(function(e){return o(e,t)})};e.race=function(t){return o(t,void 0)},e.prototype.race=function(){return o(this,void 0)}}},{"./util":36}],28:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t,n,r,i){this.constructor$(t);var s=f();this._fn=null===s?n:s.bind(n),void 0!==r&&(r=e.resolve(r),r._attachCancellationCallback(this)),this._initialValue=r,this._currentCancellable=null,this._eachValues=i===o?[]:void 0,this._promise._captureStackTrace(),this._init$(void 0,-5)}function u(t,e){this.isFulfilled()?e._resolve(t):e._reject(t)}function c(t,e,n,i){if("function"!=typeof e)return r("expecting a function but got "+p.classString(e));var o=new a(t,e,n,i);return o.promise()}function l(t){this.accum=t,this.array._gotAccum(t);var n=i(this.value,this.array._promise);return n instanceof e?(this.array._currentCancellable=n,n._then(h,void 0,void 0,this,void 0)):h.call(this,n)}function h(t){var n=this.array,r=n._promise,i=_(n._fn);r._pushContext();var o;o=void 0!==n._eachValues?i.call(r._boundValue(),t,this.index,this.length):i.call(r._boundValue(),this.accum,t,this.index,this.length),o instanceof e&&(n._currentCancellable=o);var a=r._popContext();return s.checkForgottenReturns(o,a,void 0!==n._eachValues?"Promise.each":"Promise.reduce",r),o}var f=e._getDomain,p=t("./util"),_=p.tryCatch;p.inherits(a,n),a.prototype._gotAccum=function(t){void 0!==this._eachValues&&t!==o&&this._eachValues.push(t)},a.prototype._eachComplete=function(t){return this._eachValues.push(t),this._eachValues},a.prototype._init=function(){},a.prototype._resolveEmptyArray=function(){this._resolve(void 0!==this._eachValues?this._eachValues:this._initialValue)},a.prototype.shouldCopyValues=function(){return!1},a.prototype._resolve=function(t){this._promise._resolveCallback(t),this._values=null},a.prototype._resultCancelled=function(t){return t===this._initialValue?this._cancel():void(this._isResolved()||(this._resultCancelled$(),this._currentCancellable instanceof e&&this._currentCancellable.cancel(),this._initialValue instanceof e&&this._initialValue.cancel()))},a.prototype._iterate=function(t){this._values=t;var n,r,i=t.length;if(void 0!==this._initialValue?(n=this._initialValue,r=0):(n=e.resolve(t[0]),r=1),this._currentCancellable=n,!n.isRejected())for(;i>r;++r){var o={accum:null,value:t[r],index:r,length:i,array:this};n=n._then(l,void 0,void 0,o,void 0)}void 0!==this._eachValues&&(n=n._then(this._eachComplete,void 0,void 0,this,void 0)),n._then(u,u,void 0,n,this)},e.prototype.reduce=function(t,e){return c(this,t,e,null)},e.reduce=function(t,e,n,r){return c(t,e,n,r)}}},{"./util":36}],29:[function(e,n,i){"use strict";var o,s=e("./util"),a=function(){throw new Error("No async scheduler available\n\n See http://goo.gl/MqrFmX\n")};if(s.isNode&&"undefined"==typeof MutationObserver){var u=r.setImmediate,c=t.nextTick;o=s.isRecentNode?function(t){u.call(r,t)}:function(e){c.call(t,e)}}else"undefined"==typeof MutationObserver||"undefined"!=typeof window&&window.navigator&&window.navigator.standalone?o="undefined"!=typeof setImmediate?function(t){setImmediate(t)}:"undefined"!=typeof setTimeout?function(t){setTimeout(t,0)}:a:(o=function(t){var e=document.createElement("div"),n=new MutationObserver(t);return n.observe(e,{attributes:!0}),function(){e.classList.toggle("foo")}},o.isStatic=!0);n.exports=o},{"./util":36}],30:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t)}var o=e.PromiseInspection,s=t("./util");s.inherits(i,n),i.prototype._promiseResolved=function(t,e){this._values[t]=e;var n=++this._totalResolved;return n>=this._length?(this._resolve(this._values),!0):!1},i.prototype._promiseFulfilled=function(t,e){var n=new o;return n._bitField=33554432,n._settledValueField=t,this._promiseResolved(e,n)},i.prototype._promiseRejected=function(t,e){var n=new o;return n._bitField=16777216,n._settledValueField=t,this._promiseResolved(e,n)},e.settle=function(t){return r.deprecated(".settle()",".reflect()"),new i(t).promise()},e.prototype.settle=function(){return e.settle(this)}}},{"./util":36}],31:[function(t,e,n){"use strict";e.exports=function(e,n,r){function i(t){this.constructor$(t),this._howMany=0,this._unwrap=!1,this._initialized=!1}function o(t,e){if((0|e)!==e||0>e)return r("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n"); var n=new i(t),o=n.promise();return n.setHowMany(e),n.init(),o}var s=t("./util"),a=t("./errors").RangeError,u=t("./errors").AggregateError,c=s.isArray,l={};s.inherits(i,n),i.prototype._init=function(){if(this._initialized){if(0===this._howMany)return void this._resolve([]);this._init$(void 0,-5);var t=c(this._values);!this._isResolved()&&t&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}},i.prototype.init=function(){this._initialized=!0,this._init()},i.prototype.setUnwrap=function(){this._unwrap=!0},i.prototype.howMany=function(){return this._howMany},i.prototype.setHowMany=function(t){this._howMany=t},i.prototype._promiseFulfilled=function(t){return this._addFulfilled(t),this._fulfilled()===this.howMany()?(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0):!1},i.prototype._promiseRejected=function(t){return this._addRejected(t),this._checkOutcome()},i.prototype._promiseCancelled=function(){return this._values instanceof e||null==this._values?this._cancel():(this._addRejected(l),this._checkOutcome())},i.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var t=new u,e=this.length();e0?this._reject(t):this._cancel(),!0}return!1},i.prototype._fulfilled=function(){return this._totalResolved},i.prototype._rejected=function(){return this._values.length-this.length()},i.prototype._addRejected=function(t){this._values.push(t)},i.prototype._addFulfilled=function(t){this._values[this._totalResolved++]=t},i.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},i.prototype._getRangeError=function(t){var e="Input array must contain at least "+this._howMany+" items but contains only "+t+" items";return new a(e)},i.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},e.some=function(t,e){return o(t,e)},e.prototype.some=function(t){return o(this,t)},e._SomePromiseArray=i}},{"./errors":12,"./util":36}],32:[function(t,e,n){"use strict";e.exports=function(t){function e(t){void 0!==t?(t=t._target(),this._bitField=t._bitField,this._settledValueField=t._isFateSealed()?t._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}e.prototype._settledValue=function(){return this._settledValueField};var n=e.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=e.prototype.error=e.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=e.prototype.isFulfilled=function(){return 0!==(33554432&this._bitField)},o=e.prototype.isRejected=function(){return 0!==(16777216&this._bitField)},s=e.prototype.isPending=function(){return 0===(50397184&this._bitField)},a=e.prototype.isResolved=function(){return 0!==(50331648&this._bitField)};e.prototype.isCancelled=t.prototype._isCancelled=function(){return 65536===(65536&this._bitField)},t.prototype.isCancelled=function(){return this._target()._isCancelled()},t.prototype.isPending=function(){return s.call(this._target())},t.prototype.isRejected=function(){return o.call(this._target())},t.prototype.isFulfilled=function(){return i.call(this._target())},t.prototype.isResolved=function(){return a.call(this._target())},t.prototype.value=function(){return n.call(this._target())},t.prototype.reason=function(){var t=this._target();return t._unsetRejectionIsUnhandled(),r.call(t)},t.prototype._value=function(){return this._settledValue()},t.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},t.PromiseInspection=e}},{}],33:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t,r){if(l(t)){if(t instanceof e)return t;var i=o(t);if(i===c){r&&r._pushContext();var u=e.reject(i.e);return r&&r._popContext(),u}if("function"==typeof i){if(s(t)){var u=new e(n);return t._then(u._fulfill,u._reject,void 0,u,null),u}return a(t,i,r)}}return t}function i(t){return t.then}function o(t){try{return i(t)}catch(t){return c.e=t,c}}function s(t){return h.call(t,"_promise0")}function a(t,r,i){function o(t){a&&(a._resolveCallback(t),a=null)}function s(t){a&&(a._rejectCallback(t,h),a=null)}var a=new e(n),l=a;i&&i._pushContext(),a._captureStackTrace(),i&&i._popContext();var h=!0,f=u.tryCatch(r).call(t,o,s);return h=!1,a&&f===c&&(a._rejectCallback(f.e,!0),a=null),l}var u=t("./util"),c=u.errorObj,l=u.isObject,h={}.hasOwnProperty;return r}},{"./util":36}],34:[function(t,e,n){"use strict";e.exports=function(e,n){function r(t){var e=this;return e instanceof Number&&(e=+e),clearTimeout(e),t}function i(t){var e=this;throw e instanceof Number&&(e=+e),clearTimeout(e),t}var o=t("./util"),s=e.TimeoutError,a=function(t,e){if(t.isPending()){var n;n="string"!=typeof e?e instanceof Error?e:new s("operation timed out"):new s(e),o.markAsOriginatingFromRejection(n),t._attachExtraTrace(n),t._reject(n)}},u=function(t){return c(+this).thenReturn(t)},c=e.delay=function(t,r){var i;return void 0!==r?i=e.resolve(r)._then(u,null,null,t,void 0):(i=new e(n),setTimeout(function(){i._fulfill()},+t)),i._setAsyncGuaranteed(),i};e.prototype.delay=function(t){return c(t,this)},e.prototype.timeout=function(t,e){t=+t;var n=this.then(),o=setTimeout(function(){a(n,e)},t);return n._then(r,i,void 0,o,void 0)}}},{"./util":36}],35:[function(t,e,n){"use strict";e.exports=function(e,n,r,i,o,s){function a(t){setTimeout(function(){throw t},0)}function u(t){var e=r(t);return e!==t&&"function"==typeof t._isDisposable&&"function"==typeof t._getDisposer&&t._isDisposable()&&e._setDisposable(t._getDisposer()),e}function c(t,n){function i(){if(s>=c)return l._fulfill();var o=u(t[s++]);if(o instanceof e&&o._isDisposable()){try{o=r(o._getDisposer().tryDispose(n),t.promise)}catch(t){return a(t)}if(o instanceof e)return o._then(i,a,null,null,null)}i()}var s=0,c=t.length,l=new e(o);return i(),l}function l(t,e,n){this._data=t,this._promise=e,this._context=n}function h(t,e,n){this.constructor$(t,e,n)}function f(t){return l.isDisposer(t)?(this.resources[this.index]._setDisposable(t),t.promise()):t}function p(t){this.length=t,this.promise=null,this[t-1]=null}var _=t("./util"),d=t("./errors").TypeError,v=t("./util").inherits,y=_.errorObj,m=_.tryCatch;l.prototype.data=function(){return this._data},l.prototype.promise=function(){return this._promise},l.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():null},l.prototype.tryDispose=function(t){var e=this.resource(),n=this._context;void 0!==n&&n._pushContext();var r=null!==e?this.doDispose(e,t):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,r},l.isDisposer=function(t){return null!=t&&"function"==typeof t.resource&&"function"==typeof t.tryDispose},v(h,l),h.prototype.doDispose=function(t,e){var n=this.data();return n.call(t,t,e)},p.prototype._resultCancelled=function(){for(var t=this.length,n=0;t>n;++n){var r=this[n];r instanceof e&&r.cancel()}},e.using=function(){var t=arguments.length;if(2>t)return n("you must pass at least 2 arguments to Promise.using");var i=arguments[t-1];if("function"!=typeof i)return n("expecting a function but got "+_.classString(i));var o,a=!0;2===t&&Array.isArray(arguments[0])?(o=arguments[0],t=o.length,a=!1):(o=arguments,t--);for(var u=new p(t),h=0;t>h;++h){var d=o[h];if(l.isDisposer(d)){var v=d;d=d.promise(),d._setDisposable(v)}else{var g=r(d);g instanceof e&&(d=g._then(f,null,null,{resources:u,index:h},void 0))}u[h]=d}for(var b=new Array(u.length),h=0;h0},e.prototype._getDisposer=function(){return this._disposer},e.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},e.prototype.disposer=function(t){if("function"==typeof t)return new h(t,this,i());throw new d}}},{"./errors":12,"./util":36}],36:[function(e,n,r){"use strict";function i(){try{var t=E;return E=null,t.apply(this,arguments)}catch(t){return x.e=t,x}}function o(t){return E=t,i}function s(t){return null==t||t===!0||t===!1||"string"==typeof t||"number"==typeof t}function a(t){return"function"==typeof t||"object"==typeof t&&null!==t}function u(t){return s(t)?new Error(y(t)):t}function c(t,e){var n,r=t.length,i=new Array(r+1);for(n=0;r>n;++n)i[n]=t[n];return i[n]=e,i}function l(t,e,n){if(!F.isES5)return{}.hasOwnProperty.call(t,e)?t[e]:void 0;var r=Object.getOwnPropertyDescriptor(t,e);return null!=r?null==r.get&&null==r.set?r.value:n:void 0}function h(t,e,n){if(s(t))return t;var r={value:n,configurable:!0,enumerable:!1,writable:!0};return F.defineProperty(t,e,r),t}function f(t){throw t}function p(t){try{if("function"==typeof t){var e=F.names(t.prototype),n=F.isES5&&e.length>1,r=e.length>0&&!(1===e.length&&"constructor"===e[0]),i=R.test(t+"")&&F.names(t).length>0;if(n||r||i)return!0}return!1}catch(t){return!1}}function _(t){function e(){}e.prototype=t;for(var n=8;n--;)new e;return t}function d(t){return A.test(t)}function v(t,e,n){for(var r=new Array(t),i=0;t>i;++i)r[i]=e+i+n;return r}function y(t){try{return t+""}catch(t){return"[no string representation]"}}function m(t){try{h(t,"isOperational",!0)}catch(t){}}function g(t){return null==t?!1:t instanceof Error.__BluebirdErrorTypes__.OperationalError||t.isOperational===!0}function b(t){return t instanceof Error&&F.propertyIsWritable(t,"stack")}function w(t){return{}.toString.call(t)}function C(t,e,n){for(var r=F.names(t),i=0;i10||e[0]>0}(),V.isNode&&V.toFastProperties(t);try{throw new Error}catch(t){V.lastLineError=t}n.exports=V},{"./es5":13}]},{},[4])(4)}),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:3}],3:[function(t,e,n){function r(){l=!1,a.length?c=a.concat(c):h=-1,c.length&&i()}function i(){if(!l){var t=setTimeout(r);l=!0;for(var e=c.length;e;){for(a=c,c=[];++h1)for(var n=1;ne||e>256||e&e-1)throw"Invalid code/color length, must be power of 2 and 2 .. 256.";return e}var s=0,r=void 0===r?{}:r,a=void 0===r.loop?null:r.loop,u=void 0===r.palette?null:r.palette;if(0>=e||0>=n||e>65535||n>65535)throw"Width/Height invalid.";t[s++]=71,t[s++]=73,t[s++]=70,t[s++]=56,t[s++]=57,t[s++]=97;var c=0,l=0;if(null!==u){for(var h=o(u);h>>=1;)++c;if(h=1<=h)throw"Background index out of range.";if(0===l)throw"Background index explicitly passed as 0."}}if(t[s++]=255&e,t[s++]=e>>8&255,t[s++]=255&n,t[s++]=n>>8&255,t[s++]=(null!==u?128:0)|c,t[s++]=l,t[s++]=0,null!==u)for(var f=0,p=u.length;p>f;++f){var _=u[f];t[s++]=_>>16&255,t[s++]=_>>8&255,t[s++]=255&_}if(null!==a){if(0>a||a>65535)throw"Loop count invalid.";t[s++]=33,t[s++]=255,t[s++]=11,t[s++]=78,t[s++]=69,t[s++]=84,t[s++]=83,t[s++]=67,t[s++]=65,t[s++]=80,t[s++]=69,t[s++]=50,t[s++]=46,t[s++]=48,t[s++]=3,t[s++]=1,t[s++]=255&a,t[s++]=a>>8&255,t[s++]=0}var d=!1;this.addFrame=function(e,n,r,a,c,l){if(d===!0&&(--s,d=!1),l=void 0===l?{}:l,0>e||0>n||e>65535||n>65535)throw"x/y invalid.";if(0>=r||0>=a||r>65535||a>65535)throw"Width/Height invalid.";if(c.length>=1;)++_;p=1<<_;var v=void 0===l.delay?0:l.delay,y=void 0===l.disposal?0:l.disposal;if(0>y||y>3)throw"Disposal out of range.";var m=!1,g=0;if(void 0!==l.transparent&&null!==l.transparent&&(m=!0,g=l.transparent,0>g||g>=p))throw"Transparent color index.";if((0!==y||m||0!==v)&&(t[s++]=33,t[s++]=249,t[s++]=4,t[s++]=y<<2|(m===!0?1:0),t[s++]=255&v,t[s++]=v>>8&255,t[s++]=g,t[s++]=0),t[s++]=44,t[s++]=255&e,t[s++]=e>>8&255,t[s++]=255&n,t[s++]=n>>8&255,t[s++]=255&r,t[s++]=r>>8&255,t[s++]=255&a,t[s++]=a>>8&255,t[s++]=h===!0?128|_-1:0,h===!0)for(var b=0,w=f.length;w>b;++b){var C=f[b];t[s++]=C>>16&255,t[s++]=C>>8&255,t[s++]=255&C}s=i(t,s,2>_?2:_,c)},this.end=function(){return d===!1&&(t[s++]=59,d=!0),s}}function i(t,e,n,r){function i(n){for(;f>=n;)t[e++]=255&p,p>>=8,f-=8,e===s+256&&(t[s]=255,s=e++)}function o(t){p|=t<v;++v){var m=r[v]&u,g=_<<8|m,b=d[g];if(void 0===b){for(p|=_<=8;)t[e++]=255&p,p>>=8,f-=8,e===s+256&&(t[s]=255,s=e++);4096===l?(o(a),l=c+1,h=n+1,d={}):(l>=1<>7,a=7&i,u=1<>2&7,e++;break;case 254:for(;;){var v=t[e++];if(0===v)break;e+=v}break;default:throw"Unknown graphic control label: 0x"+t[e-1].toString(16)}break;case 44:var m=t[e++]|t[e++]<<8,g=t[e++]|t[e++]<<8,b=t[e++]|t[e++]<<8,w=t[e++]|t[e++]<<8,C=t[e++],j=C>>7,F=C>>6&1,k=7&C,x=1<t||t>=h.length)throw"Frame index out of range.";return h[t]},this.decodeAndBlitFrameBGRA=function(e,r){var i=this.frameInfo(e),o=i.width*i.height,a=new Uint8Array(o);s(t,i.data_offset,a,o);var u=i.palette_offset,c=i.transparent_index;null===c&&(c=256);var l=i.width,h=n-l,f=l,p=4*(i.y*n+i.x),_=4*((i.y+i.height)*n+i.x),d=p,v=4*h;i.interlaced===!0&&(v+=4*n*7);for(var y=8,m=0,g=a.length;g>m;++m){var b=a[m];if(0===f&&(d+=v,f=l,d>=_&&(v=4*h+4*n*(y-1),d=p+(l+h)*(y<<1),y>>=1)),b===c)d+=4;else{var w=t[u+3*b],C=t[u+3*b+1],j=t[u+3*b+2];r[d++]=j,r[d++]=C,r[d++]=w,r[d++]=255}--f}},this.decodeAndBlitFrameRGBA=function(e,r){var i=this.frameInfo(e),o=i.width*i.height,a=new Uint8Array(o);s(t,i.data_offset,a,o);var u=i.palette_offset,c=i.transparent_index;null===c&&(c=256);var l=i.width,h=n-l,f=l,p=4*(i.y*n+i.x),_=4*((i.y+i.height)*n+i.x),d=p,v=4*h;i.interlaced===!0&&(v+=4*n*7);for(var y=8,m=0,g=a.length;g>m;++m){var b=a[m];if(0===f&&(d+=v,f=l,d>=_&&(v=4*h+4*n*(y-1),d=p+(l+h)*(y<<1),y>>=1)),b===c)d+=4;else{var w=t[u+3*b],C=t[u+3*b+1],j=t[u+3*b+2];r[d++]=w,r[d++]=C,r[d++]=j,r[d++]=255}--f}}}function s(t,e,n,r){for(var i=t[e++],o=1<l&&0!==p;)h|=t[e++]<l)break;var v=h&c;if(h>>=u,l-=u,v!==o){if(v===s)break;for(var y=a>v?v:d,m=0,g=y;g>o;)g=_[g]>>8,++m;var b=g,w=f+m+(y!==v?1:0);if(w>r)return void console.log("Warning, gif stream longer than expected.");n[f++]=b,f+=m;var C=f;for(y!==v&&(n[f++]=b),g=y;m--;)g=_[g],n[--C]=255&g,g>>=8;null!==d&&4096>a&&(_[a++]=d<<8|b,a>=c+1&&12>u&&(++u,c=c<<1|1)),d=v}else a=s+1,u=i+1,c=(1</gm,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0==t.index}function a(e){return/^(no-?highlight|plain|text)$/i.test(e)}function i(e){var n,t,r,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=/\blang(?:uage)?-([\w-]+)\b/i.exec(i))return w(t[1])?t[1]:"no-highlight";for(i=i.split(/\s+/),n=0,r=i.length;r>n;n++)if(w(i[n])||a(i[n]))return i[n]}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3==i.nodeType?a+=i.nodeValue.length:1==i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!=r[0].offset?e[0].offset"}function u(e){f+=""}function c(e){("start"==e.event?o:u)(e.node)}for(var s=0,f="",l=[];e.length||r.length;){var g=i();if(f+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g==e){l.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g==e&&g.length&&g[0].offset==s);l.reverse().forEach(o)}else"start"==g[0].event?l.push(g[0].node):l.pop(),c(g.splice(0,1)[0])}return f+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):Object.keys(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\b\w+\b/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),void 0===a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"==e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var f=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=f.length?t(f.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){for(var t=0;t";return i+=e+'">',i+n+o}function p(){if(!L.k)return n(y);var e="",t=0;L.lR.lastIndex=0;for(var r=L.lR.exec(y);r;){e+=n(y.substr(t,r.index-t));var a=g(L,r);a?(B+=a[1],e+=h(a[0],n(r[0]))):e+=n(r[0]),t=L.lR.lastIndex,r=L.lR.exec(y)}return e+n(y.substr(t))}function d(){var e="string"==typeof L.sL;if(e&&!x[L.sL])return n(y);var t=e?f(L.sL,y,!0,M[L.sL]):l(y,L.sL.length?L.sL:void 0);return L.r>0&&(B+=t.r),e&&(M[L.sL]=t.top),h(t.language,t.value,!1,!0)}function b(){return void 0!==L.sL?d():p()}function v(e,t){var r=e.cN?h(e.cN,"",!0):"";e.rB?(k+=r,y=""):e.eB?(k+=n(t)+r,y=""):(k+=r,y=t),L=Object.create(e,{parent:{value:L}})}function m(e,t){if(y+=e,void 0===t)return k+=b(),0;var r=o(t,L);if(r)return k+=b(),v(r,t),r.rB?0:t.length;var a=u(L,t);if(a){var i=L;i.rE||i.eE||(y+=t),k+=b();do L.cN&&(k+=""),B+=L.r,L=L.parent;while(L!=a.parent);return i.eE&&(k+=n(t)),y="",a.starts&&v(a.starts,""),i.rE?0:t.length}if(c(t,L))throw new Error('Illegal lexeme "'+t+'" for mode "'+(L.cN||"")+'"');return y+=t,t.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var R,L=i||N,M={},k="";for(R=L;R!=N;R=R.parent)R.cN&&(k=h(R.cN,"",!0)+k);var y="",B=0;try{for(var C,j,I=0;;){if(L.t.lastIndex=I,C=L.t.exec(t),!C)break;j=m(t.substr(I,C.index-I),C[0]),I=C.index+j}for(m(t.substr(I)),R=L;R.parent;R=R.parent)R.cN&&(k+="");return{r:B,value:k,language:e,top:L}}catch(O){if(-1!=O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function l(e,t){t=t||E.languages||Object.keys(x);var r={r:0,value:n(e)},a=r;return t.forEach(function(n){if(w(n)){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}}),a.language&&(r.second_best=a),r}function g(e){return E.tabReplace&&(e=e.replace(/^((<[^>]+>|\t)+)/gm,function(e,n){return n.replace(/\t/g,E.tabReplace)})),E.useBR&&(e=e.replace(/\n/g,"
")),e}function h(e,n,t){var r=n?R[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function p(e){var n=i(e);if(!a(n)){var t;E.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):t=e;var r=t.textContent,o=n?f(n,r,!0):l(r),s=u(t);if(s.length){var p=document.createElementNS("http://www.w3.org/1999/xhtml","div");p.innerHTML=o.value,o.value=c(s,u(p),r)}o.value=g(o.value),e.innerHTML=o.value,e.className=h(e.className,n,o.language),e.result={language:o.language,re:o.r},o.second_best&&(e.second_best={language:o.second_best.language,re:o.second_best.r})}}function d(e){E=o(E,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");Array.prototype.forEach.call(e,p)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=x[n]=t(e);r.aliases&&r.aliases.forEach(function(e){R[e]=n})}function N(){return Object.keys(x)}function w(e){return e=e.toLowerCase(),x[e]||x[R[e]]}var E={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},x={},R={};return e.highlight=f,e.highlightAuto=l,e.fixMarkup=g,e.highlightBlock=p,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/-?[a-z\.]+/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",operator:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"shebang",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,e.NM,s,a,t]}});hljs.registerLanguage("css",function(e){var c="[a-zA-Z-][a-zA-Z0-9_-]*",a={cN:"function",b:c+"\\(",rB:!0,eE:!0,e:"\\("},r={cN:"rule",b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{cN:"value",eW:!0,eE:!0,c:[a,e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"hexcolor",b:"#[0-9A-Fa-f]+"},{cN:"important",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,r,{cN:"id",b:/\#[A-Za-z0-9_-]+/},{cN:"class",b:/\.[A-Za-z0-9_-]+/},{cN:"attr_selector",b:/\[/,e:/\]/,i:"$"},{cN:"pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"']+/},{cN:"at_rule",b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{cN:"at_rule",b:"@",e:"[{;]",c:[{cN:"keyword",b:/\S+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[a,e.ASM,e.QSM,e.CSSNM]}]},{cN:"tag",b:c,r:0},{cN:"rules",b:"{",e:"}",i:/\S/,c:[e.CBCM,r]}]}});hljs.registerLanguage("markdown",function(e){return{aliases:["md","mkdown","mkd"],c:[{cN:"header",v:[{b:"^#{1,6}",e:"$"},{b:"^.+?\\n[=-]{2,}$"}]},{b:"<",e:">",sL:"xml",r:0},{cN:"bullet",b:"^([*+-]|(\\d+\\.))\\s+"},{cN:"strong",b:"[*_]{2}.+?[*_]{2}"},{cN:"emphasis",v:[{b:"\\*.+?\\*"},{b:"_.+?_",r:0}]},{cN:"blockquote",b:"^>\\s+",e:"$"},{cN:"code",v:[{b:"`.+?`"},{b:"^( {4}| )",e:"$",r:0}]},{cN:"horizontal_rule",b:"^[-\\*]{3,}",e:"$"},{b:"\\[.+?\\][\\(\\[].*?[\\)\\]]",rB:!0,c:[{cN:"link_label",b:"\\[",e:"\\]",eB:!0,rE:!0,r:0},{cN:"link_url",b:"\\]\\(",e:"\\)",eB:!0,eE:!0},{cN:"link_reference",b:"\\]\\[",e:"\\]",eB:!0,eE:!0}],r:10},{b:"^\\[.+\\]:",rB:!0,c:[{cN:"link_reference",b:"\\[",e:"\\]:",eB:!0,eE:!0,starts:{cN:"link_url",e:"$"}}]}]}});hljs.registerLanguage("diff",function(e){return{aliases:["patch"],c:[{cN:"chunk",r:10,v:[{b:/^@@ +\-\d+,\d+ +\+\d+,\d+ +@@$/},{b:/^\*\*\* +\d+,\d+ +\*\*\*\*$/},{b:/^\-\-\- +\d+,\d+ +\-\-\-\-$/}]},{cN:"header",v:[{b:/Index: /,e:/$/},{b:/=====/,e:/=====$/},{b:/^\-\-\-/,e:/$/},{b:/^\*{3} /,e:/$/},{b:/^\+\+\+/,e:/$/},{b:/\*{5}/,e:/\*{5}$/}]},{cN:"addition",b:"^\\+",e:"$"},{cN:"deletion",b:"^\\-",e:"$"},{cN:"change",b:"^\\!",e:"$"}]}});hljs.registerLanguage("json",function(e){var t={literal:"true false null"},i=[e.QSM,e.CNM],l={cN:"value",e:",",eW:!0,eE:!0,c:i,k:t},c={b:"{",e:"}",c:[{cN:"attribute",b:'\\s*"',e:'"\\s*:\\s*',eB:!0,eE:!0,c:[e.BE],i:"\\n",starts:l}],i:"\\S"},n={b:"\\[",e:"\\]",c:[e.inherit(l,{cN:null})],i:"\\S"};return i.splice(i.length,0,c,n),{c:i,k:t,i:"\\S"}});hljs.registerLanguage("coffeescript",function(e){var c={keyword:"in if for while finally new do return else break catch instanceof throw try this switch continue typeof delete debugger super then unless until loop of by when and or is isnt not",literal:"true false null undefined yes no on off",built_in:"npm require console print module global window document"},n="[A-Za-z$_][0-9A-Za-z$_]*",r={cN:"subst",b:/#\{/,e:/}/,k:c},t=[e.BNM,e.inherit(e.CNM,{starts:{e:"(\\s*/)?",r:0}}),{cN:"string",v:[{b:/'''/,e:/'''/,c:[e.BE]},{b:/'/,e:/'/,c:[e.BE]},{b:/"""/,e:/"""/,c:[e.BE,r]},{b:/"/,e:/"/,c:[e.BE,r]}]},{cN:"regexp",v:[{b:"///",e:"///",c:[r,e.HCM]},{b:"//[gim]*",r:0},{b:/\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)/}]},{cN:"property",b:"@"+n},{b:"`",e:"`",eB:!0,eE:!0,sL:"javascript"}];r.c=t;var s=e.inherit(e.TM,{b:n}),i="(\\(.*\\))?\\s*\\B[-=]>",o={cN:"params",b:"\\([^\\(]",rB:!0,c:[{b:/\(/,e:/\)/,k:c,c:["self"].concat(t)}]};return{aliases:["coffee","cson","iced"],k:c,i:/\/\*/,c:t.concat([e.C("###","###"),e.HCM,{cN:"function",b:"^\\s*"+n+"\\s*=\\s*"+i,e:"[-=]>",rB:!0,c:[s,o]},{b:/[:\(,=]\s*/,r:0,c:[{cN:"function",b:i,e:"[-=]>",rB:!0,c:[o]}]},{cN:"class",bK:"class",e:"$",i:/[:="\[\]]/,c:[{bK:"extends",eW:!0,i:/[:="\[\]]/,c:[s]},s]},{cN:"attribute",b:n+":",e:":",rB:!0,rE:!0,r:0}])}});hljs.registerLanguage("javascript",function(e){return{aliases:["js"],k:{keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},c:[{cN:"pi",r:10,b:/^\s*['"]use (strict|asm)['"]/},e.ASM,e.QSM,{cN:"string",b:"`",e:"`",c:[e.BE,{cN:"subst",b:"\\$\\{",e:"\\}"}]},e.CLCM,e.CBCM,{cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{b:/\s*[);\]]/,r:0,sL:"xml"}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:[e.CLCM,e.CBCM]}],i:/\[|%/},{b:/\$[(.]/},{b:"\\."+e.IR,r:0},{bK:"import",e:"[;$]",k:"import from as",c:[e.ASM,e.QSM]},{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]}],i:/#/}});hljs.registerLanguage("xml",function(t){var s="[A-Za-z0-9\\._:-]+",c={b:/<\?(php)?(?!\w)/,e:/\?>/,sL:"php"},e={eW:!0,i:/]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xsl","plist"],cI:!0,c:[{cN:"doctype",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},t.C("",{r:10}),{cN:"cdata",b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"|$)",e:">",k:{title:"style"},c:[e],starts:{e:"",rE:!0,sL:"css"}},{cN:"tag",b:"|$)",e:">",k:{title:"script"},c:[e],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars"]}},c,{cN:"pi",b:/<\?\w+/,e:/\?>/,r:10},{cN:"tag",b:"",c:[{cN:"title",b:/[^ \/><\n\t]+/,r:0},e]}]}}); ================================================ FILE: site/assets/lib/monokai_sublime.css ================================================ /* Monokai Sublime style. Derived from Monokai by noformnocontent http://nn.mit-license.org/ */ .hljs { display: block; overflow-x: auto; padding: 0.5em; background: #23241f; -webkit-text-size-adjust: none; } .hljs, .hljs-tag, .css .hljs-rule, .css .hljs-value, .aspectj .hljs-function, .css .hljs-function .hljs-preprocessor, .hljs-pragma { color: #f8f8f2; } .hljs-strongemphasis, .hljs-strong, .hljs-emphasis { color: #a8a8a2; } .hljs-bullet, .hljs-blockquote, .hljs-horizontal_rule, .hljs-number, .hljs-regexp, .alias .hljs-keyword, .hljs-literal, .hljs-hexcolor { color: #ae81ff; } .hljs-tag .hljs-value, .hljs-code, .hljs-title, .css .hljs-class, .hljs-class .hljs-title:last-child { color: #a6e22e; } .hljs-link_url { font-size: 80%; } .hljs-strong, .hljs-strongemphasis { font-weight: bold; } .hljs-emphasis, .hljs-strongemphasis, .hljs-class .hljs-title:last-child, .hljs-typename { font-style: italic; } .hljs-keyword, .ruby .hljs-class .hljs-keyword:first-child, .ruby .hljs-function .hljs-keyword, .hljs-function, .hljs-change, .hljs-winutils, .hljs-flow, .nginx .hljs-title, .tex .hljs-special, .hljs-header, .hljs-attribute, .hljs-symbol, .hljs-symbol .hljs-string, .hljs-tag .hljs-title, .hljs-value, .alias .hljs-keyword:first-child, .css .hljs-tag, .css .unit, .css .hljs-important { color: #f92672; } .hljs-function .hljs-keyword, .hljs-class .hljs-keyword:first-child, .hljs-aspect .hljs-keyword:first-child, .hljs-constant, .hljs-typename, .hljs-name, .css .hljs-attribute { color: #66d9ef; } .hljs-variable, .hljs-params, .hljs-class .hljs-title, .hljs-aspect .hljs-title { color: #f8f8f2; } .hljs-string, .css .hljs-id, .hljs-subst, .hljs-type, .ruby .hljs-class .hljs-parent, .hljs-built_in, .django .hljs-template_tag, .django .hljs-variable, .smalltalk .hljs-class, .django .hljs-filter .hljs-argument, .smalltalk .hljs-localvars, .smalltalk .hljs-array, .hljs-attr_selector, .hljs-pseudo, .hljs-addition, .hljs-stream, .hljs-envvar, .apache .hljs-tag, .apache .hljs-cbracket, .tex .hljs-command, .hljs-prompt, .hljs-link_label, .hljs-link_url { color: #e6db74; } .hljs-comment, .hljs-annotation, .hljs-decorator, .hljs-pi, .hljs-doctype, .hljs-deletion, .hljs-shebang, .apache .hljs-sqbracket, .tex .hljs-formula { color: #75715e; } .coffeescript .javascript, .javascript .xml, .tex .hljs-formula, .xml .javascript, .xml .vbscript, .xml .css, .xml .hljs-cdata, .xml .php, .php .xml { opacity: 0.5; } ================================================ FILE: site/docs.jade ================================================ extend _layout.jade block style link(rel="stylesheet" href="docs.css") mixin documentation(doc) a(name=doc.head href="##{doc.head}") h2 #{doc.head} - if(doc.text) for text in doc.text p.text !{text} - if(doc.args) h4 Arguments table.arguments for description, name in doc.args tr td.name #{name} td.desc #{description} - if(doc.return) h4 Returns p.returns #{doc.return} block content for doc in docs +documentation(doc) ================================================ FILE: site/docs.less ================================================ @import "_constants.less"; h2 { font-weight : 100; color : @color-nav; font-size : 30px; line-height : 30px; margin-top : 20px; margin-bottom : 10px; } h4 { font-weight : 700; margin-top : 30px; margin-bottom : 20px; } p.text { line-height : 1.2em; } table.arguments { width : 100%; border-collapse : collapse; table-layout : fixed; td { padding : 10px 15px; border : 1px solid #DDD; vertical-align : top; } td.name { width : 110px; } } ================================================ FILE: site/examples.jade ================================================ --- base : 'assets/gif' examples : nyancat : url : 'nyan.gif' source : 'http://www.wired.co.uk/' florian : url : 'florian-8.gif' source : 'Florian de Looij' pots : url : 'pots.gif' source : 'http://www.weshootfood.net/' toroid : url : 'toroid.gif' source : 'David Ope' --- extend _layout.jade block style link(rel="stylesheet" href="examples.css") mixin comparison(example, key) tr td: img(class=key) td: canvas(class=key) tr td(colspan="2") .source Source: #{example.source} script. var url = "#{base}/#{example.url}"; var selector = ".#{key}"; gifler(url).animate(document.querySelector('canvas' + selector)); document.querySelector('img' + selector).src = url; block content table.comparisons tr th: h3 #{''} th: h3 #{''} for example, key in examples +comparison(example, key) ================================================ FILE: site/examples.less ================================================ @import "_constants.less"; h3 { font-size : 30px; line-height : 40px; } .example-size(@dim) { td img { width : @dim; height : @dim; } td canvas { width : @dim; height : @dim; } } table.comparisons { width : 100%; table-layout : fixed; text-align : center; .example-size(300px); @media only screen and (max-device-width: 480px){ .example-size(150px); } } .source { font-size : 14px; color : #AAA; float : right; margin-right : 20px; margin-bottom : 20px; clear : both; } ================================================ FILE: site/index.jade ================================================ --- examples : - title : 'Hello, Gifler!' key : 'running-pikachu' description : > Getting started is easy! Just call the gifler function to load a GIF. Then run the animation in a canvas using the .animate() method. The method .animate() accepts a canvas DOM element or a string selector to a canvas element. source : '_examples/simple.js' - title : 'Custom Rendering' key : 'rainbow-pikachus' description : > Gifler makes it easy to manipulate the underlying frames from the GIF. Just call the .frames() method with a canvas selector and a callback that will be called when each frame should be renderd. Gifler handles all the timing calculations and GIF transition logic. Just put the pixels you want to see into the canvas. source : '_examples/rainbow.js' - title : 'Play/Pause Control' key : 'play-pause' description : > With access to Gifler''s animator, you can stop and start the animation with ease. When running, the animator will automatically compensate for canvas render time when computing when to draw the next GIF frame.

Try clicking the animation below to start/stop it. source : '_examples/control.js' --- extend _layout.jade block style link(rel="stylesheet" href="index.css") script(type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js") mixin example(example) //- header label and flavor .block h2 #{example.title} .flavor !{example.description} //- canvas with actual script .canvas-wrapper: canvas(class="#{example.key}") script !{raw(example.source)} //- code block .block: pre: code(class="#{example.key}").javascript #{raw(example.source)} block hero .hero.row h1 Gifler h2 Render GIF frames to #{''} a(href="https://raw.githubusercontent.com/themadcreator/gifler/master/gifler.min.js"): .button.download Download block content for example in examples +example(example) .tech-icons span.devicons.devicons-coffeescript(title="CoffeeScript") span.devicons.devicons-javascript_badge(title="Javascript") span.devicons.devicons-less(title="less") span.devicons.devicons-npm(title="npm") ================================================ FILE: site/index.less ================================================ @import "_constants.less"; .hero { width : 100vw; height : 66vh; background-color : @color-hero-bg; .table-center(); h1 { color : @color-hero-fg; font-size : 140px; line-height : 150px; font-weight : 100; margin-top : @pad; } h2 { color : fade(@color-hero-fg, 50%); font-size : 20px; font-weight : normal; } .download { margin-top : 50px; margin-bottom : @pad; padding : 0px 0px; width : 200px; height : 60px; line-height : 60px; font-size : 24px; } } .canvas-wrapper { max-width : 100vw; padding : @pad @pad; canvas { max-width : 100%; } canvas.rainbow-pikachus { width : 100%; height : 100px; } } pre code { padding : 15px 15px !important; box-sizing : border-box; overflow-x : scroll !important; .user-select(text); } .tech-icons { font-size : 50px; text-align : center; margin : (@pad * 2) 0px; color : #AAA; span { margin : 0px @pad; } } ================================================ FILE: site/theme.less ================================================ @import "_constants.less"; a,div { box-sizing : border-box; } a { text-decoration : none; } h1, h2, h3, h4 { color : @color-highlight; box-sizing : border-box; font-weight : 700; padding : 0px 0px; margin : 0px 0px; } body { font-family : "Roboto"; text-align : center; background : @color-bg; color : @color-text; margin : 0; .user-select(none); > div { font-size : 16px; line-height : 1em; } } .nav-top { width : 100%; height : @med-size; background-color : @color-nav; .nav-left { float : left; margin-left : 20px; @media only screen and (max-device-width: 400px){ margin-left : 0px; } } .nav-right { float : right; margin-right : 20px; @media only screen and (max-device-width: 400px){ display : none; } } .devicons { font-size : 50px; line-height : @med-size; } a { display : inline-block; color : white; line-height : @med-size; height : @med-size; border-bottom : 5px solid transparent; padding : 0px @pad; @media only screen and (max-device-width: 400px){ // padding : 0px 5px; } &:hover { border-bottom-color : lighten(@color-nav, 20%); } } } .content-row { text-align : center; background : @color-content; } .content { display : inline-block; text-align : left; padding : @pad 0px; width : @content-width; max-width : 100vw; h2 { font-size : @min-size; line-height : @min-size; padding : @pad*2 0px @pad 0px; } .flavor { font-weight : 300; line-height : 1.2em; margin-bottom : 2em; } } .block { padding-left : @pad; padding-right : @pad; } .button { padding : (@pad) (@pad * 2); background : @color-nav; color : white; cursor : pointer; display : inline-block; &:hover { background : lighten(@color-nav, 20%); } } .footer { margin : (@pad * 2) 0px; color : @color-nav; a { color : @color-nav; } } ================================================ FILE: src/gifler.coffee ================================================ {GifReader} = require 'omggif' Promise = require 'bluebird' # For more on the file format for GIFs # http://www.w3.org/Graphics/GIF/spec-gif89a.txt ###--- head : 'gifler()' text : - This is the main entrypoint to the library. - Prepares and sends an XHR request to load the GIF file. - Returns a Gif instance for interacting with the library. args : url : 'URL to .gif file' return : 'a Gif instance object' ### gifler = (url) -> # Prepare XHR xhr = new XMLHttpRequest() xhr.open('GET', url, aync = true) xhr.responseType = 'arraybuffer' promise = new Promise((resolve, reject) -> xhr.onload = (e) -> resolve(@response) ) xhr.send() return new Gif(promise) class Gif @getCanvasElement : (selector) -> if typeof selector is 'string' and (element = document.querySelector(selector))?.tagName is 'CANVAS' return element else if selector?.tagName is 'CANVAS' return selector else throw new Error('Unexpected selector type. Valid types are query-selector-string/canvas-element') constructor : (dataPromise) -> @_animatorPromise = dataPromise.then (data) -> reader = new GifReader(new Uint8Array(data)) return Decoder.decodeFramesAsync(reader).then (frames) -> return new Animator(reader, frames) ###--- head : 'gif.animate()' text : - > Animates the loaded GIF, drawing each frame into the canvas. This matches the look of an <img> tag. args : selector : 'A element or query selector for a element.' ### animate : (selector) -> canvas = Gif.getCanvasElement(selector) return @_animatorPromise.then (animator) -> animator.animateInCanvas(canvas) ###--- head : 'gif.frames()' text : - > Runs the animation on the loaded GIF, but passes the canvas context and GIF frame to the onDrawFrame callback for rendering. - > This gives you complete control of how the frame is drawn into the canvas context. args : selector : 'A element or query selector for a element.' onDrawFrame : 'A callback that will be invoked when each frame should be drawn into the canvas. see Animator.onDrawFrame.' setDimesions : 'OPTIONAL. If true, the canvas''s width/height will be set to the dimension of the loaded GIF. default: false.' ### frames : (selector, onDrawFrame, setCanvasDimesions = false) -> canvas = Gif.getCanvasElement(selector) return @_animatorPromise.then (animator) -> animator.onDrawFrame = onDrawFrame animator.animateInCanvas(canvas, setCanvasDimesions) ###--- head : 'gif.get()' text : - > To get even more control, and for your convenience, this method returns a promise that will be fulfilled with an Animator instance. The animator will be in an unstarted state, but can be started with a call to animator.animateInCanvas() ### get : (callback) -> return @_animatorPromise ### These methods decode the pixels for each frame (decompressing and de-interlacing) into a Uint8ClampedArray, which is suitable for canvas ImageData. ### class Decoder @decodeFramesSync : (reader) -> return [0...reader.numFrames()].map (frameIndex) -> return Decoder.decodeFrame(reader, frameIndex) @decodeFramesAsync : (reader) -> return Promise.map([0...reader.numFrames()], ((i) -> Decoder.decodeFrame(reader, i)), concurrency = 1) @decodeFrame : (reader, frameIndex) -> frameInfo = reader.frameInfo(frameIndex) frameInfo.pixels = new Uint8ClampedArray(reader.width * reader.height * 4) reader.decodeAndBlitFrameRGBA(frameIndex, frameInfo.pixels) return frameInfo class Animator ###--- head : 'animator::createBufferCanvas()' text : - > Creates a buffer canvas element since it is much faster to call .putImage() than .putImageData(). - > The omggif library decodes the pixels into the full gif dimensions. We only need to store the frame dimensions, so we offset the putImageData call. args : frame : A frame of the GIF (from the omggif library) width : width of the GIF (not the frame) height : height of the GIF return : A element containing the frame's image. ### @createBufferCanvas : (frame, width, height) -> # Create empty buffer bufferCanvas = document.createElement('canvas') bufferContext = bufferCanvas.getContext('2d') bufferCanvas.width = frame.width bufferCanvas.height = frame.height # Create image date from pixels imageData = bufferContext.createImageData(width, height) imageData.data.set(frame.pixels) # Fill canvas with image data bufferContext.putImageData(imageData, -frame.x, -frame.y) return bufferCanvas constructor : (@_reader, @_frames) -> {@width, @height} = @_reader @_loopCount = @_reader.loopCount() @_loops = 0 @_frameIndex = 0 @_running = false ###--- head : 'animator.start()' text : - Starts running the GIF animation loop. ### start : -> @_lastTime = new Date().valueOf() @_delayCompensation = 0 @_running = true setTimeout(@_nextFrame, 0) return @ ###--- head : 'animator.stop()' text : - Stops running the GIF animation loop. ### stop : -> @_running = false return @ ###--- head : 'animator.reset()' text : - Resets the animation loop to the first frame. - Does not stop the animation from running. ### reset : -> @_frameIndex = 0 @_loops = 0 return @ ###--- head : 'animator.running()' return : A boolean indicating whether or not the animation is running. ### running : -> return @_running _nextFrame : => requestAnimationFrame(@_nextFrameRender) return _nextFrameRender : => return unless @_running # Render frame with callback. frame = @_frames[@_frameIndex] @onFrame?.apply(@, [frame, @_frameIndex]) @_enqueueNextFrame() _advanceFrame : => # If we are at the end of the animation, either loop or stop. @_frameIndex += 1 if @_frameIndex >= @_frames.length if @_loopCount isnt 0 and @_loopCount is @_loops @stop() else @_frameIndex = 0 @_loops += 1 return _enqueueNextFrame : -> @_advanceFrame() while @_running frame = @_frames[@_frameIndex] # Perform frame delay compensation to make sure each frame is drawn at # the right time. This helps canvas GIFs match native img GIFs timing. delta = new Date().valueOf() - @_lastTime @_lastTime += delta @_delayCompensation += delta frameDelay = frame.delay * 10 actualDelay = frameDelay - @_delayCompensation @_delayCompensation -= frameDelay # Skip frames while our frame timeout is negative. This is necessary # because browsers such as Chrome will disable javascript while the # window is not in focus. When we re-focus the window, it would attempt # render all the missed frames as fast as possible. if actualDelay < 0 @_advanceFrame() continue else setTimeout(@_nextFrame, actualDelay) break return ###--- head : 'animator.animateInCanvas()' text : - > This method prepares the canvas to be drawn into and sets up the callbacks for each frame while the animation is running. - > To change how each frame is drawn into the canvas, override animator.onDrawFrame() before calling this method. If animator.onDrawFrame() is not set, we simply draw the frame directly into the canvas as is. - > You may also override animator.onFrame() before calling this method. onFrame handles the lazy construction of canvas buffers for each frame as well as the disposal method for each frame. args : canvas : A canvas element. setDimensions : 'OPTIONAL. If true, the canvas width/height will be set to match the GIF. default: true.' ### animateInCanvas : (canvas, setDimensions = true) -> if setDimensions canvas.width = @width canvas.height = @height ctx = canvas.getContext('2d') @onDrawFrame ?= (ctx, frame, i) -> ctx.drawImage(frame.buffer, frame.x, frame.y) @onFrame ?= (frame, i) => # Lazily create canvas buffer. frame.buffer ?= Animator.createBufferCanvas(frame, @width, @height) # Handle frame disposal. @disposeFrame?() switch frame.disposal when 2 @disposeFrame = -> ctx.clearRect(0, 0, canvas.width, canvas.height) when 3 saved = ctx.getImageData(0, 0, canvas.width, canvas.height) @disposeFrame = -> ctx.putImageData(saved, 0, 0) else @disposeFrame = null # Draw current frame. @onDrawFrame?.apply(@, [ctx, frame, i]) # Start animation. @start() return @ # Attach classes to API function gifler.Gif = Gif gifler.Decoder = Decoder gifler.Animator = Animator # Export window?.gifler = gifler module?.exports = gifler