UNPKG

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