@whatwg-node/node-fetch 0.8.0-alpha-20241212160430-140b66f028923f44368e67598b6b66f47f690454 → 0.8.0-alpha-20250917053118-2dc604e028627df01a83e41a3dd6dd3f89ca0b40

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/AbortError.js +10 -3
  2. package/cjs/Blob.js +21 -19
  3. package/cjs/Body.js +146 -76
  4. package/cjs/FormData.js +54 -41
  5. package/cjs/Headers.js +54 -15
  6. package/cjs/ReadableStream.js +62 -26
  7. package/cjs/Request.js +9 -16
  8. package/cjs/Response.js +56 -10
  9. package/cjs/TextEncoderDecoder.js +6 -5
  10. package/cjs/TextEncoderDecoderStream.js +2 -6
  11. package/cjs/TransformStream.js +2 -1
  12. package/cjs/URL.js +10 -66
  13. package/cjs/URLSearchParams.js +1 -117
  14. package/cjs/WritableStream.js +35 -111
  15. package/cjs/fetch.js +37 -8
  16. package/cjs/fetchCurl.js +30 -61
  17. package/cjs/fetchNodeHttp.js +60 -64
  18. package/cjs/index.js +1 -7
  19. package/cjs/utils.js +76 -55
  20. package/esm/AbortError.js +10 -3
  21. package/esm/Blob.js +6 -4
  22. package/esm/Body.js +134 -63
  23. package/esm/FormData.js +54 -41
  24. package/esm/Headers.js +54 -15
  25. package/esm/ReadableStream.js +57 -21
  26. package/esm/Request.js +7 -14
  27. package/esm/Response.js +55 -9
  28. package/esm/TextEncoderDecoder.js +1 -0
  29. package/esm/TextEncoderDecoderStream.js +2 -6
  30. package/esm/TransformStream.js +2 -1
  31. package/esm/URL.js +9 -64
  32. package/esm/URLSearchParams.js +1 -115
  33. package/esm/WritableStream.js +33 -109
  34. package/esm/fetch.js +35 -6
  35. package/esm/fetchCurl.js +28 -59
  36. package/esm/fetchNodeHttp.js +55 -59
  37. package/esm/index.js +0 -3
  38. package/esm/utils.js +70 -53
  39. package/package.json +4 -5
  40. package/typings/AbortError.d.cts +2 -2
  41. package/typings/AbortError.d.ts +2 -2
  42. package/typings/Blob.d.cts +5 -4
  43. package/typings/Blob.d.ts +5 -4
  44. package/typings/Body.d.cts +11 -6
  45. package/typings/Body.d.ts +11 -6
  46. package/typings/Headers.d.cts +1 -1
  47. package/typings/Headers.d.ts +1 -1
  48. package/typings/ReadableStream.d.cts +8 -2
  49. package/typings/ReadableStream.d.ts +8 -2
  50. package/typings/Request.d.cts +9 -10
  51. package/typings/Request.d.ts +9 -10
  52. package/typings/Response.d.cts +6 -5
  53. package/typings/Response.d.ts +6 -5
  54. package/typings/TextEncoderDecoder.d.cts +2 -1
  55. package/typings/TextEncoderDecoder.d.ts +2 -1
  56. package/typings/URL.d.cts +12 -16
  57. package/typings/URL.d.ts +12 -16
  58. package/typings/URLSearchParams.d.cts +4 -21
  59. package/typings/URLSearchParams.d.ts +4 -21
  60. package/typings/WritableStream.d.cts +1 -1
  61. package/typings/WritableStream.d.ts +1 -1
  62. package/typings/index.d.cts +0 -3
  63. package/typings/index.d.ts +0 -3
  64. package/typings/utils.d.cts +13 -8
  65. package/typings/utils.d.ts +13 -8
  66. package/cjs/AbortController.js +0 -18
  67. package/cjs/AbortSignal.js +0 -92
  68. package/esm/AbortController.js +0 -14
  69. package/esm/AbortSignal.js +0 -88
  70. package/typings/AbortController.d.cts +0 -8
  71. package/typings/AbortController.d.ts +0 -8
  72. package/typings/AbortSignal.d.cts +0 -15
  73. package/typings/AbortSignal.d.ts +0 -15
package/cjs/FormData.js CHANGED
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PonyfillFormData = void 0;
4
4
  exports.getStreamFromFormData = getStreamFromFormData;
5
+ const node_buffer_1 = require("node:buffer");
5
6
  const IteratorObject_js_1 = require("./IteratorObject.js");
6
7
  const ReadableStream_js_1 = require("./ReadableStream.js");
7
8
  class PonyfillFormData {
@@ -73,54 +74,66 @@ class PonyfillFormData {
73
74
  }
74
75
  exports.PonyfillFormData = PonyfillFormData;
75
76
  function getStreamFromFormData(formData, boundary = '---') {
76
- const entries = [];
77
+ let entriesIterator;
77
78
  let sentInitialHeader = false;
78
- return new ReadableStream_js_1.PonyfillReadableStream({
79
- start: controller => {
80
- formData.forEach((value, key) => {
81
- if (!sentInitialHeader) {
82
- controller.enqueue(Buffer.from(`--${boundary}\r\n`));
83
- sentInitialHeader = true;
79
+ let currentAsyncIterator;
80
+ let hasBefore = false;
81
+ function handleNextEntry(controller) {
82
+ const { done, value } = entriesIterator.next();
83
+ if (done) {
84
+ controller.enqueue(node_buffer_1.Buffer.from(`\r\n--${boundary}--\r\n`));
85
+ return controller.close();
86
+ }
87
+ if (hasBefore) {
88
+ controller.enqueue(node_buffer_1.Buffer.from(`\r\n--${boundary}\r\n`));
89
+ }
90
+ if (value) {
91
+ const [key, blobOrString] = value;
92
+ if (typeof blobOrString === 'string') {
93
+ controller.enqueue(node_buffer_1.Buffer.from(`Content-Disposition: form-data; name="${key}"\r\n\r\n`));
94
+ controller.enqueue(node_buffer_1.Buffer.from(blobOrString));
95
+ }
96
+ else {
97
+ let filenamePart = '';
98
+ if (blobOrString.name) {
99
+ filenamePart = `; filename="${blobOrString.name}"`;
84
100
  }
85
- entries.push([key, value]);
86
- });
87
- if (!sentInitialHeader) {
88
- controller.enqueue(Buffer.from(`--${boundary}--\r\n`));
89
- controller.close();
101
+ controller.enqueue(node_buffer_1.Buffer.from(`Content-Disposition: form-data; name="${key}"${filenamePart}\r\n`));
102
+ controller.enqueue(node_buffer_1.Buffer.from(`Content-Type: ${blobOrString.type || 'application/octet-stream'}\r\n\r\n`));
103
+ const entryStream = blobOrString.stream();
104
+ // @ts-expect-error - ReadableStream is async iterable
105
+ currentAsyncIterator = entryStream[Symbol.asyncIterator]();
90
106
  }
107
+ hasBefore = true;
108
+ }
109
+ }
110
+ return new ReadableStream_js_1.PonyfillReadableStream({
111
+ start: () => {
112
+ entriesIterator = formData.entries();
91
113
  },
92
- pull: async (controller) => {
93
- const entry = entries.shift();
94
- if (entry) {
95
- const [key, value] = entry;
96
- if (typeof value === 'string') {
97
- controller.enqueue(Buffer.from(`Content-Disposition: form-data; name="${key}"\r\n\r\n`));
98
- controller.enqueue(Buffer.from(value));
99
- }
100
- else {
101
- let filenamePart = '';
102
- if (value.name) {
103
- filenamePart = `; filename="${value.name}"`;
114
+ pull: controller => {
115
+ if (!sentInitialHeader) {
116
+ sentInitialHeader = true;
117
+ return controller.enqueue(node_buffer_1.Buffer.from(`--${boundary}\r\n`));
118
+ }
119
+ if (currentAsyncIterator) {
120
+ return currentAsyncIterator.next().then(({ done, value }) => {
121
+ if (done) {
122
+ currentAsyncIterator = undefined;
104
123
  }
105
- controller.enqueue(Buffer.from(`Content-Disposition: form-data; name="${key}"${filenamePart}\r\n`));
106
- controller.enqueue(Buffer.from(`Content-Type: ${value.type || 'application/octet-stream'}\r\n\r\n`));
107
- const entryStream = value.stream();
108
- for await (const chunk of entryStream) {
109
- controller.enqueue(chunk);
124
+ if (value) {
125
+ return controller.enqueue(value);
110
126
  }
111
- }
112
- if (entries.length === 0) {
113
- controller.enqueue(Buffer.from(`\r\n--${boundary}--\r\n`));
114
- controller.close();
115
- }
116
- else {
117
- controller.enqueue(Buffer.from(`\r\n--${boundary}\r\n`));
118
- }
119
- }
120
- else {
121
- controller.enqueue(Buffer.from(`\r\n--${boundary}--\r\n`));
122
- controller.close();
127
+ else {
128
+ return handleNextEntry(controller);
129
+ }
130
+ });
123
131
  }
132
+ return handleNextEntry(controller);
133
+ },
134
+ cancel: err => {
135
+ entriesIterator?.return?.(err);
136
+ currentAsyncIterator?.return?.(err);
124
137
  },
125
138
  });
126
139
  }
package/cjs/Headers.js CHANGED
@@ -12,14 +12,14 @@ class PonyfillHeaders {
12
12
  _map;
13
13
  objectNormalizedKeysOfHeadersInit = [];
14
14
  objectOriginalKeysOfHeadersInit = [];
15
- _setCookies = [];
15
+ _setCookies;
16
16
  constructor(headersInit) {
17
17
  this.headersInit = headersInit;
18
18
  }
19
19
  // perf: we don't need to build `this.map` for Requests, as we can access the headers directly
20
20
  _get(key) {
21
21
  const normalized = key.toLowerCase();
22
- if (normalized === 'set-cookie') {
22
+ if (normalized === 'set-cookie' && this._setCookies?.length) {
23
23
  return this._setCookies.join(', ');
24
24
  }
25
25
  // If the map is built, reuse it
@@ -31,7 +31,14 @@ class PonyfillHeaders {
31
31
  return null;
32
32
  }
33
33
  if (Array.isArray(this.headersInit)) {
34
- return this.headersInit.find(header => header[0].toLowerCase() === normalized)?.[1] || null;
34
+ const found = this.headersInit.filter(([headerKey]) => headerKey.toLowerCase() === normalized);
35
+ if (found.length === 0) {
36
+ return null;
37
+ }
38
+ if (found.length === 1) {
39
+ return found[0][1];
40
+ }
41
+ return found.map(([, value]) => value).join(', ');
35
42
  }
36
43
  else if (isHeadersLike(this.headersInit)) {
37
44
  return this.headersInit.get(normalized);
@@ -59,22 +66,24 @@ class PonyfillHeaders {
59
66
  // I could do a getter here, but I'm too lazy to type `getter`.
60
67
  getMap() {
61
68
  if (!this._map) {
69
+ this._setCookies ||= [];
62
70
  if (this.headersInit != null) {
63
71
  if (Array.isArray(this.headersInit)) {
64
72
  this._map = new Map();
65
- this.headersInit.forEach(([key, value]) => {
73
+ for (const [key, value] of this.headersInit) {
66
74
  const normalizedKey = key.toLowerCase();
67
75
  if (normalizedKey === 'set-cookie') {
68
76
  this._setCookies.push(value);
69
- return;
77
+ continue;
70
78
  }
71
79
  this._map.set(normalizedKey, value);
72
- });
80
+ }
73
81
  }
74
82
  else if (isHeadersLike(this.headersInit)) {
75
83
  this._map = new Map();
76
84
  this.headersInit.forEach((value, key) => {
77
85
  if (key === 'set-cookie') {
86
+ this._setCookies ||= [];
78
87
  this._setCookies.push(value);
79
88
  return;
80
89
  }
@@ -88,6 +97,7 @@ class PonyfillHeaders {
88
97
  if (initValue != null) {
89
98
  const normalizedKey = initKey.toLowerCase();
90
99
  if (normalizedKey === 'set-cookie') {
100
+ this._setCookies ||= [];
91
101
  this._setCookies.push(initValue);
92
102
  continue;
93
103
  }
@@ -105,6 +115,7 @@ class PonyfillHeaders {
105
115
  append(name, value) {
106
116
  const key = name.toLowerCase();
107
117
  if (key === 'set-cookie') {
118
+ this._setCookies ||= [];
108
119
  this._setCookies.push(value);
109
120
  return;
110
121
  }
@@ -117,11 +128,12 @@ class PonyfillHeaders {
117
128
  if (value == null) {
118
129
  return null;
119
130
  }
120
- return value;
131
+ return value.toString();
121
132
  }
122
133
  has(name) {
123
- if (name === 'set-cookie') {
124
- return this._setCookies.length > 0;
134
+ const key = name.toLowerCase();
135
+ if (key === 'set-cookie') {
136
+ return !!this._setCookies?.length;
125
137
  }
126
138
  return !!this._get(name); // we might need to check if header exists and not just check if it's not nullable
127
139
  }
@@ -131,6 +143,26 @@ class PonyfillHeaders {
131
143
  this._setCookies = [value];
132
144
  return;
133
145
  }
146
+ if (!this._map && this.headersInit != null) {
147
+ if (Array.isArray(this.headersInit)) {
148
+ const found = this.headersInit.find(([headerKey]) => headerKey.toLowerCase() === key);
149
+ if (found) {
150
+ found[1] = value;
151
+ }
152
+ else {
153
+ this.headersInit.push([key, value]);
154
+ }
155
+ return;
156
+ }
157
+ else if (isHeadersLike(this.headersInit)) {
158
+ this.headersInit.set(key, value);
159
+ return;
160
+ }
161
+ else {
162
+ this.headersInit[key] = value;
163
+ return;
164
+ }
165
+ }
134
166
  this.getMap().set(key, value);
135
167
  }
136
168
  delete(name) {
@@ -142,7 +174,7 @@ class PonyfillHeaders {
142
174
  this.getMap().delete(key);
143
175
  }
144
176
  forEach(callback) {
145
- this._setCookies.forEach(setCookie => {
177
+ this._setCookies?.forEach(setCookie => {
146
178
  callback(setCookie, 'set-cookie', this);
147
179
  });
148
180
  if (!this._map) {
@@ -170,7 +202,7 @@ class PonyfillHeaders {
170
202
  });
171
203
  }
172
204
  *_keys() {
173
- if (this._setCookies.length) {
205
+ if (this._setCookies?.length) {
174
206
  yield 'set-cookie';
175
207
  }
176
208
  if (!this._map) {
@@ -193,7 +225,9 @@ class PonyfillHeaders {
193
225
  return new IteratorObject_js_1.PonyfillIteratorObject(this._keys(), 'HeadersIterator');
194
226
  }
195
227
  *_values() {
196
- yield* this._setCookies;
228
+ if (this._setCookies?.length) {
229
+ yield* this._setCookies;
230
+ }
197
231
  if (!this._map) {
198
232
  if (this.headersInit) {
199
233
  if (Array.isArray(this.headersInit)) {
@@ -214,7 +248,9 @@ class PonyfillHeaders {
214
248
  return new IteratorObject_js_1.PonyfillIteratorObject(this._values(), 'HeadersIterator');
215
249
  }
216
250
  *_entries() {
217
- yield* this._setCookies.map(cookie => ['set-cookie', cookie]);
251
+ if (this._setCookies?.length) {
252
+ yield* this._setCookies.map(cookie => ['set-cookie', cookie]);
253
+ }
218
254
  if (!this._map) {
219
255
  if (this.headersInit) {
220
256
  if (Array.isArray(this.headersInit)) {
@@ -235,6 +271,9 @@ class PonyfillHeaders {
235
271
  return new IteratorObject_js_1.PonyfillIteratorObject(this._entries(), 'HeadersIterator');
236
272
  }
237
273
  getSetCookie() {
274
+ if (!this._setCookies) {
275
+ this.getMap();
276
+ }
238
277
  return this._setCookies;
239
278
  }
240
279
  [Symbol.iterator]() {
@@ -244,10 +283,10 @@ class PonyfillHeaders {
244
283
  const record = {};
245
284
  this.forEach((value, key) => {
246
285
  if (key === 'set-cookie') {
247
- record['set-cookie'] = this._setCookies;
286
+ record['set-cookie'] = this._setCookies || [];
248
287
  }
249
288
  else {
250
- record[key] = value.includes(',') ? value.split(',').map(el => el.trim()) : value;
289
+ record[key] = value?.includes(',') ? value.split(',').map(el => el.trim()) : value;
251
290
  }
252
291
  });
253
292
  return `Headers ${(0, node_util_1.inspect)(record)}`;
@@ -1,7 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PonyfillReadableStream = void 0;
4
- const stream_1 = require("stream");
4
+ const node_buffer_1 = require("node:buffer");
5
+ const node_events_1 = require("node:events");
6
+ const node_stream_1 = require("node:stream");
7
+ const promises_1 = require("node:stream/promises");
8
+ const promise_helpers_1 = require("@whatwg-node/promise-helpers");
5
9
  const utils_js_1 = require("./utils.js");
6
10
  function createController(desiredSize, readable) {
7
11
  let chunks = [];
@@ -10,7 +14,7 @@ function createController(desiredSize, readable) {
10
14
  return {
11
15
  desiredSize,
12
16
  enqueue(chunk) {
13
- const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
17
+ const buf = typeof chunk === 'string' ? node_buffer_1.Buffer.from(chunk) : chunk;
14
18
  if (!flushed) {
15
19
  chunks.push(buf);
16
20
  }
@@ -37,7 +41,7 @@ function createController(desiredSize, readable) {
37
41
  _flush() {
38
42
  flushed = true;
39
43
  if (chunks.length > 0) {
40
- const concatenated = chunks.length > 1 ? Buffer.concat(chunks) : chunks[0];
44
+ const concatenated = chunks.length > 1 ? node_buffer_1.Buffer.concat(chunks) : chunks[0];
41
45
  readable.push(concatenated);
42
46
  chunks = [];
43
47
  }
@@ -60,27 +64,38 @@ class PonyfillReadableStream {
60
64
  this.readable = underlyingSource;
61
65
  }
62
66
  else if (isReadableStream(underlyingSource)) {
63
- this.readable = stream_1.Readable.fromWeb(underlyingSource);
67
+ this.readable = node_stream_1.Readable.fromWeb(underlyingSource);
64
68
  }
65
69
  else {
66
70
  let started = false;
67
71
  let ongoing = false;
68
- const readImpl = async (desiredSize) => {
72
+ const handleStart = (desiredSize) => {
69
73
  if (!started) {
70
74
  const controller = createController(desiredSize, this.readable);
71
75
  started = true;
72
- await underlyingSource?.start?.(controller);
73
- controller._flush();
74
- if (controller._closed) {
76
+ return (0, promise_helpers_1.handleMaybePromise)(() => underlyingSource?.start?.(controller), () => {
77
+ controller._flush();
78
+ if (controller._closed) {
79
+ return false;
80
+ }
81
+ return true;
82
+ });
83
+ }
84
+ return true;
85
+ };
86
+ const readImpl = (desiredSize) => {
87
+ return (0, promise_helpers_1.handleMaybePromise)(() => handleStart(desiredSize), shouldContinue => {
88
+ if (!shouldContinue) {
75
89
  return;
76
90
  }
77
- }
78
- const controller = createController(desiredSize, this.readable);
79
- await underlyingSource?.pull?.(controller);
80
- controller._flush();
81
- ongoing = false;
91
+ const controller = createController(desiredSize, this.readable);
92
+ return (0, promise_helpers_1.handleMaybePromise)(() => underlyingSource?.pull?.(controller), () => {
93
+ controller._flush();
94
+ ongoing = false;
95
+ });
96
+ });
82
97
  };
83
- this.readable = new stream_1.Readable({
98
+ this.readable = new node_stream_1.Readable({
84
99
  read(desiredSize) {
85
100
  if (ongoing) {
86
101
  return;
@@ -112,12 +127,14 @@ class PonyfillReadableStream {
112
127
  }
113
128
  cancel(reason) {
114
129
  this.readable.destroy(reason);
115
- return new Promise(resolve => this.readable.once('end', resolve));
130
+ // @ts-expect-error - we know it is void
131
+ return (0, node_events_1.once)(this.readable, 'close');
116
132
  }
117
133
  locked = false;
118
134
  getReader(_options) {
119
135
  const iterator = this.readable[Symbol.asyncIterator]();
120
136
  this.locked = true;
137
+ const thisReadable = this.readable;
121
138
  return {
122
139
  read() {
123
140
  return iterator.next();
@@ -144,16 +161,36 @@ class PonyfillReadableStream {
144
161
  }
145
162
  }
146
163
  this.locked = false;
147
- return (0, utils_js_1.fakePromise)(undefined);
164
+ return (0, utils_js_1.fakePromise)();
165
+ },
166
+ get closed() {
167
+ return Promise.race([
168
+ (0, node_events_1.once)(thisReadable, 'end'),
169
+ (0, node_events_1.once)(thisReadable, 'error').then(err => Promise.reject(err)),
170
+ ]);
148
171
  },
149
- closed: new Promise((resolve, reject) => {
150
- this.readable.once('end', resolve);
151
- this.readable.once('error', reject);
152
- }),
153
172
  };
154
173
  }
155
174
  [Symbol.asyncIterator]() {
156
- return this.readable[Symbol.asyncIterator]();
175
+ const iterator = this.readable[Symbol.asyncIterator]();
176
+ return {
177
+ [Symbol.asyncIterator]() {
178
+ return this;
179
+ },
180
+ next: () => iterator.next(),
181
+ return: () => {
182
+ if (!this.readable.destroyed) {
183
+ this.readable.destroy();
184
+ }
185
+ return iterator.return?.() || (0, utils_js_1.fakePromise)({ done: true, value: undefined });
186
+ },
187
+ throw: (err) => {
188
+ if (!this.readable.destroyed) {
189
+ this.readable.destroy(err);
190
+ }
191
+ return iterator.throw?.(err) || (0, utils_js_1.fakePromise)({ done: true, value: undefined });
192
+ },
193
+ };
157
194
  }
158
195
  tee() {
159
196
  throw new Error('Not implemented');
@@ -171,10 +208,8 @@ class PonyfillReadableStream {
171
208
  }
172
209
  pipeTo(destination) {
173
210
  if (isPonyfillWritableStream(destination)) {
174
- return new Promise((resolve, reject) => {
175
- this.readable.pipe(destination.writable);
176
- destination.writable.once('finish', resolve);
177
- destination.writable.once('error', reject);
211
+ return (0, promises_1.pipeline)(this.readable, destination.writable, {
212
+ end: true,
178
213
  });
179
214
  }
180
215
  else {
@@ -197,8 +232,9 @@ class PonyfillReadableStream {
197
232
  return isReadableStream(instance);
198
233
  }
199
234
  static from(iterable) {
200
- return new PonyfillReadableStream(stream_1.Readable.from(iterable));
235
+ return new PonyfillReadableStream(node_stream_1.Readable.from(iterable));
201
236
  }
237
+ [Symbol.toStringTag] = 'ReadableStream';
202
238
  }
203
239
  exports.PonyfillReadableStream = PonyfillReadableStream;
204
240
  function isPonyfillReadableStream(obj) {
package/cjs/Request.js CHANGED
@@ -1,9 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PonyfillRequest = void 0;
4
- const http_1 = require("http");
5
- const https_1 = require("https");
6
- const AbortController_js_1 = require("./AbortController.js");
4
+ const node_http_1 = require("node:http");
5
+ const node_https_1 = require("node:https");
7
6
  const Body_js_1 = require("./Body.js");
8
7
  const Headers_js_1 = require("./Headers.js");
9
8
  const URL_js_1 = require("./URL.js");
@@ -42,7 +41,7 @@ class PonyfillRequest extends Body_js_1.PonyfillBody {
42
41
  bodyInit = options.body || null;
43
42
  requestInit = options;
44
43
  }
45
- super(bodyInit, options);
44
+ super(bodyInit, requestInit);
46
45
  this._url = _url;
47
46
  this._parsedUrl = _parsedUrl;
48
47
  this.cache = requestInit?.cache || 'default';
@@ -58,7 +57,6 @@ class PonyfillRequest extends Body_js_1.PonyfillBody {
58
57
  this.redirect = requestInit?.redirect || 'follow';
59
58
  this.referrer = requestInit?.referrer || 'about:client';
60
59
  this.referrerPolicy = requestInit?.referrerPolicy || 'no-referrer';
61
- this._signal = requestInit?.signal;
62
60
  this.headersSerializer = requestInit?.headersSerializer;
63
61
  this.duplex = requestInit?.duplex || 'half';
64
62
  this.destination = 'document';
@@ -71,10 +69,10 @@ class PonyfillRequest extends Body_js_1.PonyfillBody {
71
69
  if (requestInit.agent === false) {
72
70
  this.agent = false;
73
71
  }
74
- else if (protocol.startsWith('http:') && requestInit.agent instanceof http_1.Agent) {
72
+ else if (protocol.startsWith('http:') && requestInit.agent instanceof node_http_1.Agent) {
75
73
  this.agent = requestInit.agent;
76
74
  }
77
- else if (protocol.startsWith('https:') && requestInit.agent instanceof https_1.Agent) {
75
+ else if (protocol.startsWith('https:') && requestInit.agent instanceof node_https_1.Agent) {
78
76
  this.agent = requestInit.agent;
79
77
  }
80
78
  }
@@ -93,6 +91,10 @@ class PonyfillRequest extends Body_js_1.PonyfillBody {
93
91
  referrer;
94
92
  referrerPolicy;
95
93
  _url;
94
+ get signal() {
95
+ this._signal ||= new AbortController().signal;
96
+ return this._signal;
97
+ }
96
98
  get url() {
97
99
  if (this._url == null) {
98
100
  if (this._parsedUrl) {
@@ -118,15 +120,6 @@ class PonyfillRequest extends Body_js_1.PonyfillBody {
118
120
  }
119
121
  duplex;
120
122
  agent;
121
- _signal;
122
- get signal() {
123
- // Create a new signal only if needed
124
- // Because the creation of signal is expensive
125
- if (!this._signal) {
126
- this._signal = new AbortController_js_1.PonyfillAbortController().signal;
127
- }
128
- return this._signal;
129
- }
130
123
  clone() {
131
124
  return this;
132
125
  }
package/cjs/Response.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PonyfillResponse = void 0;
4
- const http_1 = require("http");
4
+ const node_http_1 = require("node:http");
5
5
  const Body_js_1 = require("./Body.js");
6
6
  const Headers_js_1 = require("./Headers.js");
7
7
  const JSON_CONTENT_TYPE = 'application/json; charset=utf-8';
@@ -14,7 +14,7 @@ class PonyfillResponse extends Body_js_1.PonyfillBody {
14
14
  ? init.headers
15
15
  : new Headers_js_1.PonyfillHeaders(init?.headers);
16
16
  this.status = init?.status || 200;
17
- this.statusText = init?.statusText || http_1.STATUS_CODES[this.status] || 'OK';
17
+ this.statusText = init?.statusText || node_http_1.STATUS_CODES[this.status] || 'OK';
18
18
  this.url = init?.url || '';
19
19
  this.redirected = init?.redirected || false;
20
20
  this.type = init?.type || 'default';
@@ -48,15 +48,61 @@ class PonyfillResponse extends Body_js_1.PonyfillBody {
48
48
  status,
49
49
  });
50
50
  }
51
- static json(data, init = {}) {
52
- init.headers =
53
- init?.headers && (0, Headers_js_1.isHeadersLike)(init.headers)
54
- ? init.headers
55
- : new Headers_js_1.PonyfillHeaders(init?.headers);
56
- if (!init.headers.has('content-type')) {
57
- init.headers.set('content-type', JSON_CONTENT_TYPE);
51
+ static json(data, init) {
52
+ const bodyInit = JSON.stringify(data);
53
+ if (!init) {
54
+ init = {
55
+ headers: {
56
+ 'content-type': JSON_CONTENT_TYPE,
57
+ 'content-length': Buffer.byteLength(bodyInit).toString(),
58
+ },
59
+ };
60
+ }
61
+ else if (!init.headers) {
62
+ init.headers = {
63
+ 'content-type': JSON_CONTENT_TYPE,
64
+ 'content-length': Buffer.byteLength(bodyInit).toString(),
65
+ };
66
+ }
67
+ else if ((0, Headers_js_1.isHeadersLike)(init.headers)) {
68
+ if (!init.headers.has('content-type')) {
69
+ init.headers.set('content-type', JSON_CONTENT_TYPE);
70
+ }
71
+ if (!init.headers.has('content-length')) {
72
+ init.headers.set('content-length', Buffer.byteLength(bodyInit).toString());
73
+ }
74
+ }
75
+ else if (Array.isArray(init.headers)) {
76
+ let contentTypeExists = false;
77
+ let contentLengthExists = false;
78
+ for (const [key] of init.headers) {
79
+ if (contentLengthExists && contentTypeExists) {
80
+ break;
81
+ }
82
+ if (!contentTypeExists && key.toLowerCase() === 'content-type') {
83
+ contentTypeExists = true;
84
+ }
85
+ else if (!contentLengthExists && key.toLowerCase() === 'content-length') {
86
+ contentLengthExists = true;
87
+ }
88
+ }
89
+ if (!contentTypeExists) {
90
+ init.headers.push(['content-type', JSON_CONTENT_TYPE]);
91
+ }
92
+ if (!contentLengthExists) {
93
+ init.headers.push(['content-length', Buffer.byteLength(bodyInit).toString()]);
94
+ }
95
+ }
96
+ else if (typeof init.headers === 'object') {
97
+ if (init.headers?.['content-type'] == null) {
98
+ init.headers['content-type'] = JSON_CONTENT_TYPE;
99
+ }
100
+ if (init.headers?.['content-length'] == null) {
101
+ init.headers['content-length'] = Buffer.byteLength(bodyInit).toString();
102
+ }
58
103
  }
59
- return new PonyfillResponse(JSON.stringify(data), init);
104
+ return new PonyfillResponse(bodyInit, init);
60
105
  }
106
+ [Symbol.toStringTag] = 'Response';
61
107
  }
62
108
  exports.PonyfillResponse = PonyfillResponse;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PonyfillTextDecoder = exports.PonyfillTextEncoder = void 0;
4
4
  exports.PonyfillBtoa = PonyfillBtoa;
5
+ const node_buffer_1 = require("node:buffer");
5
6
  const utils_js_1 = require("./utils.js");
6
7
  class PonyfillTextEncoder {
7
8
  encoding;
@@ -9,7 +10,7 @@ class PonyfillTextEncoder {
9
10
  this.encoding = encoding;
10
11
  }
11
12
  encode(input) {
12
- return Buffer.from(input, this.encoding);
13
+ return node_buffer_1.Buffer.from(input, this.encoding);
13
14
  }
14
15
  encodeInto(source, destination) {
15
16
  const buffer = this.encode(source);
@@ -33,16 +34,16 @@ class PonyfillTextDecoder {
33
34
  }
34
35
  }
35
36
  decode(input) {
36
- if (Buffer.isBuffer(input)) {
37
+ if (node_buffer_1.Buffer.isBuffer(input)) {
37
38
  return input.toString(this.encoding);
38
39
  }
39
40
  if ((0, utils_js_1.isArrayBufferView)(input)) {
40
- return Buffer.from(input.buffer, input.byteOffset, input.byteLength).toString(this.encoding);
41
+ return node_buffer_1.Buffer.from(input.buffer, input.byteOffset, input.byteLength).toString(this.encoding);
41
42
  }
42
- return Buffer.from(input).toString(this.encoding);
43
+ return node_buffer_1.Buffer.from(input).toString(this.encoding);
43
44
  }
44
45
  }
45
46
  exports.PonyfillTextDecoder = PonyfillTextDecoder;
46
47
  function PonyfillBtoa(input) {
47
- return Buffer.from(input, 'binary').toString('base64');
48
+ return node_buffer_1.Buffer.from(input, 'binary').toString('base64');
48
49
  }
@@ -7,9 +7,7 @@ class PonyfillTextDecoderStream extends TransformStream_js_1.PonyfillTransformSt
7
7
  textDecoder;
8
8
  constructor(encoding, options) {
9
9
  super({
10
- transform: (chunk, controller) => {
11
- controller.enqueue(this.textDecoder.decode(chunk, { stream: true }));
12
- },
10
+ transform: (chunk, controller) => controller.enqueue(this.textDecoder.decode(chunk, { stream: true })),
13
11
  });
14
12
  this.textDecoder = new TextEncoderDecoder_js_1.PonyfillTextDecoder(encoding, options);
15
13
  }
@@ -28,9 +26,7 @@ class PonyfillTextEncoderStream extends TransformStream_js_1.PonyfillTransformSt
28
26
  textEncoder;
29
27
  constructor(encoding) {
30
28
  super({
31
- transform: (chunk, controller) => {
32
- controller.enqueue(this.textEncoder.encode(chunk));
33
- },
29
+ transform: (chunk, controller) => controller.enqueue(this.textEncoder.encode(chunk)),
34
30
  });
35
31
  this.textEncoder = new TextEncoderDecoder_js_1.PonyfillTextEncoder(encoding);
36
32
  }