system-polyfills.src.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345
  1. /*
  2. * SystemJS Polyfills for URL and Promise providing IE8+ Support
  3. */
  4. (function(define) {
  5. // from https://gist.github.com/Yaffle/1088850
  6. (function(global) {
  7. function URLPolyfill(url, baseURL) {
  8. if (typeof url != 'string')
  9. throw new TypeError('URL must be a string');
  10. var m = String(url).replace(/^\s+|\s+$/g, "").match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@\/?#]*)(?::([^:@\/?#]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
  11. if (!m) {
  12. throw new RangeError();
  13. }
  14. var protocol = m[1] || "";
  15. var username = m[2] || "";
  16. var password = m[3] || "";
  17. var host = m[4] || "";
  18. var hostname = m[5] || "";
  19. var port = m[6] || "";
  20. var pathname = m[7] || "";
  21. var search = m[8] || "";
  22. var hash = m[9] || "";
  23. if (baseURL !== undefined) {
  24. var base = baseURL instanceof URLPolyfill ? baseURL : new URLPolyfill(baseURL);
  25. var flag = protocol === "" && host === "" && username === "";
  26. if (flag && pathname === "" && search === "") {
  27. search = base.search;
  28. }
  29. if (flag && pathname.charAt(0) !== "/") {
  30. pathname = (pathname !== "" ? (((base.host !== "" || base.username !== "") && base.pathname === "" ? "/" : "") + base.pathname.slice(0, base.pathname.lastIndexOf("/") + 1) + pathname) : base.pathname);
  31. }
  32. // dot segments removal
  33. var output = [];
  34. pathname.replace(/^(\.\.?(\/|$))+/, "")
  35. .replace(/\/(\.(\/|$))+/g, "/")
  36. .replace(/\/\.\.$/, "/../")
  37. .replace(/\/?[^\/]*/g, function (p) {
  38. if (p === "/..") {
  39. output.pop();
  40. } else {
  41. output.push(p);
  42. }
  43. });
  44. pathname = output.join("").replace(/^\//, pathname.charAt(0) === "/" ? "/" : "");
  45. if (flag) {
  46. port = base.port;
  47. hostname = base.hostname;
  48. host = base.host;
  49. password = base.password;
  50. username = base.username;
  51. }
  52. if (protocol === "") {
  53. protocol = base.protocol;
  54. }
  55. }
  56. // convert windows file URLs to use /
  57. if (protocol == 'file:')
  58. pathname = pathname.replace(/\\/g, '/');
  59. this.origin = protocol + (protocol !== "" || host !== "" ? "//" : "") + host;
  60. this.href = protocol + (protocol !== "" || host !== "" ? "//" : "") + (username !== "" ? username + (password !== "" ? ":" + password : "") + "@" : "") + host + pathname + search + hash;
  61. this.protocol = protocol;
  62. this.username = username;
  63. this.password = password;
  64. this.host = host;
  65. this.hostname = hostname;
  66. this.port = port;
  67. this.pathname = pathname;
  68. this.search = search;
  69. this.hash = hash;
  70. }
  71. global.URLPolyfill = URLPolyfill;
  72. })(typeof self != 'undefined' ? self : global);!function(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):"undefined"!=typeof window?window.Promise=e():"undefined"!=typeof global?global.Promise=e():"undefined"!=typeof self&&(self.Promise=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  73. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  74. /** @author Brian Cavalier */
  75. /** @author John Hann */
  76. /**
  77. * ES6 global Promise shim
  78. */
  79. var unhandledRejections = require('../lib/decorators/unhandledRejection');
  80. var PromiseConstructor = unhandledRejections(require('../lib/Promise'));
  81. module.exports = typeof global != 'undefined' ? (global.Promise = PromiseConstructor)
  82. : typeof self != 'undefined' ? (self.Promise = PromiseConstructor)
  83. : PromiseConstructor;
  84. },{"../lib/Promise":2,"../lib/decorators/unhandledRejection":4}],2:[function(require,module,exports){
  85. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  86. /** @author Brian Cavalier */
  87. /** @author John Hann */
  88. (function(define) { 'use strict';
  89. define(function (require) {
  90. var makePromise = require('./makePromise');
  91. var Scheduler = require('./Scheduler');
  92. var async = require('./env').asap;
  93. return makePromise({
  94. scheduler: new Scheduler(async)
  95. });
  96. });
  97. })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });
  98. },{"./Scheduler":3,"./env":5,"./makePromise":7}],3:[function(require,module,exports){
  99. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  100. /** @author Brian Cavalier */
  101. /** @author John Hann */
  102. (function(define) { 'use strict';
  103. define(function() {
  104. // Credit to Twisol (https://github.com/Twisol) for suggesting
  105. // this type of extensible queue + trampoline approach for next-tick conflation.
  106. /**
  107. * Async task scheduler
  108. * @param {function} async function to schedule a single async function
  109. * @constructor
  110. */
  111. function Scheduler(async) {
  112. this._async = async;
  113. this._running = false;
  114. this._queue = this;
  115. this._queueLen = 0;
  116. this._afterQueue = {};
  117. this._afterQueueLen = 0;
  118. var self = this;
  119. this.drain = function() {
  120. self._drain();
  121. };
  122. }
  123. /**
  124. * Enqueue a task
  125. * @param {{ run:function }} task
  126. */
  127. Scheduler.prototype.enqueue = function(task) {
  128. this._queue[this._queueLen++] = task;
  129. this.run();
  130. };
  131. /**
  132. * Enqueue a task to run after the main task queue
  133. * @param {{ run:function }} task
  134. */
  135. Scheduler.prototype.afterQueue = function(task) {
  136. this._afterQueue[this._afterQueueLen++] = task;
  137. this.run();
  138. };
  139. Scheduler.prototype.run = function() {
  140. if (!this._running) {
  141. this._running = true;
  142. this._async(this.drain);
  143. }
  144. };
  145. /**
  146. * Drain the handler queue entirely, and then the after queue
  147. */
  148. Scheduler.prototype._drain = function() {
  149. var i = 0;
  150. for (; i < this._queueLen; ++i) {
  151. this._queue[i].run();
  152. this._queue[i] = void 0;
  153. }
  154. this._queueLen = 0;
  155. this._running = false;
  156. for (i = 0; i < this._afterQueueLen; ++i) {
  157. this._afterQueue[i].run();
  158. this._afterQueue[i] = void 0;
  159. }
  160. this._afterQueueLen = 0;
  161. };
  162. return Scheduler;
  163. });
  164. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  165. },{}],4:[function(require,module,exports){
  166. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  167. /** @author Brian Cavalier */
  168. /** @author John Hann */
  169. (function(define) { 'use strict';
  170. define(function(require) {
  171. var setTimer = require('../env').setTimer;
  172. var format = require('../format');
  173. return function unhandledRejection(Promise) {
  174. var logError = noop;
  175. var logInfo = noop;
  176. var localConsole;
  177. if(typeof console !== 'undefined') {
  178. // Alias console to prevent things like uglify's drop_console option from
  179. // removing console.log/error. Unhandled rejections fall into the same
  180. // category as uncaught exceptions, and build tools shouldn't silence them.
  181. localConsole = console;
  182. logError = typeof localConsole.error !== 'undefined'
  183. ? function (e) { localConsole.error(e); }
  184. : function (e) { localConsole.log(e); };
  185. logInfo = typeof localConsole.info !== 'undefined'
  186. ? function (e) { localConsole.info(e); }
  187. : function (e) { localConsole.log(e); };
  188. }
  189. Promise.onPotentiallyUnhandledRejection = function(rejection) {
  190. enqueue(report, rejection);
  191. };
  192. Promise.onPotentiallyUnhandledRejectionHandled = function(rejection) {
  193. enqueue(unreport, rejection);
  194. };
  195. Promise.onFatalRejection = function(rejection) {
  196. enqueue(throwit, rejection.value);
  197. };
  198. var tasks = [];
  199. var reported = [];
  200. var running = null;
  201. function report(r) {
  202. if(!r.handled) {
  203. reported.push(r);
  204. logError('Potentially unhandled rejection [' + r.id + '] ' + format.formatError(r.value));
  205. }
  206. }
  207. function unreport(r) {
  208. var i = reported.indexOf(r);
  209. if(i >= 0) {
  210. reported.splice(i, 1);
  211. logInfo('Handled previous rejection [' + r.id + '] ' + format.formatObject(r.value));
  212. }
  213. }
  214. function enqueue(f, x) {
  215. tasks.push(f, x);
  216. if(running === null) {
  217. running = setTimer(flush, 0);
  218. }
  219. }
  220. function flush() {
  221. running = null;
  222. while(tasks.length > 0) {
  223. tasks.shift()(tasks.shift());
  224. }
  225. }
  226. return Promise;
  227. };
  228. function throwit(e) {
  229. throw e;
  230. }
  231. function noop() {}
  232. });
  233. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  234. },{"../env":5,"../format":6}],5:[function(require,module,exports){
  235. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  236. /** @author Brian Cavalier */
  237. /** @author John Hann */
  238. /*global process,document,setTimeout,clearTimeout,MutationObserver,WebKitMutationObserver*/
  239. (function(define) { 'use strict';
  240. define(function(require) {
  241. /*jshint maxcomplexity:6*/
  242. // Sniff "best" async scheduling option
  243. // Prefer process.nextTick or MutationObserver, then check for
  244. // setTimeout, and finally vertx, since its the only env that doesn't
  245. // have setTimeout
  246. var MutationObs;
  247. var capturedSetTimeout = typeof setTimeout !== 'undefined' && setTimeout;
  248. // Default env
  249. var setTimer = function(f, ms) { return setTimeout(f, ms); };
  250. var clearTimer = function(t) { return clearTimeout(t); };
  251. var asap = function (f) { return capturedSetTimeout(f, 0); };
  252. // Detect specific env
  253. if (isNode()) { // Node
  254. asap = function (f) { return process.nextTick(f); };
  255. } else if (MutationObs = hasMutationObserver()) { // Modern browser
  256. asap = initMutationObserver(MutationObs);
  257. } else if (!capturedSetTimeout) { // vert.x
  258. var vertxRequire = require;
  259. var vertx = vertxRequire('vertx');
  260. setTimer = function (f, ms) { return vertx.setTimer(ms, f); };
  261. clearTimer = vertx.cancelTimer;
  262. asap = vertx.runOnLoop || vertx.runOnContext;
  263. }
  264. return {
  265. setTimer: setTimer,
  266. clearTimer: clearTimer,
  267. asap: asap
  268. };
  269. function isNode () {
  270. return typeof process !== 'undefined' && process !== null &&
  271. typeof process.nextTick === 'function';
  272. }
  273. function hasMutationObserver () {
  274. return (typeof MutationObserver === 'function' && MutationObserver) ||
  275. (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver);
  276. }
  277. function initMutationObserver(MutationObserver) {
  278. var scheduled;
  279. var node = document.createTextNode('');
  280. var o = new MutationObserver(run);
  281. o.observe(node, { characterData: true });
  282. function run() {
  283. var f = scheduled;
  284. scheduled = void 0;
  285. f();
  286. }
  287. var i = 0;
  288. return function (f) {
  289. scheduled = f;
  290. node.data = (i ^= 1);
  291. };
  292. }
  293. });
  294. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(require); }));
  295. },{}],6:[function(require,module,exports){
  296. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  297. /** @author Brian Cavalier */
  298. /** @author John Hann */
  299. (function(define) { 'use strict';
  300. define(function() {
  301. return {
  302. formatError: formatError,
  303. formatObject: formatObject,
  304. tryStringify: tryStringify
  305. };
  306. /**
  307. * Format an error into a string. If e is an Error and has a stack property,
  308. * it's returned. Otherwise, e is formatted using formatObject, with a
  309. * warning added about e not being a proper Error.
  310. * @param {*} e
  311. * @returns {String} formatted string, suitable for output to developers
  312. */
  313. function formatError(e) {
  314. var s = typeof e === 'object' && e !== null && e.stack ? e.stack : formatObject(e);
  315. return e instanceof Error ? s : s + ' (WARNING: non-Error used)';
  316. }
  317. /**
  318. * Format an object, detecting "plain" objects and running them through
  319. * JSON.stringify if possible.
  320. * @param {Object} o
  321. * @returns {string}
  322. */
  323. function formatObject(o) {
  324. var s = String(o);
  325. if(s === '[object Object]' && typeof JSON !== 'undefined') {
  326. s = tryStringify(o, s);
  327. }
  328. return s;
  329. }
  330. /**
  331. * Try to return the result of JSON.stringify(x). If that fails, return
  332. * defaultValue
  333. * @param {*} x
  334. * @param {*} defaultValue
  335. * @returns {String|*} JSON.stringify(x) or defaultValue
  336. */
  337. function tryStringify(x, defaultValue) {
  338. try {
  339. return JSON.stringify(x);
  340. } catch(e) {
  341. return defaultValue;
  342. }
  343. }
  344. });
  345. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  346. },{}],7:[function(require,module,exports){
  347. /** @license MIT License (c) copyright 2010-2014 original author or authors */
  348. /** @author Brian Cavalier */
  349. /** @author John Hann */
  350. (function(define) { 'use strict';
  351. define(function() {
  352. return function makePromise(environment) {
  353. var tasks = environment.scheduler;
  354. var emitRejection = initEmitRejection();
  355. var objectCreate = Object.create ||
  356. function(proto) {
  357. function Child() {}
  358. Child.prototype = proto;
  359. return new Child();
  360. };
  361. /**
  362. * Create a promise whose fate is determined by resolver
  363. * @constructor
  364. * @returns {Promise} promise
  365. * @name Promise
  366. */
  367. function Promise(resolver, handler) {
  368. this._handler = resolver === Handler ? handler : init(resolver);
  369. }
  370. /**
  371. * Run the supplied resolver
  372. * @param resolver
  373. * @returns {Pending}
  374. */
  375. function init(resolver) {
  376. var handler = new Pending();
  377. try {
  378. resolver(promiseResolve, promiseReject, promiseNotify);
  379. } catch (e) {
  380. promiseReject(e);
  381. }
  382. return handler;
  383. /**
  384. * Transition from pre-resolution state to post-resolution state, notifying
  385. * all listeners of the ultimate fulfillment or rejection
  386. * @param {*} x resolution value
  387. */
  388. function promiseResolve (x) {
  389. handler.resolve(x);
  390. }
  391. /**
  392. * Reject this promise with reason, which will be used verbatim
  393. * @param {Error|*} reason rejection reason, strongly suggested
  394. * to be an Error type
  395. */
  396. function promiseReject (reason) {
  397. handler.reject(reason);
  398. }
  399. /**
  400. * @deprecated
  401. * Issue a progress event, notifying all progress listeners
  402. * @param {*} x progress event payload to pass to all listeners
  403. */
  404. function promiseNotify (x) {
  405. handler.notify(x);
  406. }
  407. }
  408. // Creation
  409. Promise.resolve = resolve;
  410. Promise.reject = reject;
  411. Promise.never = never;
  412. Promise._defer = defer;
  413. Promise._handler = getHandler;
  414. /**
  415. * Returns a trusted promise. If x is already a trusted promise, it is
  416. * returned, otherwise returns a new trusted Promise which follows x.
  417. * @param {*} x
  418. * @return {Promise} promise
  419. */
  420. function resolve(x) {
  421. return isPromise(x) ? x
  422. : new Promise(Handler, new Async(getHandler(x)));
  423. }
  424. /**
  425. * Return a reject promise with x as its reason (x is used verbatim)
  426. * @param {*} x
  427. * @returns {Promise} rejected promise
  428. */
  429. function reject(x) {
  430. return new Promise(Handler, new Async(new Rejected(x)));
  431. }
  432. /**
  433. * Return a promise that remains pending forever
  434. * @returns {Promise} forever-pending promise.
  435. */
  436. function never() {
  437. return foreverPendingPromise; // Should be frozen
  438. }
  439. /**
  440. * Creates an internal {promise, resolver} pair
  441. * @private
  442. * @returns {Promise}
  443. */
  444. function defer() {
  445. return new Promise(Handler, new Pending());
  446. }
  447. // Transformation and flow control
  448. /**
  449. * Transform this promise's fulfillment value, returning a new Promise
  450. * for the transformed result. If the promise cannot be fulfilled, onRejected
  451. * is called with the reason. onProgress *may* be called with updates toward
  452. * this promise's fulfillment.
  453. * @param {function=} onFulfilled fulfillment handler
  454. * @param {function=} onRejected rejection handler
  455. * @param {function=} onProgress @deprecated progress handler
  456. * @return {Promise} new promise
  457. */
  458. Promise.prototype.then = function(onFulfilled, onRejected, onProgress) {
  459. var parent = this._handler;
  460. var state = parent.join().state();
  461. if ((typeof onFulfilled !== 'function' && state > 0) ||
  462. (typeof onRejected !== 'function' && state < 0)) {
  463. // Short circuit: value will not change, simply share handler
  464. return new this.constructor(Handler, parent);
  465. }
  466. var p = this._beget();
  467. var child = p._handler;
  468. parent.chain(child, parent.receiver, onFulfilled, onRejected, onProgress);
  469. return p;
  470. };
  471. /**
  472. * If this promise cannot be fulfilled due to an error, call onRejected to
  473. * handle the error. Shortcut for .then(undefined, onRejected)
  474. * @param {function?} onRejected
  475. * @return {Promise}
  476. */
  477. Promise.prototype['catch'] = function(onRejected) {
  478. return this.then(void 0, onRejected);
  479. };
  480. /**
  481. * Creates a new, pending promise of the same type as this promise
  482. * @private
  483. * @returns {Promise}
  484. */
  485. Promise.prototype._beget = function() {
  486. return begetFrom(this._handler, this.constructor);
  487. };
  488. function begetFrom(parent, Promise) {
  489. var child = new Pending(parent.receiver, parent.join().context);
  490. return new Promise(Handler, child);
  491. }
  492. // Array combinators
  493. Promise.all = all;
  494. Promise.race = race;
  495. Promise._traverse = traverse;
  496. /**
  497. * Return a promise that will fulfill when all promises in the
  498. * input array have fulfilled, or will reject when one of the
  499. * promises rejects.
  500. * @param {array} promises array of promises
  501. * @returns {Promise} promise for array of fulfillment values
  502. */
  503. function all(promises) {
  504. return traverseWith(snd, null, promises);
  505. }
  506. /**
  507. * Array<Promise<X>> -> Promise<Array<f(X)>>
  508. * @private
  509. * @param {function} f function to apply to each promise's value
  510. * @param {Array} promises array of promises
  511. * @returns {Promise} promise for transformed values
  512. */
  513. function traverse(f, promises) {
  514. return traverseWith(tryCatch2, f, promises);
  515. }
  516. function traverseWith(tryMap, f, promises) {
  517. var handler = typeof f === 'function' ? mapAt : settleAt;
  518. var resolver = new Pending();
  519. var pending = promises.length >>> 0;
  520. var results = new Array(pending);
  521. for (var i = 0, x; i < promises.length && !resolver.resolved; ++i) {
  522. x = promises[i];
  523. if (x === void 0 && !(i in promises)) {
  524. --pending;
  525. continue;
  526. }
  527. traverseAt(promises, handler, i, x, resolver);
  528. }
  529. if(pending === 0) {
  530. resolver.become(new Fulfilled(results));
  531. }
  532. return new Promise(Handler, resolver);
  533. function mapAt(i, x, resolver) {
  534. if(!resolver.resolved) {
  535. traverseAt(promises, settleAt, i, tryMap(f, x, i), resolver);
  536. }
  537. }
  538. function settleAt(i, x, resolver) {
  539. results[i] = x;
  540. if(--pending === 0) {
  541. resolver.become(new Fulfilled(results));
  542. }
  543. }
  544. }
  545. function traverseAt(promises, handler, i, x, resolver) {
  546. if (maybeThenable(x)) {
  547. var h = getHandlerMaybeThenable(x);
  548. var s = h.state();
  549. if (s === 0) {
  550. h.fold(handler, i, void 0, resolver);
  551. } else if (s > 0) {
  552. handler(i, h.value, resolver);
  553. } else {
  554. resolver.become(h);
  555. visitRemaining(promises, i+1, h);
  556. }
  557. } else {
  558. handler(i, x, resolver);
  559. }
  560. }
  561. Promise._visitRemaining = visitRemaining;
  562. function visitRemaining(promises, start, handler) {
  563. for(var i=start; i<promises.length; ++i) {
  564. markAsHandled(getHandler(promises[i]), handler);
  565. }
  566. }
  567. function markAsHandled(h, handler) {
  568. if(h === handler) {
  569. return;
  570. }
  571. var s = h.state();
  572. if(s === 0) {
  573. h.visit(h, void 0, h._unreport);
  574. } else if(s < 0) {
  575. h._unreport();
  576. }
  577. }
  578. /**
  579. * Fulfill-reject competitive race. Return a promise that will settle
  580. * to the same state as the earliest input promise to settle.
  581. *
  582. * WARNING: The ES6 Promise spec requires that race()ing an empty array
  583. * must return a promise that is pending forever. This implementation
  584. * returns a singleton forever-pending promise, the same singleton that is
  585. * returned by Promise.never(), thus can be checked with ===
  586. *
  587. * @param {array} promises array of promises to race
  588. * @returns {Promise} if input is non-empty, a promise that will settle
  589. * to the same outcome as the earliest input promise to settle. if empty
  590. * is empty, returns a promise that will never settle.
  591. */
  592. function race(promises) {
  593. if(typeof promises !== 'object' || promises === null) {
  594. return reject(new TypeError('non-iterable passed to race()'));
  595. }
  596. // Sigh, race([]) is untestable unless we return *something*
  597. // that is recognizable without calling .then() on it.
  598. return promises.length === 0 ? never()
  599. : promises.length === 1 ? resolve(promises[0])
  600. : runRace(promises);
  601. }
  602. function runRace(promises) {
  603. var resolver = new Pending();
  604. var i, x, h;
  605. for(i=0; i<promises.length; ++i) {
  606. x = promises[i];
  607. if (x === void 0 && !(i in promises)) {
  608. continue;
  609. }
  610. h = getHandler(x);
  611. if(h.state() !== 0) {
  612. resolver.become(h);
  613. visitRemaining(promises, i+1, h);
  614. break;
  615. } else {
  616. h.visit(resolver, resolver.resolve, resolver.reject);
  617. }
  618. }
  619. return new Promise(Handler, resolver);
  620. }
  621. // Promise internals
  622. // Below this, everything is @private
  623. /**
  624. * Get an appropriate handler for x, without checking for cycles
  625. * @param {*} x
  626. * @returns {object} handler
  627. */
  628. function getHandler(x) {
  629. if(isPromise(x)) {
  630. return x._handler.join();
  631. }
  632. return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x);
  633. }
  634. /**
  635. * Get a handler for thenable x.
  636. * NOTE: You must only call this if maybeThenable(x) == true
  637. * @param {object|function|Promise} x
  638. * @returns {object} handler
  639. */
  640. function getHandlerMaybeThenable(x) {
  641. return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x);
  642. }
  643. /**
  644. * Get a handler for potentially untrusted thenable x
  645. * @param {*} x
  646. * @returns {object} handler
  647. */
  648. function getHandlerUntrusted(x) {
  649. try {
  650. var untrustedThen = x.then;
  651. return typeof untrustedThen === 'function'
  652. ? new Thenable(untrustedThen, x)
  653. : new Fulfilled(x);
  654. } catch(e) {
  655. return new Rejected(e);
  656. }
  657. }
  658. /**
  659. * Handler for a promise that is pending forever
  660. * @constructor
  661. */
  662. function Handler() {}
  663. Handler.prototype.when
  664. = Handler.prototype.become
  665. = Handler.prototype.notify // deprecated
  666. = Handler.prototype.fail
  667. = Handler.prototype._unreport
  668. = Handler.prototype._report
  669. = noop;
  670. Handler.prototype._state = 0;
  671. Handler.prototype.state = function() {
  672. return this._state;
  673. };
  674. /**
  675. * Recursively collapse handler chain to find the handler
  676. * nearest to the fully resolved value.
  677. * @returns {object} handler nearest the fully resolved value
  678. */
  679. Handler.prototype.join = function() {
  680. var h = this;
  681. while(h.handler !== void 0) {
  682. h = h.handler;
  683. }
  684. return h;
  685. };
  686. Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) {
  687. this.when({
  688. resolver: to,
  689. receiver: receiver,
  690. fulfilled: fulfilled,
  691. rejected: rejected,
  692. progress: progress
  693. });
  694. };
  695. Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) {
  696. this.chain(failIfRejected, receiver, fulfilled, rejected, progress);
  697. };
  698. Handler.prototype.fold = function(f, z, c, to) {
  699. this.when(new Fold(f, z, c, to));
  700. };
  701. /**
  702. * Handler that invokes fail() on any handler it becomes
  703. * @constructor
  704. */
  705. function FailIfRejected() {}
  706. inherit(Handler, FailIfRejected);
  707. FailIfRejected.prototype.become = function(h) {
  708. h.fail();
  709. };
  710. var failIfRejected = new FailIfRejected();
  711. /**
  712. * Handler that manages a queue of consumers waiting on a pending promise
  713. * @constructor
  714. */
  715. function Pending(receiver, inheritedContext) {
  716. Promise.createContext(this, inheritedContext);
  717. this.consumers = void 0;
  718. this.receiver = receiver;
  719. this.handler = void 0;
  720. this.resolved = false;
  721. }
  722. inherit(Handler, Pending);
  723. Pending.prototype._state = 0;
  724. Pending.prototype.resolve = function(x) {
  725. this.become(getHandler(x));
  726. };
  727. Pending.prototype.reject = function(x) {
  728. if(this.resolved) {
  729. return;
  730. }
  731. this.become(new Rejected(x));
  732. };
  733. Pending.prototype.join = function() {
  734. if (!this.resolved) {
  735. return this;
  736. }
  737. var h = this;
  738. while (h.handler !== void 0) {
  739. h = h.handler;
  740. if (h === this) {
  741. return this.handler = cycle();
  742. }
  743. }
  744. return h;
  745. };
  746. Pending.prototype.run = function() {
  747. var q = this.consumers;
  748. var handler = this.handler;
  749. this.handler = this.handler.join();
  750. this.consumers = void 0;
  751. for (var i = 0; i < q.length; ++i) {
  752. handler.when(q[i]);
  753. }
  754. };
  755. Pending.prototype.become = function(handler) {
  756. if(this.resolved) {
  757. return;
  758. }
  759. this.resolved = true;
  760. this.handler = handler;
  761. if(this.consumers !== void 0) {
  762. tasks.enqueue(this);
  763. }
  764. if(this.context !== void 0) {
  765. handler._report(this.context);
  766. }
  767. };
  768. Pending.prototype.when = function(continuation) {
  769. if(this.resolved) {
  770. tasks.enqueue(new ContinuationTask(continuation, this.handler));
  771. } else {
  772. if(this.consumers === void 0) {
  773. this.consumers = [continuation];
  774. } else {
  775. this.consumers.push(continuation);
  776. }
  777. }
  778. };
  779. /**
  780. * @deprecated
  781. */
  782. Pending.prototype.notify = function(x) {
  783. if(!this.resolved) {
  784. tasks.enqueue(new ProgressTask(x, this));
  785. }
  786. };
  787. Pending.prototype.fail = function(context) {
  788. var c = typeof context === 'undefined' ? this.context : context;
  789. this.resolved && this.handler.join().fail(c);
  790. };
  791. Pending.prototype._report = function(context) {
  792. this.resolved && this.handler.join()._report(context);
  793. };
  794. Pending.prototype._unreport = function() {
  795. this.resolved && this.handler.join()._unreport();
  796. };
  797. /**
  798. * Wrap another handler and force it into a future stack
  799. * @param {object} handler
  800. * @constructor
  801. */
  802. function Async(handler) {
  803. this.handler = handler;
  804. }
  805. inherit(Handler, Async);
  806. Async.prototype.when = function(continuation) {
  807. tasks.enqueue(new ContinuationTask(continuation, this));
  808. };
  809. Async.prototype._report = function(context) {
  810. this.join()._report(context);
  811. };
  812. Async.prototype._unreport = function() {
  813. this.join()._unreport();
  814. };
  815. /**
  816. * Handler that wraps an untrusted thenable and assimilates it in a future stack
  817. * @param {function} then
  818. * @param {{then: function}} thenable
  819. * @constructor
  820. */
  821. function Thenable(then, thenable) {
  822. Pending.call(this);
  823. tasks.enqueue(new AssimilateTask(then, thenable, this));
  824. }
  825. inherit(Pending, Thenable);
  826. /**
  827. * Handler for a fulfilled promise
  828. * @param {*} x fulfillment value
  829. * @constructor
  830. */
  831. function Fulfilled(x) {
  832. Promise.createContext(this);
  833. this.value = x;
  834. }
  835. inherit(Handler, Fulfilled);
  836. Fulfilled.prototype._state = 1;
  837. Fulfilled.prototype.fold = function(f, z, c, to) {
  838. runContinuation3(f, z, this, c, to);
  839. };
  840. Fulfilled.prototype.when = function(cont) {
  841. runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver);
  842. };
  843. var errorId = 0;
  844. /**
  845. * Handler for a rejected promise
  846. * @param {*} x rejection reason
  847. * @constructor
  848. */
  849. function Rejected(x) {
  850. Promise.createContext(this);
  851. this.id = ++errorId;
  852. this.value = x;
  853. this.handled = false;
  854. this.reported = false;
  855. this._report();
  856. }
  857. inherit(Handler, Rejected);
  858. Rejected.prototype._state = -1;
  859. Rejected.prototype.fold = function(f, z, c, to) {
  860. to.become(this);
  861. };
  862. Rejected.prototype.when = function(cont) {
  863. if(typeof cont.rejected === 'function') {
  864. this._unreport();
  865. }
  866. runContinuation1(cont.rejected, this, cont.receiver, cont.resolver);
  867. };
  868. Rejected.prototype._report = function(context) {
  869. tasks.afterQueue(new ReportTask(this, context));
  870. };
  871. Rejected.prototype._unreport = function() {
  872. if(this.handled) {
  873. return;
  874. }
  875. this.handled = true;
  876. tasks.afterQueue(new UnreportTask(this));
  877. };
  878. Rejected.prototype.fail = function(context) {
  879. this.reported = true;
  880. emitRejection('unhandledRejection', this);
  881. Promise.onFatalRejection(this, context === void 0 ? this.context : context);
  882. };
  883. function ReportTask(rejection, context) {
  884. this.rejection = rejection;
  885. this.context = context;
  886. }
  887. ReportTask.prototype.run = function() {
  888. if(!this.rejection.handled && !this.rejection.reported) {
  889. this.rejection.reported = true;
  890. emitRejection('unhandledRejection', this.rejection) ||
  891. Promise.onPotentiallyUnhandledRejection(this.rejection, this.context);
  892. }
  893. };
  894. function UnreportTask(rejection) {
  895. this.rejection = rejection;
  896. }
  897. UnreportTask.prototype.run = function() {
  898. if(this.rejection.reported) {
  899. emitRejection('rejectionHandled', this.rejection) ||
  900. Promise.onPotentiallyUnhandledRejectionHandled(this.rejection);
  901. }
  902. };
  903. // Unhandled rejection hooks
  904. // By default, everything is a noop
  905. Promise.createContext
  906. = Promise.enterContext
  907. = Promise.exitContext
  908. = Promise.onPotentiallyUnhandledRejection
  909. = Promise.onPotentiallyUnhandledRejectionHandled
  910. = Promise.onFatalRejection
  911. = noop;
  912. // Errors and singletons
  913. var foreverPendingHandler = new Handler();
  914. var foreverPendingPromise = new Promise(Handler, foreverPendingHandler);
  915. function cycle() {
  916. return new Rejected(new TypeError('Promise cycle'));
  917. }
  918. // Task runners
  919. /**
  920. * Run a single consumer
  921. * @constructor
  922. */
  923. function ContinuationTask(continuation, handler) {
  924. this.continuation = continuation;
  925. this.handler = handler;
  926. }
  927. ContinuationTask.prototype.run = function() {
  928. this.handler.join().when(this.continuation);
  929. };
  930. /**
  931. * Run a queue of progress handlers
  932. * @constructor
  933. */
  934. function ProgressTask(value, handler) {
  935. this.handler = handler;
  936. this.value = value;
  937. }
  938. ProgressTask.prototype.run = function() {
  939. var q = this.handler.consumers;
  940. if(q === void 0) {
  941. return;
  942. }
  943. for (var c, i = 0; i < q.length; ++i) {
  944. c = q[i];
  945. runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver);
  946. }
  947. };
  948. /**
  949. * Assimilate a thenable, sending it's value to resolver
  950. * @param {function} then
  951. * @param {object|function} thenable
  952. * @param {object} resolver
  953. * @constructor
  954. */
  955. function AssimilateTask(then, thenable, resolver) {
  956. this._then = then;
  957. this.thenable = thenable;
  958. this.resolver = resolver;
  959. }
  960. AssimilateTask.prototype.run = function() {
  961. var h = this.resolver;
  962. tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify);
  963. function _resolve(x) { h.resolve(x); }
  964. function _reject(x) { h.reject(x); }
  965. function _notify(x) { h.notify(x); }
  966. };
  967. function tryAssimilate(then, thenable, resolve, reject, notify) {
  968. try {
  969. then.call(thenable, resolve, reject, notify);
  970. } catch (e) {
  971. reject(e);
  972. }
  973. }
  974. /**
  975. * Fold a handler value with z
  976. * @constructor
  977. */
  978. function Fold(f, z, c, to) {
  979. this.f = f; this.z = z; this.c = c; this.to = to;
  980. this.resolver = failIfRejected;
  981. this.receiver = this;
  982. }
  983. Fold.prototype.fulfilled = function(x) {
  984. this.f.call(this.c, this.z, x, this.to);
  985. };
  986. Fold.prototype.rejected = function(x) {
  987. this.to.reject(x);
  988. };
  989. Fold.prototype.progress = function(x) {
  990. this.to.notify(x);
  991. };
  992. // Other helpers
  993. /**
  994. * @param {*} x
  995. * @returns {boolean} true iff x is a trusted Promise
  996. */
  997. function isPromise(x) {
  998. return x instanceof Promise;
  999. }
  1000. /**
  1001. * Test just enough to rule out primitives, in order to take faster
  1002. * paths in some code
  1003. * @param {*} x
  1004. * @returns {boolean} false iff x is guaranteed *not* to be a thenable
  1005. */
  1006. function maybeThenable(x) {
  1007. return (typeof x === 'object' || typeof x === 'function') && x !== null;
  1008. }
  1009. function runContinuation1(f, h, receiver, next) {
  1010. if(typeof f !== 'function') {
  1011. return next.become(h);
  1012. }
  1013. Promise.enterContext(h);
  1014. tryCatchReject(f, h.value, receiver, next);
  1015. Promise.exitContext();
  1016. }
  1017. function runContinuation3(f, x, h, receiver, next) {
  1018. if(typeof f !== 'function') {
  1019. return next.become(h);
  1020. }
  1021. Promise.enterContext(h);
  1022. tryCatchReject3(f, x, h.value, receiver, next);
  1023. Promise.exitContext();
  1024. }
  1025. /**
  1026. * @deprecated
  1027. */
  1028. function runNotify(f, x, h, receiver, next) {
  1029. if(typeof f !== 'function') {
  1030. return next.notify(x);
  1031. }
  1032. Promise.enterContext(h);
  1033. tryCatchReturn(f, x, receiver, next);
  1034. Promise.exitContext();
  1035. }
  1036. function tryCatch2(f, a, b) {
  1037. try {
  1038. return f(a, b);
  1039. } catch(e) {
  1040. return reject(e);
  1041. }
  1042. }
  1043. /**
  1044. * Return f.call(thisArg, x), or if it throws return a rejected promise for
  1045. * the thrown exception
  1046. */
  1047. function tryCatchReject(f, x, thisArg, next) {
  1048. try {
  1049. next.become(getHandler(f.call(thisArg, x)));
  1050. } catch(e) {
  1051. next.become(new Rejected(e));
  1052. }
  1053. }
  1054. /**
  1055. * Same as above, but includes the extra argument parameter.
  1056. */
  1057. function tryCatchReject3(f, x, y, thisArg, next) {
  1058. try {
  1059. f.call(thisArg, x, y, next);
  1060. } catch(e) {
  1061. next.become(new Rejected(e));
  1062. }
  1063. }
  1064. /**
  1065. * @deprecated
  1066. * Return f.call(thisArg, x), or if it throws, *return* the exception
  1067. */
  1068. function tryCatchReturn(f, x, thisArg, next) {
  1069. try {
  1070. next.notify(f.call(thisArg, x));
  1071. } catch(e) {
  1072. next.notify(e);
  1073. }
  1074. }
  1075. function inherit(Parent, Child) {
  1076. Child.prototype = objectCreate(Parent.prototype);
  1077. Child.prototype.constructor = Child;
  1078. }
  1079. function snd(x, y) {
  1080. return y;
  1081. }
  1082. function noop() {}
  1083. function initEmitRejection() {
  1084. /*global process, self, CustomEvent*/
  1085. if(typeof process !== 'undefined' && process !== null
  1086. && typeof process.emit === 'function') {
  1087. // Returning falsy here means to call the default
  1088. // onPotentiallyUnhandledRejection API. This is safe even in
  1089. // browserify since process.emit always returns falsy in browserify:
  1090. // https://github.com/defunctzombie/node-process/blob/master/browser.js#L40-L46
  1091. return function(type, rejection) {
  1092. return type === 'unhandledRejection'
  1093. ? process.emit(type, rejection.value, rejection)
  1094. : process.emit(type, rejection);
  1095. };
  1096. } else if(typeof self !== 'undefined' && typeof CustomEvent === 'function') {
  1097. return (function(noop, self, CustomEvent) {
  1098. var hasCustomEvent = false;
  1099. try {
  1100. var ev = new CustomEvent('unhandledRejection');
  1101. hasCustomEvent = ev instanceof CustomEvent;
  1102. } catch (e) {}
  1103. return !hasCustomEvent ? noop : function(type, rejection) {
  1104. var ev = new CustomEvent(type, {
  1105. detail: {
  1106. reason: rejection.value,
  1107. key: rejection
  1108. },
  1109. bubbles: false,
  1110. cancelable: true
  1111. });
  1112. return !self.dispatchEvent(ev);
  1113. };
  1114. }(noop, self, CustomEvent));
  1115. }
  1116. return noop;
  1117. }
  1118. return Promise;
  1119. };
  1120. });
  1121. }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
  1122. },{}]},{},[1])
  1123. (1)
  1124. });
  1125. ;if (typeof systemJSBootstrap !== 'undefined')
  1126. systemJSBootstrap();})();