Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.es.js 41KB

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