UNPKG

19.3 kBJavaScriptView Raw
1// Save global object in a variable
2var __global__ =
3(typeof globalThis !== 'undefined' && globalThis) ||
4(typeof self !== 'undefined' && self) ||
5(typeof global !== 'undefined' && global);
6// Create an object that extends from __global__ without the fetch function
7var __globalThis__ = (function () {
8function F() {
9this.fetch = false;
10this.DOMException = __global__.DOMException
11}
12F.prototype = __global__; // Needed for feature detection on whatwg-fetch's code
13return new F();
14})();
15// Wraps whatwg-fetch with a function scope to hijack the global object
16// "globalThis" that's going to be patched
17(function(globalThis) {
18
19var irrelevant = (function (exports) {
20
21 var global =
22 (typeof globalThis !== 'undefined' && globalThis) ||
23 (typeof self !== 'undefined' && self) ||
24 (typeof global !== 'undefined' && global);
25
26 var support = {
27 searchParams: 'URLSearchParams' in global,
28 iterable: 'Symbol' in global && 'iterator' in Symbol,
29 blob:
30 'FileReader' in global &&
31 'Blob' in global &&
32 (function() {
33 try {
34 new Blob();
35 return true
36 } catch (e) {
37 return false
38 }
39 })(),
40 formData: 'FormData' in global,
41 arrayBuffer: 'ArrayBuffer' in global
42 };
43
44 function isDataView(obj) {
45 return obj && DataView.prototype.isPrototypeOf(obj)
46 }
47
48 if (support.arrayBuffer) {
49 var viewClasses = [
50 '[object Int8Array]',
51 '[object Uint8Array]',
52 '[object Uint8ClampedArray]',
53 '[object Int16Array]',
54 '[object Uint16Array]',
55 '[object Int32Array]',
56 '[object Uint32Array]',
57 '[object Float32Array]',
58 '[object Float64Array]'
59 ];
60
61 var isArrayBufferView =
62 ArrayBuffer.isView ||
63 function(obj) {
64 return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1
65 };
66 }
67
68 function normalizeName(name) {
69 if (typeof name !== 'string') {
70 name = String(name);
71 }
72 if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name) || name === '') {
73 throw new TypeError('Invalid character in header field name: "' + name + '"')
74 }
75 return name.toLowerCase()
76 }
77
78 function normalizeValue(value) {
79 if (typeof value !== 'string') {
80 value = String(value);
81 }
82 return value
83 }
84
85 // Build a destructive iterator for the value list
86 function iteratorFor(items) {
87 var iterator = {
88 next: function() {
89 var value = items.shift();
90 return {done: value === undefined, value: value}
91 }
92 };
93
94 if (support.iterable) {
95 iterator[Symbol.iterator] = function() {
96 return iterator
97 };
98 }
99
100 return iterator
101 }
102
103 function Headers(headers) {
104 this.map = {};
105
106 if (headers instanceof Headers) {
107 headers.forEach(function(value, name) {
108 this.append(name, value);
109 }, this);
110 } else if (Array.isArray(headers)) {
111 headers.forEach(function(header) {
112 this.append(header[0], header[1]);
113 }, this);
114 } else if (headers) {
115 Object.getOwnPropertyNames(headers).forEach(function(name) {
116 this.append(name, headers[name]);
117 }, this);
118 }
119 }
120
121 Headers.prototype.append = function(name, value) {
122 name = normalizeName(name);
123 value = normalizeValue(value);
124 var oldValue = this.map[name];
125 this.map[name] = oldValue ? oldValue + ', ' + value : value;
126 };
127
128 Headers.prototype['delete'] = function(name) {
129 delete this.map[normalizeName(name)];
130 };
131
132 Headers.prototype.get = function(name) {
133 name = normalizeName(name);
134 return this.has(name) ? this.map[name] : null
135 };
136
137 Headers.prototype.has = function(name) {
138 return this.map.hasOwnProperty(normalizeName(name))
139 };
140
141 Headers.prototype.set = function(name, value) {
142 this.map[normalizeName(name)] = normalizeValue(value);
143 };
144
145 Headers.prototype.forEach = function(callback, thisArg) {
146 for (var name in this.map) {
147 if (this.map.hasOwnProperty(name)) {
148 callback.call(thisArg, this.map[name], name, this);
149 }
150 }
151 };
152
153 Headers.prototype.keys = function() {
154 var items = [];
155 this.forEach(function(value, name) {
156 items.push(name);
157 });
158 return iteratorFor(items)
159 };
160
161 Headers.prototype.values = function() {
162 var items = [];
163 this.forEach(function(value) {
164 items.push(value);
165 });
166 return iteratorFor(items)
167 };
168
169 Headers.prototype.entries = function() {
170 var items = [];
171 this.forEach(function(value, name) {
172 items.push([name, value]);
173 });
174 return iteratorFor(items)
175 };
176
177 if (support.iterable) {
178 Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
179 }
180
181 function consumed(body) {
182 if (body.bodyUsed) {
183 return Promise.reject(new TypeError('Already read'))
184 }
185 body.bodyUsed = true;
186 }
187
188 function fileReaderReady(reader) {
189 return new Promise(function(resolve, reject) {
190 reader.onload = function() {
191 resolve(reader.result);
192 };
193 reader.onerror = function() {
194 reject(reader.error);
195 };
196 })
197 }
198
199 function readBlobAsArrayBuffer(blob) {
200 var reader = new FileReader();
201 var promise = fileReaderReady(reader);
202 reader.readAsArrayBuffer(blob);
203 return promise
204 }
205
206 function readBlobAsText(blob) {
207 var reader = new FileReader();
208 var promise = fileReaderReady(reader);
209 reader.readAsText(blob);
210 return promise
211 }
212
213 function readArrayBufferAsText(buf) {
214 var view = new Uint8Array(buf);
215 var chars = new Array(view.length);
216
217 for (var i = 0; i < view.length; i++) {
218 chars[i] = String.fromCharCode(view[i]);
219 }
220 return chars.join('')
221 }
222
223 function bufferClone(buf) {
224 if (buf.slice) {
225 return buf.slice(0)
226 } else {
227 var view = new Uint8Array(buf.byteLength);
228 view.set(new Uint8Array(buf));
229 return view.buffer
230 }
231 }
232
233 function Body() {
234 this.bodyUsed = false;
235
236 this._initBody = function(body) {
237 /*
238 fetch-mock wraps the Response object in an ES6 Proxy to
239 provide useful test harness features such as flush. However, on
240 ES5 browsers without fetch or Proxy support pollyfills must be used;
241 the proxy-pollyfill is unable to proxy an attribute unless it exists
242 on the object before the Proxy is created. This change ensures
243 Response.bodyUsed exists on the instance, while maintaining the
244 semantic of setting Request.bodyUsed in the constructor before
245 _initBody is called.
246 */
247 this.bodyUsed = this.bodyUsed;
248 this._bodyInit = body;
249 if (!body) {
250 this._bodyText = '';
251 } else if (typeof body === 'string') {
252 this._bodyText = body;
253 } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
254 this._bodyBlob = body;
255 } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
256 this._bodyFormData = body;
257 } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
258 this._bodyText = body.toString();
259 } else if (support.arrayBuffer && support.blob && isDataView(body)) {
260 this._bodyArrayBuffer = bufferClone(body.buffer);
261 // IE 10-11 can't handle a DataView body.
262 this._bodyInit = new Blob([this._bodyArrayBuffer]);
263 } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
264 this._bodyArrayBuffer = bufferClone(body);
265 } else {
266 this._bodyText = body = Object.prototype.toString.call(body);
267 }
268
269 if (!this.headers.get('content-type')) {
270 if (typeof body === 'string') {
271 this.headers.set('content-type', 'text/plain;charset=UTF-8');
272 } else if (this._bodyBlob && this._bodyBlob.type) {
273 this.headers.set('content-type', this._bodyBlob.type);
274 } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
275 this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
276 }
277 }
278 };
279
280 if (support.blob) {
281 this.blob = function() {
282 var rejected = consumed(this);
283 if (rejected) {
284 return rejected
285 }
286
287 if (this._bodyBlob) {
288 return Promise.resolve(this._bodyBlob)
289 } else if (this._bodyArrayBuffer) {
290 return Promise.resolve(new Blob([this._bodyArrayBuffer]))
291 } else if (this._bodyFormData) {
292 throw new Error('could not read FormData body as blob')
293 } else {
294 return Promise.resolve(new Blob([this._bodyText]))
295 }
296 };
297
298 this.arrayBuffer = function() {
299 if (this._bodyArrayBuffer) {
300 var isConsumed = consumed(this);
301 if (isConsumed) {
302 return isConsumed
303 }
304 if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
305 return Promise.resolve(
306 this._bodyArrayBuffer.buffer.slice(
307 this._bodyArrayBuffer.byteOffset,
308 this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
309 )
310 )
311 } else {
312 return Promise.resolve(this._bodyArrayBuffer)
313 }
314 } else {
315 return this.blob().then(readBlobAsArrayBuffer)
316 }
317 };
318 }
319
320 this.text = function() {
321 var rejected = consumed(this);
322 if (rejected) {
323 return rejected
324 }
325
326 if (this._bodyBlob) {
327 return readBlobAsText(this._bodyBlob)
328 } else if (this._bodyArrayBuffer) {
329 return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))
330 } else if (this._bodyFormData) {
331 throw new Error('could not read FormData body as text')
332 } else {
333 return Promise.resolve(this._bodyText)
334 }
335 };
336
337 if (support.formData) {
338 this.formData = function() {
339 return this.text().then(decode)
340 };
341 }
342
343 this.json = function() {
344 return this.text().then(JSON.parse)
345 };
346
347 return this
348 }
349
350 // HTTP methods whose capitalization should be normalized
351 var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];
352
353 function normalizeMethod(method) {
354 var upcased = method.toUpperCase();
355 return methods.indexOf(upcased) > -1 ? upcased : method
356 }
357
358 function Request(input, options) {
359 if (!(this instanceof Request)) {
360 throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
361 }
362
363 options = options || {};
364 var body = options.body;
365
366 if (input instanceof Request) {
367 if (input.bodyUsed) {
368 throw new TypeError('Already read')
369 }
370 this.url = input.url;
371 this.credentials = input.credentials;
372 if (!options.headers) {
373 this.headers = new Headers(input.headers);
374 }
375 this.method = input.method;
376 this.mode = input.mode;
377 this.signal = input.signal;
378 if (!body && input._bodyInit != null) {
379 body = input._bodyInit;
380 input.bodyUsed = true;
381 }
382 } else {
383 this.url = String(input);
384 }
385
386 this.credentials = options.credentials || this.credentials || 'same-origin';
387 if (options.headers || !this.headers) {
388 this.headers = new Headers(options.headers);
389 }
390 this.method = normalizeMethod(options.method || this.method || 'GET');
391 this.mode = options.mode || this.mode || null;
392 this.signal = options.signal || this.signal;
393 this.referrer = null;
394
395 if ((this.method === 'GET' || this.method === 'HEAD') && body) {
396 throw new TypeError('Body not allowed for GET or HEAD requests')
397 }
398 this._initBody(body);
399
400 if (this.method === 'GET' || this.method === 'HEAD') {
401 if (options.cache === 'no-store' || options.cache === 'no-cache') {
402 // Search for a '_' parameter in the query string
403 var reParamSearch = /([?&])_=[^&]*/;
404 if (reParamSearch.test(this.url)) {
405 // If it already exists then set the value with the current time
406 this.url = this.url.replace(reParamSearch, '$1_=' + new Date().getTime());
407 } else {
408 // Otherwise add a new '_' parameter to the end with the current time
409 var reQueryString = /\?/;
410 this.url += (reQueryString.test(this.url) ? '&' : '?') + '_=' + new Date().getTime();
411 }
412 }
413 }
414 }
415
416 Request.prototype.clone = function() {
417 return new Request(this, {body: this._bodyInit})
418 };
419
420 function decode(body) {
421 var form = new FormData();
422 body
423 .trim()
424 .split('&')
425 .forEach(function(bytes) {
426 if (bytes) {
427 var split = bytes.split('=');
428 var name = split.shift().replace(/\+/g, ' ');
429 var value = split.join('=').replace(/\+/g, ' ');
430 form.append(decodeURIComponent(name), decodeURIComponent(value));
431 }
432 });
433 return form
434 }
435
436 function parseHeaders(rawHeaders) {
437 var headers = new Headers();
438 // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
439 // https://tools.ietf.org/html/rfc7230#section-3.2
440 var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
441 // Avoiding split via regex to work around a common IE11 bug with the core-js 3.6.0 regex polyfill
442 // https://github.com/github/fetch/issues/748
443 // https://github.com/zloirock/core-js/issues/751
444 preProcessedHeaders
445 .split('\r')
446 .map(function(header) {
447 return header.indexOf('\n') === 0 ? header.substr(1, header.length) : header
448 })
449 .forEach(function(line) {
450 var parts = line.split(':');
451 var key = parts.shift().trim();
452 if (key) {
453 var value = parts.join(':').trim();
454 headers.append(key, value);
455 }
456 });
457 return headers
458 }
459
460 Body.call(Request.prototype);
461
462 function Response(bodyInit, options) {
463 if (!(this instanceof Response)) {
464 throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.')
465 }
466 if (!options) {
467 options = {};
468 }
469
470 this.type = 'default';
471 this.status = options.status === undefined ? 200 : options.status;
472 this.ok = this.status >= 200 && this.status < 300;
473 this.statusText = options.statusText === undefined ? '' : '' + options.statusText;
474 this.headers = new Headers(options.headers);
475 this.url = options.url || '';
476 this._initBody(bodyInit);
477 }
478
479 Body.call(Response.prototype);
480
481 Response.prototype.clone = function() {
482 return new Response(this._bodyInit, {
483 status: this.status,
484 statusText: this.statusText,
485 headers: new Headers(this.headers),
486 url: this.url
487 })
488 };
489
490 Response.error = function() {
491 var response = new Response(null, {status: 0, statusText: ''});
492 response.type = 'error';
493 return response
494 };
495
496 var redirectStatuses = [301, 302, 303, 307, 308];
497
498 Response.redirect = function(url, status) {
499 if (redirectStatuses.indexOf(status) === -1) {
500 throw new RangeError('Invalid status code')
501 }
502
503 return new Response(null, {status: status, headers: {location: url}})
504 };
505
506 exports.DOMException = global.DOMException;
507 try {
508 new exports.DOMException();
509 } catch (err) {
510 exports.DOMException = function(message, name) {
511 this.message = message;
512 this.name = name;
513 var error = Error(message);
514 this.stack = error.stack;
515 };
516 exports.DOMException.prototype = Object.create(Error.prototype);
517 exports.DOMException.prototype.constructor = exports.DOMException;
518 }
519
520 function fetch(input, init) {
521 return new Promise(function(resolve, reject) {
522 var request = new Request(input, init);
523
524 if (request.signal && request.signal.aborted) {
525 return reject(new exports.DOMException('Aborted', 'AbortError'))
526 }
527
528 var xhr = new XMLHttpRequest();
529
530 function abortXhr() {
531 xhr.abort();
532 }
533
534 xhr.onload = function() {
535 var options = {
536 status: xhr.status,
537 statusText: xhr.statusText,
538 headers: parseHeaders(xhr.getAllResponseHeaders() || '')
539 };
540 options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
541 var body = 'response' in xhr ? xhr.response : xhr.responseText;
542 setTimeout(function() {
543 resolve(new Response(body, options));
544 }, 0);
545 };
546
547 xhr.onerror = function() {
548 setTimeout(function() {
549 reject(new TypeError('Network request failed'));
550 }, 0);
551 };
552
553 xhr.ontimeout = function() {
554 setTimeout(function() {
555 reject(new TypeError('Network request failed'));
556 }, 0);
557 };
558
559 xhr.onabort = function() {
560 setTimeout(function() {
561 reject(new exports.DOMException('Aborted', 'AbortError'));
562 }, 0);
563 };
564
565 function fixUrl(url) {
566 try {
567 return url === '' && global.location.href ? global.location.href : url
568 } catch (e) {
569 return url
570 }
571 }
572
573 xhr.open(request.method, fixUrl(request.url), true);
574
575 if (request.credentials === 'include') {
576 xhr.withCredentials = true;
577 } else if (request.credentials === 'omit') {
578 xhr.withCredentials = false;
579 }
580
581 if ('responseType' in xhr) {
582 if (support.blob) {
583 xhr.responseType = 'blob';
584 } else if (
585 support.arrayBuffer &&
586 request.headers.get('Content-Type') &&
587 request.headers.get('Content-Type').indexOf('application/octet-stream') !== -1
588 ) {
589 xhr.responseType = 'arraybuffer';
590 }
591 }
592
593 if (init && typeof init.headers === 'object' && !(init.headers instanceof Headers)) {
594 Object.getOwnPropertyNames(init.headers).forEach(function(name) {
595 xhr.setRequestHeader(name, normalizeValue(init.headers[name]));
596 });
597 } else {
598 request.headers.forEach(function(value, name) {
599 xhr.setRequestHeader(name, value);
600 });
601 }
602
603 if (request.signal) {
604 request.signal.addEventListener('abort', abortXhr);
605
606 xhr.onreadystatechange = function() {
607 // DONE (success or failure)
608 if (xhr.readyState === 4) {
609 request.signal.removeEventListener('abort', abortXhr);
610 }
611 };
612 }
613
614 xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
615 })
616 }
617
618 fetch.polyfill = true;
619
620 if (!global.fetch) {
621 global.fetch = fetch;
622 global.Headers = Headers;
623 global.Request = Request;
624 global.Response = Response;
625 }
626
627 exports.Headers = Headers;
628 exports.Request = Request;
629 exports.Response = Response;
630 exports.fetch = fetch;
631
632 return exports;
633
634})({});
635})(__globalThis__);
636// This is a ponyfill, so...
637__globalThis__.fetch.ponyfill = true;
638delete __globalThis__.fetch.polyfill;
639// Choose between native implementation (__global__) or custom implementation (__globalThis__)
640var ctx = __global__.fetch ? __global__ : __globalThis__;
641exports = ctx.fetch // To enable: import fetch from 'cross-fetch'
642exports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.
643exports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'
644exports.Headers = ctx.Headers
645exports.Request = ctx.Request
646exports.Response = ctx.Response
647module.exports = exports