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