@data-loom/node-fetch 0.0.2-alpha.1

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