UNPKG

13.6 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
3 typeof define === 'function' && define.amd ? define(factory) :
4 (factory());
5}(this, (function () { 'use strict';
6
7 var classCallCheck = function (instance, Constructor) {
8 if (!(instance instanceof Constructor)) {
9 throw new TypeError("Cannot call a class as a function");
10 }
11 };
12
13 var createClass = function () {
14 function defineProperties(target, props) {
15 for (var i = 0; i < props.length; i++) {
16 var descriptor = props[i];
17 descriptor.enumerable = descriptor.enumerable || false;
18 descriptor.configurable = true;
19 if ("value" in descriptor) descriptor.writable = true;
20 Object.defineProperty(target, descriptor.key, descriptor);
21 }
22 }
23
24 return function (Constructor, protoProps, staticProps) {
25 if (protoProps) defineProperties(Constructor.prototype, protoProps);
26 if (staticProps) defineProperties(Constructor, staticProps);
27 return Constructor;
28 };
29 }();
30
31 var get = function get(object, property, receiver) {
32 if (object === null) object = Function.prototype;
33 var desc = Object.getOwnPropertyDescriptor(object, property);
34
35 if (desc === undefined) {
36 var parent = Object.getPrototypeOf(object);
37
38 if (parent === null) {
39 return undefined;
40 } else {
41 return get(parent, property, receiver);
42 }
43 } else if ("value" in desc) {
44 return desc.value;
45 } else {
46 var getter = desc.get;
47
48 if (getter === undefined) {
49 return undefined;
50 }
51
52 return getter.call(receiver);
53 }
54 };
55
56 var inherits = function (subClass, superClass) {
57 if (typeof superClass !== "function" && superClass !== null) {
58 throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
59 }
60
61 subClass.prototype = Object.create(superClass && superClass.prototype, {
62 constructor: {
63 value: subClass,
64 enumerable: false,
65 writable: true,
66 configurable: true
67 }
68 });
69 if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
70 };
71
72 var possibleConstructorReturn = function (self, call) {
73 if (!self) {
74 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
75 }
76
77 return call && (typeof call === "object" || typeof call === "function") ? call : self;
78 };
79
80 var Emitter = function () {
81 function Emitter() {
82 classCallCheck(this, Emitter);
83
84 this.listeners = {};
85 }
86
87 createClass(Emitter, [{
88 key: 'addEventListener',
89 value: function addEventListener(type, callback) {
90 if (!(type in this.listeners)) {
91 this.listeners[type] = [];
92 }
93 this.listeners[type].push(callback);
94 }
95 }, {
96 key: 'removeEventListener',
97 value: function removeEventListener(type, callback) {
98 if (!(type in this.listeners)) {
99 return;
100 }
101 var stack = this.listeners[type];
102 for (var i = 0, l = stack.length; i < l; i++) {
103 if (stack[i] === callback) {
104 stack.splice(i, 1);
105 return;
106 }
107 }
108 }
109 }, {
110 key: 'dispatchEvent',
111 value: function dispatchEvent(event) {
112 var _this = this;
113
114 if (!(event.type in this.listeners)) {
115 return;
116 }
117 var debounce = function debounce(callback) {
118 setTimeout(function () {
119 return callback.call(_this, event);
120 });
121 };
122 var stack = this.listeners[event.type];
123 for (var i = 0, l = stack.length; i < l; i++) {
124 debounce(stack[i]);
125 }
126 return !event.defaultPrevented;
127 }
128 }]);
129 return Emitter;
130 }();
131
132 var AbortSignal = function (_Emitter) {
133 inherits(AbortSignal, _Emitter);
134
135 function AbortSignal() {
136 classCallCheck(this, AbortSignal);
137
138 var _this2 = possibleConstructorReturn(this, (AbortSignal.__proto__ || Object.getPrototypeOf(AbortSignal)).call(this));
139
140 _this2.aborted = false;
141 _this2.onabort = null;
142 return _this2;
143 }
144
145 createClass(AbortSignal, [{
146 key: 'toString',
147 value: function toString() {
148 return '[object AbortSignal]';
149 }
150 }, {
151 key: 'dispatchEvent',
152 value: function dispatchEvent(event) {
153 if (event.type === 'abort') {
154 this.aborted = true;
155 if (typeof this.onabort === 'function') {
156 this.onabort.call(this, event);
157 }
158 }
159
160 get(AbortSignal.prototype.__proto__ || Object.getPrototypeOf(AbortSignal.prototype), 'dispatchEvent', this).call(this, event);
161 }
162 }]);
163 return AbortSignal;
164 }(Emitter);
165
166 var AbortController = function () {
167 function AbortController() {
168 classCallCheck(this, AbortController);
169
170 this.signal = new AbortSignal();
171 }
172
173 createClass(AbortController, [{
174 key: 'abort',
175 value: function abort() {
176 var event = void 0;
177 try {
178 event = new Event('abort');
179 } catch (e) {
180 if (typeof document !== 'undefined') {
181 if (!document.createEvent) {
182 // For Internet Explorer 8:
183 event = document.createEventObject();
184 event.type = 'abort';
185 } else {
186 // For Internet Explorer 11:
187 event = document.createEvent('Event');
188 event.initEvent('abort', false, false);
189 }
190 } else {
191 // Fallback where document isn't available:
192 event = {
193 type: 'abort',
194 bubbles: false,
195 cancelable: false
196 };
197 }
198 }
199 this.signal.dispatchEvent(event);
200 }
201 }, {
202 key: 'toString',
203 value: function toString() {
204 return '[object AbortController]';
205 }
206 }]);
207 return AbortController;
208 }();
209
210 if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
211 // These are necessary to make sure that we get correct output for:
212 // Object.prototype.toString.call(new AbortController())
213 AbortController.prototype[Symbol.toStringTag] = 'AbortController';
214 AbortSignal.prototype[Symbol.toStringTag] = 'AbortSignal';
215 }
216
217 function polyfillNeeded(self) {
218 if (self.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
219 console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill');
220 return true;
221 }
222
223 // Note that the "unfetch" minimal fetch polyfill defines fetch() without
224 // defining window.Request, and this polyfill need to work on top of unfetch
225 // so the below feature detection needs the !self.AbortController part.
226 // The Request.prototype check is also needed because Safari versions 11.1.2
227 // up to and including 12.1.x has a window.AbortController present but still
228 // does NOT correctly implement abortable fetch:
229 // https://bugs.webkit.org/show_bug.cgi?id=174980#c2
230 return typeof self.Request === 'function' && !self.Request.prototype.hasOwnProperty('signal') || !self.AbortController;
231 }
232
233 /**
234 * Note: the "fetch.Request" default value is available for fetch imported from
235 * the "node-fetch" package and not in browsers. This is OK since browsers
236 * will be importing umd-polyfill.js from that path "self" is passed the
237 * decorator so the default value will not be used (because browsers that define
238 * fetch also has Request). One quirky setup where self.fetch exists but
239 * self.Request does not is when the "unfetch" minimal fetch polyfill is used
240 * on top of IE11; for this case the browser will try to use the fetch.Request
241 * default value which in turn will be undefined but then then "if (Request)"
242 * will ensure that you get a patched fetch but still no Request (as expected).
243 * @param {fetch, Request = fetch.Request}
244 * @returns {fetch: abortableFetch, Request: AbortableRequest}
245 */
246 function abortableFetchDecorator(patchTargets) {
247 if ('function' === typeof patchTargets) {
248 patchTargets = { fetch: patchTargets };
249 }
250
251 var _patchTargets = patchTargets,
252 fetch = _patchTargets.fetch,
253 _patchTargets$Request = _patchTargets.Request,
254 NativeRequest = _patchTargets$Request === undefined ? fetch.Request : _patchTargets$Request,
255 NativeAbortController = _patchTargets.AbortController,
256 _patchTargets$__FORCE = _patchTargets.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,
257 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL = _patchTargets$__FORCE === undefined ? false : _patchTargets$__FORCE;
258
259 if (!polyfillNeeded({ fetch: fetch, Request: NativeRequest, AbortController: NativeAbortController, __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL: __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL })) {
260 return { fetch: fetch, Request: Request };
261 }
262
263 var Request = NativeRequest;
264 // Note that the "unfetch" minimal fetch polyfill defines fetch() without
265 // defining window.Request, and this polyfill need to work on top of unfetch
266 // hence we only patch it if it's available. Also we don't patch it if signal
267 // is already available on the Request prototype because in this case support
268 // is present and the patching below can cause a crash since it assigns to
269 // request.signal which is technically a read-only property. This latter error
270 // happens when you run the main5.js node-fetch example in the repo
271 // "abortcontroller-polyfill-examples". The exact error is:
272 // request.signal = init.signal;
273 // ^
274 // TypeError: Cannot set property signal of #<Request> which has only a getter
275 if (Request && !Request.prototype.hasOwnProperty('signal') || __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
276 Request = function Request(input, init) {
277 var signal = void 0;
278 if (init && init.signal) {
279 signal = init.signal;
280 // Never pass init.signal to the native Request implementation when the polyfill has
281 // been installed because if we're running on top of a browser with a
282 // working native AbortController (i.e. the polyfill was installed due to
283 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
284 // fake AbortSignal to the native fetch will trigger:
285 // TypeError: Failed to construct 'Request': member signal is not of type AbortSignal.
286 delete init.signal;
287 }
288 var request = new NativeRequest(input, init);
289 if (signal) {
290 Object.defineProperty(request, 'signal', {
291 writable: false,
292 enumerable: false,
293 configurable: true,
294 value: signal
295 });
296 }
297 return request;
298 };
299 Request.prototype = NativeRequest.prototype;
300 }
301
302 var realFetch = fetch;
303 var abortableFetch = function abortableFetch(input, init) {
304 var signal = Request && Request.prototype.isPrototypeOf(input) ? input.signal : init ? init.signal : undefined;
305
306 if (signal) {
307 var abortError = void 0;
308 try {
309 abortError = new DOMException('Aborted', 'AbortError');
310 } catch (err) {
311 // IE 11 does not support calling the DOMException constructor, use a
312 // regular error object on it instead.
313 abortError = new Error('Aborted');
314 abortError.name = 'AbortError';
315 }
316
317 // Return early if already aborted, thus avoiding making an HTTP request
318 if (signal.aborted) {
319 return Promise.reject(abortError);
320 }
321
322 // Turn an event into a promise, reject it once `abort` is dispatched
323 var cancellation = new Promise(function (_, reject) {
324 signal.addEventListener('abort', function () {
325 return reject(abortError);
326 }, { once: true });
327 });
328
329 if (init && init.signal) {
330 // Never pass .signal to the native implementation when the polyfill has
331 // been installed because if we're running on top of a browser with a
332 // working native AbortController (i.e. the polyfill was installed due to
333 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
334 // fake AbortSignal to the native fetch will trigger:
335 // TypeError: Failed to execute 'fetch' on 'Window': member signal is not of type AbortSignal.
336 delete init.signal;
337 }
338 // Return the fastest promise (don't need to wait for request to finish)
339 return Promise.race([cancellation, realFetch(input, init)]);
340 }
341
342 return realFetch(input, init);
343 };
344
345 return { fetch: abortableFetch, Request: Request };
346 }
347
348 (function (self) {
349
350 if (!polyfillNeeded(self)) {
351 return;
352 }
353
354 if (!self.fetch) {
355 console.warn('fetch() is not available, cannot install abortcontroller-polyfill');
356 return;
357 }
358
359 var _abortableFetch = abortableFetchDecorator(self),
360 fetch = _abortableFetch.fetch,
361 Request = _abortableFetch.Request;
362
363 self.fetch = fetch;
364 self.Request = Request;
365
366 Object.defineProperty(self, 'AbortController', {
367 writable: true,
368 enumerable: false,
369 configurable: true,
370 value: AbortController
371 });
372
373 Object.defineProperty(self, 'AbortSignal', {
374 writable: true,
375 enumerable: false,
376 configurable: true,
377 value: AbortSignal
378 });
379 })(typeof self !== 'undefined' ? self : global);
380
381})));