got 13.0.0 → 14.0.0

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.
@@ -3,7 +3,7 @@ import type { Buffer } from 'node:buffer';
3
3
  import type PCancelable from 'p-cancelable';
4
4
  import { RequestError } from '../core/errors.js';
5
5
  import type Request from '../core/index.js';
6
- import type { RequestEvents } from '../core/index.js';
6
+ import { type RequestEvents } from '../core/index.js';
7
7
  import type { Response } from '../core/response.js';
8
8
  /**
9
9
  An error to be thrown when the request is aborted with `.cancel()`.
@@ -8,44 +8,14 @@ An error to be thrown when a request fails.
8
8
  Contains a `code` property with error class code, like `ECONNREFUSED`.
9
9
  */
10
10
  export class RequestError extends Error {
11
+ input;
12
+ code;
13
+ stack;
14
+ response;
15
+ request;
16
+ timings;
11
17
  constructor(message, error, self) {
12
18
  super(message);
13
- Object.defineProperty(this, "input", {
14
- enumerable: true,
15
- configurable: true,
16
- writable: true,
17
- value: void 0
18
- });
19
- Object.defineProperty(this, "code", {
20
- enumerable: true,
21
- configurable: true,
22
- writable: true,
23
- value: void 0
24
- });
25
- Object.defineProperty(this, "stack", {
26
- enumerable: true,
27
- configurable: true,
28
- writable: true,
29
- value: void 0
30
- });
31
- Object.defineProperty(this, "response", {
32
- enumerable: true,
33
- configurable: true,
34
- writable: true,
35
- value: void 0
36
- });
37
- Object.defineProperty(this, "request", {
38
- enumerable: true,
39
- configurable: true,
40
- writable: true,
41
- value: void 0
42
- });
43
- Object.defineProperty(this, "timings", {
44
- enumerable: true,
45
- configurable: true,
46
- writable: true,
47
- value: void 0
48
- });
49
19
  Error.captureStackTrace(this, this.constructor);
50
20
  this.name = 'RequestError';
51
21
  this.code = error.code ?? 'ERR_GOT_REQUEST_ERROR';
@@ -127,20 +97,10 @@ An error to be thrown when the request is aborted due to a timeout.
127
97
  Includes an `event` and `timings` property.
128
98
  */
129
99
  export class TimeoutError extends RequestError {
100
+ timings;
101
+ event;
130
102
  constructor(error, timings, request) {
131
103
  super(error.message, error, request);
132
- Object.defineProperty(this, "timings", {
133
- enumerable: true,
134
- configurable: true,
135
- writable: true,
136
- value: void 0
137
- });
138
- Object.defineProperty(this, "event", {
139
- enumerable: true,
140
- configurable: true,
141
- writable: true,
142
- value: void 0
143
- });
144
104
  this.name = 'TimeoutError';
145
105
  this.event = error.event;
146
106
  this.timings = timings;
@@ -3,10 +3,11 @@
3
3
  /// <reference types="node" resolution-mode="require"/>
4
4
  /// <reference types="node" resolution-mode="require"/>
5
5
  /// <reference types="node" resolution-mode="require"/>
6
+ /// <reference types="node" resolution-mode="require"/>
6
7
  import { Duplex } from 'node:stream';
7
- import type { ClientRequest } from 'node:http';
8
+ import { type ClientRequest } from 'node:http';
8
9
  import type { Socket } from 'node:net';
9
- import type { Timings } from '@szmarczak/http-timer';
10
+ import { type Timings } from '@szmarczak/http-timer';
10
11
  import Options from './options.js';
11
12
  import { type PlainResponse, type Response } from './response.js';
12
13
  import { RequestError } from './errors.js';
@@ -6,7 +6,7 @@ import timer from '@szmarczak/http-timer';
6
6
  import CacheableRequest, { CacheError as CacheableCacheError, } from 'cacheable-request';
7
7
  import decompressResponse from 'decompress-response';
8
8
  import is from '@sindresorhus/is';
9
- import getStream from 'get-stream';
9
+ import { getStreamAsBuffer } from 'get-stream';
10
10
  import { FormDataEncoder, isFormData as isFormDataLike } from 'form-data-encoder';
11
11
  import getBodySize from './utils/get-body-size.js';
12
12
  import isFormData from './utils/is-form-data.js';
@@ -20,7 +20,6 @@ import { isResponseOk } from './response.js';
20
20
  import isClientRequest from './utils/is-client-request.js';
21
21
  import isUnixSocketURL from './utils/is-unix-socket-url.js';
22
22
  import { RequestError, ReadError, MaxRedirectsError, HTTPError, TimeoutError, UploadError, CacheError, AbortError, } from './errors.js';
23
- const { buffer: getStreamAsBuffer } = getStream;
24
23
  const supportsBrotli = is.string(process.versions.brotli);
25
24
  const methodsWithoutBody = new Set(['GET', 'HEAD']);
26
25
  const cacheableStore = new WeakableMap();
@@ -34,6 +33,34 @@ const proxiedRequestEvents = [
34
33
  ];
35
34
  const noop = () => { };
36
35
  export default class Request extends Duplex {
36
+ // @ts-expect-error - Ignoring for now.
37
+ ['constructor'];
38
+ _noPipe;
39
+ // @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
40
+ options;
41
+ response;
42
+ requestUrl;
43
+ redirectUrls;
44
+ retryCount;
45
+ _stopRetry;
46
+ _downloadedSize;
47
+ _uploadedSize;
48
+ _stopReading;
49
+ _pipedServerResponses;
50
+ _request;
51
+ _responseSize;
52
+ _bodySize;
53
+ _unproxyEvents;
54
+ _isFromCache;
55
+ _cannotHaveBody;
56
+ _triggerRead;
57
+ _cancelTimeouts;
58
+ _removeListeners;
59
+ _nativeResponse;
60
+ _flushed;
61
+ _aborted;
62
+ // We need this because `this._request` if `undefined` when using cache
63
+ _requestInitialized;
37
64
  constructor(url, options, defaults) {
38
65
  super({
39
66
  // Don't destroy immediately, as the error may be emitted on unsuccessful retry
@@ -41,159 +68,6 @@ export default class Request extends Duplex {
41
68
  // It needs to be zero because we're just proxying the data to another stream
42
69
  highWaterMark: 0,
43
70
  });
44
- // @ts-expect-error - Ignoring for now.
45
- Object.defineProperty(this, 'constructor', {
46
- enumerable: true,
47
- configurable: true,
48
- writable: true,
49
- value: void 0
50
- });
51
- Object.defineProperty(this, "_noPipe", {
52
- enumerable: true,
53
- configurable: true,
54
- writable: true,
55
- value: void 0
56
- });
57
- // @ts-expect-error https://github.com/microsoft/TypeScript/issues/9568
58
- Object.defineProperty(this, "options", {
59
- enumerable: true,
60
- configurable: true,
61
- writable: true,
62
- value: void 0
63
- });
64
- Object.defineProperty(this, "response", {
65
- enumerable: true,
66
- configurable: true,
67
- writable: true,
68
- value: void 0
69
- });
70
- Object.defineProperty(this, "requestUrl", {
71
- enumerable: true,
72
- configurable: true,
73
- writable: true,
74
- value: void 0
75
- });
76
- Object.defineProperty(this, "redirectUrls", {
77
- enumerable: true,
78
- configurable: true,
79
- writable: true,
80
- value: void 0
81
- });
82
- Object.defineProperty(this, "retryCount", {
83
- enumerable: true,
84
- configurable: true,
85
- writable: true,
86
- value: void 0
87
- });
88
- Object.defineProperty(this, "_stopRetry", {
89
- enumerable: true,
90
- configurable: true,
91
- writable: true,
92
- value: void 0
93
- });
94
- Object.defineProperty(this, "_downloadedSize", {
95
- enumerable: true,
96
- configurable: true,
97
- writable: true,
98
- value: void 0
99
- });
100
- Object.defineProperty(this, "_uploadedSize", {
101
- enumerable: true,
102
- configurable: true,
103
- writable: true,
104
- value: void 0
105
- });
106
- Object.defineProperty(this, "_stopReading", {
107
- enumerable: true,
108
- configurable: true,
109
- writable: true,
110
- value: void 0
111
- });
112
- Object.defineProperty(this, "_pipedServerResponses", {
113
- enumerable: true,
114
- configurable: true,
115
- writable: true,
116
- value: void 0
117
- });
118
- Object.defineProperty(this, "_request", {
119
- enumerable: true,
120
- configurable: true,
121
- writable: true,
122
- value: void 0
123
- });
124
- Object.defineProperty(this, "_responseSize", {
125
- enumerable: true,
126
- configurable: true,
127
- writable: true,
128
- value: void 0
129
- });
130
- Object.defineProperty(this, "_bodySize", {
131
- enumerable: true,
132
- configurable: true,
133
- writable: true,
134
- value: void 0
135
- });
136
- Object.defineProperty(this, "_unproxyEvents", {
137
- enumerable: true,
138
- configurable: true,
139
- writable: true,
140
- value: void 0
141
- });
142
- Object.defineProperty(this, "_isFromCache", {
143
- enumerable: true,
144
- configurable: true,
145
- writable: true,
146
- value: void 0
147
- });
148
- Object.defineProperty(this, "_cannotHaveBody", {
149
- enumerable: true,
150
- configurable: true,
151
- writable: true,
152
- value: void 0
153
- });
154
- Object.defineProperty(this, "_triggerRead", {
155
- enumerable: true,
156
- configurable: true,
157
- writable: true,
158
- value: void 0
159
- });
160
- Object.defineProperty(this, "_cancelTimeouts", {
161
- enumerable: true,
162
- configurable: true,
163
- writable: true,
164
- value: void 0
165
- });
166
- Object.defineProperty(this, "_removeListeners", {
167
- enumerable: true,
168
- configurable: true,
169
- writable: true,
170
- value: void 0
171
- });
172
- Object.defineProperty(this, "_nativeResponse", {
173
- enumerable: true,
174
- configurable: true,
175
- writable: true,
176
- value: void 0
177
- });
178
- Object.defineProperty(this, "_flushed", {
179
- enumerable: true,
180
- configurable: true,
181
- writable: true,
182
- value: void 0
183
- });
184
- Object.defineProperty(this, "_aborted", {
185
- enumerable: true,
186
- configurable: true,
187
- writable: true,
188
- value: void 0
189
- });
190
- // We need this because `this._request` if `undefined` when using cache
191
- Object.defineProperty(this, "_requestInitialized", {
192
- enumerable: true,
193
- configurable: true,
194
- writable: true,
195
- value: void 0
196
- });
197
71
  this._downloadedSize = 0;
198
72
  this._uploadedSize = 0;
199
73
  this._stopReading = false;
@@ -313,7 +187,7 @@ export default class Request extends Duplex {
313
187
  void (async () => {
314
188
  // Node.js parser is really weird.
315
189
  // It emits post-request Parse Errors on the same instance as previous request. WTF.
316
- // Therefore we need to check if it has been destroyed as well.
190
+ // Therefore, we need to check if it has been destroyed as well.
317
191
  //
318
192
  // Furthermore, Node.js 16 `response.destroy()` doesn't immediately destroy the socket,
319
193
  // but makes the response unreadable. So we additionally need to check `response.readable`.
@@ -630,76 +504,79 @@ export default class Request extends Duplex {
630
504
  if (this.isAborted) {
631
505
  return;
632
506
  }
633
- if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {
507
+ if (response.headers.location && redirectCodes.has(statusCode)) {
634
508
  // We're being redirected, we don't care about the response.
635
509
  // It'd be best to abort the request, but we can't because
636
510
  // we would have to sacrifice the TCP connection. We don't want that.
637
- response.resume();
638
- this._cancelTimeouts();
639
- this._unproxyEvents();
640
- if (this.redirectUrls.length >= options.maxRedirects) {
641
- this._beforeError(new MaxRedirectsError(this));
642
- return;
643
- }
644
- this._request = undefined;
645
- const updatedOptions = new Options(undefined, undefined, this.options);
646
- const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD';
647
- const canRewrite = statusCode !== 307 && statusCode !== 308;
648
- const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
649
- if (serverRequestedGet || userRequestedGet) {
650
- updatedOptions.method = 'GET';
651
- updatedOptions.body = undefined;
652
- updatedOptions.json = undefined;
653
- updatedOptions.form = undefined;
654
- delete updatedOptions.headers['content-length'];
655
- }
656
- try {
657
- // We need this in order to support UTF-8
658
- const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
659
- const redirectUrl = new URL(redirectBuffer, url);
660
- if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) {
661
- this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));
511
+ const shouldFollow = typeof options.followRedirect === 'function' ? options.followRedirect(typedResponse) : options.followRedirect;
512
+ if (shouldFollow) {
513
+ response.resume();
514
+ this._cancelTimeouts();
515
+ this._unproxyEvents();
516
+ if (this.redirectUrls.length >= options.maxRedirects) {
517
+ this._beforeError(new MaxRedirectsError(this));
662
518
  return;
663
519
  }
664
- // Redirecting to a different site, clear sensitive data.
665
- if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) {
666
- if ('host' in updatedOptions.headers) {
667
- delete updatedOptions.headers.host;
520
+ this._request = undefined;
521
+ const updatedOptions = new Options(undefined, undefined, this.options);
522
+ const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD';
523
+ const canRewrite = statusCode !== 307 && statusCode !== 308;
524
+ const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
525
+ if (serverRequestedGet || userRequestedGet) {
526
+ updatedOptions.method = 'GET';
527
+ updatedOptions.body = undefined;
528
+ updatedOptions.json = undefined;
529
+ updatedOptions.form = undefined;
530
+ delete updatedOptions.headers['content-length'];
531
+ }
532
+ try {
533
+ // We need this in order to support UTF-8
534
+ const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
535
+ const redirectUrl = new URL(redirectBuffer, url);
536
+ if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) {
537
+ this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));
538
+ return;
668
539
  }
669
- if ('cookie' in updatedOptions.headers) {
670
- delete updatedOptions.headers.cookie;
540
+ // Redirecting to a different site, clear sensitive data.
541
+ if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) {
542
+ if ('host' in updatedOptions.headers) {
543
+ delete updatedOptions.headers.host;
544
+ }
545
+ if ('cookie' in updatedOptions.headers) {
546
+ delete updatedOptions.headers.cookie;
547
+ }
548
+ if ('authorization' in updatedOptions.headers) {
549
+ delete updatedOptions.headers.authorization;
550
+ }
551
+ if (updatedOptions.username || updatedOptions.password) {
552
+ updatedOptions.username = '';
553
+ updatedOptions.password = '';
554
+ }
671
555
  }
672
- if ('authorization' in updatedOptions.headers) {
673
- delete updatedOptions.headers.authorization;
556
+ else {
557
+ redirectUrl.username = updatedOptions.username;
558
+ redirectUrl.password = updatedOptions.password;
674
559
  }
675
- if (updatedOptions.username || updatedOptions.password) {
676
- updatedOptions.username = '';
677
- updatedOptions.password = '';
560
+ this.redirectUrls.push(redirectUrl);
561
+ updatedOptions.prefixUrl = '';
562
+ updatedOptions.url = redirectUrl;
563
+ for (const hook of updatedOptions.hooks.beforeRedirect) {
564
+ // eslint-disable-next-line no-await-in-loop
565
+ await hook(updatedOptions, typedResponse);
678
566
  }
567
+ this.emit('redirect', updatedOptions, typedResponse);
568
+ this.options = updatedOptions;
569
+ await this._makeRequest();
679
570
  }
680
- else {
681
- redirectUrl.username = updatedOptions.username;
682
- redirectUrl.password = updatedOptions.password;
683
- }
684
- this.redirectUrls.push(redirectUrl);
685
- updatedOptions.prefixUrl = '';
686
- updatedOptions.url = redirectUrl;
687
- for (const hook of updatedOptions.hooks.beforeRedirect) {
688
- // eslint-disable-next-line no-await-in-loop
689
- await hook(updatedOptions, typedResponse);
571
+ catch (error) {
572
+ this._beforeError(error);
573
+ return;
690
574
  }
691
- this.emit('redirect', updatedOptions, typedResponse);
692
- this.options = updatedOptions;
693
- await this._makeRequest();
694
- }
695
- catch (error) {
696
- this._beforeError(error);
697
575
  return;
698
576
  }
699
- return;
700
577
  }
701
578
  // `HTTPError`s always have `error.response.body` defined.
702
- // Therefore we cannot retry if `options.throwHttpErrors` is false.
579
+ // Therefore, we cannot retry if `options.throwHttpErrors` is false.
703
580
  // On the last retry, if `options.throwHttpErrors` is false, we would need to return the body,
704
581
  // but that wouldn't be possible since the body would be already read in `error.response.body`.
705
582
  if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) {
@@ -8,17 +8,14 @@
8
8
  /// <reference types="node" resolution-mode="require"/>
9
9
  /// <reference types="node" resolution-mode="require"/>
10
10
  import type { Buffer } from 'node:buffer';
11
- import { checkServerIdentity } from 'node:tls';
12
- import http from 'node:http';
13
- import https from 'node:https';
11
+ import { checkServerIdentity, type SecureContextOptions, type DetailedPeerCertificate } from 'node:tls';
12
+ import https, { type RequestOptions as HttpsRequestOptions, type Agent as HttpsAgent } from 'node:https';
13
+ import http, { type Agent as HttpAgent, type ClientRequest } from 'node:http';
14
14
  import type { Readable } from 'node:stream';
15
15
  import type { Socket } from 'node:net';
16
- import type { SecureContextOptions, DetailedPeerCertificate } from 'node:tls';
17
- import type { Agent as HttpAgent, ClientRequest } from 'node:http';
18
- import type { RequestOptions as HttpsRequestOptions, Agent as HttpsAgent } from 'node:https';
19
16
  import CacheableLookup from 'cacheable-lookup';
20
17
  import http2wrapper, { type ClientHttp2Session } from 'http2-wrapper';
21
- import type { FormDataLike } from 'form-data-encoder';
18
+ import { type FormDataLike } from 'form-data-encoder';
22
19
  import type { StorageAdapter } from 'cacheable-request';
23
20
  import type ResponseLike from 'responselike';
24
21
  import type { IncomingMessageWithTimings } from '@szmarczak/http-timer';
@@ -841,15 +838,17 @@ export default class Options {
841
838
  get hooks(): Hooks;
842
839
  set hooks(value: Hooks);
843
840
  /**
844
- Defines if redirect responses should be followed automatically.
841
+ Whether redirect responses should be followed automatically.
842
+
843
+ Optionally, pass a function to dynamically decide based on the response object.
845
844
 
846
845
  Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`.
847
846
  This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`.
848
847
 
849
848
  @default true
850
849
  */
851
- get followRedirect(): boolean;
852
- set followRedirect(value: boolean);
850
+ get followRedirect(): boolean | ((response: PlainResponse) => boolean);
851
+ set followRedirect(value: boolean | ((response: PlainResponse) => boolean));
853
852
  get followRedirects(): unknown;
854
853
  set followRedirects(_value: unknown);
855
854
  /**
@@ -1135,6 +1134,7 @@ export default class Options {
1135
1134
  username: string;
1136
1135
  password: string;
1137
1136
  json: unknown;
1137
+ followRedirect: boolean | ((response: PlainResponse) => boolean);
1138
1138
  retry: Partial<RetryOptions>;
1139
1139
  agent: Agents;
1140
1140
  h2session: http2wrapper.ClientHttp2Session | undefined;
@@ -1158,7 +1158,6 @@ export default class Options {
1158
1158
  dnsCache: boolean | CacheableLookup | undefined;
1159
1159
  context: Record<string, unknown>;
1160
1160
  hooks: Hooks;
1161
- followRedirect: boolean;
1162
1161
  maxRedirects: number;
1163
1162
  cache: string | boolean | StorageAdapter | undefined;
1164
1163
  throwHttpErrors: boolean;
@@ -1209,7 +1208,7 @@ export default class Options {
1209
1208
  (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1210
1209
  } | undefined;
1211
1210
  family: DnsLookupIpVersion;
1212
- agent: false | Agents | http.Agent | undefined;
1211
+ agent: false | http.Agent | Agents | undefined;
1213
1212
  setHost: boolean;
1214
1213
  method: Method;
1215
1214
  maxHeaderSize: number | undefined;
@@ -1233,6 +1232,10 @@ export default class Options {
1233
1232
  socketPath?: string | undefined;
1234
1233
  uniqueHeaders?: (string | string[])[] | undefined;
1235
1234
  joinDuplicateHeaders?: boolean | undefined;
1235
+ ALPNCallback?: ((arg: {
1236
+ servername: string;
1237
+ protocols: string[];
1238
+ }) => string | undefined) | undefined;
1236
1239
  clientCertEngine?: string | undefined;
1237
1240
  privateKeyEngine?: string | undefined;
1238
1241
  privateKeyIdentifier?: string | undefined;
@@ -2,8 +2,8 @@ import process from 'node:process';
2
2
  import { promisify, inspect } from 'node:util';
3
3
  import { checkServerIdentity } from 'node:tls';
4
4
  // DO NOT use destructuring for `https.request` and `http.request` as it's not compatible with `nock`.
5
- import http from 'node:http';
6
5
  import https from 'node:https';
6
+ import http from 'node:http';
7
7
  import is, { assert } from '@sindresorhus/is';
8
8
  import lowercaseKeys from 'lowercase-keys';
9
9
  import CacheableLookup from 'cacheable-lookup';
@@ -295,31 +295,11 @@ const init = (options, withOptions, self) => {
295
295
  }
296
296
  };
297
297
  export default class Options {
298
+ _unixOptions;
299
+ _internals;
300
+ _merging;
301
+ _init;
298
302
  constructor(input, options, defaults) {
299
- Object.defineProperty(this, "_unixOptions", {
300
- enumerable: true,
301
- configurable: true,
302
- writable: true,
303
- value: void 0
304
- });
305
- Object.defineProperty(this, "_internals", {
306
- enumerable: true,
307
- configurable: true,
308
- writable: true,
309
- value: void 0
310
- });
311
- Object.defineProperty(this, "_merging", {
312
- enumerable: true,
313
- configurable: true,
314
- writable: true,
315
- value: void 0
316
- });
317
- Object.defineProperty(this, "_init", {
318
- enumerable: true,
319
- configurable: true,
320
- writable: true,
321
- value: void 0
322
- });
323
303
  assert.any([is.string, is.urlInstance, is.object, is.undefined], input);
324
304
  assert.any([is.object, is.undefined], options);
325
305
  assert.any([is.object, is.undefined], defaults);
@@ -1000,7 +980,9 @@ export default class Options {
1000
980
  }
1001
981
  }
1002
982
  /**
1003
- Defines if redirect responses should be followed automatically.
983
+ Whether redirect responses should be followed automatically.
984
+
985
+ Optionally, pass a function to dynamically decide based on the response object.
1004
986
 
1005
987
  Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`.
1006
988
  This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4). You can optionally turn on this behavior also for other redirect codes - see `methodRewriting`.
@@ -1011,7 +993,7 @@ export default class Options {
1011
993
  return this._internals.followRedirect;
1012
994
  }
1013
995
  set followRedirect(value) {
1014
- assert.boolean(value);
996
+ assert.any([is.boolean, is.function_], value);
1015
997
  this._internals.followRedirect = value;
1016
998
  }
1017
999
  get followRedirects() {
@@ -6,7 +6,7 @@ export default function parseLinkHeader(link) {
6
6
  const [rawUriReference, ...rawLinkParameters] = item.split(';');
7
7
  const trimmedUriReference = rawUriReference.trim();
8
8
  // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
9
- if (trimmedUriReference[0] !== '<' || trimmedUriReference[trimmedUriReference.length - 1] !== '>') {
9
+ if (trimmedUriReference[0] !== '<' || trimmedUriReference.at(-1) !== '>') {
10
10
  throw new Error(`Invalid format of the Link header reference: ${trimmedUriReference}`);
11
11
  }
12
12
  const reference = trimmedUriReference.slice(1, -1);
@@ -1,7 +1,9 @@
1
1
  import { RequestError } from './errors.js';
2
2
  export const isResponseOk = (response) => {
3
3
  const { statusCode } = response;
4
- const limitStatusCode = response.request.options.followRedirect ? 299 : 399;
4
+ const { followRedirect } = response.request.options;
5
+ const shouldFollow = typeof followRedirect === 'function' ? followRedirect(response) : followRedirect;
6
+ const limitStatusCode = shouldFollow ? 299 : 399;
5
7
  return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;
6
8
  };
7
9
  /**
@@ -1,3 +1,4 @@
1
+ /// <reference types="node" resolution-mode="require"/>
1
2
  import type { ClientRequest } from 'node:http';
2
3
  declare const reentry: unique symbol;
3
4
  type TimedOutOptions = {
@@ -3,20 +3,11 @@ import unhandler from './utils/unhandle.js';
3
3
  const reentry = Symbol('reentry');
4
4
  const noop = () => { };
5
5
  export class TimeoutError extends Error {
6
+ event;
7
+ code;
6
8
  constructor(threshold, event) {
7
9
  super(`Timeout awaiting '${event}' for ${threshold}ms`);
8
- Object.defineProperty(this, "event", {
9
- enumerable: true,
10
- configurable: true,
11
- writable: true,
12
- value: event
13
- });
14
- Object.defineProperty(this, "code", {
15
- enumerable: true,
16
- configurable: true,
17
- writable: true,
18
- value: void 0
19
- });
10
+ this.event = event;
20
11
  this.name = 'TimeoutError';
21
12
  this.code = 'ETIMEDOUT';
22
13
  }
@@ -1,4 +1,5 @@
1
1
  /// <reference types="node" resolution-mode="require"/>
2
+ /// <reference types="node" resolution-mode="require"/>
2
3
  import type { Writable, Readable } from 'node:stream';
3
4
  import type { ClientRequest } from 'node:http';
4
5
  declare function isClientRequest(clientRequest: Writable | Readable): clientRequest is ClientRequest;
@@ -1,17 +1,7 @@
1
1
  export default class WeakableMap {
2
+ weakMap;
3
+ map;
2
4
  constructor() {
3
- Object.defineProperty(this, "weakMap", {
4
- enumerable: true,
5
- configurable: true,
6
- writable: true,
7
- value: void 0
8
- });
9
- Object.defineProperty(this, "map", {
10
- enumerable: true,
11
- configurable: true,
12
- writable: true,
13
- value: void 0
14
- });
15
5
  this.weakMap = new WeakMap();
16
6
  this.map = new Map();
17
7
  }
@@ -7,6 +7,7 @@ const defaults = {
7
7
  };
8
8
  const got = create(defaults);
9
9
  export default got;
10
+ // TODO: Remove this in the next major version.
10
11
  export { got };
11
12
  export { default as Options } from './core/options.js';
12
13
  export * from './core/options.js';
@@ -4,7 +4,7 @@ import type { Buffer } from 'node:buffer';
4
4
  import type { CancelableRequest } from './as-promise/types.js';
5
5
  import type { Response } from './core/response.js';
6
6
  import type Options from './core/options.js';
7
- import type { PaginationOptions, OptionsInit } from './core/options.js';
7
+ import { type PaginationOptions, type OptionsInit } from './core/options.js';
8
8
  import type Request from './core/index.js';
9
9
  type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
10
10
  type Merge<FirstType, SecondType> = Except<FirstType, Extract<keyof FirstType, keyof SecondType>> & SecondType;
package/license CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
3
+ Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
6
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "got",
3
- "version": "13.0.0",
3
+ "version": "14.0.0",
4
4
  "description": "Human-friendly and powerful HTTP request library for Node.js",
5
5
  "license": "MIT",
6
6
  "repository": "sindresorhus/got",
@@ -10,11 +10,12 @@
10
10
  "types": "./dist/source/index.d.ts",
11
11
  "default": "./dist/source/index.js"
12
12
  },
13
+ "sideEffects": false,
13
14
  "engines": {
14
- "node": ">=16"
15
+ "node": ">=20"
15
16
  },
16
17
  "scripts": {
17
- "test": "xo && tsc --noEmit && ava",
18
+ "test": "xo && tsc --noEmit && NODE_OPTIONS='--import=tsx/esm' ava",
18
19
  "release": "np",
19
20
  "build": "del-cli dist && tsc",
20
21
  "prepare": "npm run build"
@@ -47,64 +48,61 @@
47
48
  "ky"
48
49
  ],
49
50
  "dependencies": {
50
- "@sindresorhus/is": "^5.2.0",
51
+ "@sindresorhus/is": "^6.1.0",
51
52
  "@szmarczak/http-timer": "^5.0.1",
52
53
  "cacheable-lookup": "^7.0.0",
53
- "cacheable-request": "^10.2.8",
54
+ "cacheable-request": "^10.2.14",
54
55
  "decompress-response": "^6.0.0",
55
- "form-data-encoder": "^2.1.2",
56
- "get-stream": "^6.0.1",
57
- "http2-wrapper": "^2.1.10",
56
+ "form-data-encoder": "^4.0.2",
57
+ "get-stream": "^8.0.1",
58
+ "http2-wrapper": "^2.2.1",
58
59
  "lowercase-keys": "^3.0.0",
59
- "p-cancelable": "^3.0.0",
60
+ "p-cancelable": "^4.0.1",
60
61
  "responselike": "^3.0.0"
61
62
  },
62
63
  "devDependencies": {
63
64
  "@hapi/bourne": "^3.0.0",
64
- "@sindresorhus/tsconfig": "^3.0.1",
65
- "@sinonjs/fake-timers": "^10.0.2",
66
- "@types/benchmark": "^2.1.2",
67
- "@types/express": "^4.17.17",
68
- "@types/node": "^18.14.5",
69
- "@types/pem": "^1.9.6",
70
- "@types/pify": "^5.0.1",
71
- "@types/readable-stream": "^2.3.13",
72
- "@types/request": "^2.48.8",
73
- "@types/sinon": "^10.0.11",
74
- "@types/sinonjs__fake-timers": "^8.1.1",
75
- "@types/tough-cookie": "^4.0.1",
76
- "ava": "^5.2.0",
77
- "axios": "^0.27.2",
65
+ "@sindresorhus/tsconfig": "^5.0.0",
66
+ "@sinonjs/fake-timers": "^11.2.2",
67
+ "@types/benchmark": "^2.1.5",
68
+ "@types/express": "^4.17.21",
69
+ "@types/node": "^20.10.0",
70
+ "@types/pem": "^1.14.4",
71
+ "@types/readable-stream": "^4.0.9",
72
+ "@types/request": "^2.48.12",
73
+ "@types/sinon": "^17.0.2",
74
+ "@types/sinonjs__fake-timers": "^8.1.5",
75
+ "ava": "^5.3.1",
76
+ "axios": "^1.6.2",
78
77
  "benchmark": "^2.1.4",
79
78
  "bluebird": "^3.7.2",
80
79
  "body-parser": "^1.20.2",
81
80
  "create-cert": "^1.0.6",
82
81
  "create-test-server": "^3.0.1",
83
- "del-cli": "^5.0.0",
84
- "delay": "^5.0.0",
85
- "express": "^4.17.3",
82
+ "del-cli": "^5.1.0",
83
+ "delay": "^6.0.0",
84
+ "express": "^4.18.2",
86
85
  "form-data": "^4.0.0",
87
- "formdata-node": "^5.0.0",
88
- "nock": "^13.3.0",
89
- "node-fetch": "^3.2.3",
90
- "np": "^7.6.0",
86
+ "formdata-node": "^6.0.3",
87
+ "nock": "^13.4.0",
88
+ "node-fetch": "^3.3.2",
89
+ "np": "^9.0.0",
91
90
  "nyc": "^15.1.0",
92
- "p-event": "^5.0.1",
93
- "pem": "^1.14.6",
94
- "pify": "^6.0.0",
95
- "readable-stream": "^4.2.0",
91
+ "p-event": "^6.0.0",
92
+ "pem": "^1.14.8",
93
+ "pify": "^6.1.0",
94
+ "readable-stream": "^4.4.2",
96
95
  "request": "^2.88.2",
97
- "sinon": "^15.0.1",
96
+ "sinon": "^17.0.1",
98
97
  "slow-stream": "0.0.4",
99
- "tempy": "^3.0.0",
98
+ "tempy": "^3.1.0",
100
99
  "then-busboy": "^5.2.1",
101
- "tough-cookie": "4.1.2",
102
- "ts-node": "^10.8.2",
103
- "type-fest": "^3.6.1",
104
- "typescript": "^5.0.4",
105
- "xo": "^0.54.2"
100
+ "tough-cookie": "^4.1.3",
101
+ "tsx": "^4.6.0",
102
+ "type-fest": "^4.8.2",
103
+ "typescript": "^5.3.2",
104
+ "xo": "^0.56.0"
106
105
  },
107
- "sideEffects": false,
108
106
  "ava": {
109
107
  "files": [
110
108
  "test/*"
@@ -113,9 +111,7 @@
113
111
  "extensions": {
114
112
  "ts": "module"
115
113
  },
116
- "nodeArguments": [
117
- "--loader=ts-node/esm"
118
- ]
114
+ "workerThreads": false
119
115
  },
120
116
  "nyc": {
121
117
  "reporter": [
@@ -148,7 +144,8 @@
148
144
  "@typescript-eslint/no-unsafe-argument": "off",
149
145
  "@typescript-eslint/promise-function-async": "off",
150
146
  "no-lone-blocks": "off",
151
- "unicorn/no-await-expression-member": "off"
147
+ "unicorn/no-await-expression-member": "off",
148
+ "unicorn/prefer-event-target": "off"
152
149
  }
153
150
  },
154
151
  "runkitExampleFilename": "./documentation/examples/runkit-example.js"
package/readme.md CHANGED
@@ -80,7 +80,7 @@
80
80
 
81
81
  ---
82
82
 
83
- For browser usage, we recommend [Ky](https://github.com/sindresorhus/ky) by the same people.
83
+ **You probably want [Ky](https://github.com/sindresorhus/ky) instead, by the same people. It's smaller, works in the browser too, and is more stable since it's built upon [`Fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).**
84
84
 
85
85
  ---
86
86
 
@@ -92,7 +92,7 @@ For browser usage, we recommend [Ky](https://github.com/sindresorhus/ky) by the
92
92
  npm install got
93
93
  ```
94
94
 
95
- **Warning:** This package is native [ESM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and no longer provides a CommonJS export. If your project uses CommonJS, you will have to [convert to ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) or use the [dynamic `import()`](https://v8.dev/features/dynamic-import) function. Please don't open issues for questions regarding CommonJS / ESM.
95
+ **Warning:** This package is native [ESM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) and no longer provides a CommonJS export. If your project uses CommonJS, you will have to [convert to ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). Please don't open issues for questions regarding CommonJS / ESM.
96
96
 
97
97
  **Got v11 is no longer maintained and we will not accept any backport requests.**
98
98
 
@@ -124,7 +124,7 @@ For advanced JSON usage, check out the [`parseJson`](documentation/2-options.md#
124
124
 
125
125
  ## Highlights
126
126
 
127
- - [Used by 8K+ packages and 4M+ repos](https://github.com/sindresorhus/got/network/dependents)
127
+ - [Used by 10K+ packages and 5M+ repos](https://github.com/sindresorhus/got/network/dependents)
128
128
  - [Actively maintained](https://github.com/sindresorhus/got/graphs/contributors)
129
129
  - [Trusted by many companies](#widely-used)
130
130
 
@@ -187,11 +187,6 @@ By default, Got will retry on failure. To disable this option, set [`options.ret
187
187
  - [`got-scraping`](https://github.com/apify/got-scraping) - Got wrapper specifically designed for web scraping purposes
188
188
  - [`got-ssrf`](https://github.com/JaneJeon/got-ssrf) - Got wrapper to protect server-side requests against SSRF attacks
189
189
 
190
- ### Legacy
191
-
192
- - [travis-got](https://github.com/samverschueren/travis-got) - Got convenience wrapper to interact with the Travis API
193
- - [graphql-got](https://github.com/kevva/graphql-got) - Got convenience wrapper to interact with GraphQL
194
-
195
190
  ## Comparison
196
191
 
197
192
  | | `got` | [`node-fetch`][n0] | [`ky`][k0] | [`axios`][a0] | [`superagent`][s0] |
@@ -393,14 +388,6 @@ By default, Got will retry on failure. To disable this option, set [`options.ret
393
388
  ---|---
394
389
  [Sindre Sorhus](https://sindresorhus.com) | [Szymon Marczak](https://github.com/szmarczak)
395
390
 
396
- ###### Former
397
-
398
- - [Vsevolod Strukchinsky](https://github.com/floatdrop)
399
- - [Alexander Tesfamichael](https://github.com/alextes)
400
- - [Brandon Smith](https://github.com/brandon93s)
401
- - [Luke Childs](https://github.com/lukechilds)
402
- - [Giovanni Minotti](https://github.com/Giotino)
403
-
404
391
  <a name="widely-used"></a>
405
392
  ## These amazing companies are using Got
406
393
 
@@ -519,9 +506,3 @@ By default, Got will retry on failure. To disable this option, set [`options.ret
519
506
  > Got has been a crucial component of Apify's scraping for years. We use it to extract data from billions of web pages every month, and we really appreciate the powerful API and extensibility, which allowed us to build our own specialized HTTP client on top of Got. The support has always been stellar too.
520
507
  >
521
508
  > — <a href="https://github.com/mnmkng">Ondra Urban</a>
522
-
523
- ## For enterprise
524
-
525
- Available as part of the Tidelift Subscription.
526
-
527
- The maintainers of `got` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-got?utm_source=npm-got&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)