UNPKG

16.3 kBJavaScriptView Raw
1(function (factory) {
2 typeof define === 'function' && define.amd ? define(factory) :
3 factory();
4}((function () { 'use strict';
5
6 function _classCallCheck(instance, Constructor) {
7 if (!(instance instanceof Constructor)) {
8 throw new TypeError("Cannot call a class as a function");
9 }
10 }
11
12 function _defineProperties(target, props) {
13 for (var i = 0; i < props.length; i++) {
14 var descriptor = props[i];
15 descriptor.enumerable = descriptor.enumerable || false;
16 descriptor.configurable = true;
17 if ("value" in descriptor) descriptor.writable = true;
18 Object.defineProperty(target, descriptor.key, descriptor);
19 }
20 }
21
22 function _createClass(Constructor, protoProps, staticProps) {
23 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
24 if (staticProps) _defineProperties(Constructor, staticProps);
25 return Constructor;
26 }
27
28 function _inherits(subClass, superClass) {
29 if (typeof superClass !== "function" && superClass !== null) {
30 throw new TypeError("Super expression must either be null or a function");
31 }
32
33 subClass.prototype = Object.create(superClass && superClass.prototype, {
34 constructor: {
35 value: subClass,
36 writable: true,
37 configurable: true
38 }
39 });
40 if (superClass) _setPrototypeOf(subClass, superClass);
41 }
42
43 function _getPrototypeOf(o) {
44 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
45 return o.__proto__ || Object.getPrototypeOf(o);
46 };
47 return _getPrototypeOf(o);
48 }
49
50 function _setPrototypeOf(o, p) {
51 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
52 o.__proto__ = p;
53 return o;
54 };
55
56 return _setPrototypeOf(o, p);
57 }
58
59 function _isNativeReflectConstruct() {
60 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
61 if (Reflect.construct.sham) return false;
62 if (typeof Proxy === "function") return true;
63
64 try {
65 Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
66 return true;
67 } catch (e) {
68 return false;
69 }
70 }
71
72 function _assertThisInitialized(self) {
73 if (self === void 0) {
74 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
75 }
76
77 return self;
78 }
79
80 function _possibleConstructorReturn(self, call) {
81 if (call && (typeof call === "object" || typeof call === "function")) {
82 return call;
83 }
84
85 return _assertThisInitialized(self);
86 }
87
88 function _createSuper(Derived) {
89 var hasNativeReflectConstruct = _isNativeReflectConstruct();
90
91 return function _createSuperInternal() {
92 var Super = _getPrototypeOf(Derived),
93 result;
94
95 if (hasNativeReflectConstruct) {
96 var NewTarget = _getPrototypeOf(this).constructor;
97
98 result = Reflect.construct(Super, arguments, NewTarget);
99 } else {
100 result = Super.apply(this, arguments);
101 }
102
103 return _possibleConstructorReturn(this, result);
104 };
105 }
106
107 function _superPropBase(object, property) {
108 while (!Object.prototype.hasOwnProperty.call(object, property)) {
109 object = _getPrototypeOf(object);
110 if (object === null) break;
111 }
112
113 return object;
114 }
115
116 function _get(target, property, receiver) {
117 if (typeof Reflect !== "undefined" && Reflect.get) {
118 _get = Reflect.get;
119 } else {
120 _get = function _get(target, property, receiver) {
121 var base = _superPropBase(target, property);
122
123 if (!base) return;
124 var desc = Object.getOwnPropertyDescriptor(base, property);
125
126 if (desc.get) {
127 return desc.get.call(receiver);
128 }
129
130 return desc.value;
131 };
132 }
133
134 return _get(target, property, receiver || target);
135 }
136
137 var Emitter = /*#__PURE__*/function () {
138 function Emitter() {
139 _classCallCheck(this, Emitter);
140
141 Object.defineProperty(this, 'listeners', {
142 value: {},
143 writable: true,
144 configurable: true
145 });
146 }
147
148 _createClass(Emitter, [{
149 key: "addEventListener",
150 value: function addEventListener(type, callback) {
151 if (!(type in this.listeners)) {
152 this.listeners[type] = [];
153 }
154
155 this.listeners[type].push(callback);
156 }
157 }, {
158 key: "removeEventListener",
159 value: function removeEventListener(type, callback) {
160 if (!(type in this.listeners)) {
161 return;
162 }
163
164 var stack = this.listeners[type];
165
166 for (var i = 0, l = stack.length; i < l; i++) {
167 if (stack[i] === callback) {
168 stack.splice(i, 1);
169 return;
170 }
171 }
172 }
173 }, {
174 key: "dispatchEvent",
175 value: function dispatchEvent(event) {
176 if (!(event.type in this.listeners)) {
177 return;
178 }
179
180 var stack = this.listeners[event.type];
181
182 for (var i = 0, l = stack.length; i < l; i++) {
183 try {
184 stack[i].call(this, event);
185 } catch (e) {
186 Promise.resolve().then(function () {
187 throw e;
188 });
189 }
190 }
191
192 return !event.defaultPrevented;
193 }
194 }]);
195
196 return Emitter;
197 }();
198
199 var AbortSignal = /*#__PURE__*/function (_Emitter) {
200 _inherits(AbortSignal, _Emitter);
201
202 var _super = _createSuper(AbortSignal);
203
204 function AbortSignal() {
205 var _this;
206
207 _classCallCheck(this, AbortSignal);
208
209 _this = _super.call(this); // Some versions of babel does not transpile super() correctly for IE <= 10, if the parent
210 // constructor has failed to run, then "this.listeners" will still be undefined and then we call
211 // the parent constructor directly instead as a workaround. For general details, see babel bug:
212 // https://github.com/babel/babel/issues/3041
213 // This hack was added as a fix for the issue described here:
214 // https://github.com/Financial-Times/polyfill-library/pull/59#issuecomment-477558042
215
216 if (!_this.listeners) {
217 Emitter.call(_assertThisInitialized(_this));
218 } // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and
219 // we want Object.keys(new AbortController().signal) to be [] for compat with the native impl
220
221
222 Object.defineProperty(_assertThisInitialized(_this), 'aborted', {
223 value: false,
224 writable: true,
225 configurable: true
226 });
227 Object.defineProperty(_assertThisInitialized(_this), 'onabort', {
228 value: null,
229 writable: true,
230 configurable: true
231 });
232 return _this;
233 }
234
235 _createClass(AbortSignal, [{
236 key: "toString",
237 value: function toString() {
238 return '[object AbortSignal]';
239 }
240 }, {
241 key: "dispatchEvent",
242 value: function dispatchEvent(event) {
243 if (event.type === 'abort') {
244 this.aborted = true;
245
246 if (typeof this.onabort === 'function') {
247 this.onabort.call(this, event);
248 }
249 }
250
251 _get(_getPrototypeOf(AbortSignal.prototype), "dispatchEvent", this).call(this, event);
252 }
253 }]);
254
255 return AbortSignal;
256 }(Emitter);
257 var AbortController = /*#__PURE__*/function () {
258 function AbortController() {
259 _classCallCheck(this, AbortController);
260
261 // Compared to assignment, Object.defineProperty makes properties non-enumerable by default and
262 // we want Object.keys(new AbortController()) to be [] for compat with the native impl
263 Object.defineProperty(this, 'signal', {
264 value: new AbortSignal(),
265 writable: true,
266 configurable: true
267 });
268 }
269
270 _createClass(AbortController, [{
271 key: "abort",
272 value: function abort() {
273 var event;
274
275 try {
276 event = new Event('abort');
277 } catch (e) {
278 if (typeof document !== 'undefined') {
279 if (!document.createEvent) {
280 // For Internet Explorer 8:
281 event = document.createEventObject();
282 event.type = 'abort';
283 } else {
284 // For Internet Explorer 11:
285 event = document.createEvent('Event');
286 event.initEvent('abort', false, false);
287 }
288 } else {
289 // Fallback where document isn't available:
290 event = {
291 type: 'abort',
292 bubbles: false,
293 cancelable: false
294 };
295 }
296 }
297
298 this.signal.dispatchEvent(event);
299 }
300 }, {
301 key: "toString",
302 value: function toString() {
303 return '[object AbortController]';
304 }
305 }]);
306
307 return AbortController;
308 }();
309
310 if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
311 // These are necessary to make sure that we get correct output for:
312 // Object.prototype.toString.call(new AbortController())
313 AbortController.prototype[Symbol.toStringTag] = 'AbortController';
314 AbortSignal.prototype[Symbol.toStringTag] = 'AbortSignal';
315 }
316
317 function polyfillNeeded(self) {
318 if (self.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
319 console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill');
320 return true;
321 } // Note that the "unfetch" minimal fetch polyfill defines fetch() without
322 // defining window.Request, and this polyfill need to work on top of unfetch
323 // so the below feature detection needs the !self.AbortController part.
324 // The Request.prototype check is also needed because Safari versions 11.1.2
325 // up to and including 12.1.x has a window.AbortController present but still
326 // does NOT correctly implement abortable fetch:
327 // https://bugs.webkit.org/show_bug.cgi?id=174980#c2
328
329
330 return typeof self.Request === 'function' && !self.Request.prototype.hasOwnProperty('signal') || !self.AbortController;
331 }
332
333 /**
334 * Note: the "fetch.Request" default value is available for fetch imported from
335 * the "node-fetch" package and not in browsers. This is OK since browsers
336 * will be importing umd-polyfill.js from that path "self" is passed the
337 * decorator so the default value will not be used (because browsers that define
338 * fetch also has Request). One quirky setup where self.fetch exists but
339 * self.Request does not is when the "unfetch" minimal fetch polyfill is used
340 * on top of IE11; for this case the browser will try to use the fetch.Request
341 * default value which in turn will be undefined but then then "if (Request)"
342 * will ensure that you get a patched fetch but still no Request (as expected).
343 * @param {fetch, Request = fetch.Request}
344 * @returns {fetch: abortableFetch, Request: AbortableRequest}
345 */
346
347 function abortableFetchDecorator(patchTargets) {
348 if ('function' === typeof patchTargets) {
349 patchTargets = {
350 fetch: patchTargets
351 };
352 }
353
354 var _patchTargets = patchTargets,
355 fetch = _patchTargets.fetch,
356 _patchTargets$Request = _patchTargets.Request,
357 NativeRequest = _patchTargets$Request === void 0 ? fetch.Request : _patchTargets$Request,
358 NativeAbortController = _patchTargets.AbortController,
359 _patchTargets$__FORCE = _patchTargets.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,
360 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL = _patchTargets$__FORCE === void 0 ? false : _patchTargets$__FORCE;
361
362 if (!polyfillNeeded({
363 fetch: fetch,
364 Request: NativeRequest,
365 AbortController: NativeAbortController,
366 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL: __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL
367 })) {
368 return {
369 fetch: fetch,
370 Request: Request
371 };
372 }
373
374 var Request = NativeRequest; // Note that the "unfetch" minimal fetch polyfill defines fetch() without
375 // defining window.Request, and this polyfill need to work on top of unfetch
376 // hence we only patch it if it's available. Also we don't patch it if signal
377 // is already available on the Request prototype because in this case support
378 // is present and the patching below can cause a crash since it assigns to
379 // request.signal which is technically a read-only property. This latter error
380 // happens when you run the main5.js node-fetch example in the repo
381 // "abortcontroller-polyfill-examples". The exact error is:
382 // request.signal = init.signal;
383 // ^
384 // TypeError: Cannot set property signal of #<Request> which has only a getter
385
386 if (Request && !Request.prototype.hasOwnProperty('signal') || __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
387 Request = function Request(input, init) {
388 var signal;
389
390 if (init && init.signal) {
391 signal = init.signal; // Never pass init.signal to the native Request implementation when the polyfill has
392 // been installed because if we're running on top of a browser with a
393 // working native AbortController (i.e. the polyfill was installed due to
394 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
395 // fake AbortSignal to the native fetch will trigger:
396 // TypeError: Failed to construct 'Request': member signal is not of type AbortSignal.
397
398 delete init.signal;
399 }
400
401 var request = new NativeRequest(input, init);
402
403 if (signal) {
404 Object.defineProperty(request, 'signal', {
405 writable: false,
406 enumerable: false,
407 configurable: true,
408 value: signal
409 });
410 }
411
412 return request;
413 };
414
415 Request.prototype = NativeRequest.prototype;
416 }
417
418 var realFetch = fetch;
419
420 var abortableFetch = function abortableFetch(input, init) {
421 var signal = Request && Request.prototype.isPrototypeOf(input) ? input.signal : init ? init.signal : undefined;
422
423 if (signal) {
424 var abortError;
425
426 try {
427 abortError = new DOMException('Aborted', 'AbortError');
428 } catch (err) {
429 // IE 11 does not support calling the DOMException constructor, use a
430 // regular error object on it instead.
431 abortError = new Error('Aborted');
432 abortError.name = 'AbortError';
433 } // Return early if already aborted, thus avoiding making an HTTP request
434
435
436 if (signal.aborted) {
437 return Promise.reject(abortError);
438 } // Turn an event into a promise, reject it once `abort` is dispatched
439
440
441 var cancellation = new Promise(function (_, reject) {
442 signal.addEventListener('abort', function () {
443 return reject(abortError);
444 }, {
445 once: true
446 });
447 });
448
449 if (init && init.signal) {
450 // Never pass .signal to the native implementation when the polyfill has
451 // been installed because if we're running on top of a browser with a
452 // working native AbortController (i.e. the polyfill was installed due to
453 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
454 // fake AbortSignal to the native fetch will trigger:
455 // TypeError: Failed to execute 'fetch' on 'Window': member signal is not of type AbortSignal.
456 delete init.signal;
457 } // Return the fastest promise (don't need to wait for request to finish)
458
459
460 return Promise.race([cancellation, realFetch(input, init)]);
461 }
462
463 return realFetch(input, init);
464 };
465
466 return {
467 fetch: abortableFetch,
468 Request: Request
469 };
470 }
471
472 (function (self) {
473
474 if (!polyfillNeeded(self)) {
475 return;
476 }
477
478 if (!self.fetch) {
479 console.warn('fetch() is not available, cannot install abortcontroller-polyfill');
480 return;
481 }
482
483 var _abortableFetch = abortableFetchDecorator(self),
484 fetch = _abortableFetch.fetch,
485 Request = _abortableFetch.Request;
486
487 self.fetch = fetch;
488 self.Request = Request;
489 Object.defineProperty(self, 'AbortController', {
490 writable: true,
491 enumerable: false,
492 configurable: true,
493 value: AbortController
494 });
495 Object.defineProperty(self, 'AbortSignal', {
496 writable: true,
497 enumerable: false,
498 configurable: true,
499 value: AbortSignal
500 });
501 })(typeof self !== 'undefined' ? self : global);
502
503})));