@whatwg-node/node-fetch 0.3.0 → 0.4.0-alpha-20230215085115-d099e0b

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.
Files changed (73) hide show
  1. package/cjs/AbortController.js +14 -0
  2. package/cjs/AbortError.js +20 -0
  3. package/cjs/AbortSignal.js +37 -0
  4. package/cjs/Blob.js +119 -0
  5. package/cjs/Body.js +372 -0
  6. package/cjs/File.js +13 -0
  7. package/cjs/FormData.js +121 -0
  8. package/cjs/Headers.js +121 -0
  9. package/cjs/ReadableStream.js +172 -0
  10. package/cjs/Request.js +69 -0
  11. package/cjs/Response.js +75 -0
  12. package/cjs/TextEncoderDecoder.js +39 -0
  13. package/cjs/URL.js +55 -0
  14. package/cjs/URLSearchParams.js +103 -0
  15. package/cjs/fetch.js +127 -0
  16. package/cjs/index.js +35 -0
  17. package/cjs/package.json +1 -0
  18. package/cjs/utils.js +18 -0
  19. package/esm/AbortController.js +10 -0
  20. package/esm/AbortError.js +16 -0
  21. package/esm/AbortSignal.js +33 -0
  22. package/esm/Blob.js +115 -0
  23. package/esm/Body.js +367 -0
  24. package/esm/File.js +9 -0
  25. package/esm/FormData.js +116 -0
  26. package/esm/Headers.js +117 -0
  27. package/esm/ReadableStream.js +168 -0
  28. package/esm/Request.js +65 -0
  29. package/esm/Response.js +71 -0
  30. package/esm/TextEncoderDecoder.js +33 -0
  31. package/esm/URL.js +50 -0
  32. package/esm/URLSearchParams.js +98 -0
  33. package/esm/fetch.js +123 -0
  34. package/esm/index.js +15 -0
  35. package/esm/utils.js +13 -0
  36. package/package.json +19 -12
  37. package/typings/AbortController.d.cts +5 -0
  38. package/{AbortController.d.ts → typings/AbortController.d.ts} +1 -1
  39. package/{AbortError.d.ts → typings/AbortError.d.cts} +0 -0
  40. package/typings/AbortError.d.ts +4 -0
  41. package/{AbortSignal.d.ts → typings/AbortSignal.d.cts} +0 -0
  42. package/typings/AbortSignal.d.ts +11 -0
  43. package/{Blob.d.ts → typings/Blob.d.cts} +0 -0
  44. package/typings/Blob.d.ts +18 -0
  45. package/typings/Body.d.cts +41 -0
  46. package/{Body.d.ts → typings/Body.d.ts} +3 -3
  47. package/typings/File.d.cts +7 -0
  48. package/{File.d.ts → typings/File.d.ts} +1 -1
  49. package/typings/FormData.d.cts +14 -0
  50. package/{FormData.d.ts → typings/FormData.d.ts} +2 -2
  51. package/{Headers.d.ts → typings/Headers.d.cts} +0 -0
  52. package/typings/Headers.d.ts +19 -0
  53. package/{ReadableStream.d.ts → typings/ReadableStream.d.cts} +0 -0
  54. package/typings/ReadableStream.d.ts +20 -0
  55. package/typings/Request.d.cts +24 -0
  56. package/{Request.d.ts → typings/Request.d.ts} +2 -2
  57. package/typings/Response.d.cts +22 -0
  58. package/{Response.d.ts → typings/Response.d.ts} +2 -2
  59. package/{TextEncoderDecoder.d.ts → typings/TextEncoderDecoder.d.cts} +0 -0
  60. package/typings/TextEncoderDecoder.d.ts +15 -0
  61. package/typings/URL.d.cts +14 -0
  62. package/{URL.d.ts → typings/URL.d.ts} +1 -1
  63. package/{URLSearchParams.d.ts → typings/URLSearchParams.d.cts} +0 -0
  64. package/typings/URLSearchParams.d.ts +17 -0
  65. package/typings/fetch.d.cts +3 -0
  66. package/{fetch.d.ts → typings/fetch.d.ts} +2 -2
  67. package/typings/index.d.cts +15 -0
  68. package/typings/index.d.ts +15 -0
  69. package/{utils.d.ts → typings/utils.d.cts} +0 -0
  70. package/typings/utils.d.ts +2 -0
  71. package/index.d.ts +0 -15
  72. package/index.js +0 -1417
  73. package/index.mjs +0 -1395
package/index.js DELETED
@@ -1,1417 +0,0 @@
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
- const fs = require('fs');
8
- const http = require('http');
9
- const https = require('https');
10
- const stream = require('stream');
11
- const url = require('url');
12
- const events = require('@whatwg-node/events');
13
- const busboy = _interopDefault(require('busboy'));
14
- const FastQuerystring = _interopDefault(require('fast-querystring'));
15
- const FastUrl = _interopDefault(require('fast-url-parser'));
16
-
17
- // Will be removed after v14 reaches EOL
18
- class PonyfillAbortError extends Error {
19
- constructor(reason) {
20
- let message = 'The operation was aborted.';
21
- if (reason) {
22
- message += ` reason: ${reason}`;
23
- }
24
- super(message, {
25
- cause: reason,
26
- });
27
- this.name = 'AbortError';
28
- }
29
- get reason() {
30
- return this.cause;
31
- }
32
- }
33
-
34
- function createController(desiredSize, readable) {
35
- let chunks = [];
36
- let _closed = false;
37
- let flushed = false;
38
- return {
39
- desiredSize,
40
- enqueue(chunk) {
41
- const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
42
- if (!flushed) {
43
- chunks.push(buf);
44
- }
45
- else {
46
- readable.push(buf);
47
- }
48
- },
49
- close() {
50
- if (chunks.length > 0) {
51
- this._flush();
52
- }
53
- readable.push(null);
54
- _closed = true;
55
- },
56
- error(error) {
57
- if (chunks.length > 0) {
58
- this._flush();
59
- }
60
- readable.destroy(error);
61
- },
62
- get _closed() {
63
- return _closed;
64
- },
65
- _flush() {
66
- flushed = true;
67
- if (chunks.length > 0) {
68
- const concatenated = Buffer.concat(chunks);
69
- readable.push(concatenated);
70
- chunks = [];
71
- }
72
- },
73
- };
74
- }
75
- class PonyfillReadableStream {
76
- constructor(underlyingSource) {
77
- this.locked = false;
78
- if (underlyingSource instanceof PonyfillReadableStream) {
79
- this.readable = underlyingSource.readable;
80
- }
81
- else if (underlyingSource && 'read' in underlyingSource) {
82
- this.readable = underlyingSource;
83
- }
84
- else if (underlyingSource && 'getReader' in underlyingSource) {
85
- let reader;
86
- let started = false;
87
- this.readable = new stream.Readable({
88
- read() {
89
- if (!started) {
90
- started = true;
91
- reader = underlyingSource.getReader();
92
- }
93
- reader
94
- .read()
95
- .then(({ value, done }) => {
96
- if (done) {
97
- this.push(null);
98
- }
99
- else {
100
- this.push(value);
101
- }
102
- })
103
- .catch(err => {
104
- this.destroy(err);
105
- });
106
- },
107
- destroy(err, callback) {
108
- reader.cancel(err).then(() => callback(err), callback);
109
- },
110
- });
111
- }
112
- else {
113
- let started = false;
114
- let ongoing = false;
115
- this.readable = new stream.Readable({
116
- read(desiredSize) {
117
- if (ongoing) {
118
- return;
119
- }
120
- ongoing = true;
121
- return Promise.resolve().then(async () => {
122
- var _a, _b;
123
- if (!started) {
124
- const controller = createController(desiredSize, this);
125
- started = true;
126
- await ((_a = underlyingSource === null || underlyingSource === void 0 ? void 0 : underlyingSource.start) === null || _a === void 0 ? void 0 : _a.call(underlyingSource, controller));
127
- controller._flush();
128
- if (controller._closed) {
129
- return;
130
- }
131
- }
132
- const controller = createController(desiredSize, this);
133
- await ((_b = underlyingSource === null || underlyingSource === void 0 ? void 0 : underlyingSource.pull) === null || _b === void 0 ? void 0 : _b.call(underlyingSource, controller));
134
- controller._flush();
135
- ongoing = false;
136
- });
137
- },
138
- async destroy(err, callback) {
139
- var _a;
140
- try {
141
- await ((_a = underlyingSource === null || underlyingSource === void 0 ? void 0 : underlyingSource.cancel) === null || _a === void 0 ? void 0 : _a.call(underlyingSource, err));
142
- callback(null);
143
- }
144
- catch (err) {
145
- callback(err);
146
- }
147
- },
148
- });
149
- }
150
- }
151
- cancel(reason) {
152
- this.readable.destroy(reason);
153
- return Promise.resolve();
154
- }
155
- getReader(_options) {
156
- const iterator = this.readable[Symbol.asyncIterator]();
157
- this.locked = true;
158
- return {
159
- read() {
160
- return iterator.next();
161
- },
162
- releaseLock: () => {
163
- var _a;
164
- (_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator);
165
- this.locked = false;
166
- },
167
- cancel: async (reason) => {
168
- var _a;
169
- await ((_a = iterator.return) === null || _a === void 0 ? void 0 : _a.call(iterator, reason));
170
- this.locked = false;
171
- },
172
- closed: new Promise((resolve, reject) => {
173
- this.readable.once('end', resolve);
174
- this.readable.once('error', reject);
175
- }),
176
- };
177
- }
178
- [Symbol.asyncIterator]() {
179
- return this.readable[Symbol.asyncIterator]();
180
- }
181
- tee() {
182
- throw new Error('Not implemented');
183
- }
184
- async pipeTo(destination) {
185
- const writer = destination.getWriter();
186
- await writer.ready;
187
- for await (const chunk of this.readable) {
188
- await writer.write(chunk);
189
- }
190
- await writer.ready;
191
- return writer.close();
192
- }
193
- pipeThrough({ writable, readable, }) {
194
- this.pipeTo(writable);
195
- return readable;
196
- }
197
- static [Symbol.hasInstance](instance) {
198
- return instance != null && typeof instance === 'object' && 'getReader' in instance;
199
- }
200
- }
201
-
202
- function getHeadersObj(headers) {
203
- if (headers == null || !('forEach' in headers)) {
204
- return headers;
205
- }
206
- const obj = {};
207
- headers.forEach((value, key) => {
208
- obj[key] = value;
209
- });
210
- return obj;
211
- }
212
- function uint8ArrayToArrayBuffer(uint8array) {
213
- return uint8array.buffer.slice(uint8array.byteOffset, uint8array.byteOffset + uint8array.byteLength);
214
- }
215
-
216
- function getBlobPartAsBuffer(blobPart) {
217
- if (typeof blobPart === 'string') {
218
- return Buffer.from(blobPart);
219
- }
220
- else if (Buffer.isBuffer(blobPart)) {
221
- return blobPart;
222
- }
223
- else if (blobPart instanceof Uint8Array) {
224
- return Buffer.from(blobPart);
225
- }
226
- else if ('buffer' in blobPart) {
227
- return Buffer.from(blobPart.buffer, blobPart.byteOffset, blobPart.byteLength);
228
- }
229
- else {
230
- return Buffer.from(blobPart);
231
- }
232
- }
233
- function isBlob(obj) {
234
- return obj != null && typeof obj === 'object' && obj.arrayBuffer != null;
235
- }
236
- // Will be removed after v14 reaches EOL
237
- // Needed because v14 doesn't have .stream() implemented
238
- class PonyfillBlob {
239
- constructor(blobParts, options) {
240
- this.blobParts = blobParts;
241
- this.type = (options === null || options === void 0 ? void 0 : options.type) || 'application/octet-stream';
242
- this.encoding = (options === null || options === void 0 ? void 0 : options.encoding) || 'utf8';
243
- }
244
- async buffer() {
245
- const bufferChunks = [];
246
- for (const blobPart of this.blobParts) {
247
- if (isBlob(blobPart)) {
248
- const arrayBuf = await blobPart.arrayBuffer();
249
- const buf = Buffer.from(arrayBuf, undefined, blobPart.size);
250
- bufferChunks.push(buf);
251
- }
252
- else {
253
- const buf = getBlobPartAsBuffer(blobPart);
254
- bufferChunks.push(buf);
255
- }
256
- }
257
- return Buffer.concat(bufferChunks);
258
- }
259
- async arrayBuffer() {
260
- const buffer = await this.buffer();
261
- return uint8ArrayToArrayBuffer(buffer);
262
- }
263
- async text() {
264
- let text = '';
265
- for (const blobPart of this.blobParts) {
266
- if (typeof blobPart === 'string') {
267
- text += blobPart;
268
- }
269
- else if ('text' in blobPart) {
270
- text += await blobPart.text();
271
- }
272
- else {
273
- const buf = getBlobPartAsBuffer(blobPart);
274
- text += buf.toString(this.encoding);
275
- }
276
- }
277
- return text;
278
- }
279
- get size() {
280
- let size = 0;
281
- for (const blobPart of this.blobParts) {
282
- if (typeof blobPart === 'string') {
283
- size += Buffer.byteLength(blobPart);
284
- }
285
- else if (isBlob(blobPart)) {
286
- size += blobPart.size;
287
- }
288
- else if ('length' in blobPart) {
289
- size += blobPart.length;
290
- }
291
- else if ('byteLength' in blobPart) {
292
- size += blobPart.byteLength;
293
- }
294
- }
295
- return size;
296
- }
297
- stream() {
298
- let partQueue = [];
299
- return new PonyfillReadableStream({
300
- start: controller => {
301
- partQueue = [...this.blobParts];
302
- if (partQueue.length === 0) {
303
- controller.close();
304
- }
305
- },
306
- pull: async (controller) => {
307
- const blobPart = partQueue.pop();
308
- if (blobPart) {
309
- if (isBlob(blobPart)) {
310
- const arrayBuffer = await blobPart.arrayBuffer();
311
- const buf = Buffer.from(arrayBuffer, undefined, blobPart.size);
312
- controller.enqueue(buf);
313
- }
314
- else {
315
- const buf = getBlobPartAsBuffer(blobPart);
316
- controller.enqueue(buf);
317
- }
318
- }
319
- else {
320
- controller.close();
321
- }
322
- },
323
- });
324
- }
325
- slice() {
326
- throw new Error('Not implemented');
327
- }
328
- }
329
-
330
- // Will be removed after v14 reaches EOL
331
- class PonyfillAbortSignal extends events.EventTarget {
332
- constructor() {
333
- super(...arguments);
334
- this.aborted = false;
335
- this._onabort = null;
336
- }
337
- throwIfAborted() {
338
- if (this.aborted) {
339
- throw new PonyfillAbortError();
340
- }
341
- }
342
- get onabort() {
343
- return this._onabort;
344
- }
345
- set onabort(value) {
346
- if (this._onabort) {
347
- this.removeEventListener('abort', this._onabort);
348
- }
349
- this.addEventListener('abort', value);
350
- }
351
- abort(reason) {
352
- const abortEvent = new events.CustomEvent('abort', { detail: reason });
353
- this.dispatchEvent(abortEvent);
354
- }
355
- static timeout(milliseconds) {
356
- const signal = new PonyfillAbortSignal();
357
- setTimeout(() => signal.abort(`timeout in ${milliseconds} ms`), milliseconds);
358
- return signal;
359
- }
360
- }
361
-
362
- // Will be removed after v14 reaches EOL
363
- class PonyfillAbortController {
364
- constructor() {
365
- this.signal = new PonyfillAbortSignal();
366
- }
367
- abort(reason) {
368
- this.signal.abort(reason);
369
- }
370
- }
371
-
372
- class PonyfillFile extends PonyfillBlob {
373
- constructor(fileBits, name, options) {
374
- super(fileBits, options);
375
- this.name = name;
376
- this.webkitRelativePath = '';
377
- this.lastModified = (options === null || options === void 0 ? void 0 : options.lastModified) || Date.now();
378
- }
379
- }
380
-
381
- class PonyfillFormData {
382
- constructor() {
383
- this.map = new Map();
384
- }
385
- append(name, value, fileName) {
386
- let values = this.map.get(name);
387
- if (!values) {
388
- values = [];
389
- this.map.set(name, values);
390
- }
391
- const entry = isBlob$1(value)
392
- ? getNormalizedFile(name, value, fileName)
393
- : value;
394
- values.push(entry);
395
- }
396
- delete(name) {
397
- this.map.delete(name);
398
- }
399
- get(name) {
400
- const values = this.map.get(name);
401
- return values ? values[0] : null;
402
- }
403
- getAll(name) {
404
- return this.map.get(name) || [];
405
- }
406
- has(name) {
407
- return this.map.has(name);
408
- }
409
- set(name, value, fileName) {
410
- const entry = isBlob$1(value)
411
- ? getNormalizedFile(name, value, fileName)
412
- : value;
413
- this.map.set(name, [entry]);
414
- }
415
- *[Symbol.iterator]() {
416
- for (const [key, values] of this.map) {
417
- for (const value of values) {
418
- yield [key, value];
419
- }
420
- }
421
- }
422
- forEach(callback) {
423
- for (const [key, value] of this) {
424
- callback(value, key, this);
425
- }
426
- }
427
- }
428
- function getStreamFromFormData(formData, boundary = '---') {
429
- const entries = [];
430
- let sentInitialHeader = false;
431
- return new PonyfillReadableStream({
432
- start: controller => {
433
- formData.forEach((value, key) => {
434
- if (!sentInitialHeader) {
435
- controller.enqueue(Buffer.from(`--${boundary}\r\n`));
436
- sentInitialHeader = true;
437
- }
438
- entries.push([key, value]);
439
- });
440
- if (!sentInitialHeader) {
441
- controller.enqueue(Buffer.from(`--${boundary}--\r\n`));
442
- controller.close();
443
- }
444
- },
445
- pull: async (controller) => {
446
- const entry = entries.shift();
447
- if (entry) {
448
- const [key, value] = entry;
449
- if (typeof value === 'string') {
450
- controller.enqueue(Buffer.from(`Content-Disposition: form-data; name="${key}"\r\n\r\n`));
451
- controller.enqueue(Buffer.from(value));
452
- }
453
- else {
454
- let filenamePart = '';
455
- if (value.name) {
456
- filenamePart = `; filename="${value.name}"`;
457
- }
458
- controller.enqueue(Buffer.from(`Content-Disposition: form-data; name="${key}"${filenamePart}\r\n`));
459
- controller.enqueue(Buffer.from(`Content-Type: ${value.type || 'application/octet-stream'}\r\n\r\n`));
460
- const entryStream = value.stream();
461
- for await (const chunk of entryStream) {
462
- controller.enqueue(chunk);
463
- }
464
- }
465
- if (entries.length === 0) {
466
- controller.enqueue(Buffer.from(`\r\n--${boundary}--\r\n`));
467
- controller.close();
468
- }
469
- else {
470
- controller.enqueue(Buffer.from(`\r\n--${boundary}\r\n`));
471
- }
472
- }
473
- else {
474
- controller.enqueue(Buffer.from(`\r\n--${boundary}--\r\n`));
475
- controller.close();
476
- }
477
- },
478
- });
479
- }
480
- function getNormalizedFile(name, blob, fileName) {
481
- if (blob instanceof PonyfillFile) {
482
- if (fileName != null) {
483
- return new PonyfillFile([blob], fileName, {
484
- type: blob.type,
485
- lastModified: blob.lastModified,
486
- });
487
- }
488
- return blob;
489
- }
490
- return new PonyfillFile([blob], fileName || name, { type: blob.type });
491
- }
492
- function isBlob$1(value) {
493
- return value != null && typeof value === 'object' && typeof value.arrayBuffer === 'function';
494
- }
495
-
496
- var BodyInitType;
497
- (function (BodyInitType) {
498
- BodyInitType["ReadableStream"] = "ReadableStream";
499
- BodyInitType["Blob"] = "Blob";
500
- BodyInitType["FormData"] = "FormData";
501
- BodyInitType["ArrayBuffer"] = "ArrayBuffer";
502
- BodyInitType["String"] = "String";
503
- BodyInitType["Readable"] = "Readable";
504
- BodyInitType["Buffer"] = "Buffer";
505
- BodyInitType["Uint8Array"] = "Uint8Array";
506
- })(BodyInitType || (BodyInitType = {}));
507
- class PonyfillBody {
508
- constructor(bodyInit, options = {}) {
509
- this.bodyInit = bodyInit;
510
- this.options = options;
511
- this.bodyUsed = false;
512
- this.contentType = null;
513
- this.contentLength = null;
514
- this._bodyFactory = () => null;
515
- this._generatedBody = null;
516
- const { bodyFactory, contentType, contentLength, bodyType } = processBodyInit(bodyInit);
517
- this._bodyFactory = bodyFactory;
518
- this.contentType = contentType;
519
- this.contentLength = contentLength;
520
- this.bodyType = bodyType;
521
- }
522
- generateBody() {
523
- if (this._generatedBody) {
524
- return this._generatedBody;
525
- }
526
- const body = this._bodyFactory();
527
- this._generatedBody = body;
528
- return body;
529
- }
530
- get body() {
531
- const _body = this.generateBody();
532
- if (_body != null) {
533
- const ponyfillReadableStream = _body;
534
- const readable = _body.readable;
535
- return new Proxy(_body.readable, {
536
- get(_, prop) {
537
- if (prop in ponyfillReadableStream) {
538
- const ponyfillReadableStreamProp = ponyfillReadableStream[prop];
539
- if (typeof ponyfillReadableStreamProp === 'function') {
540
- return ponyfillReadableStreamProp.bind(ponyfillReadableStream);
541
- }
542
- return ponyfillReadableStreamProp;
543
- }
544
- if (prop in readable) {
545
- const readableProp = readable[prop];
546
- if (typeof readableProp === 'function') {
547
- return readableProp.bind(readable);
548
- }
549
- return readableProp;
550
- }
551
- },
552
- });
553
- }
554
- return null;
555
- }
556
- async arrayBuffer() {
557
- if (this.bodyType === BodyInitType.ArrayBuffer) {
558
- return this.bodyInit;
559
- }
560
- if (this.bodyType === BodyInitType.Uint8Array || this.bodyType === BodyInitType.Buffer) {
561
- const typedBodyInit = this.bodyInit;
562
- return uint8ArrayToArrayBuffer(typedBodyInit);
563
- }
564
- if (this.bodyType === BodyInitType.String) {
565
- const buffer = Buffer.from(this.bodyInit);
566
- return uint8ArrayToArrayBuffer(buffer);
567
- }
568
- if (this.bodyType === BodyInitType.Blob) {
569
- const blob = this.bodyInit;
570
- const arrayBuffer = await blob.arrayBuffer();
571
- return arrayBuffer;
572
- }
573
- const blob = await this.blob();
574
- return blob.arrayBuffer();
575
- }
576
- async _collectChunksFromReadable() {
577
- const chunks = [];
578
- const _body = this.generateBody();
579
- if (_body) {
580
- for await (const chunk of _body.readable) {
581
- chunks.push(chunk);
582
- }
583
- }
584
- return chunks;
585
- }
586
- async blob() {
587
- if (this.bodyType === BodyInitType.Blob) {
588
- return this.bodyInit;
589
- }
590
- if (this.bodyType === BodyInitType.String ||
591
- this.bodyType === BodyInitType.Buffer ||
592
- this.bodyType === BodyInitType.Uint8Array) {
593
- const bodyInitTyped = this.bodyInit;
594
- return new PonyfillBlob([bodyInitTyped], {
595
- type: this.contentType || '',
596
- });
597
- }
598
- if (this.bodyType === BodyInitType.ArrayBuffer) {
599
- const bodyInitTyped = this.bodyInit;
600
- const buf = Buffer.from(bodyInitTyped, undefined, bodyInitTyped.byteLength);
601
- return new PonyfillBlob([buf], {
602
- type: this.contentType || '',
603
- });
604
- }
605
- const chunks = await this._collectChunksFromReadable();
606
- return new PonyfillBlob(chunks, {
607
- type: this.contentType || '',
608
- });
609
- }
610
- formData(opts) {
611
- if (this.bodyType === BodyInitType.FormData) {
612
- return Promise.resolve(this.bodyInit);
613
- }
614
- const formData = new PonyfillFormData();
615
- const _body = this.generateBody();
616
- if (_body == null) {
617
- return Promise.resolve(formData);
618
- }
619
- const formDataLimits = {
620
- ...this.options.formDataLimits,
621
- ...opts === null || opts === void 0 ? void 0 : opts.formDataLimits,
622
- };
623
- return new Promise((resolve, reject) => {
624
- const bb = busboy({
625
- headers: {
626
- 'content-type': this.contentType || '',
627
- },
628
- limits: formDataLimits,
629
- defParamCharset: 'utf-8',
630
- });
631
- bb.on('field', (name, value, { nameTruncated, valueTruncated }) => {
632
- if (nameTruncated) {
633
- reject(new Error(`Field name size exceeded: ${formDataLimits === null || formDataLimits === void 0 ? void 0 : formDataLimits.fieldNameSize} bytes`));
634
- }
635
- if (valueTruncated) {
636
- reject(new Error(`Field value size exceeded: ${formDataLimits === null || formDataLimits === void 0 ? void 0 : formDataLimits.fieldSize} bytes`));
637
- }
638
- formData.set(name, value);
639
- });
640
- bb.on('fieldsLimit', () => {
641
- reject(new Error(`Fields limit exceeded: ${formDataLimits === null || formDataLimits === void 0 ? void 0 : formDataLimits.fields}`));
642
- });
643
- bb.on('file', (name, fileStream, { filename, mimeType }) => {
644
- const chunks = [];
645
- fileStream.on('limit', () => {
646
- reject(new Error(`File size limit exceeded: ${formDataLimits === null || formDataLimits === void 0 ? void 0 : formDataLimits.fileSize} bytes`));
647
- });
648
- fileStream.on('data', chunk => {
649
- chunks.push(Buffer.from(chunk));
650
- });
651
- fileStream.on('close', () => {
652
- if (fileStream.truncated) {
653
- reject(new Error(`File size limit exceeded: ${formDataLimits === null || formDataLimits === void 0 ? void 0 : formDataLimits.fileSize} bytes`));
654
- }
655
- const file = new PonyfillFile(chunks, filename, { type: mimeType });
656
- formData.set(name, file);
657
- });
658
- });
659
- bb.on('filesLimit', () => {
660
- reject(new Error(`Files limit exceeded: ${formDataLimits === null || formDataLimits === void 0 ? void 0 : formDataLimits.files}`));
661
- });
662
- bb.on('partsLimit', () => {
663
- reject(new Error(`Parts limit exceeded: ${formDataLimits === null || formDataLimits === void 0 ? void 0 : formDataLimits.parts}`));
664
- });
665
- bb.on('close', () => {
666
- resolve(formData);
667
- });
668
- bb.on('error', err => {
669
- reject(err);
670
- });
671
- _body === null || _body === void 0 ? void 0 : _body.readable.pipe(bb);
672
- });
673
- }
674
- async buffer() {
675
- if (this.bodyType === BodyInitType.Buffer) {
676
- return this.bodyInit;
677
- }
678
- if (this.bodyType === BodyInitType.String) {
679
- return Buffer.from(this.bodyInit);
680
- }
681
- if (this.bodyType === BodyInitType.Uint8Array || this.bodyType === BodyInitType.ArrayBuffer) {
682
- const bodyInitTyped = this.bodyInit;
683
- const buffer = Buffer.from(bodyInitTyped, 'byteOffset' in bodyInitTyped ? bodyInitTyped.byteOffset : undefined, bodyInitTyped.byteLength);
684
- return buffer;
685
- }
686
- if (this.bodyType === BodyInitType.Blob) {
687
- if (this.bodyInit instanceof PonyfillBlob) {
688
- return this.bodyInit.buffer();
689
- }
690
- const bodyInitTyped = this.bodyInit;
691
- const buffer = Buffer.from(await bodyInitTyped.arrayBuffer(), undefined, bodyInitTyped.size);
692
- return buffer;
693
- }
694
- const chunks = await this._collectChunksFromReadable();
695
- return Buffer.concat(chunks);
696
- }
697
- async json() {
698
- const text = await this.text();
699
- return JSON.parse(text);
700
- }
701
- async text() {
702
- if (this.bodyType === BodyInitType.String) {
703
- return this.bodyInit;
704
- }
705
- const buffer = await this.buffer();
706
- return buffer.toString('utf-8');
707
- }
708
- }
709
- function processBodyInit(bodyInit) {
710
- if (bodyInit == null) {
711
- return {
712
- bodyFactory: () => null,
713
- contentType: null,
714
- contentLength: null,
715
- };
716
- }
717
- if (typeof bodyInit === 'string') {
718
- return {
719
- bodyType: BodyInitType.String,
720
- contentType: 'text/plain;charset=UTF-8',
721
- contentLength: Buffer.byteLength(bodyInit),
722
- bodyFactory() {
723
- const readable = stream.Readable.from(bodyInit);
724
- return new PonyfillReadableStream(readable);
725
- },
726
- };
727
- }
728
- if (bodyInit instanceof PonyfillReadableStream) {
729
- return {
730
- bodyType: BodyInitType.ReadableStream,
731
- bodyFactory: () => bodyInit,
732
- contentType: null,
733
- contentLength: null,
734
- };
735
- }
736
- if (bodyInit instanceof PonyfillBlob) {
737
- return {
738
- bodyType: BodyInitType.Blob,
739
- contentType: bodyInit.type,
740
- contentLength: bodyInit.size,
741
- bodyFactory() {
742
- return bodyInit.stream();
743
- },
744
- };
745
- }
746
- if (bodyInit instanceof Buffer) {
747
- const contentLength = bodyInit.length;
748
- return {
749
- bodyType: BodyInitType.Buffer,
750
- contentLength,
751
- contentType: null,
752
- bodyFactory() {
753
- const readable = stream.Readable.from(bodyInit);
754
- const body = new PonyfillReadableStream(readable);
755
- return body;
756
- },
757
- };
758
- }
759
- if (bodyInit instanceof Uint8Array) {
760
- const contentLength = bodyInit.byteLength;
761
- return {
762
- bodyType: BodyInitType.Uint8Array,
763
- contentLength,
764
- contentType: null,
765
- bodyFactory() {
766
- const readable = stream.Readable.from(bodyInit);
767
- const body = new PonyfillReadableStream(readable);
768
- return body;
769
- },
770
- };
771
- }
772
- if ('buffer' in bodyInit) {
773
- const contentLength = bodyInit.byteLength;
774
- return {
775
- contentLength,
776
- contentType: null,
777
- bodyFactory() {
778
- const buffer = Buffer.from(bodyInit);
779
- const readable = stream.Readable.from(buffer);
780
- const body = new PonyfillReadableStream(readable);
781
- return body;
782
- },
783
- };
784
- }
785
- if (bodyInit instanceof ArrayBuffer) {
786
- const contentLength = bodyInit.byteLength;
787
- return {
788
- bodyType: BodyInitType.ArrayBuffer,
789
- contentType: null,
790
- contentLength,
791
- bodyFactory() {
792
- const buffer = Buffer.from(bodyInit, undefined, bodyInit.byteLength);
793
- const readable = stream.Readable.from(buffer);
794
- const body = new PonyfillReadableStream(readable);
795
- return body;
796
- },
797
- };
798
- }
799
- if (bodyInit instanceof stream.Readable) {
800
- return {
801
- bodyType: BodyInitType.Readable,
802
- contentType: null,
803
- contentLength: null,
804
- bodyFactory() {
805
- const body = new PonyfillReadableStream(bodyInit);
806
- return body;
807
- },
808
- };
809
- }
810
- if ('stream' in bodyInit) {
811
- return {
812
- contentType: bodyInit.type,
813
- contentLength: bodyInit.size,
814
- bodyFactory() {
815
- const bodyStream = bodyInit.stream();
816
- const body = new PonyfillReadableStream(bodyStream);
817
- return body;
818
- },
819
- };
820
- }
821
- if ('sort' in bodyInit) {
822
- const contentType = 'application/x-www-form-urlencoded;charset=UTF-8';
823
- return {
824
- bodyType: BodyInitType.String,
825
- contentType,
826
- contentLength: null,
827
- bodyFactory() {
828
- const body = new PonyfillReadableStream(stream.Readable.from(bodyInit.toString()));
829
- return body;
830
- },
831
- };
832
- }
833
- if ('forEach' in bodyInit) {
834
- const boundary = Math.random().toString(36).substr(2);
835
- const contentType = `multipart/form-data; boundary=${boundary}`;
836
- return {
837
- contentType,
838
- contentLength: null,
839
- bodyFactory() {
840
- return getStreamFromFormData(bodyInit, boundary);
841
- },
842
- };
843
- }
844
- if (bodyInit[Symbol.iterator] || bodyInit[Symbol.asyncIterator]) {
845
- return {
846
- contentType: null,
847
- contentLength: null,
848
- bodyFactory() {
849
- const readable = stream.Readable.from(bodyInit);
850
- return new PonyfillReadableStream(readable);
851
- },
852
- };
853
- }
854
- throw new Error('Unknown body type');
855
- }
856
-
857
- function isHeadersLike(headers) {
858
- return headers && typeof headers.get === 'function';
859
- }
860
- class PonyfillHeaders {
861
- constructor(headersInit) {
862
- this.headersInit = headersInit;
863
- this.map = new Map();
864
- this.mapIsBuilt = false;
865
- this.objectNormalizedKeysOfHeadersInit = [];
866
- this.objectOriginalKeysOfHeadersInit = [];
867
- }
868
- // perf: we don't need to build `this.map` for Requests, as we can access the headers directly
869
- _get(key) {
870
- // If the map is built, reuse it
871
- if (this.mapIsBuilt) {
872
- return this.map.get(key.toLowerCase()) || null;
873
- }
874
- // If the map is not built, try to get the value from the this.headersInit
875
- if (this.headersInit == null) {
876
- return null;
877
- }
878
- const normalized = key.toLowerCase();
879
- if (Array.isArray(this.headersInit)) {
880
- return this.headersInit.find(header => header[0] === normalized);
881
- }
882
- else if (isHeadersLike(this.headersInit)) {
883
- return this.headersInit.get(normalized);
884
- }
885
- else {
886
- const initValue = this.headersInit[key] || this.headersInit[normalized];
887
- if (initValue != null) {
888
- return initValue;
889
- }
890
- if (!this.objectNormalizedKeysOfHeadersInit.length) {
891
- Object.keys(this.headersInit).forEach(k => {
892
- this.objectOriginalKeysOfHeadersInit.push(k);
893
- this.objectNormalizedKeysOfHeadersInit.push(k.toLowerCase());
894
- });
895
- }
896
- const index = this.objectNormalizedKeysOfHeadersInit.indexOf(normalized);
897
- if (index === -1) {
898
- return null;
899
- }
900
- const originalKey = this.objectOriginalKeysOfHeadersInit[index];
901
- return this.headersInit[originalKey];
902
- }
903
- }
904
- // perf: Build the map of headers lazily, only when we need to access all headers or write to it.
905
- // I could do a getter here, but I'm too lazy to type `getter`.
906
- getMap() {
907
- if (this.mapIsBuilt) {
908
- return this.map;
909
- }
910
- if (this.headersInit != null) {
911
- if (Array.isArray(this.headersInit)) {
912
- this.map = new Map(this.headersInit);
913
- }
914
- else if (isHeadersLike(this.headersInit)) {
915
- this.headersInit.forEach((value, key) => {
916
- this.map.set(key, value);
917
- });
918
- }
919
- else {
920
- for (const initKey in this.headersInit) {
921
- const initValue = this.headersInit[initKey];
922
- if (initValue != null) {
923
- const normalizedValue = Array.isArray(initValue) ? initValue.join(', ') : initValue;
924
- const normalizedKey = initKey.toLowerCase();
925
- this.map.set(normalizedKey, normalizedValue);
926
- }
927
- }
928
- }
929
- }
930
- this.mapIsBuilt = true;
931
- return this.map;
932
- }
933
- append(name, value) {
934
- const key = name.toLowerCase();
935
- const existingValue = this.getMap().get(key);
936
- const finalValue = existingValue ? `${existingValue}, ${value}` : value;
937
- this.getMap().set(key, finalValue);
938
- }
939
- get(name) {
940
- const key = name.toLowerCase();
941
- const value = this._get(key);
942
- if (value == null) {
943
- return null;
944
- }
945
- if (Array.isArray(value)) {
946
- return value.join(', ');
947
- }
948
- return value;
949
- }
950
- has(name) {
951
- const key = name.toLowerCase();
952
- return !!this._get(key); // we might need to check if header exists and not just check if it's not nullable
953
- }
954
- set(name, value) {
955
- const key = name.toLowerCase();
956
- this.getMap().set(key, value);
957
- }
958
- delete(name) {
959
- const key = name.toLowerCase();
960
- this.getMap().delete(key);
961
- }
962
- forEach(callback) {
963
- this.getMap().forEach((value, key) => {
964
- callback(value, key, this);
965
- });
966
- }
967
- entries() {
968
- return this.getMap().entries();
969
- }
970
- [Symbol.iterator]() {
971
- return this.getMap().entries();
972
- }
973
- }
974
-
975
- function isRequest(input) {
976
- return input[Symbol.toStringTag] === 'Request';
977
- }
978
- class PonyfillRequest extends PonyfillBody {
979
- constructor(input, options) {
980
- var _a;
981
- let url;
982
- let bodyInit = null;
983
- let requestInit;
984
- if (typeof input === 'string') {
985
- url = input;
986
- }
987
- else if ('href' in input) {
988
- url = input.toString();
989
- }
990
- else if (isRequest(input)) {
991
- url = input.url;
992
- bodyInit = input.body;
993
- requestInit = input;
994
- }
995
- if (options != null) {
996
- bodyInit = options.body || null;
997
- requestInit = options;
998
- }
999
- super(bodyInit, options);
1000
- this.destination = '';
1001
- this.priority = 'auto';
1002
- this.cache = (requestInit === null || requestInit === void 0 ? void 0 : requestInit.cache) || 'default';
1003
- this.credentials = (requestInit === null || requestInit === void 0 ? void 0 : requestInit.credentials) || 'same-origin';
1004
- this.headers = new PonyfillHeaders(requestInit === null || requestInit === void 0 ? void 0 : requestInit.headers);
1005
- this.integrity = (requestInit === null || requestInit === void 0 ? void 0 : requestInit.integrity) || '';
1006
- this.keepalive = (requestInit === null || requestInit === void 0 ? void 0 : requestInit.keepalive) != null ? requestInit === null || requestInit === void 0 ? void 0 : requestInit.keepalive : false;
1007
- this.method = ((_a = requestInit === null || requestInit === void 0 ? void 0 : requestInit.method) === null || _a === void 0 ? void 0 : _a.toUpperCase()) || 'GET';
1008
- this.mode = (requestInit === null || requestInit === void 0 ? void 0 : requestInit.mode) || 'cors';
1009
- this.redirect = (requestInit === null || requestInit === void 0 ? void 0 : requestInit.redirect) || 'follow';
1010
- this.referrer = (requestInit === null || requestInit === void 0 ? void 0 : requestInit.referrer) || 'about:client';
1011
- this.referrerPolicy = (requestInit === null || requestInit === void 0 ? void 0 : requestInit.referrerPolicy) || 'no-referrer';
1012
- this.signal = (requestInit === null || requestInit === void 0 ? void 0 : requestInit.signal) || new PonyfillAbortController().signal;
1013
- this.url = url || '';
1014
- const contentTypeInHeaders = this.headers.get('content-type');
1015
- if (!contentTypeInHeaders) {
1016
- if (this.contentType) {
1017
- this.headers.set('content-type', this.contentType);
1018
- }
1019
- }
1020
- else {
1021
- this.contentType = contentTypeInHeaders;
1022
- }
1023
- const contentLengthInHeaders = this.headers.get('content-length');
1024
- if (!contentLengthInHeaders) {
1025
- if (this.contentLength) {
1026
- this.headers.set('content-length', this.contentLength.toString());
1027
- }
1028
- }
1029
- else {
1030
- this.contentLength = parseInt(contentLengthInHeaders, 10);
1031
- }
1032
- }
1033
- clone() {
1034
- return new Request(this);
1035
- }
1036
- }
1037
-
1038
- class PonyfillResponse extends PonyfillBody {
1039
- constructor(body, init) {
1040
- super(body || null, init);
1041
- this.headers = new PonyfillHeaders();
1042
- this.status = 200;
1043
- this.statusText = 'OK';
1044
- this.url = '';
1045
- this.redirected = false;
1046
- this.type = 'default';
1047
- if (init) {
1048
- this.headers = new PonyfillHeaders(init.headers);
1049
- this.status = init.status || 200;
1050
- this.statusText = init.statusText || 'OK';
1051
- this.url = init.url || '';
1052
- this.redirected = init.redirected || false;
1053
- this.type = init.type || 'default';
1054
- }
1055
- const contentTypeInHeaders = this.headers.get('content-type');
1056
- if (!contentTypeInHeaders) {
1057
- if (this.contentType) {
1058
- this.headers.set('content-type', this.contentType);
1059
- }
1060
- }
1061
- else {
1062
- this.contentType = contentTypeInHeaders;
1063
- }
1064
- const contentLengthInHeaders = this.headers.get('content-length');
1065
- if (!contentLengthInHeaders) {
1066
- if (this.contentLength) {
1067
- this.headers.set('content-length', this.contentLength.toString());
1068
- }
1069
- }
1070
- else {
1071
- this.contentLength = parseInt(contentLengthInHeaders, 10);
1072
- }
1073
- }
1074
- get ok() {
1075
- return this.status >= 200 && this.status < 300;
1076
- }
1077
- clone() {
1078
- return new PonyfillResponse(this.body, this);
1079
- }
1080
- static error() {
1081
- return new PonyfillResponse(null, {
1082
- status: 500,
1083
- statusText: 'Internal Server Error',
1084
- });
1085
- }
1086
- static redirect(url, status = 301) {
1087
- if (status < 300 || status > 399) {
1088
- throw new RangeError('Invalid status code');
1089
- }
1090
- return new PonyfillResponse(null, {
1091
- headers: {
1092
- location: url,
1093
- },
1094
- status,
1095
- });
1096
- }
1097
- static json(data, init = {}) {
1098
- return new PonyfillResponse(JSON.stringify(data), {
1099
- ...init,
1100
- headers: {
1101
- 'Content-Type': 'application/json',
1102
- ...init === null || init === void 0 ? void 0 : init.headers,
1103
- },
1104
- });
1105
- }
1106
- }
1107
-
1108
- class PonyfillURLSearchParams {
1109
- constructor(init) {
1110
- if (init) {
1111
- if (typeof init === 'string') {
1112
- this.params = FastQuerystring.parse(init);
1113
- }
1114
- else if (Array.isArray(init)) {
1115
- this.params = {};
1116
- for (const [key, value] of init) {
1117
- this.params[key] = value;
1118
- }
1119
- }
1120
- else if ('entries' in init) {
1121
- this.params = {};
1122
- for (const [key, value] of init.entries()) {
1123
- this.params[key] = value;
1124
- }
1125
- }
1126
- else {
1127
- this.params = init;
1128
- }
1129
- }
1130
- else {
1131
- this.params = {};
1132
- }
1133
- }
1134
- append(name, value) {
1135
- const existingValue = this.params[name];
1136
- const finalValue = existingValue ? `${existingValue},${value}` : value;
1137
- this.params[name] = finalValue;
1138
- }
1139
- delete(name) {
1140
- delete this.params[name];
1141
- }
1142
- get(name) {
1143
- const value = this.params[name];
1144
- if (Array.isArray(value)) {
1145
- return value[0] || null;
1146
- }
1147
- return value || null;
1148
- }
1149
- getAll(name) {
1150
- const value = this.params[name];
1151
- if (!Array.isArray(value)) {
1152
- return value ? [value] : [];
1153
- }
1154
- return value;
1155
- }
1156
- has(name) {
1157
- return name in this.params;
1158
- }
1159
- set(name, value) {
1160
- this.params[name] = value;
1161
- }
1162
- sort() {
1163
- const sortedKeys = Object.keys(this.params).sort();
1164
- const sortedParams = {};
1165
- for (const key of sortedKeys) {
1166
- sortedParams[key] = this.params[key];
1167
- }
1168
- this.params = sortedParams;
1169
- }
1170
- toString() {
1171
- return FastQuerystring.stringify(this.params);
1172
- }
1173
- *keys() {
1174
- for (const key in this.params) {
1175
- yield key;
1176
- }
1177
- }
1178
- *entries() {
1179
- for (const key of this.keys()) {
1180
- const value = this.params[key];
1181
- if (Array.isArray(value)) {
1182
- for (const item of value) {
1183
- yield [key, item];
1184
- }
1185
- }
1186
- else {
1187
- yield [key, value];
1188
- }
1189
- }
1190
- }
1191
- *values() {
1192
- for (const [, value] of this) {
1193
- yield value;
1194
- }
1195
- }
1196
- [Symbol.iterator]() {
1197
- return this.entries();
1198
- }
1199
- forEach(callback) {
1200
- for (const [key, value] of this) {
1201
- callback(value, key, this);
1202
- }
1203
- }
1204
- }
1205
-
1206
- FastUrl.queryString = FastQuerystring;
1207
- class PonyfillURL extends FastUrl {
1208
- constructor(url, base) {
1209
- super();
1210
- if (url.startsWith('data:')) {
1211
- this.protocol = 'data:';
1212
- this.pathname = url.slice('data:'.length);
1213
- return;
1214
- }
1215
- this.parse(url, false);
1216
- if (base) {
1217
- const baseParsed = typeof base === 'string' ? new PonyfillURL(base) : base;
1218
- this.protocol = this.protocol || baseParsed.protocol;
1219
- this.host = this.host || baseParsed.host;
1220
- this.pathname = this.pathname || baseParsed.pathname;
1221
- }
1222
- }
1223
- get origin() {
1224
- return `${this.protocol}//${this.host}`;
1225
- }
1226
- get searchParams() {
1227
- if (!this._searchParams) {
1228
- this._searchParams = new PonyfillURLSearchParams(this.query);
1229
- }
1230
- return this._searchParams;
1231
- }
1232
- get username() {
1233
- var _a;
1234
- return ((_a = this.auth) === null || _a === void 0 ? void 0 : _a.split(':')[0]) || '';
1235
- }
1236
- set username(value) {
1237
- this.auth = `${value}:${this.password}`;
1238
- }
1239
- get password() {
1240
- var _a;
1241
- return ((_a = this.auth) === null || _a === void 0 ? void 0 : _a.split(':')[1]) || '';
1242
- }
1243
- set password(value) {
1244
- this.auth = `${this.username}:${value}`;
1245
- }
1246
- toString() {
1247
- return this.format();
1248
- }
1249
- toJSON() {
1250
- return this.toString();
1251
- }
1252
- }
1253
-
1254
- function getResponseForFile(url$1) {
1255
- const path = url.fileURLToPath(url$1);
1256
- const readable = fs.createReadStream(path);
1257
- return new PonyfillResponse(readable);
1258
- }
1259
- function getRequestFnForProtocol(protocol) {
1260
- switch (protocol) {
1261
- case 'http:':
1262
- return http.request;
1263
- case 'https:':
1264
- return https.request;
1265
- }
1266
- throw new Error(`Unsupported protocol: ${protocol}`);
1267
- }
1268
- const BASE64_SUFFIX = ';base64';
1269
- function fetchPonyfill(info, init) {
1270
- if (typeof info === 'string' || 'href' in info) {
1271
- const ponyfillRequest = new PonyfillRequest(info, init);
1272
- return fetchPonyfill(ponyfillRequest);
1273
- }
1274
- const fetchRequest = info;
1275
- return new Promise((resolve, reject) => {
1276
- try {
1277
- const url = new PonyfillURL(fetchRequest.url, 'http://localhost');
1278
- if (url.protocol === 'data:') {
1279
- const [mimeType = 'text/plain', ...datas] = url.pathname.split(',');
1280
- const data = decodeURIComponent(datas.join(','));
1281
- if (mimeType.endsWith(BASE64_SUFFIX)) {
1282
- const buffer = Buffer.from(data, 'base64url');
1283
- const realMimeType = mimeType.slice(0, -BASE64_SUFFIX.length);
1284
- const file = new PonyfillBlob([buffer], { type: realMimeType });
1285
- const response = new PonyfillResponse(file, {
1286
- status: 200,
1287
- statusText: 'OK',
1288
- });
1289
- resolve(response);
1290
- return;
1291
- }
1292
- const response = new PonyfillResponse(data, {
1293
- status: 200,
1294
- statusText: 'OK',
1295
- headers: {
1296
- 'content-type': mimeType,
1297
- },
1298
- });
1299
- resolve(response);
1300
- return;
1301
- }
1302
- if (url.protocol === 'file:') {
1303
- const response = getResponseForFile(fetchRequest.url);
1304
- resolve(response);
1305
- return;
1306
- }
1307
- const requestFn = getRequestFnForProtocol(url.protocol);
1308
- const nodeReadable = (fetchRequest.body != null
1309
- ? 'pipe' in fetchRequest.body
1310
- ? fetchRequest.body
1311
- : stream.Readable.from(fetchRequest.body)
1312
- : null);
1313
- const nodeHeaders = getHeadersObj(fetchRequest.headers);
1314
- const abortListener = function abortListener(event) {
1315
- nodeRequest.destroy();
1316
- const reason = event.detail;
1317
- reject(new PonyfillAbortError(reason));
1318
- };
1319
- fetchRequest.signal.addEventListener('abort', abortListener);
1320
- const nodeRequest = requestFn(fetchRequest.url, {
1321
- // signal: fetchRequest.signal will be added when v14 reaches EOL
1322
- method: fetchRequest.method,
1323
- headers: nodeHeaders,
1324
- });
1325
- nodeRequest.once('response', nodeResponse => {
1326
- if (nodeResponse.headers.location) {
1327
- if (fetchRequest.redirect === 'error') {
1328
- const redirectError = new Error('Redirects are not allowed');
1329
- reject(redirectError);
1330
- nodeResponse.resume();
1331
- return;
1332
- }
1333
- if (fetchRequest.redirect === 'follow') {
1334
- const redirectedUrl = new PonyfillURL(nodeResponse.headers.location, url);
1335
- const redirectResponse$ = fetchPonyfill(redirectedUrl, info);
1336
- resolve(redirectResponse$.then(redirectResponse => {
1337
- redirectResponse.redirected = true;
1338
- return redirectResponse;
1339
- }));
1340
- nodeResponse.resume();
1341
- return;
1342
- }
1343
- }
1344
- const responseHeaders = nodeResponse.headers;
1345
- const ponyfillResponse = new PonyfillResponse(nodeResponse, {
1346
- status: nodeResponse.statusCode,
1347
- statusText: nodeResponse.statusMessage,
1348
- headers: responseHeaders,
1349
- url: info.url,
1350
- });
1351
- resolve(ponyfillResponse);
1352
- });
1353
- nodeRequest.once('error', reject);
1354
- if (nodeReadable) {
1355
- nodeReadable.pipe(nodeRequest);
1356
- }
1357
- else {
1358
- nodeRequest.end();
1359
- }
1360
- }
1361
- catch (e) {
1362
- reject(e);
1363
- }
1364
- });
1365
- }
1366
-
1367
- class PonyfillTextEncoder {
1368
- constructor(encoding = 'utf-8') {
1369
- this.encoding = encoding;
1370
- }
1371
- encode(input) {
1372
- return Buffer.from(input, this.encoding);
1373
- }
1374
- encodeInto(source, destination) {
1375
- const buffer = this.encode(source);
1376
- const copied = buffer.copy(destination);
1377
- return {
1378
- read: copied,
1379
- written: copied,
1380
- };
1381
- }
1382
- }
1383
- class PonyfillTextDecoder {
1384
- constructor(encoding = 'utf-8', options) {
1385
- this.encoding = encoding;
1386
- this.fatal = false;
1387
- this.ignoreBOM = false;
1388
- if (options) {
1389
- this.fatal = options.fatal || false;
1390
- this.ignoreBOM = options.ignoreBOM || false;
1391
- }
1392
- }
1393
- decode(input) {
1394
- return Buffer.from(input).toString(this.encoding);
1395
- }
1396
- }
1397
- function PonyfillBtoa(input) {
1398
- return Buffer.from(input, 'binary').toString('base64');
1399
- }
1400
-
1401
- exports.AbortController = PonyfillAbortController;
1402
- exports.AbortError = PonyfillAbortError;
1403
- exports.AbortSignal = PonyfillAbortSignal;
1404
- exports.Blob = PonyfillBlob;
1405
- exports.Body = PonyfillBody;
1406
- exports.File = PonyfillFile;
1407
- exports.FormData = PonyfillFormData;
1408
- exports.Headers = PonyfillHeaders;
1409
- exports.ReadableStream = PonyfillReadableStream;
1410
- exports.Request = PonyfillRequest;
1411
- exports.Response = PonyfillResponse;
1412
- exports.TextDecoder = PonyfillTextDecoder;
1413
- exports.TextEncoder = PonyfillTextEncoder;
1414
- exports.URL = PonyfillURL;
1415
- exports.URLSearchParams = PonyfillURLSearchParams;
1416
- exports.btoa = PonyfillBtoa;
1417
- exports.fetch = fetchPonyfill;