1 process.emitWarning("The .es.js file is deprecated. Use .mjs instead.");
3 import Stream from 'stream';
4 import http from 'http';
6 import https from 'https';
7 import zlib from 'zlib';
9 // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
11 // fix for "Readable" isn't a named export issue
12 const Readable = Stream.Readable;
14 const BUFFER = Symbol('buffer');
15 const TYPE = Symbol('type');
21 const blobParts = arguments[0];
22 const options = arguments[1];
29 const length = Number(a.length);
30 for (let i = 0; i < length; i++) {
33 if (element instanceof Buffer) {
35 } else if (ArrayBuffer.isView(element)) {
36 buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
37 } else if (element instanceof ArrayBuffer) {
38 buffer = Buffer.from(element);
39 } else if (element instanceof Blob) {
40 buffer = element[BUFFER];
42 buffer = Buffer.from(typeof element === 'string' ? element : String(element));
44 size += buffer.length;
49 this[BUFFER] = Buffer.concat(buffers);
51 let type = options && options.type !== undefined && String(options.type).toLowerCase();
52 if (type && !/[^\u0020-\u007E]/.test(type)) {
57 return this[BUFFER].length;
63 return Promise.resolve(this[BUFFER].toString());
66 const buf = this[BUFFER];
67 const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
68 return Promise.resolve(ab);
71 const readable = new Readable();
72 readable._read = function () {};
73 readable.push(this[BUFFER]);
78 return '[object Blob]';
81 const size = this.size;
83 const start = arguments[0];
84 const end = arguments[1];
85 let relativeStart, relativeEnd;
86 if (start === undefined) {
88 } else if (start < 0) {
89 relativeStart = Math.max(size + start, 0);
91 relativeStart = Math.min(start, size);
93 if (end === undefined) {
96 relativeEnd = Math.max(size + end, 0);
98 relativeEnd = Math.min(end, size);
100 const span = Math.max(relativeEnd - relativeStart, 0);
102 const buffer = this[BUFFER];
103 const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
104 const blob = new Blob([], { type: arguments[2] });
105 blob[BUFFER] = slicedBuffer;
110 Object.defineProperties(Blob.prototype, {
111 size: { enumerable: true },
112 type: { enumerable: true },
113 slice: { enumerable: true }
116 Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
126 * FetchError interface for operational errors
130 * Create FetchError instance
132 * @param String message Error message for human
133 * @param String type Error type for machine
134 * @param String systemError For Node.js system error
137 function FetchError(message, type, systemError) {
138 Error.call(this, message);
140 this.message = message;
143 // when err.type is `system`, err.code contains system error code
145 this.code = this.errno = systemError.code;
148 // hide custom error implementation details from end-users
149 Error.captureStackTrace(this, this.constructor);
152 FetchError.prototype = Object.create(Error.prototype);
153 FetchError.prototype.constructor = FetchError;
154 FetchError.prototype.name = 'FetchError';
158 convert = require('encoding').convert;
161 const INTERNALS = Symbol('Body internals');
163 // fix an issue where "PassThrough" isn't a named export for node <10
164 const PassThrough = Stream.PassThrough;
169 * Ref: https://fetch.spec.whatwg.org/#body
171 * @param Stream body Readable stream
172 * @param Object opts Response options
175 function Body(body) {
178 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
179 _ref$size = _ref.size;
181 let size = _ref$size === undefined ? 0 : _ref$size;
182 var _ref$timeout = _ref.timeout;
183 let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
186 // body is undefined or null
188 } else if (isURLSearchParams(body)) {
189 // body is a URLSearchParams
190 body = Buffer.from(body.toString());
191 } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
192 // body is ArrayBuffer
193 body = Buffer.from(body);
194 } else if (ArrayBuffer.isView(body)) {
195 // body is ArrayBufferView
196 body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
197 } else if (body instanceof Stream) ; else {
199 // coerce to string then buffer
200 body = Buffer.from(String(body));
208 this.timeout = timeout;
210 if (body instanceof Stream) {
211 body.on('error', function (err) {
212 const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
213 _this[INTERNALS].error = error;
220 return this[INTERNALS].body;
224 return this[INTERNALS].disturbed;
228 * Decode response as ArrayBuffer
233 return consumeBody.call(this).then(function (buf) {
234 return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
239 * Return raw response as Blob
244 let ct = this.headers && this.headers.get('content-type') || '';
245 return consumeBody.call(this).then(function (buf) {
246 return Object.assign(
249 type: ct.toLowerCase()
257 * Decode response as json
264 return consumeBody.call(this).then(function (buffer) {
266 return JSON.parse(buffer.toString());
268 return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
274 * Decode response as text
279 return consumeBody.call(this).then(function (buffer) {
280 return buffer.toString();
285 * Decode response as buffer (non-spec api)
290 return consumeBody.call(this);
294 * Decode response as text, while automatically detecting the encoding and
295 * trying to decode to UTF-8 (non-spec api)
302 return consumeBody.call(this).then(function (buffer) {
303 return convertBody(buffer, _this3.headers);
308 // In browsers, all properties are enumerable.
309 Object.defineProperties(Body.prototype, {
310 body: { enumerable: true },
311 bodyUsed: { enumerable: true },
312 arrayBuffer: { enumerable: true },
313 blob: { enumerable: true },
314 json: { enumerable: true },
315 text: { enumerable: true }
318 Body.mixIn = function (proto) {
319 for (const name of Object.getOwnPropertyNames(Body.prototype)) {
320 // istanbul ignore else: future proof
321 if (!(name in proto)) {
322 const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
323 Object.defineProperty(proto, name, desc);
329 * Consume and convert an entire Body to a Buffer.
331 * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
335 function consumeBody() {
338 if (this[INTERNALS].disturbed) {
339 return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
342 this[INTERNALS].disturbed = true;
344 if (this[INTERNALS].error) {
345 return Body.Promise.reject(this[INTERNALS].error);
348 let body = this.body;
352 return Body.Promise.resolve(Buffer.alloc(0));
357 body = body.stream();
361 if (Buffer.isBuffer(body)) {
362 return Body.Promise.resolve(body);
365 // istanbul ignore if: should never happen
366 if (!(body instanceof Stream)) {
367 return Body.Promise.resolve(Buffer.alloc(0));
371 // get ready to actually consume the body
376 return new Body.Promise(function (resolve, reject) {
379 // allow timeout on slow response body
380 if (_this4.timeout) {
381 resTimeout = setTimeout(function () {
383 reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
387 // handle stream errors
388 body.on('error', function (err) {
389 if (err.name === 'AbortError') {
390 // if the request was aborted, reject with this Error
394 // other errors, such as incorrect content-encoding
395 reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
399 body.on('data', function (chunk) {
400 if (abort || chunk === null) {
404 if (_this4.size && accumBytes + chunk.length > _this4.size) {
406 reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
410 accumBytes += chunk.length;
414 body.on('end', function () {
419 clearTimeout(resTimeout);
422 resolve(Buffer.concat(accum, accumBytes));
424 // handle streams that have accumulated too much data (issue #414)
425 reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
432 * Detect buffer encoding and convert to target encoding
433 * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
435 * @param Buffer buffer Incoming buffer
436 * @param String encoding Target encoding
439 function convertBody(buffer, headers) {
440 if (typeof convert !== 'function') {
441 throw new Error('The package `encoding` must be installed to use the textConverted() function');
444 const ct = headers.get('content-type');
445 let charset = 'utf-8';
450 res = /charset=([^;]*)/i.exec(ct);
453 // no charset in content type, peek at response body for at most 1024 bytes
454 str = buffer.slice(0, 1024).toString();
458 res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
463 res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
465 res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
467 res.pop(); // drop last quote
472 res = /charset=(.*)/i.exec(res.pop());
478 res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
485 // prevent decode issues when sites use incorrect encoding
486 // ref: https://hsivonen.fi/encoding-menu/
487 if (charset === 'gb2312' || charset === 'gbk') {
492 // turn raw buffers into a single utf-8 buffer
493 return convert(buffer, 'UTF-8', charset).toString();
497 * Detect a URLSearchParams object
498 * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
500 * @param Object obj Object to detect by type or brand
503 function isURLSearchParams(obj) {
504 // Duck-typing as a necessary condition.
505 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') {
509 // Brand-checking and more duck-typing as optional condition.
510 return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
514 * Check if `obj` is a W3C `Blob` object (which `File` inherits from)
518 function isBlob(obj) {
519 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]);
523 * Clone body given Res/Req instance
525 * @param Mixed instance Response or Request instance
528 function clone(instance) {
530 let body = instance.body;
532 // don't allow cloning a used body
533 if (instance.bodyUsed) {
534 throw new Error('cannot clone body after it is used');
537 // check that body is a stream and not form-data object
538 // note: we can't clone the form-data object without having it as a dependency
539 if (body instanceof Stream && typeof body.getBoundary !== 'function') {
541 p1 = new PassThrough();
542 p2 = new PassThrough();
545 // set instance body to teed body and return the other teed body
546 instance[INTERNALS].body = p1;
554 * Performs the operation "extract a `Content-Type` value from |object|" as
555 * specified in the specification:
556 * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
558 * This function assumes that instance.body is present.
560 * @param Mixed instance Any options.body input
562 function extractContentType(body) {
566 } else if (typeof body === 'string') {
568 return 'text/plain;charset=UTF-8';
569 } else if (isURLSearchParams(body)) {
570 // body is a URLSearchParams
571 return 'application/x-www-form-urlencoded;charset=UTF-8';
572 } else if (isBlob(body)) {
574 return body.type || null;
575 } else if (Buffer.isBuffer(body)) {
578 } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
579 // body is ArrayBuffer
581 } else if (ArrayBuffer.isView(body)) {
582 // body is ArrayBufferView
584 } else if (typeof body.getBoundary === 'function') {
585 // detect form data input from form-data module
586 return `multipart/form-data;boundary=${body.getBoundary()}`;
587 } else if (body instanceof Stream) {
589 // can't really do much about this
592 // Body constructor defaults other things to string
593 return 'text/plain;charset=UTF-8';
598 * The Fetch Standard treats this as if "total bytes" is a property on the body.
599 * For us, we have to explicitly get it with a function.
601 * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
603 * @param Body instance Instance of Body
604 * @return Number? Number of bytes, or null if not possible
606 function getTotalBytes(instance) {
607 const body = instance.body;
613 } else if (isBlob(body)) {
615 } else if (Buffer.isBuffer(body)) {
618 } else if (body && typeof body.getLengthSync === 'function') {
619 // detect form data input from form-data module
620 if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
621 body.hasKnownLength && body.hasKnownLength()) {
623 return body.getLengthSync();
633 * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
635 * @param Body instance Instance of Body
638 function writeToStream(dest, instance) {
639 const body = instance.body;
645 } else if (isBlob(body)) {
646 body.stream().pipe(dest);
647 } else if (Buffer.isBuffer(body)) {
658 Body.Promise = global.Promise;
663 * Headers class offers convenient helpers
666 const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
667 const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
669 function validateName(name) {
671 if (invalidTokenRegex.test(name) || name === '') {
672 throw new TypeError(`${name} is not a legal HTTP header name`);
676 function validateValue(value) {
678 if (invalidHeaderCharRegex.test(value)) {
679 throw new TypeError(`${value} is not a legal HTTP header value`);
684 * Find the key in the map object given a header name.
686 * Returns undefined if not found.
688 * @param String name Header name
689 * @return String|Undefined
691 function find(map, name) {
692 name = name.toLowerCase();
693 for (const key in map) {
694 if (key.toLowerCase() === name) {
701 const MAP = Symbol('map');
706 * @param Object headers Response headers
710 let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
712 this[MAP] = Object.create(null);
714 if (init instanceof Headers) {
715 const rawHeaders = init.raw();
716 const headerNames = Object.keys(rawHeaders);
718 for (const headerName of headerNames) {
719 for (const value of rawHeaders[headerName]) {
720 this.append(headerName, value);
727 // We don't worry about converting prop to ByteString here as append()
729 if (init == null) ; else if (typeof init === 'object') {
730 const method = init[Symbol.iterator];
731 if (method != null) {
732 if (typeof method !== 'function') {
733 throw new TypeError('Header pairs must be iterable');
736 // sequence<sequence<ByteString>>
737 // Note: per spec we have to first exhaust the lists then process them
739 for (const pair of init) {
740 if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
741 throw new TypeError('Each header pair must be iterable');
743 pairs.push(Array.from(pair));
746 for (const pair of pairs) {
747 if (pair.length !== 2) {
748 throw new TypeError('Each header pair must be a name/value tuple');
750 this.append(pair[0], pair[1]);
753 // record<ByteString, ByteString>
754 for (const key of Object.keys(init)) {
755 const value = init[key];
756 this.append(key, value);
760 throw new TypeError('Provided initializer must be an object');
765 * Return combined header value given name
767 * @param String name Header name
773 const key = find(this[MAP], name);
774 if (key === undefined) {
778 return this[MAP][key].join(', ');
782 * Iterate over all headers
784 * @param Function callback Executed for each item with parameters (value, name, thisArg)
785 * @param Boolean thisArg `this` context for callback function
789 let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
791 let pairs = getHeaders(this);
793 while (i < pairs.length) {
794 var _pairs$i = pairs[i];
795 const name = _pairs$i[0],
798 callback.call(thisArg, value, name, this);
799 pairs = getHeaders(this);
805 * Overwrite header values given name
807 * @param String name Header name
808 * @param String value Header value
815 validateValue(value);
816 const key = find(this[MAP], name);
817 this[MAP][key !== undefined ? key : name] = [value];
821 * Append a value onto existing header
823 * @param String name Header name
824 * @param String value Header value
827 append(name, value) {
831 validateValue(value);
832 const key = find(this[MAP], name);
833 if (key !== undefined) {
834 this[MAP][key].push(value);
836 this[MAP][name] = [value];
841 * Check for header name existence
843 * @param String name Header name
849 return find(this[MAP], name) !== undefined;
853 * Delete all header values given name
855 * @param String name Header name
861 const key = find(this[MAP], name);
862 if (key !== undefined) {
863 delete this[MAP][key];
868 * Return raw headers (non-spec api)
877 * Get an iterator on keys.
882 return createHeadersIterator(this, 'key');
886 * Get an iterator on values.
891 return createHeadersIterator(this, 'value');
895 * Get an iterator on entries.
897 * This is the default iterator of the Headers object.
901 [Symbol.iterator]() {
902 return createHeadersIterator(this, 'key+value');
905 Headers.prototype.entries = Headers.prototype[Symbol.iterator];
907 Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
914 Object.defineProperties(Headers.prototype, {
915 get: { enumerable: true },
916 forEach: { enumerable: true },
917 set: { enumerable: true },
918 append: { enumerable: true },
919 has: { enumerable: true },
920 delete: { enumerable: true },
921 keys: { enumerable: true },
922 values: { enumerable: true },
923 entries: { enumerable: true }
926 function getHeaders(headers) {
927 let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
929 const keys = Object.keys(headers[MAP]).sort();
930 return keys.map(kind === 'key' ? function (k) {
931 return k.toLowerCase();
932 } : kind === 'value' ? function (k) {
933 return headers[MAP][k].join(', ');
935 return [k.toLowerCase(), headers[MAP][k].join(', ')];
939 const INTERNAL = Symbol('internal');
941 function createHeadersIterator(target, kind) {
942 const iterator = Object.create(HeadersIteratorPrototype);
943 iterator[INTERNAL] = {
951 const HeadersIteratorPrototype = Object.setPrototypeOf({
953 // istanbul ignore if
954 if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
955 throw new TypeError('Value of `this` is not a HeadersIterator');
958 var _INTERNAL = this[INTERNAL];
959 const target = _INTERNAL.target,
960 kind = _INTERNAL.kind,
961 index = _INTERNAL.index;
963 const values = getHeaders(target, kind);
964 const len = values.length;
972 this[INTERNAL].index = index + 1;
975 value: values[index],
979 }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
981 Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
982 value: 'HeadersIterator',
989 * Export the Headers object in a form that Node.js can consume.
991 * @param Headers headers
994 function exportNodeCompatibleHeaders(headers) {
995 const obj = Object.assign({ __proto__: null }, headers[MAP]);
997 // http.request() only supports string as Host header. This hack makes
998 // specifying custom Host header possible.
999 const hostHeaderKey = find(headers[MAP], 'Host');
1000 if (hostHeaderKey !== undefined) {
1001 obj[hostHeaderKey] = obj[hostHeaderKey][0];
1008 * Create a Headers object from an object of headers, ignoring those that do
1009 * not conform to HTTP grammar productions.
1011 * @param Object obj Object of headers
1014 function createHeadersLenient(obj) {
1015 const headers = new Headers();
1016 for (const name of Object.keys(obj)) {
1017 if (invalidTokenRegex.test(name)) {
1020 if (Array.isArray(obj[name])) {
1021 for (const val of obj[name]) {
1022 if (invalidHeaderCharRegex.test(val)) {
1025 if (headers[MAP][name] === undefined) {
1026 headers[MAP][name] = [val];
1028 headers[MAP][name].push(val);
1031 } else if (!invalidHeaderCharRegex.test(obj[name])) {
1032 headers[MAP][name] = [obj[name]];
1038 const INTERNALS$1 = Symbol('Response internals');
1040 // fix an issue where "STATUS_CODES" aren't a named export for node <10
1041 const STATUS_CODES = http.STATUS_CODES;
1046 * @param Stream body Readable stream
1047 * @param Object opts Response options
1052 let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
1053 let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1055 Body.call(this, body, opts);
1057 const status = opts.status || 200;
1058 const headers = new Headers(opts.headers);
1060 if (body != null && !headers.has('Content-Type')) {
1061 const contentType = extractContentType(body);
1063 headers.append('Content-Type', contentType);
1067 this[INTERNALS$1] = {
1070 statusText: opts.statusText || STATUS_CODES[status],
1072 counter: opts.counter
1077 return this[INTERNALS$1].url || '';
1081 return this[INTERNALS$1].status;
1085 * Convenience property representing if the request ended normally
1088 return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
1092 return this[INTERNALS$1].counter > 0;
1096 return this[INTERNALS$1].statusText;
1100 return this[INTERNALS$1].headers;
1104 * Clone this response
1109 return new Response(clone(this), {
1111 status: this.status,
1112 statusText: this.statusText,
1113 headers: this.headers,
1115 redirected: this.redirected
1120 Body.mixIn(Response.prototype);
1122 Object.defineProperties(Response.prototype, {
1123 url: { enumerable: true },
1124 status: { enumerable: true },
1125 ok: { enumerable: true },
1126 redirected: { enumerable: true },
1127 statusText: { enumerable: true },
1128 headers: { enumerable: true },
1129 clone: { enumerable: true }
1132 Object.defineProperty(Response.prototype, Symbol.toStringTag, {
1139 const INTERNALS$2 = Symbol('Request internals');
1141 // fix an issue where "format", "parse" aren't a named export for node <10
1142 const parse_url = Url.parse;
1143 const format_url = Url.format;
1145 const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
1148 * Check if a value is an instance of Request.
1150 * @param Mixed input
1153 function isRequest(input) {
1154 return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
1157 function isAbortSignal(signal) {
1158 const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
1159 return !!(proto && proto.constructor.name === 'AbortSignal');
1165 * @param Mixed input Url or Request instance
1166 * @param Object init Custom options
1170 constructor(input) {
1171 let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1176 if (!isRequest(input)) {
1177 if (input && input.href) {
1178 // in order to support Node.js' Url objects; though WHATWG's URL objects
1179 // will fall into this branch also (since their `toString()` will return
1180 // `href` property anyway)
1181 parsedURL = parse_url(input.href);
1183 // coerce input to a string before attempting to parse
1184 parsedURL = parse_url(`${input}`);
1188 parsedURL = parse_url(input.url);
1191 let method = init.method || input.method || 'GET';
1192 method = method.toUpperCase();
1194 if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
1195 throw new TypeError('Request with GET/HEAD method cannot have body');
1198 let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
1200 Body.call(this, inputBody, {
1201 timeout: init.timeout || input.timeout || 0,
1202 size: init.size || input.size || 0
1205 const headers = new Headers(init.headers || input.headers || {});
1207 if (inputBody != null && !headers.has('Content-Type')) {
1208 const contentType = extractContentType(inputBody);
1210 headers.append('Content-Type', contentType);
1214 let signal = isRequest(input) ? input.signal : null;
1215 if ('signal' in init) signal = init.signal;
1217 if (signal != null && !isAbortSignal(signal)) {
1218 throw new TypeError('Expected signal to be an instanceof AbortSignal');
1221 this[INTERNALS$2] = {
1223 redirect: init.redirect || input.redirect || 'follow',
1229 // node-fetch-only options
1230 this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
1231 this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
1232 this.counter = init.counter || input.counter || 0;
1233 this.agent = init.agent || input.agent;
1237 return this[INTERNALS$2].method;
1241 return format_url(this[INTERNALS$2].parsedURL);
1245 return this[INTERNALS$2].headers;
1249 return this[INTERNALS$2].redirect;
1253 return this[INTERNALS$2].signal;
1257 * Clone this request
1262 return new Request(this);
1266 Body.mixIn(Request.prototype);
1268 Object.defineProperty(Request.prototype, Symbol.toStringTag, {
1275 Object.defineProperties(Request.prototype, {
1276 method: { enumerable: true },
1277 url: { enumerable: true },
1278 headers: { enumerable: true },
1279 redirect: { enumerable: true },
1280 clone: { enumerable: true },
1281 signal: { enumerable: true }
1285 * Convert a Request to Node.js http request options.
1287 * @param Request A Request instance
1288 * @return Object The options object to be passed to http.request
1290 function getNodeRequestOptions(request) {
1291 const parsedURL = request[INTERNALS$2].parsedURL;
1292 const headers = new Headers(request[INTERNALS$2].headers);
1295 if (!headers.has('Accept')) {
1296 headers.set('Accept', '*/*');
1300 if (!parsedURL.protocol || !parsedURL.hostname) {
1301 throw new TypeError('Only absolute URLs are supported');
1304 if (!/^https?:$/.test(parsedURL.protocol)) {
1305 throw new TypeError('Only HTTP(S) protocols are supported');
1308 if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
1309 throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
1312 // HTTP-network-or-cache fetch steps 2.4-2.7
1313 let contentLengthValue = null;
1314 if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
1315 contentLengthValue = '0';
1317 if (request.body != null) {
1318 const totalBytes = getTotalBytes(request);
1319 if (typeof totalBytes === 'number') {
1320 contentLengthValue = String(totalBytes);
1323 if (contentLengthValue) {
1324 headers.set('Content-Length', contentLengthValue);
1327 // HTTP-network-or-cache fetch step 2.11
1328 if (!headers.has('User-Agent')) {
1329 headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
1332 // HTTP-network-or-cache fetch step 2.15
1333 if (request.compress && !headers.has('Accept-Encoding')) {
1334 headers.set('Accept-Encoding', 'gzip,deflate');
1337 let agent = request.agent;
1338 if (typeof agent === 'function') {
1339 agent = agent(parsedURL);
1342 if (!headers.has('Connection') && !agent) {
1343 headers.set('Connection', 'close');
1346 // HTTP-network fetch step 4.2
1347 // chunked encoding is handled by Node.js
1349 return Object.assign({}, parsedURL, {
1350 method: request.method,
1351 headers: exportNodeCompatibleHeaders(headers),
1359 * AbortError interface for cancelled requests
1363 * Create AbortError instance
1365 * @param String message Error message for human
1366 * @return AbortError
1368 function AbortError(message) {
1369 Error.call(this, message);
1371 this.type = 'aborted';
1372 this.message = message;
1374 // hide custom error implementation details from end-users
1375 Error.captureStackTrace(this, this.constructor);
1378 AbortError.prototype = Object.create(Error.prototype);
1379 AbortError.prototype.constructor = AbortError;
1380 AbortError.prototype.name = 'AbortError';
1382 // fix an issue where "PassThrough", "resolve" aren't a named export for node <10
1383 const PassThrough$1 = Stream.PassThrough;
1384 const resolve_url = Url.resolve;
1389 * @param Mixed url Absolute url or Request instance
1390 * @param Object opts Fetch options
1393 function fetch(url, opts) {
1395 // allow custom promise
1396 if (!fetch.Promise) {
1397 throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
1400 Body.Promise = fetch.Promise;
1402 // wrap http.request into fetch
1403 return new fetch.Promise(function (resolve, reject) {
1404 // build request object
1405 const request = new Request(url, opts);
1406 const options = getNodeRequestOptions(request);
1408 const send = (options.protocol === 'https:' ? https : http).request;
1409 const signal = request.signal;
1411 let response = null;
1413 const abort = function abort() {
1414 let error = new AbortError('The user aborted a request.');
1416 if (request.body && request.body instanceof Stream.Readable) {
1417 request.body.destroy(error);
1419 if (!response || !response.body) return;
1420 response.body.emit('error', error);
1423 if (signal && signal.aborted) {
1428 const abortAndFinalize = function abortAndFinalize() {
1434 const req = send(options);
1438 signal.addEventListener('abort', abortAndFinalize);
1441 function finalize() {
1443 if (signal) signal.removeEventListener('abort', abortAndFinalize);
1444 clearTimeout(reqTimeout);
1447 if (request.timeout) {
1448 req.once('socket', function (socket) {
1449 reqTimeout = setTimeout(function () {
1450 reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
1452 }, request.timeout);
1456 req.on('error', function (err) {
1457 reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
1461 req.on('response', function (res) {
1462 clearTimeout(reqTimeout);
1464 const headers = createHeadersLenient(res.headers);
1466 // HTTP fetch step 5
1467 if (fetch.isRedirect(res.statusCode)) {
1468 // HTTP fetch step 5.2
1469 const location = headers.get('Location');
1471 // HTTP fetch step 5.3
1472 const locationURL = location === null ? null : resolve_url(request.url, location);
1474 // HTTP fetch step 5.5
1475 switch (request.redirect) {
1477 reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
1481 // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
1482 if (locationURL !== null) {
1483 // handle corrupted header
1485 headers.set('Location', locationURL);
1487 // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
1493 // HTTP-redirect fetch step 2
1494 if (locationURL === null) {
1498 // HTTP-redirect fetch step 5
1499 if (request.counter >= request.follow) {
1500 reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
1505 // HTTP-redirect fetch step 6 (counter increment)
1506 // Create a new Request object.
1507 const requestOpts = {
1508 headers: new Headers(request.headers),
1509 follow: request.follow,
1510 counter: request.counter + 1,
1511 agent: request.agent,
1512 compress: request.compress,
1513 method: request.method,
1515 signal: request.signal,
1516 timeout: request.timeout,
1520 // HTTP-redirect fetch step 9
1521 if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
1522 reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
1527 // HTTP-redirect fetch step 11
1528 if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
1529 requestOpts.method = 'GET';
1530 requestOpts.body = undefined;
1531 requestOpts.headers.delete('content-length');
1534 // HTTP-redirect fetch step 15
1535 resolve(fetch(new Request(locationURL, requestOpts)));
1542 res.once('end', function () {
1543 if (signal) signal.removeEventListener('abort', abortAndFinalize);
1545 let body = res.pipe(new PassThrough$1());
1547 const response_options = {
1549 status: res.statusCode,
1550 statusText: res.statusMessage,
1553 timeout: request.timeout,
1554 counter: request.counter
1557 // HTTP-network fetch step 12.1.1.3
1558 const codings = headers.get('Content-Encoding');
1560 // HTTP-network fetch step 12.1.1.4: handle content codings
1562 // in following scenarios we ignore compression support
1563 // 1. compression support is disabled
1565 // 3. no Content-Encoding header
1566 // 4. no content response (204)
1567 // 5. content not modified response (304)
1568 if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
1569 response = new Response(body, response_options);
1575 // Be less strict when decoding compressed responses, since sometimes
1576 // servers send slightly invalid responses that are still accepted
1577 // by common browsers.
1578 // Always using Z_SYNC_FLUSH is what cURL does.
1579 const zlibOptions = {
1580 flush: zlib.Z_SYNC_FLUSH,
1581 finishFlush: zlib.Z_SYNC_FLUSH
1585 if (codings == 'gzip' || codings == 'x-gzip') {
1586 body = body.pipe(zlib.createGunzip(zlibOptions));
1587 response = new Response(body, response_options);
1593 if (codings == 'deflate' || codings == 'x-deflate') {
1594 // handle the infamous raw deflate response from old servers
1595 // a hack for old IIS and Apache servers
1596 const raw = res.pipe(new PassThrough$1());
1597 raw.once('data', function (chunk) {
1598 // see http://stackoverflow.com/questions/37519828
1599 if ((chunk[0] & 0x0F) === 0x08) {
1600 body = body.pipe(zlib.createInflate());
1602 body = body.pipe(zlib.createInflateRaw());
1604 response = new Response(body, response_options);
1611 if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
1612 body = body.pipe(zlib.createBrotliDecompress());
1613 response = new Response(body, response_options);
1618 // otherwise, use response as-is
1619 response = new Response(body, response_options);
1623 writeToStream(req, request);
1627 * Redirect code matching
1629 * @param Number code Status code
1632 fetch.isRedirect = function (code) {
1633 return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
1637 fetch.Promise = global.Promise;
1639 export default fetch;
1640 export { Headers, Request, Response, FetchError };