1 | 'use strict';
|
2 |
|
3 | Object.defineProperty(exports, '__esModule', { value: true });
|
4 |
|
5 | function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
6 |
|
7 | var Stream = _interopDefault(require('stream'));
|
8 | var http = _interopDefault(require('http'));
|
9 | var Url = _interopDefault(require('url'));
|
10 | var whatwgUrl = _interopDefault(require('whatwg-url'));
|
11 | var https = _interopDefault(require('https'));
|
12 | var zlib = _interopDefault(require('zlib'));
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const Readable = Stream.Readable;
|
18 |
|
19 | const BUFFER = Symbol('buffer');
|
20 | const TYPE = Symbol('type');
|
21 |
|
22 | class Blob {
|
23 | constructor() {
|
24 | this[TYPE] = '';
|
25 |
|
26 | const blobParts = arguments[0];
|
27 | const options = arguments[1];
|
28 |
|
29 | const buffers = [];
|
30 | let size = 0;
|
31 |
|
32 | if (blobParts) {
|
33 | const a = blobParts;
|
34 | const length = Number(a.length);
|
35 | for (let i = 0; i < length; i++) {
|
36 | const element = a[i];
|
37 | let buffer;
|
38 | if (element instanceof Buffer) {
|
39 | buffer = element;
|
40 | } else if (ArrayBuffer.isView(element)) {
|
41 | buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
|
42 | } else if (element instanceof ArrayBuffer) {
|
43 | buffer = Buffer.from(element);
|
44 | } else if (element instanceof Blob) {
|
45 | buffer = element[BUFFER];
|
46 | } else {
|
47 | buffer = Buffer.from(typeof element === 'string' ? element : String(element));
|
48 | }
|
49 | size += buffer.length;
|
50 | buffers.push(buffer);
|
51 | }
|
52 | }
|
53 |
|
54 | this[BUFFER] = Buffer.concat(buffers);
|
55 |
|
56 | let type = options && options.type !== undefined && String(options.type).toLowerCase();
|
57 | if (type && !/[^\u0020-\u007E]/.test(type)) {
|
58 | this[TYPE] = type;
|
59 | }
|
60 | }
|
61 | get size() {
|
62 | return this[BUFFER].length;
|
63 | }
|
64 | get type() {
|
65 | return this[TYPE];
|
66 | }
|
67 | text() {
|
68 | return Promise.resolve(this[BUFFER].toString());
|
69 | }
|
70 | arrayBuffer() {
|
71 | const buf = this[BUFFER];
|
72 | const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
73 | return Promise.resolve(ab);
|
74 | }
|
75 | stream() {
|
76 | const readable = new Readable();
|
77 | readable._read = function () {};
|
78 | readable.push(this[BUFFER]);
|
79 | readable.push(null);
|
80 | return readable;
|
81 | }
|
82 | toString() {
|
83 | return '[object Blob]';
|
84 | }
|
85 | slice() {
|
86 | const size = this.size;
|
87 |
|
88 | const start = arguments[0];
|
89 | const end = arguments[1];
|
90 | let relativeStart, relativeEnd;
|
91 | if (start === undefined) {
|
92 | relativeStart = 0;
|
93 | } else if (start < 0) {
|
94 | relativeStart = Math.max(size + start, 0);
|
95 | } else {
|
96 | relativeStart = Math.min(start, size);
|
97 | }
|
98 | if (end === undefined) {
|
99 | relativeEnd = size;
|
100 | } else if (end < 0) {
|
101 | relativeEnd = Math.max(size + end, 0);
|
102 | } else {
|
103 | relativeEnd = Math.min(end, size);
|
104 | }
|
105 | const span = Math.max(relativeEnd - relativeStart, 0);
|
106 |
|
107 | const buffer = this[BUFFER];
|
108 | const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
|
109 | const blob = new Blob([], { type: arguments[2] });
|
110 | blob[BUFFER] = slicedBuffer;
|
111 | return blob;
|
112 | }
|
113 | }
|
114 |
|
115 | Object.defineProperties(Blob.prototype, {
|
116 | size: { enumerable: true },
|
117 | type: { enumerable: true },
|
118 | slice: { enumerable: true }
|
119 | });
|
120 |
|
121 | Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
|
122 | value: 'Blob',
|
123 | writable: false,
|
124 | enumerable: false,
|
125 | configurable: true
|
126 | });
|
127 |
|
128 |
|
129 |
|
130 |
|
131 |
|
132 |
|
133 |
|
134 |
|
135 |
|
136 |
|
137 |
|
138 |
|
139 |
|
140 |
|
141 |
|
142 | function FetchError(message, type, systemError) {
|
143 | Error.call(this, message);
|
144 |
|
145 | this.message = message;
|
146 | this.type = type;
|
147 |
|
148 |
|
149 | if (systemError) {
|
150 | this.code = this.errno = systemError.code;
|
151 | }
|
152 |
|
153 |
|
154 | Error.captureStackTrace(this, this.constructor);
|
155 | }
|
156 |
|
157 | FetchError.prototype = Object.create(Error.prototype);
|
158 | FetchError.prototype.constructor = FetchError;
|
159 | FetchError.prototype.name = 'FetchError';
|
160 |
|
161 | let convert;
|
162 | try {
|
163 | convert = require('encoding').convert;
|
164 | } catch (e) {}
|
165 |
|
166 | const INTERNALS = Symbol('Body internals');
|
167 |
|
168 |
|
169 | const PassThrough = Stream.PassThrough;
|
170 |
|
171 |
|
172 |
|
173 |
|
174 |
|
175 |
|
176 |
|
177 |
|
178 |
|
179 |
|
180 | function Body(body) {
|
181 | var _this = this;
|
182 |
|
183 | var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
|
184 | _ref$size = _ref.size;
|
185 |
|
186 | let size = _ref$size === undefined ? 0 : _ref$size;
|
187 | var _ref$timeout = _ref.timeout;
|
188 | let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
|
189 |
|
190 | if (body == null) {
|
191 |
|
192 | body = null;
|
193 | } else if (isURLSearchParams(body)) {
|
194 |
|
195 | body = Buffer.from(body.toString());
|
196 | } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
|
197 |
|
198 | body = Buffer.from(body);
|
199 | } else if (ArrayBuffer.isView(body)) {
|
200 |
|
201 | body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
|
202 | } else if (body instanceof Stream) ; else {
|
203 |
|
204 |
|
205 | body = Buffer.from(String(body));
|
206 | }
|
207 | this[INTERNALS] = {
|
208 | body,
|
209 | disturbed: false,
|
210 | error: null
|
211 | };
|
212 | this.size = size;
|
213 | this.timeout = timeout;
|
214 |
|
215 | if (body instanceof Stream) {
|
216 | body.on('error', function (err) {
|
217 | const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
|
218 | _this[INTERNALS].error = error;
|
219 | });
|
220 | }
|
221 | }
|
222 |
|
223 | Body.prototype = {
|
224 | get body() {
|
225 | return this[INTERNALS].body;
|
226 | },
|
227 |
|
228 | get bodyUsed() {
|
229 | return this[INTERNALS].disturbed;
|
230 | },
|
231 |
|
232 | |
233 |
|
234 |
|
235 |
|
236 |
|
237 | arrayBuffer() {
|
238 | return consumeBody.call(this).then(function (buf) {
|
239 | return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
240 | });
|
241 | },
|
242 |
|
243 | |
244 |
|
245 |
|
246 |
|
247 |
|
248 | blob() {
|
249 | let ct = this.headers && this.headers.get('content-type') || '';
|
250 | return consumeBody.call(this).then(function (buf) {
|
251 | return Object.assign(
|
252 |
|
253 | new Blob([], {
|
254 | type: ct.toLowerCase()
|
255 | }), {
|
256 | [BUFFER]: buf
|
257 | });
|
258 | });
|
259 | },
|
260 |
|
261 | |
262 |
|
263 |
|
264 |
|
265 |
|
266 | json() {
|
267 | var _this2 = this;
|
268 |
|
269 | return consumeBody.call(this).then(function (buffer) {
|
270 | try {
|
271 | return JSON.parse(buffer.toString());
|
272 | } catch (err) {
|
273 | return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
|
274 | }
|
275 | });
|
276 | },
|
277 |
|
278 | |
279 |
|
280 |
|
281 |
|
282 |
|
283 | text() {
|
284 | return consumeBody.call(this).then(function (buffer) {
|
285 | return buffer.toString();
|
286 | });
|
287 | },
|
288 |
|
289 | |
290 |
|
291 |
|
292 |
|
293 |
|
294 | buffer() {
|
295 | return consumeBody.call(this);
|
296 | },
|
297 |
|
298 | |
299 |
|
300 |
|
301 |
|
302 |
|
303 |
|
304 | textConverted() {
|
305 | var _this3 = this;
|
306 |
|
307 | return consumeBody.call(this).then(function (buffer) {
|
308 | return convertBody(buffer, _this3.headers);
|
309 | });
|
310 | }
|
311 | };
|
312 |
|
313 |
|
314 | Object.defineProperties(Body.prototype, {
|
315 | body: { enumerable: true },
|
316 | bodyUsed: { enumerable: true },
|
317 | arrayBuffer: { enumerable: true },
|
318 | blob: { enumerable: true },
|
319 | json: { enumerable: true },
|
320 | text: { enumerable: true }
|
321 | });
|
322 |
|
323 | Body.mixIn = function (proto) {
|
324 | for (const name of Object.getOwnPropertyNames(Body.prototype)) {
|
325 |
|
326 | if (!(name in proto)) {
|
327 | const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
|
328 | Object.defineProperty(proto, name, desc);
|
329 | }
|
330 | }
|
331 | };
|
332 |
|
333 |
|
334 |
|
335 |
|
336 |
|
337 |
|
338 |
|
339 |
|
340 | function consumeBody() {
|
341 | var _this4 = this;
|
342 |
|
343 | if (this[INTERNALS].disturbed) {
|
344 | return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
|
345 | }
|
346 |
|
347 | this[INTERNALS].disturbed = true;
|
348 |
|
349 | if (this[INTERNALS].error) {
|
350 | return Body.Promise.reject(this[INTERNALS].error);
|
351 | }
|
352 |
|
353 | let body = this.body;
|
354 |
|
355 |
|
356 | if (body === null) {
|
357 | return Body.Promise.resolve(Buffer.alloc(0));
|
358 | }
|
359 |
|
360 |
|
361 | if (isBlob(body)) {
|
362 | body = body.stream();
|
363 | }
|
364 |
|
365 |
|
366 | if (Buffer.isBuffer(body)) {
|
367 | return Body.Promise.resolve(body);
|
368 | }
|
369 |
|
370 |
|
371 | if (!(body instanceof Stream)) {
|
372 | return Body.Promise.resolve(Buffer.alloc(0));
|
373 | }
|
374 |
|
375 |
|
376 |
|
377 | let accum = [];
|
378 | let accumBytes = 0;
|
379 | let abort = false;
|
380 |
|
381 | return new Body.Promise(function (resolve, reject) {
|
382 | let resTimeout;
|
383 |
|
384 |
|
385 | if (_this4.timeout) {
|
386 | resTimeout = setTimeout(function () {
|
387 | abort = true;
|
388 | reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
|
389 | }, _this4.timeout);
|
390 | }
|
391 |
|
392 |
|
393 | body.on('error', function (err) {
|
394 | if (err.name === 'AbortError') {
|
395 |
|
396 | abort = true;
|
397 | reject(err);
|
398 | } else {
|
399 |
|
400 | reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
|
401 | }
|
402 | });
|
403 |
|
404 | body.on('data', function (chunk) {
|
405 | if (abort || chunk === null) {
|
406 | return;
|
407 | }
|
408 |
|
409 | if (_this4.size && accumBytes + chunk.length > _this4.size) {
|
410 | abort = true;
|
411 | reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
|
412 | return;
|
413 | }
|
414 |
|
415 | accumBytes += chunk.length;
|
416 | accum.push(chunk);
|
417 | });
|
418 |
|
419 | body.on('end', function () {
|
420 | if (abort) {
|
421 | return;
|
422 | }
|
423 |
|
424 | clearTimeout(resTimeout);
|
425 |
|
426 | try {
|
427 | resolve(Buffer.concat(accum, accumBytes));
|
428 | } catch (err) {
|
429 |
|
430 | reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
|
431 | }
|
432 | });
|
433 | });
|
434 | }
|
435 |
|
436 |
|
437 |
|
438 |
|
439 |
|
440 |
|
441 |
|
442 |
|
443 |
|
444 | function convertBody(buffer, headers) {
|
445 | if (typeof convert !== 'function') {
|
446 | throw new Error('The package `encoding` must be installed to use the textConverted() function');
|
447 | }
|
448 |
|
449 | const ct = headers.get('content-type');
|
450 | let charset = 'utf-8';
|
451 | let res, str;
|
452 |
|
453 |
|
454 | if (ct) {
|
455 | res = /charset=([^;]*)/i.exec(ct);
|
456 | }
|
457 |
|
458 |
|
459 | str = buffer.slice(0, 1024).toString();
|
460 |
|
461 |
|
462 | if (!res && str) {
|
463 | res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
|
464 | }
|
465 |
|
466 |
|
467 | if (!res && str) {
|
468 | res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
|
469 | if (!res) {
|
470 | res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
|
471 | if (res) {
|
472 | res.pop();
|
473 | }
|
474 | }
|
475 |
|
476 | if (res) {
|
477 | res = /charset=(.*)/i.exec(res.pop());
|
478 | }
|
479 | }
|
480 |
|
481 |
|
482 | if (!res && str) {
|
483 | res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
|
484 | }
|
485 |
|
486 |
|
487 | if (res) {
|
488 | charset = res.pop();
|
489 |
|
490 |
|
491 |
|
492 | if (charset === 'gb2312' || charset === 'gbk') {
|
493 | charset = 'gb18030';
|
494 | }
|
495 | }
|
496 |
|
497 |
|
498 | return convert(buffer, 'UTF-8', charset).toString();
|
499 | }
|
500 |
|
501 |
|
502 |
|
503 |
|
504 |
|
505 |
|
506 |
|
507 |
|
508 | function isURLSearchParams(obj) {
|
509 |
|
510 | if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') {
|
511 | return false;
|
512 | }
|
513 |
|
514 |
|
515 | return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
|
516 | }
|
517 |
|
518 |
|
519 |
|
520 |
|
521 |
|
522 |
|
523 | function isBlob(obj) {
|
524 | return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]);
|
525 | }
|
526 |
|
527 |
|
528 |
|
529 |
|
530 |
|
531 |
|
532 |
|
533 | function clone(instance) {
|
534 | let p1, p2;
|
535 | let body = instance.body;
|
536 |
|
537 |
|
538 | if (instance.bodyUsed) {
|
539 | throw new Error('cannot clone body after it is used');
|
540 | }
|
541 |
|
542 |
|
543 |
|
544 | if (body instanceof Stream && typeof body.getBoundary !== 'function') {
|
545 |
|
546 | p1 = new PassThrough();
|
547 | p2 = new PassThrough();
|
548 | body.pipe(p1);
|
549 | body.pipe(p2);
|
550 |
|
551 | instance[INTERNALS].body = p1;
|
552 | body = p2;
|
553 | }
|
554 |
|
555 | return body;
|
556 | }
|
557 |
|
558 |
|
559 |
|
560 |
|
561 |
|
562 |
|
563 |
|
564 |
|
565 |
|
566 |
|
567 | function extractContentType(body) {
|
568 | if (body === null) {
|
569 |
|
570 | return null;
|
571 | } else if (typeof body === 'string') {
|
572 |
|
573 | return 'text/plain;charset=UTF-8';
|
574 | } else if (isURLSearchParams(body)) {
|
575 |
|
576 | return 'application/x-www-form-urlencoded;charset=UTF-8';
|
577 | } else if (isBlob(body)) {
|
578 |
|
579 | return body.type || null;
|
580 | } else if (Buffer.isBuffer(body)) {
|
581 |
|
582 | return null;
|
583 | } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
|
584 |
|
585 | return null;
|
586 | } else if (ArrayBuffer.isView(body)) {
|
587 |
|
588 | return null;
|
589 | } else if (typeof body.getBoundary === 'function') {
|
590 |
|
591 | return `multipart/form-data;boundary=${body.getBoundary()}`;
|
592 | } else if (body instanceof Stream) {
|
593 |
|
594 |
|
595 | return null;
|
596 | } else {
|
597 |
|
598 | return 'text/plain;charset=UTF-8';
|
599 | }
|
600 | }
|
601 |
|
602 |
|
603 |
|
604 |
|
605 |
|
606 |
|
607 |
|
608 |
|
609 |
|
610 |
|
611 | function getTotalBytes(instance) {
|
612 | const body = instance.body;
|
613 |
|
614 |
|
615 | if (body === null) {
|
616 |
|
617 | return 0;
|
618 | } else if (isBlob(body)) {
|
619 | return body.size;
|
620 | } else if (Buffer.isBuffer(body)) {
|
621 |
|
622 | return body.length;
|
623 | } else if (body && typeof body.getLengthSync === 'function') {
|
624 |
|
625 | if (body._lengthRetrievers && body._lengthRetrievers.length == 0 ||
|
626 | body.hasKnownLength && body.hasKnownLength()) {
|
627 |
|
628 | return body.getLengthSync();
|
629 | }
|
630 | return null;
|
631 | } else {
|
632 |
|
633 | return null;
|
634 | }
|
635 | }
|
636 |
|
637 |
|
638 |
|
639 |
|
640 |
|
641 |
|
642 |
|
643 | function writeToStream(dest, instance) {
|
644 | const body = instance.body;
|
645 |
|
646 |
|
647 | if (body === null) {
|
648 |
|
649 | dest.end();
|
650 | } else if (isBlob(body)) {
|
651 | body.stream().pipe(dest);
|
652 | } else if (Buffer.isBuffer(body)) {
|
653 |
|
654 | dest.write(body);
|
655 | dest.end();
|
656 | } else {
|
657 |
|
658 | body.pipe(dest);
|
659 | }
|
660 | }
|
661 |
|
662 |
|
663 | Body.Promise = global.Promise;
|
664 |
|
665 |
|
666 |
|
667 |
|
668 |
|
669 |
|
670 |
|
671 | const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
|
672 | const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
|
673 |
|
674 | function validateName(name) {
|
675 | name = `${name}`;
|
676 | if (invalidTokenRegex.test(name) || name === '') {
|
677 | throw new TypeError(`${name} is not a legal HTTP header name`);
|
678 | }
|
679 | }
|
680 |
|
681 | function validateValue(value) {
|
682 | value = `${value}`;
|
683 | if (invalidHeaderCharRegex.test(value)) {
|
684 | throw new TypeError(`${value} is not a legal HTTP header value`);
|
685 | }
|
686 | }
|
687 |
|
688 |
|
689 |
|
690 |
|
691 |
|
692 |
|
693 |
|
694 |
|
695 |
|
696 | function find(map, name) {
|
697 | name = name.toLowerCase();
|
698 | for (const key in map) {
|
699 | if (key.toLowerCase() === name) {
|
700 | return key;
|
701 | }
|
702 | }
|
703 | return undefined;
|
704 | }
|
705 |
|
706 | const MAP = Symbol('map');
|
707 | class Headers {
|
708 | |
709 |
|
710 |
|
711 |
|
712 |
|
713 |
|
714 | constructor() {
|
715 | let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
|
716 |
|
717 | this[MAP] = Object.create(null);
|
718 |
|
719 | if (init instanceof Headers) {
|
720 | const rawHeaders = init.raw();
|
721 | const headerNames = Object.keys(rawHeaders);
|
722 |
|
723 | for (const headerName of headerNames) {
|
724 | for (const value of rawHeaders[headerName]) {
|
725 | this.append(headerName, value);
|
726 | }
|
727 | }
|
728 |
|
729 | return;
|
730 | }
|
731 |
|
732 |
|
733 |
|
734 | if (init == null) ; else if (typeof init === 'object') {
|
735 | const method = init[Symbol.iterator];
|
736 | if (method != null) {
|
737 | if (typeof method !== 'function') {
|
738 | throw new TypeError('Header pairs must be iterable');
|
739 | }
|
740 |
|
741 |
|
742 |
|
743 | const pairs = [];
|
744 | for (const pair of init) {
|
745 | if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
|
746 | throw new TypeError('Each header pair must be iterable');
|
747 | }
|
748 | pairs.push(Array.from(pair));
|
749 | }
|
750 |
|
751 | for (const pair of pairs) {
|
752 | if (pair.length !== 2) {
|
753 | throw new TypeError('Each header pair must be a name/value tuple');
|
754 | }
|
755 | this.append(pair[0], pair[1]);
|
756 | }
|
757 | } else {
|
758 |
|
759 | for (const key of Object.keys(init)) {
|
760 | const value = init[key];
|
761 | this.append(key, value);
|
762 | }
|
763 | }
|
764 | } else {
|
765 | throw new TypeError('Provided initializer must be an object');
|
766 | }
|
767 | }
|
768 |
|
769 | |
770 |
|
771 |
|
772 |
|
773 |
|
774 |
|
775 | get(name) {
|
776 | name = `${name}`;
|
777 | validateName(name);
|
778 | const key = find(this[MAP], name);
|
779 | if (key === undefined) {
|
780 | return null;
|
781 | }
|
782 |
|
783 | return this[MAP][key].join(', ');
|
784 | }
|
785 |
|
786 | |
787 |
|
788 |
|
789 |
|
790 |
|
791 |
|
792 |
|
793 | forEach(callback) {
|
794 | let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
|
795 |
|
796 | let pairs = getHeaders(this);
|
797 | let i = 0;
|
798 | while (i < pairs.length) {
|
799 | var _pairs$i = pairs[i];
|
800 | const name = _pairs$i[0],
|
801 | value = _pairs$i[1];
|
802 |
|
803 | callback.call(thisArg, value, name, this);
|
804 | pairs = getHeaders(this);
|
805 | i++;
|
806 | }
|
807 | }
|
808 |
|
809 | |
810 |
|
811 |
|
812 |
|
813 |
|
814 |
|
815 |
|
816 | set(name, value) {
|
817 | name = `${name}`;
|
818 | value = `${value}`;
|
819 | validateName(name);
|
820 | validateValue(value);
|
821 | const key = find(this[MAP], name);
|
822 | this[MAP][key !== undefined ? key : name] = [value];
|
823 | }
|
824 |
|
825 | |
826 |
|
827 |
|
828 |
|
829 |
|
830 |
|
831 |
|
832 | append(name, value) {
|
833 | name = `${name}`;
|
834 | value = `${value}`;
|
835 | validateName(name);
|
836 | validateValue(value);
|
837 | const key = find(this[MAP], name);
|
838 | if (key !== undefined) {
|
839 | this[MAP][key].push(value);
|
840 | } else {
|
841 | this[MAP][name] = [value];
|
842 | }
|
843 | }
|
844 |
|
845 | |
846 |
|
847 |
|
848 |
|
849 |
|
850 |
|
851 | has(name) {
|
852 | name = `${name}`;
|
853 | validateName(name);
|
854 | return find(this[MAP], name) !== undefined;
|
855 | }
|
856 |
|
857 | |
858 |
|
859 |
|
860 |
|
861 |
|
862 |
|
863 | delete(name) {
|
864 | name = `${name}`;
|
865 | validateName(name);
|
866 | const key = find(this[MAP], name);
|
867 | if (key !== undefined) {
|
868 | delete this[MAP][key];
|
869 | }
|
870 | }
|
871 |
|
872 | |
873 |
|
874 |
|
875 |
|
876 |
|
877 | raw() {
|
878 | return this[MAP];
|
879 | }
|
880 |
|
881 | |
882 |
|
883 |
|
884 |
|
885 |
|
886 | keys() {
|
887 | return createHeadersIterator(this, 'key');
|
888 | }
|
889 |
|
890 | |
891 |
|
892 |
|
893 |
|
894 |
|
895 | values() {
|
896 | return createHeadersIterator(this, 'value');
|
897 | }
|
898 |
|
899 | |
900 |
|
901 |
|
902 |
|
903 |
|
904 |
|
905 |
|
906 | [Symbol.iterator]() {
|
907 | return createHeadersIterator(this, 'key+value');
|
908 | }
|
909 | }
|
910 | Headers.prototype.entries = Headers.prototype[Symbol.iterator];
|
911 |
|
912 | Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
|
913 | value: 'Headers',
|
914 | writable: false,
|
915 | enumerable: false,
|
916 | configurable: true
|
917 | });
|
918 |
|
919 | Object.defineProperties(Headers.prototype, {
|
920 | get: { enumerable: true },
|
921 | forEach: { enumerable: true },
|
922 | set: { enumerable: true },
|
923 | append: { enumerable: true },
|
924 | has: { enumerable: true },
|
925 | delete: { enumerable: true },
|
926 | keys: { enumerable: true },
|
927 | values: { enumerable: true },
|
928 | entries: { enumerable: true }
|
929 | });
|
930 |
|
931 | function getHeaders(headers) {
|
932 | let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
|
933 |
|
934 | const keys = Object.keys(headers[MAP]).sort();
|
935 | return keys.map(kind === 'key' ? function (k) {
|
936 | return k.toLowerCase();
|
937 | } : kind === 'value' ? function (k) {
|
938 | return headers[MAP][k].join(', ');
|
939 | } : function (k) {
|
940 | return [k.toLowerCase(), headers[MAP][k].join(', ')];
|
941 | });
|
942 | }
|
943 |
|
944 | const INTERNAL = Symbol('internal');
|
945 |
|
946 | function createHeadersIterator(target, kind) {
|
947 | const iterator = Object.create(HeadersIteratorPrototype);
|
948 | iterator[INTERNAL] = {
|
949 | target,
|
950 | kind,
|
951 | index: 0
|
952 | };
|
953 | return iterator;
|
954 | }
|
955 |
|
956 | const HeadersIteratorPrototype = Object.setPrototypeOf({
|
957 | next() {
|
958 |
|
959 | if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
|
960 | throw new TypeError('Value of `this` is not a HeadersIterator');
|
961 | }
|
962 |
|
963 | var _INTERNAL = this[INTERNAL];
|
964 | const target = _INTERNAL.target,
|
965 | kind = _INTERNAL.kind,
|
966 | index = _INTERNAL.index;
|
967 |
|
968 | const values = getHeaders(target, kind);
|
969 | const len = values.length;
|
970 | if (index >= len) {
|
971 | return {
|
972 | value: undefined,
|
973 | done: true
|
974 | };
|
975 | }
|
976 |
|
977 | this[INTERNAL].index = index + 1;
|
978 |
|
979 | return {
|
980 | value: values[index],
|
981 | done: false
|
982 | };
|
983 | }
|
984 | }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
|
985 |
|
986 | Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
|
987 | value: 'HeadersIterator',
|
988 | writable: false,
|
989 | enumerable: false,
|
990 | configurable: true
|
991 | });
|
992 |
|
993 |
|
994 |
|
995 |
|
996 |
|
997 |
|
998 |
|
999 | function exportNodeCompatibleHeaders(headers) {
|
1000 | const obj = Object.assign({ __proto__: null }, headers[MAP]);
|
1001 |
|
1002 |
|
1003 |
|
1004 | const hostHeaderKey = find(headers[MAP], 'Host');
|
1005 | if (hostHeaderKey !== undefined) {
|
1006 | obj[hostHeaderKey] = obj[hostHeaderKey][0];
|
1007 | }
|
1008 |
|
1009 | return obj;
|
1010 | }
|
1011 |
|
1012 |
|
1013 |
|
1014 |
|
1015 |
|
1016 |
|
1017 |
|
1018 |
|
1019 | function createHeadersLenient(obj) {
|
1020 | const headers = new Headers();
|
1021 | for (const name of Object.keys(obj)) {
|
1022 | if (invalidTokenRegex.test(name)) {
|
1023 | continue;
|
1024 | }
|
1025 | if (Array.isArray(obj[name])) {
|
1026 | for (const val of obj[name]) {
|
1027 | if (invalidHeaderCharRegex.test(val)) {
|
1028 | continue;
|
1029 | }
|
1030 | if (headers[MAP][name] === undefined) {
|
1031 | headers[MAP][name] = [val];
|
1032 | } else {
|
1033 | headers[MAP][name].push(val);
|
1034 | }
|
1035 | }
|
1036 | } else if (!invalidHeaderCharRegex.test(obj[name])) {
|
1037 | headers[MAP][name] = [obj[name]];
|
1038 | }
|
1039 | }
|
1040 | return headers;
|
1041 | }
|
1042 |
|
1043 | const INTERNALS$1 = Symbol('Response internals');
|
1044 |
|
1045 |
|
1046 | const STATUS_CODES = http.STATUS_CODES;
|
1047 |
|
1048 |
|
1049 |
|
1050 |
|
1051 |
|
1052 |
|
1053 |
|
1054 |
|
1055 | class Response {
|
1056 | constructor() {
|
1057 | let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
|
1058 | let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
1059 |
|
1060 | Body.call(this, body, opts);
|
1061 |
|
1062 | const status = opts.status || 200;
|
1063 | const headers = new Headers(opts.headers);
|
1064 |
|
1065 | if (body != null && !headers.has('Content-Type')) {
|
1066 | const contentType = extractContentType(body);
|
1067 | if (contentType) {
|
1068 | headers.append('Content-Type', contentType);
|
1069 | }
|
1070 | }
|
1071 |
|
1072 | this[INTERNALS$1] = {
|
1073 | url: opts.url,
|
1074 | status,
|
1075 | statusText: opts.statusText || STATUS_CODES[status],
|
1076 | headers,
|
1077 | counter: opts.counter
|
1078 | };
|
1079 | }
|
1080 |
|
1081 | get url() {
|
1082 | return this[INTERNALS$1].url || '';
|
1083 | }
|
1084 |
|
1085 | get status() {
|
1086 | return this[INTERNALS$1].status;
|
1087 | }
|
1088 |
|
1089 | |
1090 |
|
1091 |
|
1092 | get ok() {
|
1093 | return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
|
1094 | }
|
1095 |
|
1096 | get redirected() {
|
1097 | return this[INTERNALS$1].counter > 0;
|
1098 | }
|
1099 |
|
1100 | get statusText() {
|
1101 | return this[INTERNALS$1].statusText;
|
1102 | }
|
1103 |
|
1104 | get headers() {
|
1105 | return this[INTERNALS$1].headers;
|
1106 | }
|
1107 |
|
1108 | |
1109 |
|
1110 |
|
1111 |
|
1112 |
|
1113 | clone() {
|
1114 | return new Response(clone(this), {
|
1115 | url: this.url,
|
1116 | status: this.status,
|
1117 | statusText: this.statusText,
|
1118 | headers: this.headers,
|
1119 | ok: this.ok,
|
1120 | redirected: this.redirected
|
1121 | });
|
1122 | }
|
1123 | }
|
1124 |
|
1125 | Body.mixIn(Response.prototype);
|
1126 |
|
1127 | Object.defineProperties(Response.prototype, {
|
1128 | url: { enumerable: true },
|
1129 | status: { enumerable: true },
|
1130 | ok: { enumerable: true },
|
1131 | redirected: { enumerable: true },
|
1132 | statusText: { enumerable: true },
|
1133 | headers: { enumerable: true },
|
1134 | clone: { enumerable: true }
|
1135 | });
|
1136 |
|
1137 | Object.defineProperty(Response.prototype, Symbol.toStringTag, {
|
1138 | value: 'Response',
|
1139 | writable: false,
|
1140 | enumerable: false,
|
1141 | configurable: true
|
1142 | });
|
1143 |
|
1144 | const INTERNALS$2 = Symbol('Request internals');
|
1145 | const URL = Url.URL || whatwgUrl.URL;
|
1146 |
|
1147 |
|
1148 | const parse_url = Url.parse;
|
1149 | const format_url = Url.format;
|
1150 |
|
1151 |
|
1152 |
|
1153 |
|
1154 |
|
1155 |
|
1156 |
|
1157 | function parseURL(urlStr) {
|
1158 | |
1159 |
|
1160 |
|
1161 |
|
1162 |
|
1163 | if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) {
|
1164 | urlStr = new URL(urlStr).toString();
|
1165 | }
|
1166 |
|
1167 |
|
1168 | return parse_url(urlStr);
|
1169 | }
|
1170 |
|
1171 | const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
|
1172 |
|
1173 |
|
1174 |
|
1175 |
|
1176 |
|
1177 |
|
1178 |
|
1179 | function isRequest(input) {
|
1180 | return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
|
1181 | }
|
1182 |
|
1183 | function isAbortSignal(signal) {
|
1184 | const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
|
1185 | return !!(proto && proto.constructor.name === 'AbortSignal');
|
1186 | }
|
1187 |
|
1188 |
|
1189 |
|
1190 |
|
1191 |
|
1192 |
|
1193 |
|
1194 |
|
1195 | class Request {
|
1196 | constructor(input) {
|
1197 | let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
1198 |
|
1199 | let parsedURL;
|
1200 |
|
1201 |
|
1202 | if (!isRequest(input)) {
|
1203 | if (input && input.href) {
|
1204 |
|
1205 |
|
1206 |
|
1207 | parsedURL = parseURL(input.href);
|
1208 | } else {
|
1209 |
|
1210 | parsedURL = parseURL(`${input}`);
|
1211 | }
|
1212 | input = {};
|
1213 | } else {
|
1214 | parsedURL = parseURL(input.url);
|
1215 | }
|
1216 |
|
1217 | let method = init.method || input.method || 'GET';
|
1218 | method = method.toUpperCase();
|
1219 |
|
1220 | if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
|
1221 | throw new TypeError('Request with GET/HEAD method cannot have body');
|
1222 | }
|
1223 |
|
1224 | let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
|
1225 |
|
1226 | Body.call(this, inputBody, {
|
1227 | timeout: init.timeout || input.timeout || 0,
|
1228 | size: init.size || input.size || 0
|
1229 | });
|
1230 |
|
1231 | const headers = new Headers(init.headers || input.headers || {});
|
1232 |
|
1233 | if (inputBody != null && !headers.has('Content-Type')) {
|
1234 | const contentType = extractContentType(inputBody);
|
1235 | if (contentType) {
|
1236 | headers.append('Content-Type', contentType);
|
1237 | }
|
1238 | }
|
1239 |
|
1240 | let signal = isRequest(input) ? input.signal : null;
|
1241 | if ('signal' in init) signal = init.signal;
|
1242 |
|
1243 | if (signal != null && !isAbortSignal(signal)) {
|
1244 | throw new TypeError('Expected signal to be an instanceof AbortSignal');
|
1245 | }
|
1246 |
|
1247 | this[INTERNALS$2] = {
|
1248 | method,
|
1249 | redirect: init.redirect || input.redirect || 'follow',
|
1250 | headers,
|
1251 | parsedURL,
|
1252 | signal
|
1253 | };
|
1254 |
|
1255 |
|
1256 | this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
|
1257 | this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
|
1258 | this.counter = init.counter || input.counter || 0;
|
1259 | this.agent = init.agent || input.agent;
|
1260 | }
|
1261 |
|
1262 | get method() {
|
1263 | return this[INTERNALS$2].method;
|
1264 | }
|
1265 |
|
1266 | get url() {
|
1267 | return format_url(this[INTERNALS$2].parsedURL);
|
1268 | }
|
1269 |
|
1270 | get headers() {
|
1271 | return this[INTERNALS$2].headers;
|
1272 | }
|
1273 |
|
1274 | get redirect() {
|
1275 | return this[INTERNALS$2].redirect;
|
1276 | }
|
1277 |
|
1278 | get signal() {
|
1279 | return this[INTERNALS$2].signal;
|
1280 | }
|
1281 |
|
1282 | |
1283 |
|
1284 |
|
1285 |
|
1286 |
|
1287 | clone() {
|
1288 | return new Request(this);
|
1289 | }
|
1290 | }
|
1291 |
|
1292 | Body.mixIn(Request.prototype);
|
1293 |
|
1294 | Object.defineProperty(Request.prototype, Symbol.toStringTag, {
|
1295 | value: 'Request',
|
1296 | writable: false,
|
1297 | enumerable: false,
|
1298 | configurable: true
|
1299 | });
|
1300 |
|
1301 | Object.defineProperties(Request.prototype, {
|
1302 | method: { enumerable: true },
|
1303 | url: { enumerable: true },
|
1304 | headers: { enumerable: true },
|
1305 | redirect: { enumerable: true },
|
1306 | clone: { enumerable: true },
|
1307 | signal: { enumerable: true }
|
1308 | });
|
1309 |
|
1310 |
|
1311 |
|
1312 |
|
1313 |
|
1314 |
|
1315 |
|
1316 | function getNodeRequestOptions(request) {
|
1317 | const parsedURL = request[INTERNALS$2].parsedURL;
|
1318 | const headers = new Headers(request[INTERNALS$2].headers);
|
1319 |
|
1320 |
|
1321 | if (!headers.has('Accept')) {
|
1322 | headers.set('Accept', '*/*');
|
1323 | }
|
1324 |
|
1325 |
|
1326 | if (!parsedURL.protocol || !parsedURL.hostname) {
|
1327 | throw new TypeError('Only absolute URLs are supported');
|
1328 | }
|
1329 |
|
1330 | if (!/^https?:$/.test(parsedURL.protocol)) {
|
1331 | throw new TypeError('Only HTTP(S) protocols are supported');
|
1332 | }
|
1333 |
|
1334 | if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
|
1335 | throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
|
1336 | }
|
1337 |
|
1338 |
|
1339 | let contentLengthValue = null;
|
1340 | if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
|
1341 | contentLengthValue = '0';
|
1342 | }
|
1343 | if (request.body != null) {
|
1344 | const totalBytes = getTotalBytes(request);
|
1345 | if (typeof totalBytes === 'number') {
|
1346 | contentLengthValue = String(totalBytes);
|
1347 | }
|
1348 | }
|
1349 | if (contentLengthValue) {
|
1350 | headers.set('Content-Length', contentLengthValue);
|
1351 | }
|
1352 |
|
1353 |
|
1354 | if (!headers.has('User-Agent')) {
|
1355 | headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
|
1356 | }
|
1357 |
|
1358 |
|
1359 | if (request.compress && !headers.has('Accept-Encoding')) {
|
1360 | headers.set('Accept-Encoding', 'gzip,deflate');
|
1361 | }
|
1362 |
|
1363 | let agent = request.agent;
|
1364 | if (typeof agent === 'function') {
|
1365 | agent = agent(parsedURL);
|
1366 | }
|
1367 |
|
1368 | if (!headers.has('Connection') && !agent) {
|
1369 | headers.set('Connection', 'close');
|
1370 | }
|
1371 |
|
1372 |
|
1373 |
|
1374 |
|
1375 | return Object.assign({}, parsedURL, {
|
1376 | method: request.method,
|
1377 | headers: exportNodeCompatibleHeaders(headers),
|
1378 | agent
|
1379 | });
|
1380 | }
|
1381 |
|
1382 |
|
1383 |
|
1384 |
|
1385 |
|
1386 |
|
1387 |
|
1388 |
|
1389 |
|
1390 |
|
1391 |
|
1392 |
|
1393 |
|
1394 | function AbortError(message) {
|
1395 | Error.call(this, message);
|
1396 |
|
1397 | this.type = 'aborted';
|
1398 | this.message = message;
|
1399 |
|
1400 |
|
1401 | Error.captureStackTrace(this, this.constructor);
|
1402 | }
|
1403 |
|
1404 | AbortError.prototype = Object.create(Error.prototype);
|
1405 | AbortError.prototype.constructor = AbortError;
|
1406 | AbortError.prototype.name = 'AbortError';
|
1407 |
|
1408 | const URL$1 = Url.URL || whatwgUrl.URL;
|
1409 |
|
1410 |
|
1411 | const PassThrough$1 = Stream.PassThrough;
|
1412 |
|
1413 | const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) {
|
1414 | const orig = new URL$1(original).hostname;
|
1415 | const dest = new URL$1(destination).hostname;
|
1416 |
|
1417 | return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest);
|
1418 | };
|
1419 |
|
1420 |
|
1421 |
|
1422 |
|
1423 |
|
1424 |
|
1425 |
|
1426 |
|
1427 | const isSameProtocol = function isSameProtocol(destination, original) {
|
1428 | const orig = new URL$1(original).protocol;
|
1429 | const dest = new URL$1(destination).protocol;
|
1430 |
|
1431 | return orig === dest;
|
1432 | };
|
1433 |
|
1434 |
|
1435 |
|
1436 |
|
1437 |
|
1438 |
|
1439 |
|
1440 |
|
1441 | function fetch(url, opts) {
|
1442 |
|
1443 |
|
1444 | if (!fetch.Promise) {
|
1445 | throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
|
1446 | }
|
1447 |
|
1448 | Body.Promise = fetch.Promise;
|
1449 |
|
1450 |
|
1451 | return new fetch.Promise(function (resolve, reject) {
|
1452 |
|
1453 | const request = new Request(url, opts);
|
1454 | const options = getNodeRequestOptions(request);
|
1455 |
|
1456 | const send = (options.protocol === 'https:' ? https : http).request;
|
1457 | const signal = request.signal;
|
1458 |
|
1459 | let response = null;
|
1460 |
|
1461 | const abort = function abort() {
|
1462 | let error = new AbortError('The user aborted a request.');
|
1463 | reject(error);
|
1464 | if (request.body && request.body instanceof Stream.Readable) {
|
1465 | destroyStream(request.body, error);
|
1466 | }
|
1467 | if (!response || !response.body) return;
|
1468 | response.body.emit('error', error);
|
1469 | };
|
1470 |
|
1471 | if (signal && signal.aborted) {
|
1472 | abort();
|
1473 | return;
|
1474 | }
|
1475 |
|
1476 | const abortAndFinalize = function abortAndFinalize() {
|
1477 | abort();
|
1478 | finalize();
|
1479 | };
|
1480 |
|
1481 |
|
1482 | const req = send(options);
|
1483 | let reqTimeout;
|
1484 |
|
1485 | if (signal) {
|
1486 | signal.addEventListener('abort', abortAndFinalize);
|
1487 | }
|
1488 |
|
1489 | function finalize() {
|
1490 | req.abort();
|
1491 | if (signal) signal.removeEventListener('abort', abortAndFinalize);
|
1492 | clearTimeout(reqTimeout);
|
1493 | }
|
1494 |
|
1495 | if (request.timeout) {
|
1496 | req.once('socket', function (socket) {
|
1497 | reqTimeout = setTimeout(function () {
|
1498 | reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
|
1499 | finalize();
|
1500 | }, request.timeout);
|
1501 | });
|
1502 | }
|
1503 |
|
1504 | req.on('error', function (err) {
|
1505 | reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
|
1506 |
|
1507 | if (response && response.body) {
|
1508 | destroyStream(response.body, err);
|
1509 | }
|
1510 |
|
1511 | finalize();
|
1512 | });
|
1513 |
|
1514 | fixResponseChunkedTransferBadEnding(req, function (err) {
|
1515 | if (signal && signal.aborted) {
|
1516 | return;
|
1517 | }
|
1518 |
|
1519 | if (response && response.body) {
|
1520 | destroyStream(response.body, err);
|
1521 | }
|
1522 | });
|
1523 |
|
1524 |
|
1525 | if (parseInt(process.version.substring(1)) < 14) {
|
1526 |
|
1527 |
|
1528 | req.on('socket', function (s) {
|
1529 | s.addListener('close', function (hadError) {
|
1530 |
|
1531 | const hasDataListener = s.listenerCount('data') > 0;
|
1532 |
|
1533 |
|
1534 | if (response && hasDataListener && !hadError && !(signal && signal.aborted)) {
|
1535 | const err = new Error('Premature close');
|
1536 | err.code = 'ERR_STREAM_PREMATURE_CLOSE';
|
1537 | response.body.emit('error', err);
|
1538 | }
|
1539 | });
|
1540 | });
|
1541 | }
|
1542 |
|
1543 | req.on('response', function (res) {
|
1544 | clearTimeout(reqTimeout);
|
1545 |
|
1546 | const headers = createHeadersLenient(res.headers);
|
1547 |
|
1548 |
|
1549 | if (fetch.isRedirect(res.statusCode)) {
|
1550 |
|
1551 | const location = headers.get('Location');
|
1552 |
|
1553 |
|
1554 | let locationURL = null;
|
1555 | try {
|
1556 | locationURL = location === null ? null : new URL$1(location, request.url).toString();
|
1557 | } catch (err) {
|
1558 |
|
1559 |
|
1560 |
|
1561 | if (request.redirect !== 'manual') {
|
1562 | reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
|
1563 | finalize();
|
1564 | return;
|
1565 | }
|
1566 | }
|
1567 |
|
1568 |
|
1569 | switch (request.redirect) {
|
1570 | case 'error':
|
1571 | reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
|
1572 | finalize();
|
1573 | return;
|
1574 | case 'manual':
|
1575 |
|
1576 | if (locationURL !== null) {
|
1577 |
|
1578 | try {
|
1579 | headers.set('Location', locationURL);
|
1580 | } catch (err) {
|
1581 |
|
1582 | reject(err);
|
1583 | }
|
1584 | }
|
1585 | break;
|
1586 | case 'follow':
|
1587 |
|
1588 | if (locationURL === null) {
|
1589 | break;
|
1590 | }
|
1591 |
|
1592 |
|
1593 | if (request.counter >= request.follow) {
|
1594 | reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
|
1595 | finalize();
|
1596 | return;
|
1597 | }
|
1598 |
|
1599 |
|
1600 |
|
1601 | const requestOpts = {
|
1602 | headers: new Headers(request.headers),
|
1603 | follow: request.follow,
|
1604 | counter: request.counter + 1,
|
1605 | agent: request.agent,
|
1606 | compress: request.compress,
|
1607 | method: request.method,
|
1608 | body: request.body,
|
1609 | signal: request.signal,
|
1610 | timeout: request.timeout,
|
1611 | size: request.size
|
1612 | };
|
1613 |
|
1614 | if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
|
1615 | for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
|
1616 | requestOpts.headers.delete(name);
|
1617 | }
|
1618 | }
|
1619 |
|
1620 |
|
1621 | if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
|
1622 | reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
|
1623 | finalize();
|
1624 | return;
|
1625 | }
|
1626 |
|
1627 |
|
1628 | if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
|
1629 | requestOpts.method = 'GET';
|
1630 | requestOpts.body = undefined;
|
1631 | requestOpts.headers.delete('content-length');
|
1632 | }
|
1633 |
|
1634 |
|
1635 | resolve(fetch(new Request(locationURL, requestOpts)));
|
1636 | finalize();
|
1637 | return;
|
1638 | }
|
1639 | }
|
1640 |
|
1641 |
|
1642 | res.once('end', function () {
|
1643 | if (signal) signal.removeEventListener('abort', abortAndFinalize);
|
1644 | });
|
1645 | let body = res.pipe(new PassThrough$1());
|
1646 |
|
1647 | const response_options = {
|
1648 | url: request.url,
|
1649 | status: res.statusCode,
|
1650 | statusText: res.statusMessage,
|
1651 | headers: headers,
|
1652 | size: request.size,
|
1653 | timeout: request.timeout,
|
1654 | counter: request.counter
|
1655 | };
|
1656 |
|
1657 |
|
1658 | const codings = headers.get('Content-Encoding');
|
1659 |
|
1660 |
|
1661 |
|
1662 |
|
1663 |
|
1664 |
|
1665 |
|
1666 |
|
1667 |
|
1668 | if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
|
1669 | response = new Response(body, response_options);
|
1670 | resolve(response);
|
1671 | return;
|
1672 | }
|
1673 |
|
1674 |
|
1675 |
|
1676 |
|
1677 |
|
1678 |
|
1679 | const zlibOptions = {
|
1680 | flush: zlib.Z_SYNC_FLUSH,
|
1681 | finishFlush: zlib.Z_SYNC_FLUSH
|
1682 | };
|
1683 |
|
1684 |
|
1685 | if (codings == 'gzip' || codings == 'x-gzip') {
|
1686 | body = body.pipe(zlib.createGunzip(zlibOptions));
|
1687 | response = new Response(body, response_options);
|
1688 | resolve(response);
|
1689 | return;
|
1690 | }
|
1691 |
|
1692 |
|
1693 | if (codings == 'deflate' || codings == 'x-deflate') {
|
1694 |
|
1695 |
|
1696 | const raw = res.pipe(new PassThrough$1());
|
1697 | raw.once('data', function (chunk) {
|
1698 |
|
1699 | if ((chunk[0] & 0x0F) === 0x08) {
|
1700 | body = body.pipe(zlib.createInflate());
|
1701 | } else {
|
1702 | body = body.pipe(zlib.createInflateRaw());
|
1703 | }
|
1704 | response = new Response(body, response_options);
|
1705 | resolve(response);
|
1706 | });
|
1707 | raw.on('end', function () {
|
1708 |
|
1709 | if (!response) {
|
1710 | response = new Response(body, response_options);
|
1711 | resolve(response);
|
1712 | }
|
1713 | });
|
1714 | return;
|
1715 | }
|
1716 |
|
1717 |
|
1718 | if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
|
1719 | body = body.pipe(zlib.createBrotliDecompress());
|
1720 | response = new Response(body, response_options);
|
1721 | resolve(response);
|
1722 | return;
|
1723 | }
|
1724 |
|
1725 |
|
1726 | response = new Response(body, response_options);
|
1727 | resolve(response);
|
1728 | });
|
1729 |
|
1730 | writeToStream(req, request);
|
1731 | });
|
1732 | }
|
1733 | function fixResponseChunkedTransferBadEnding(request, errorCallback) {
|
1734 | let socket;
|
1735 |
|
1736 | request.on('socket', function (s) {
|
1737 | socket = s;
|
1738 | });
|
1739 |
|
1740 | request.on('response', function (response) {
|
1741 | const headers = response.headers;
|
1742 |
|
1743 | if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) {
|
1744 | response.once('close', function (hadError) {
|
1745 |
|
1746 | const hasDataListener = socket.listenerCount('data') > 0;
|
1747 |
|
1748 | if (hasDataListener && !hadError) {
|
1749 | const err = new Error('Premature close');
|
1750 | err.code = 'ERR_STREAM_PREMATURE_CLOSE';
|
1751 | errorCallback(err);
|
1752 | }
|
1753 | });
|
1754 | }
|
1755 | });
|
1756 | }
|
1757 |
|
1758 | function destroyStream(stream, err) {
|
1759 | if (stream.destroy) {
|
1760 | stream.destroy(err);
|
1761 | } else {
|
1762 |
|
1763 | stream.emit('error', err);
|
1764 | stream.end();
|
1765 | }
|
1766 | }
|
1767 |
|
1768 |
|
1769 |
|
1770 |
|
1771 |
|
1772 |
|
1773 |
|
1774 | fetch.isRedirect = function (code) {
|
1775 | return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
|
1776 | };
|
1777 |
|
1778 |
|
1779 | fetch.Promise = global.Promise;
|
1780 |
|
1781 | module.exports = exports = fetch;
|
1782 | Object.defineProperty(exports, "__esModule", { value: true });
|
1783 | exports.default = exports;
|
1784 | exports.Headers = Headers;
|
1785 | exports.Request = Request;
|
1786 | exports.Response = Response;
|
1787 | exports.FetchError = FetchError;
|