node-fetch.js 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  4. var Stream = _interopDefault(require('stream'));
  5. var http = _interopDefault(require('http'));
  6. var Url = _interopDefault(require('url'));
  7. var https = _interopDefault(require('https'));
  8. var zlib = _interopDefault(require('zlib'));
  9. // Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js
  10. // fix for "Readable" isn't a named export issue
  11. const Readable = Stream.Readable;
  12. const BUFFER = Symbol('buffer');
  13. const TYPE = Symbol('type');
  14. class Blob {
  15. constructor() {
  16. this[TYPE] = '';
  17. const blobParts = arguments[0];
  18. const options = arguments[1];
  19. const buffers = [];
  20. let size = 0;
  21. if (blobParts) {
  22. const a = blobParts;
  23. const length = Number(a.length);
  24. for (let i = 0; i < length; i++) {
  25. const element = a[i];
  26. let buffer;
  27. if (element instanceof Buffer) {
  28. buffer = element;
  29. } else if (ArrayBuffer.isView(element)) {
  30. buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength);
  31. } else if (element instanceof ArrayBuffer) {
  32. buffer = Buffer.from(element);
  33. } else if (element instanceof Blob) {
  34. buffer = element[BUFFER];
  35. } else {
  36. buffer = Buffer.from(typeof element === 'string' ? element : String(element));
  37. }
  38. size += buffer.length;
  39. buffers.push(buffer);
  40. }
  41. }
  42. this[BUFFER] = Buffer.concat(buffers);
  43. let type = options && options.type !== undefined && String(options.type).toLowerCase();
  44. if (type && !/[^\u0020-\u007E]/.test(type)) {
  45. this[TYPE] = type;
  46. }
  47. }
  48. get size() {
  49. return this[BUFFER].length;
  50. }
  51. get type() {
  52. return this[TYPE];
  53. }
  54. text() {
  55. return Promise.resolve(this[BUFFER].toString());
  56. }
  57. arrayBuffer() {
  58. const buf = this[BUFFER];
  59. const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
  60. return Promise.resolve(ab);
  61. }
  62. stream() {
  63. const readable = new Readable();
  64. readable._read = function () {};
  65. readable.push(this[BUFFER]);
  66. readable.push(null);
  67. return readable;
  68. }
  69. toString() {
  70. return '[object Blob]';
  71. }
  72. slice() {
  73. const size = this.size;
  74. const start = arguments[0];
  75. const end = arguments[1];
  76. let relativeStart, relativeEnd;
  77. if (start === undefined) {
  78. relativeStart = 0;
  79. } else if (start < 0) {
  80. relativeStart = Math.max(size + start, 0);
  81. } else {
  82. relativeStart = Math.min(start, size);
  83. }
  84. if (end === undefined) {
  85. relativeEnd = size;
  86. } else if (end < 0) {
  87. relativeEnd = Math.max(size + end, 0);
  88. } else {
  89. relativeEnd = Math.min(end, size);
  90. }
  91. const span = Math.max(relativeEnd - relativeStart, 0);
  92. const buffer = this[BUFFER];
  93. const slicedBuffer = buffer.slice(relativeStart, relativeStart + span);
  94. const blob = new Blob([], { type: arguments[2] });
  95. blob[BUFFER] = slicedBuffer;
  96. return blob;
  97. }
  98. }
  99. Object.defineProperties(Blob.prototype, {
  100. size: { enumerable: true },
  101. type: { enumerable: true },
  102. slice: { enumerable: true }
  103. });
  104. Object.defineProperty(Blob.prototype, Symbol.toStringTag, {
  105. value: 'Blob',
  106. writable: false,
  107. enumerable: false,
  108. configurable: true
  109. });
  110. /**
  111. * fetch-error.js
  112. *
  113. * FetchError interface for operational errors
  114. */
  115. /**
  116. * Create FetchError instance
  117. *
  118. * @param String message Error message for human
  119. * @param String type Error type for machine
  120. * @param String systemError For Node.js system error
  121. * @return FetchError
  122. */
  123. function FetchError(message, type, systemError) {
  124. Error.call(this, message);
  125. this.message = message;
  126. this.type = type;
  127. // when err.type is `system`, err.code contains system error code
  128. if (systemError) {
  129. this.code = this.errno = systemError.code;
  130. }
  131. // hide custom error implementation details from end-users
  132. Error.captureStackTrace(this, this.constructor);
  133. }
  134. FetchError.prototype = Object.create(Error.prototype);
  135. FetchError.prototype.constructor = FetchError;
  136. FetchError.prototype.name = 'FetchError';
  137. let convert;
  138. try {
  139. convert = require('encoding').convert;
  140. } catch (e) {}
  141. const INTERNALS = Symbol('Body internals');
  142. // fix an issue where "PassThrough" isn't a named export for node <10
  143. const PassThrough = Stream.PassThrough;
  144. /**
  145. * Body mixin
  146. *
  147. * Ref: https://fetch.spec.whatwg.org/#body
  148. *
  149. * @param Stream body Readable stream
  150. * @param Object opts Response options
  151. * @return Void
  152. */
  153. function Body(body) {
  154. var _this = this;
  155. var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
  156. _ref$size = _ref.size;
  157. let size = _ref$size === undefined ? 0 : _ref$size;
  158. var _ref$timeout = _ref.timeout;
  159. let timeout = _ref$timeout === undefined ? 0 : _ref$timeout;
  160. if (body == null) {
  161. // body is undefined or null
  162. body = null;
  163. } else if (isURLSearchParams(body)) {
  164. // body is a URLSearchParams
  165. body = Buffer.from(body.toString());
  166. } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
  167. // body is ArrayBuffer
  168. body = Buffer.from(body);
  169. } else if (ArrayBuffer.isView(body)) {
  170. // body is ArrayBufferView
  171. body = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
  172. } else if (body instanceof Stream) ; else {
  173. // none of the above
  174. // coerce to string then buffer
  175. body = Buffer.from(String(body));
  176. }
  177. this[INTERNALS] = {
  178. body,
  179. disturbed: false,
  180. error: null
  181. };
  182. this.size = size;
  183. this.timeout = timeout;
  184. if (body instanceof Stream) {
  185. body.on('error', function (err) {
  186. const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err);
  187. _this[INTERNALS].error = error;
  188. });
  189. }
  190. }
  191. Body.prototype = {
  192. get body() {
  193. return this[INTERNALS].body;
  194. },
  195. get bodyUsed() {
  196. return this[INTERNALS].disturbed;
  197. },
  198. /**
  199. * Decode response as ArrayBuffer
  200. *
  201. * @return Promise
  202. */
  203. arrayBuffer() {
  204. return consumeBody.call(this).then(function (buf) {
  205. return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
  206. });
  207. },
  208. /**
  209. * Return raw response as Blob
  210. *
  211. * @return Promise
  212. */
  213. blob() {
  214. let ct = this.headers && this.headers.get('content-type') || '';
  215. return consumeBody.call(this).then(function (buf) {
  216. return Object.assign(
  217. // Prevent copying
  218. new Blob([], {
  219. type: ct.toLowerCase()
  220. }), {
  221. [BUFFER]: buf
  222. });
  223. });
  224. },
  225. /**
  226. * Decode response as json
  227. *
  228. * @return Promise
  229. */
  230. json() {
  231. var _this2 = this;
  232. return consumeBody.call(this).then(function (buffer) {
  233. try {
  234. return JSON.parse(buffer.toString());
  235. } catch (err) {
  236. return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json'));
  237. }
  238. });
  239. },
  240. /**
  241. * Decode response as text
  242. *
  243. * @return Promise
  244. */
  245. text() {
  246. return consumeBody.call(this).then(function (buffer) {
  247. return buffer.toString();
  248. });
  249. },
  250. /**
  251. * Decode response as buffer (non-spec api)
  252. *
  253. * @return Promise
  254. */
  255. buffer() {
  256. return consumeBody.call(this);
  257. },
  258. /**
  259. * Decode response as text, while automatically detecting the encoding and
  260. * trying to decode to UTF-8 (non-spec api)
  261. *
  262. * @return Promise
  263. */
  264. textConverted() {
  265. var _this3 = this;
  266. return consumeBody.call(this).then(function (buffer) {
  267. return convertBody(buffer, _this3.headers);
  268. });
  269. }
  270. };
  271. // In browsers, all properties are enumerable.
  272. Object.defineProperties(Body.prototype, {
  273. body: { enumerable: true },
  274. bodyUsed: { enumerable: true },
  275. arrayBuffer: { enumerable: true },
  276. blob: { enumerable: true },
  277. json: { enumerable: true },
  278. text: { enumerable: true }
  279. });
  280. Body.mixIn = function (proto) {
  281. for (const name of Object.getOwnPropertyNames(Body.prototype)) {
  282. // istanbul ignore else: future proof
  283. if (!(name in proto)) {
  284. const desc = Object.getOwnPropertyDescriptor(Body.prototype, name);
  285. Object.defineProperty(proto, name, desc);
  286. }
  287. }
  288. };
  289. /**
  290. * Consume and convert an entire Body to a Buffer.
  291. *
  292. * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body
  293. *
  294. * @return Promise
  295. */
  296. function consumeBody() {
  297. var _this4 = this;
  298. if (this[INTERNALS].disturbed) {
  299. return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
  300. }
  301. this[INTERNALS].disturbed = true;
  302. if (this[INTERNALS].error) {
  303. return Body.Promise.reject(this[INTERNALS].error);
  304. }
  305. let body = this.body;
  306. // body is null
  307. if (body === null) {
  308. return Body.Promise.resolve(Buffer.alloc(0));
  309. }
  310. // body is blob
  311. if (isBlob(body)) {
  312. body = body.stream();
  313. }
  314. // body is buffer
  315. if (Buffer.isBuffer(body)) {
  316. return Body.Promise.resolve(body);
  317. }
  318. // istanbul ignore if: should never happen
  319. if (!(body instanceof Stream)) {
  320. return Body.Promise.resolve(Buffer.alloc(0));
  321. }
  322. // body is stream
  323. // get ready to actually consume the body
  324. let accum = [];
  325. let accumBytes = 0;
  326. let abort = false;
  327. return new Body.Promise(function (resolve, reject) {
  328. let resTimeout;
  329. // allow timeout on slow response body
  330. if (_this4.timeout) {
  331. resTimeout = setTimeout(function () {
  332. abort = true;
  333. reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout'));
  334. }, _this4.timeout);
  335. }
  336. // handle stream errors
  337. body.on('error', function (err) {
  338. if (err.name === 'AbortError') {
  339. // if the request was aborted, reject with this Error
  340. abort = true;
  341. reject(err);
  342. } else {
  343. // other errors, such as incorrect content-encoding
  344. reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err));
  345. }
  346. });
  347. body.on('data', function (chunk) {
  348. if (abort || chunk === null) {
  349. return;
  350. }
  351. if (_this4.size && accumBytes + chunk.length > _this4.size) {
  352. abort = true;
  353. reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size'));
  354. return;
  355. }
  356. accumBytes += chunk.length;
  357. accum.push(chunk);
  358. });
  359. body.on('end', function () {
  360. if (abort) {
  361. return;
  362. }
  363. clearTimeout(resTimeout);
  364. try {
  365. resolve(Buffer.concat(accum, accumBytes));
  366. } catch (err) {
  367. // handle streams that have accumulated too much data (issue #414)
  368. reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err));
  369. }
  370. });
  371. });
  372. }
  373. /**
  374. * Detect buffer encoding and convert to target encoding
  375. * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding
  376. *
  377. * @param Buffer buffer Incoming buffer
  378. * @param String encoding Target encoding
  379. * @return String
  380. */
  381. function convertBody(buffer, headers) {
  382. if (typeof convert !== 'function') {
  383. throw new Error('The package `encoding` must be installed to use the textConverted() function');
  384. }
  385. const ct = headers.get('content-type');
  386. let charset = 'utf-8';
  387. let res, str;
  388. // header
  389. if (ct) {
  390. res = /charset=([^;]*)/i.exec(ct);
  391. }
  392. // no charset in content type, peek at response body for at most 1024 bytes
  393. str = buffer.slice(0, 1024).toString();
  394. // html5
  395. if (!res && str) {
  396. res = /<meta.+?charset=(['"])(.+?)\1/i.exec(str);
  397. }
  398. // html4
  399. if (!res && str) {
  400. res = /<meta[\s]+?http-equiv=(['"])content-type\1[\s]+?content=(['"])(.+?)\2/i.exec(str);
  401. if (!res) {
  402. res = /<meta[\s]+?content=(['"])(.+?)\1[\s]+?http-equiv=(['"])content-type\3/i.exec(str);
  403. if (res) {
  404. res.pop(); // drop last quote
  405. }
  406. }
  407. if (res) {
  408. res = /charset=(.*)/i.exec(res.pop());
  409. }
  410. }
  411. // xml
  412. if (!res && str) {
  413. res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str);
  414. }
  415. // found charset
  416. if (res) {
  417. charset = res.pop();
  418. // prevent decode issues when sites use incorrect encoding
  419. // ref: https://hsivonen.fi/encoding-menu/
  420. if (charset === 'gb2312' || charset === 'gbk') {
  421. charset = 'gb18030';
  422. }
  423. }
  424. // turn raw buffers into a single utf-8 buffer
  425. return convert(buffer, 'UTF-8', charset).toString();
  426. }
  427. /**
  428. * Detect a URLSearchParams object
  429. * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143
  430. *
  431. * @param Object obj Object to detect by type or brand
  432. * @return String
  433. */
  434. function isURLSearchParams(obj) {
  435. // Duck-typing as a necessary condition.
  436. 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') {
  437. return false;
  438. }
  439. // Brand-checking and more duck-typing as optional condition.
  440. return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function';
  441. }
  442. /**
  443. * Check if `obj` is a W3C `Blob` object (which `File` inherits from)
  444. * @param {*} obj
  445. * @return {boolean}
  446. */
  447. function isBlob(obj) {
  448. 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]);
  449. }
  450. /**
  451. * Clone body given Res/Req instance
  452. *
  453. * @param Mixed instance Response or Request instance
  454. * @return Mixed
  455. */
  456. function clone(instance) {
  457. let p1, p2;
  458. let body = instance.body;
  459. // don't allow cloning a used body
  460. if (instance.bodyUsed) {
  461. throw new Error('cannot clone body after it is used');
  462. }
  463. // check that body is a stream and not form-data object
  464. // note: we can't clone the form-data object without having it as a dependency
  465. if (body instanceof Stream && typeof body.getBoundary !== 'function') {
  466. // tee instance body
  467. p1 = new PassThrough();
  468. p2 = new PassThrough();
  469. body.pipe(p1);
  470. body.pipe(p2);
  471. // set instance body to teed body and return the other teed body
  472. instance[INTERNALS].body = p1;
  473. body = p2;
  474. }
  475. return body;
  476. }
  477. /**
  478. * Performs the operation "extract a `Content-Type` value from |object|" as
  479. * specified in the specification:
  480. * https://fetch.spec.whatwg.org/#concept-bodyinit-extract
  481. *
  482. * This function assumes that instance.body is present.
  483. *
  484. * @param Mixed instance Any options.body input
  485. */
  486. function extractContentType(body) {
  487. if (body === null) {
  488. // body is null
  489. return null;
  490. } else if (typeof body === 'string') {
  491. // body is string
  492. return 'text/plain;charset=UTF-8';
  493. } else if (isURLSearchParams(body)) {
  494. // body is a URLSearchParams
  495. return 'application/x-www-form-urlencoded;charset=UTF-8';
  496. } else if (isBlob(body)) {
  497. // body is blob
  498. return body.type || null;
  499. } else if (Buffer.isBuffer(body)) {
  500. // body is buffer
  501. return null;
  502. } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') {
  503. // body is ArrayBuffer
  504. return null;
  505. } else if (ArrayBuffer.isView(body)) {
  506. // body is ArrayBufferView
  507. return null;
  508. } else if (typeof body.getBoundary === 'function') {
  509. // detect form data input from form-data module
  510. return `multipart/form-data;boundary=${body.getBoundary()}`;
  511. } else if (body instanceof Stream) {
  512. // body is stream
  513. // can't really do much about this
  514. return null;
  515. } else {
  516. // Body constructor defaults other things to string
  517. return 'text/plain;charset=UTF-8';
  518. }
  519. }
  520. /**
  521. * The Fetch Standard treats this as if "total bytes" is a property on the body.
  522. * For us, we have to explicitly get it with a function.
  523. *
  524. * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes
  525. *
  526. * @param Body instance Instance of Body
  527. * @return Number? Number of bytes, or null if not possible
  528. */
  529. function getTotalBytes(instance) {
  530. const body = instance.body;
  531. if (body === null) {
  532. // body is null
  533. return 0;
  534. } else if (isBlob(body)) {
  535. return body.size;
  536. } else if (Buffer.isBuffer(body)) {
  537. // body is buffer
  538. return body.length;
  539. } else if (body && typeof body.getLengthSync === 'function') {
  540. // detect form data input from form-data module
  541. if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x
  542. body.hasKnownLength && body.hasKnownLength()) {
  543. // 2.x
  544. return body.getLengthSync();
  545. }
  546. return null;
  547. } else {
  548. // body is stream
  549. return null;
  550. }
  551. }
  552. /**
  553. * Write a Body to a Node.js WritableStream (e.g. http.Request) object.
  554. *
  555. * @param Body instance Instance of Body
  556. * @return Void
  557. */
  558. function writeToStream(dest, instance) {
  559. const body = instance.body;
  560. if (body === null) {
  561. // body is null
  562. dest.end();
  563. } else if (isBlob(body)) {
  564. body.stream().pipe(dest);
  565. } else if (Buffer.isBuffer(body)) {
  566. // body is buffer
  567. dest.write(body);
  568. dest.end();
  569. } else {
  570. // body is stream
  571. body.pipe(dest);
  572. }
  573. }
  574. // expose Promise
  575. Body.Promise = global.Promise;
  576. /**
  577. * headers.js
  578. *
  579. * Headers class offers convenient helpers
  580. */
  581. const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/;
  582. const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
  583. function validateName(name) {
  584. name = `${name}`;
  585. if (invalidTokenRegex.test(name) || name === '') {
  586. throw new TypeError(`${name} is not a legal HTTP header name`);
  587. }
  588. }
  589. function validateValue(value) {
  590. value = `${value}`;
  591. if (invalidHeaderCharRegex.test(value)) {
  592. throw new TypeError(`${value} is not a legal HTTP header value`);
  593. }
  594. }
  595. /**
  596. * Find the key in the map object given a header name.
  597. *
  598. * Returns undefined if not found.
  599. *
  600. * @param String name Header name
  601. * @return String|Undefined
  602. */
  603. function find(map, name) {
  604. name = name.toLowerCase();
  605. for (const key in map) {
  606. if (key.toLowerCase() === name) {
  607. return key;
  608. }
  609. }
  610. return undefined;
  611. }
  612. const MAP = Symbol('map');
  613. class Headers {
  614. /**
  615. * Headers class
  616. *
  617. * @param Object headers Response headers
  618. * @return Void
  619. */
  620. constructor() {
  621. let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
  622. this[MAP] = Object.create(null);
  623. if (init instanceof Headers) {
  624. const rawHeaders = init.raw();
  625. const headerNames = Object.keys(rawHeaders);
  626. for (const headerName of headerNames) {
  627. for (const value of rawHeaders[headerName]) {
  628. this.append(headerName, value);
  629. }
  630. }
  631. return;
  632. }
  633. // We don't worry about converting prop to ByteString here as append()
  634. // will handle it.
  635. if (init == null) ; else if (typeof init === 'object') {
  636. const method = init[Symbol.iterator];
  637. if (method != null) {
  638. if (typeof method !== 'function') {
  639. throw new TypeError('Header pairs must be iterable');
  640. }
  641. // sequence<sequence<ByteString>>
  642. // Note: per spec we have to first exhaust the lists then process them
  643. const pairs = [];
  644. for (const pair of init) {
  645. if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') {
  646. throw new TypeError('Each header pair must be iterable');
  647. }
  648. pairs.push(Array.from(pair));
  649. }
  650. for (const pair of pairs) {
  651. if (pair.length !== 2) {
  652. throw new TypeError('Each header pair must be a name/value tuple');
  653. }
  654. this.append(pair[0], pair[1]);
  655. }
  656. } else {
  657. // record<ByteString, ByteString>
  658. for (const key of Object.keys(init)) {
  659. const value = init[key];
  660. this.append(key, value);
  661. }
  662. }
  663. } else {
  664. throw new TypeError('Provided initializer must be an object');
  665. }
  666. }
  667. /**
  668. * Return combined header value given name
  669. *
  670. * @param String name Header name
  671. * @return Mixed
  672. */
  673. get(name) {
  674. name = `${name}`;
  675. validateName(name);
  676. const key = find(this[MAP], name);
  677. if (key === undefined) {
  678. return null;
  679. }
  680. return this[MAP][key].join(', ');
  681. }
  682. /**
  683. * Iterate over all headers
  684. *
  685. * @param Function callback Executed for each item with parameters (value, name, thisArg)
  686. * @param Boolean thisArg `this` context for callback function
  687. * @return Void
  688. */
  689. forEach(callback) {
  690. let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
  691. let pairs = getHeaders(this);
  692. let i = 0;
  693. while (i < pairs.length) {
  694. var _pairs$i = pairs[i];
  695. const name = _pairs$i[0],
  696. value = _pairs$i[1];
  697. callback.call(thisArg, value, name, this);
  698. pairs = getHeaders(this);
  699. i++;
  700. }
  701. }
  702. /**
  703. * Overwrite header values given name
  704. *
  705. * @param String name Header name
  706. * @param String value Header value
  707. * @return Void
  708. */
  709. set(name, value) {
  710. name = `${name}`;
  711. value = `${value}`;
  712. validateName(name);
  713. validateValue(value);
  714. const key = find(this[MAP], name);
  715. this[MAP][key !== undefined ? key : name] = [value];
  716. }
  717. /**
  718. * Append a value onto existing header
  719. *
  720. * @param String name Header name
  721. * @param String value Header value
  722. * @return Void
  723. */
  724. append(name, value) {
  725. name = `${name}`;
  726. value = `${value}`;
  727. validateName(name);
  728. validateValue(value);
  729. const key = find(this[MAP], name);
  730. if (key !== undefined) {
  731. this[MAP][key].push(value);
  732. } else {
  733. this[MAP][name] = [value];
  734. }
  735. }
  736. /**
  737. * Check for header name existence
  738. *
  739. * @param String name Header name
  740. * @return Boolean
  741. */
  742. has(name) {
  743. name = `${name}`;
  744. validateName(name);
  745. return find(this[MAP], name) !== undefined;
  746. }
  747. /**
  748. * Delete all header values given name
  749. *
  750. * @param String name Header name
  751. * @return Void
  752. */
  753. delete(name) {
  754. name = `${name}`;
  755. validateName(name);
  756. const key = find(this[MAP], name);
  757. if (key !== undefined) {
  758. delete this[MAP][key];
  759. }
  760. }
  761. /**
  762. * Return raw headers (non-spec api)
  763. *
  764. * @return Object
  765. */
  766. raw() {
  767. return this[MAP];
  768. }
  769. /**
  770. * Get an iterator on keys.
  771. *
  772. * @return Iterator
  773. */
  774. keys() {
  775. return createHeadersIterator(this, 'key');
  776. }
  777. /**
  778. * Get an iterator on values.
  779. *
  780. * @return Iterator
  781. */
  782. values() {
  783. return createHeadersIterator(this, 'value');
  784. }
  785. /**
  786. * Get an iterator on entries.
  787. *
  788. * This is the default iterator of the Headers object.
  789. *
  790. * @return Iterator
  791. */
  792. [Symbol.iterator]() {
  793. return createHeadersIterator(this, 'key+value');
  794. }
  795. }
  796. Headers.prototype.entries = Headers.prototype[Symbol.iterator];
  797. Object.defineProperty(Headers.prototype, Symbol.toStringTag, {
  798. value: 'Headers',
  799. writable: false,
  800. enumerable: false,
  801. configurable: true
  802. });
  803. Object.defineProperties(Headers.prototype, {
  804. get: { enumerable: true },
  805. forEach: { enumerable: true },
  806. set: { enumerable: true },
  807. append: { enumerable: true },
  808. has: { enumerable: true },
  809. delete: { enumerable: true },
  810. keys: { enumerable: true },
  811. values: { enumerable: true },
  812. entries: { enumerable: true }
  813. });
  814. function getHeaders(headers) {
  815. let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value';
  816. const keys = Object.keys(headers[MAP]).sort();
  817. return keys.map(kind === 'key' ? function (k) {
  818. return k.toLowerCase();
  819. } : kind === 'value' ? function (k) {
  820. return headers[MAP][k].join(', ');
  821. } : function (k) {
  822. return [k.toLowerCase(), headers[MAP][k].join(', ')];
  823. });
  824. }
  825. const INTERNAL = Symbol('internal');
  826. function createHeadersIterator(target, kind) {
  827. const iterator = Object.create(HeadersIteratorPrototype);
  828. iterator[INTERNAL] = {
  829. target,
  830. kind,
  831. index: 0
  832. };
  833. return iterator;
  834. }
  835. const HeadersIteratorPrototype = Object.setPrototypeOf({
  836. next() {
  837. // istanbul ignore if
  838. if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) {
  839. throw new TypeError('Value of `this` is not a HeadersIterator');
  840. }
  841. var _INTERNAL = this[INTERNAL];
  842. const target = _INTERNAL.target,
  843. kind = _INTERNAL.kind,
  844. index = _INTERNAL.index;
  845. const values = getHeaders(target, kind);
  846. const len = values.length;
  847. if (index >= len) {
  848. return {
  849. value: undefined,
  850. done: true
  851. };
  852. }
  853. this[INTERNAL].index = index + 1;
  854. return {
  855. value: values[index],
  856. done: false
  857. };
  858. }
  859. }, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())));
  860. Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, {
  861. value: 'HeadersIterator',
  862. writable: false,
  863. enumerable: false,
  864. configurable: true
  865. });
  866. /**
  867. * Export the Headers object in a form that Node.js can consume.
  868. *
  869. * @param Headers headers
  870. * @return Object
  871. */
  872. function exportNodeCompatibleHeaders(headers) {
  873. const obj = Object.assign({ __proto__: null }, headers[MAP]);
  874. // http.request() only supports string as Host header. This hack makes
  875. // specifying custom Host header possible.
  876. const hostHeaderKey = find(headers[MAP], 'Host');
  877. if (hostHeaderKey !== undefined) {
  878. obj[hostHeaderKey] = obj[hostHeaderKey][0];
  879. }
  880. return obj;
  881. }
  882. /**
  883. * Create a Headers object from an object of headers, ignoring those that do
  884. * not conform to HTTP grammar productions.
  885. *
  886. * @param Object obj Object of headers
  887. * @return Headers
  888. */
  889. function createHeadersLenient(obj) {
  890. const headers = new Headers();
  891. for (const name of Object.keys(obj)) {
  892. if (invalidTokenRegex.test(name)) {
  893. continue;
  894. }
  895. if (Array.isArray(obj[name])) {
  896. for (const val of obj[name]) {
  897. if (invalidHeaderCharRegex.test(val)) {
  898. continue;
  899. }
  900. if (headers[MAP][name] === undefined) {
  901. headers[MAP][name] = [val];
  902. } else {
  903. headers[MAP][name].push(val);
  904. }
  905. }
  906. } else if (!invalidHeaderCharRegex.test(obj[name])) {
  907. headers[MAP][name] = [obj[name]];
  908. }
  909. }
  910. return headers;
  911. }
  912. const INTERNALS$1 = Symbol('Response internals');
  913. // fix an issue where "STATUS_CODES" aren't a named export for node <10
  914. const STATUS_CODES = http.STATUS_CODES;
  915. /**
  916. * Response class
  917. *
  918. * @param Stream body Readable stream
  919. * @param Object opts Response options
  920. * @return Void
  921. */
  922. class Response {
  923. constructor() {
  924. let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  925. let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  926. Body.call(this, body, opts);
  927. const status = opts.status || 200;
  928. const headers = new Headers(opts.headers);
  929. if (body != null && !headers.has('Content-Type')) {
  930. const contentType = extractContentType(body);
  931. if (contentType) {
  932. headers.append('Content-Type', contentType);
  933. }
  934. }
  935. this[INTERNALS$1] = {
  936. url: opts.url,
  937. status,
  938. statusText: opts.statusText || STATUS_CODES[status],
  939. headers,
  940. counter: opts.counter
  941. };
  942. }
  943. get url() {
  944. return this[INTERNALS$1].url || '';
  945. }
  946. get status() {
  947. return this[INTERNALS$1].status;
  948. }
  949. /**
  950. * Convenience property representing if the request ended normally
  951. */
  952. get ok() {
  953. return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300;
  954. }
  955. get redirected() {
  956. return this[INTERNALS$1].counter > 0;
  957. }
  958. get statusText() {
  959. return this[INTERNALS$1].statusText;
  960. }
  961. get headers() {
  962. return this[INTERNALS$1].headers;
  963. }
  964. /**
  965. * Clone this response
  966. *
  967. * @return Response
  968. */
  969. clone() {
  970. return new Response(clone(this), {
  971. url: this.url,
  972. status: this.status,
  973. statusText: this.statusText,
  974. headers: this.headers,
  975. ok: this.ok,
  976. redirected: this.redirected
  977. });
  978. }
  979. }
  980. Body.mixIn(Response.prototype);
  981. Object.defineProperties(Response.prototype, {
  982. url: { enumerable: true },
  983. status: { enumerable: true },
  984. ok: { enumerable: true },
  985. redirected: { enumerable: true },
  986. statusText: { enumerable: true },
  987. headers: { enumerable: true },
  988. clone: { enumerable: true }
  989. });
  990. Object.defineProperty(Response.prototype, Symbol.toStringTag, {
  991. value: 'Response',
  992. writable: false,
  993. enumerable: false,
  994. configurable: true
  995. });
  996. const INTERNALS$2 = Symbol('Request internals');
  997. // fix an issue where "format", "parse" aren't a named export for node <10
  998. const parse_url = Url.parse;
  999. const format_url = Url.format;
  1000. const streamDestructionSupported = 'destroy' in Stream.Readable.prototype;
  1001. /**
  1002. * Check if a value is an instance of Request.
  1003. *
  1004. * @param Mixed input
  1005. * @return Boolean
  1006. */
  1007. function isRequest(input) {
  1008. return typeof input === 'object' && typeof input[INTERNALS$2] === 'object';
  1009. }
  1010. function isAbortSignal(signal) {
  1011. const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal);
  1012. return !!(proto && proto.constructor.name === 'AbortSignal');
  1013. }
  1014. /**
  1015. * Request class
  1016. *
  1017. * @param Mixed input Url or Request instance
  1018. * @param Object init Custom options
  1019. * @return Void
  1020. */
  1021. class Request {
  1022. constructor(input) {
  1023. let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  1024. let parsedURL;
  1025. // normalize input
  1026. if (!isRequest(input)) {
  1027. if (input && input.href) {
  1028. // in order to support Node.js' Url objects; though WHATWG's URL objects
  1029. // will fall into this branch also (since their `toString()` will return
  1030. // `href` property anyway)
  1031. parsedURL = parse_url(input.href);
  1032. } else {
  1033. // coerce input to a string before attempting to parse
  1034. parsedURL = parse_url(`${input}`);
  1035. }
  1036. input = {};
  1037. } else {
  1038. parsedURL = parse_url(input.url);
  1039. }
  1040. let method = init.method || input.method || 'GET';
  1041. method = method.toUpperCase();
  1042. if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) {
  1043. throw new TypeError('Request with GET/HEAD method cannot have body');
  1044. }
  1045. let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
  1046. Body.call(this, inputBody, {
  1047. timeout: init.timeout || input.timeout || 0,
  1048. size: init.size || input.size || 0
  1049. });
  1050. const headers = new Headers(init.headers || input.headers || {});
  1051. if (inputBody != null && !headers.has('Content-Type')) {
  1052. const contentType = extractContentType(inputBody);
  1053. if (contentType) {
  1054. headers.append('Content-Type', contentType);
  1055. }
  1056. }
  1057. let signal = isRequest(input) ? input.signal : null;
  1058. if ('signal' in init) signal = init.signal;
  1059. if (signal != null && !isAbortSignal(signal)) {
  1060. throw new TypeError('Expected signal to be an instanceof AbortSignal');
  1061. }
  1062. this[INTERNALS$2] = {
  1063. method,
  1064. redirect: init.redirect || input.redirect || 'follow',
  1065. headers,
  1066. parsedURL,
  1067. signal
  1068. };
  1069. // node-fetch-only options
  1070. this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20;
  1071. this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true;
  1072. this.counter = init.counter || input.counter || 0;
  1073. this.agent = init.agent || input.agent;
  1074. }
  1075. get method() {
  1076. return this[INTERNALS$2].method;
  1077. }
  1078. get url() {
  1079. return format_url(this[INTERNALS$2].parsedURL);
  1080. }
  1081. get headers() {
  1082. return this[INTERNALS$2].headers;
  1083. }
  1084. get redirect() {
  1085. return this[INTERNALS$2].redirect;
  1086. }
  1087. get signal() {
  1088. return this[INTERNALS$2].signal;
  1089. }
  1090. /**
  1091. * Clone this request
  1092. *
  1093. * @return Request
  1094. */
  1095. clone() {
  1096. return new Request(this);
  1097. }
  1098. }
  1099. Body.mixIn(Request.prototype);
  1100. Object.defineProperty(Request.prototype, Symbol.toStringTag, {
  1101. value: 'Request',
  1102. writable: false,
  1103. enumerable: false,
  1104. configurable: true
  1105. });
  1106. Object.defineProperties(Request.prototype, {
  1107. method: { enumerable: true },
  1108. url: { enumerable: true },
  1109. headers: { enumerable: true },
  1110. redirect: { enumerable: true },
  1111. clone: { enumerable: true },
  1112. signal: { enumerable: true }
  1113. });
  1114. /**
  1115. * Convert a Request to Node.js http request options.
  1116. *
  1117. * @param Request A Request instance
  1118. * @return Object The options object to be passed to http.request
  1119. */
  1120. function getNodeRequestOptions(request) {
  1121. const parsedURL = request[INTERNALS$2].parsedURL;
  1122. const headers = new Headers(request[INTERNALS$2].headers);
  1123. // fetch step 1.3
  1124. if (!headers.has('Accept')) {
  1125. headers.set('Accept', '*/*');
  1126. }
  1127. // Basic fetch
  1128. if (!parsedURL.protocol || !parsedURL.hostname) {
  1129. throw new TypeError('Only absolute URLs are supported');
  1130. }
  1131. if (!/^https?:$/.test(parsedURL.protocol)) {
  1132. throw new TypeError('Only HTTP(S) protocols are supported');
  1133. }
  1134. if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) {
  1135. throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8');
  1136. }
  1137. // HTTP-network-or-cache fetch steps 2.4-2.7
  1138. let contentLengthValue = null;
  1139. if (request.body == null && /^(POST|PUT)$/i.test(request.method)) {
  1140. contentLengthValue = '0';
  1141. }
  1142. if (request.body != null) {
  1143. const totalBytes = getTotalBytes(request);
  1144. if (typeof totalBytes === 'number') {
  1145. contentLengthValue = String(totalBytes);
  1146. }
  1147. }
  1148. if (contentLengthValue) {
  1149. headers.set('Content-Length', contentLengthValue);
  1150. }
  1151. // HTTP-network-or-cache fetch step 2.11
  1152. if (!headers.has('User-Agent')) {
  1153. headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
  1154. }
  1155. // HTTP-network-or-cache fetch step 2.15
  1156. if (request.compress && !headers.has('Accept-Encoding')) {
  1157. headers.set('Accept-Encoding', 'gzip,deflate');
  1158. }
  1159. let agent = request.agent;
  1160. if (typeof agent === 'function') {
  1161. agent = agent(parsedURL);
  1162. }
  1163. if (!headers.has('Connection') && !agent) {
  1164. headers.set('Connection', 'close');
  1165. }
  1166. // HTTP-network fetch step 4.2
  1167. // chunked encoding is handled by Node.js
  1168. return Object.assign({}, parsedURL, {
  1169. method: request.method,
  1170. headers: exportNodeCompatibleHeaders(headers),
  1171. agent
  1172. });
  1173. }
  1174. /**
  1175. * abort-error.js
  1176. *
  1177. * AbortError interface for cancelled requests
  1178. */
  1179. /**
  1180. * Create AbortError instance
  1181. *
  1182. * @param String message Error message for human
  1183. * @return AbortError
  1184. */
  1185. function AbortError(message) {
  1186. Error.call(this, message);
  1187. this.type = 'aborted';
  1188. this.message = message;
  1189. // hide custom error implementation details from end-users
  1190. Error.captureStackTrace(this, this.constructor);
  1191. }
  1192. AbortError.prototype = Object.create(Error.prototype);
  1193. AbortError.prototype.constructor = AbortError;
  1194. AbortError.prototype.name = 'AbortError';
  1195. // fix an issue where "PassThrough", "resolve" aren't a named export for node <10
  1196. const PassThrough$1 = Stream.PassThrough;
  1197. const resolve_url = Url.resolve;
  1198. /**
  1199. * Fetch function
  1200. *
  1201. * @param Mixed url Absolute url or Request instance
  1202. * @param Object opts Fetch options
  1203. * @return Promise
  1204. */
  1205. function fetch(url, opts) {
  1206. // allow custom promise
  1207. if (!fetch.Promise) {
  1208. throw new Error('native promise missing, set fetch.Promise to your favorite alternative');
  1209. }
  1210. Body.Promise = fetch.Promise;
  1211. // wrap http.request into fetch
  1212. return new fetch.Promise(function (resolve, reject) {
  1213. // build request object
  1214. const request = new Request(url, opts);
  1215. const options = getNodeRequestOptions(request);
  1216. const send = (options.protocol === 'https:' ? https : http).request;
  1217. const signal = request.signal;
  1218. let response = null;
  1219. const abort = function abort() {
  1220. let error = new AbortError('The user aborted a request.');
  1221. reject(error);
  1222. if (request.body && request.body instanceof Stream.Readable) {
  1223. request.body.destroy(error);
  1224. }
  1225. if (!response || !response.body) return;
  1226. response.body.emit('error', error);
  1227. };
  1228. if (signal && signal.aborted) {
  1229. abort();
  1230. return;
  1231. }
  1232. const abortAndFinalize = function abortAndFinalize() {
  1233. abort();
  1234. finalize();
  1235. };
  1236. // send request
  1237. const req = send(options);
  1238. let reqTimeout;
  1239. if (signal) {
  1240. signal.addEventListener('abort', abortAndFinalize);
  1241. }
  1242. function finalize() {
  1243. req.abort();
  1244. if (signal) signal.removeEventListener('abort', abortAndFinalize);
  1245. clearTimeout(reqTimeout);
  1246. }
  1247. if (request.timeout) {
  1248. req.once('socket', function (socket) {
  1249. reqTimeout = setTimeout(function () {
  1250. reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
  1251. finalize();
  1252. }, request.timeout);
  1253. });
  1254. }
  1255. req.on('error', function (err) {
  1256. reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
  1257. finalize();
  1258. });
  1259. req.on('response', function (res) {
  1260. clearTimeout(reqTimeout);
  1261. const headers = createHeadersLenient(res.headers);
  1262. // HTTP fetch step 5
  1263. if (fetch.isRedirect(res.statusCode)) {
  1264. // HTTP fetch step 5.2
  1265. const location = headers.get('Location');
  1266. // HTTP fetch step 5.3
  1267. const locationURL = location === null ? null : resolve_url(request.url, location);
  1268. // HTTP fetch step 5.5
  1269. switch (request.redirect) {
  1270. case 'error':
  1271. reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect'));
  1272. finalize();
  1273. return;
  1274. case 'manual':
  1275. // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL.
  1276. if (locationURL !== null) {
  1277. // handle corrupted header
  1278. try {
  1279. headers.set('Location', locationURL);
  1280. } catch (err) {
  1281. // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request
  1282. reject(err);
  1283. }
  1284. }
  1285. break;
  1286. case 'follow':
  1287. // HTTP-redirect fetch step 2
  1288. if (locationURL === null) {
  1289. break;
  1290. }
  1291. // HTTP-redirect fetch step 5
  1292. if (request.counter >= request.follow) {
  1293. reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
  1294. finalize();
  1295. return;
  1296. }
  1297. // HTTP-redirect fetch step 6 (counter increment)
  1298. // Create a new Request object.
  1299. const requestOpts = {
  1300. headers: new Headers(request.headers),
  1301. follow: request.follow,
  1302. counter: request.counter + 1,
  1303. agent: request.agent,
  1304. compress: request.compress,
  1305. method: request.method,
  1306. body: request.body,
  1307. signal: request.signal,
  1308. timeout: request.timeout,
  1309. size: request.size
  1310. };
  1311. // HTTP-redirect fetch step 9
  1312. if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) {
  1313. reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect'));
  1314. finalize();
  1315. return;
  1316. }
  1317. // HTTP-redirect fetch step 11
  1318. if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') {
  1319. requestOpts.method = 'GET';
  1320. requestOpts.body = undefined;
  1321. requestOpts.headers.delete('content-length');
  1322. }
  1323. // HTTP-redirect fetch step 15
  1324. resolve(fetch(new Request(locationURL, requestOpts)));
  1325. finalize();
  1326. return;
  1327. }
  1328. }
  1329. // prepare response
  1330. res.once('end', function () {
  1331. if (signal) signal.removeEventListener('abort', abortAndFinalize);
  1332. });
  1333. let body = res.pipe(new PassThrough$1());
  1334. const response_options = {
  1335. url: request.url,
  1336. status: res.statusCode,
  1337. statusText: res.statusMessage,
  1338. headers: headers,
  1339. size: request.size,
  1340. timeout: request.timeout,
  1341. counter: request.counter
  1342. };
  1343. // HTTP-network fetch step 12.1.1.3
  1344. const codings = headers.get('Content-Encoding');
  1345. // HTTP-network fetch step 12.1.1.4: handle content codings
  1346. // in following scenarios we ignore compression support
  1347. // 1. compression support is disabled
  1348. // 2. HEAD request
  1349. // 3. no Content-Encoding header
  1350. // 4. no content response (204)
  1351. // 5. content not modified response (304)
  1352. if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) {
  1353. response = new Response(body, response_options);
  1354. resolve(response);
  1355. return;
  1356. }
  1357. // For Node v6+
  1358. // Be less strict when decoding compressed responses, since sometimes
  1359. // servers send slightly invalid responses that are still accepted
  1360. // by common browsers.
  1361. // Always using Z_SYNC_FLUSH is what cURL does.
  1362. const zlibOptions = {
  1363. flush: zlib.Z_SYNC_FLUSH,
  1364. finishFlush: zlib.Z_SYNC_FLUSH
  1365. };
  1366. // for gzip
  1367. if (codings == 'gzip' || codings == 'x-gzip') {
  1368. body = body.pipe(zlib.createGunzip(zlibOptions));
  1369. response = new Response(body, response_options);
  1370. resolve(response);
  1371. return;
  1372. }
  1373. // for deflate
  1374. if (codings == 'deflate' || codings == 'x-deflate') {
  1375. // handle the infamous raw deflate response from old servers
  1376. // a hack for old IIS and Apache servers
  1377. const raw = res.pipe(new PassThrough$1());
  1378. raw.once('data', function (chunk) {
  1379. // see http://stackoverflow.com/questions/37519828
  1380. if ((chunk[0] & 0x0F) === 0x08) {
  1381. body = body.pipe(zlib.createInflate());
  1382. } else {
  1383. body = body.pipe(zlib.createInflateRaw());
  1384. }
  1385. response = new Response(body, response_options);
  1386. resolve(response);
  1387. });
  1388. return;
  1389. }
  1390. // for br
  1391. if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') {
  1392. body = body.pipe(zlib.createBrotliDecompress());
  1393. response = new Response(body, response_options);
  1394. resolve(response);
  1395. return;
  1396. }
  1397. // otherwise, use response as-is
  1398. response = new Response(body, response_options);
  1399. resolve(response);
  1400. });
  1401. writeToStream(req, request);
  1402. });
  1403. }
  1404. /**
  1405. * Redirect code matching
  1406. *
  1407. * @param Number code Status code
  1408. * @return Boolean
  1409. */
  1410. fetch.isRedirect = function (code) {
  1411. return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
  1412. };
  1413. // expose Promise
  1414. fetch.Promise = global.Promise;
  1415. module.exports = exports = fetch;
  1416. Object.defineProperty(exports, "__esModule", { value: true });
  1417. exports.default = exports;
  1418. exports.Headers = Headers;
  1419. exports.Request = Request;
  1420. exports.Response = Response;
  1421. exports.FetchError = FetchError;