got 13.0.0 → 14.1.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()`.
@@ -9,12 +9,12 @@ type Error = NodeJS.ErrnoException;
9
9
  An error to be thrown when a request fails.
10
10
  Contains a `code` property with error class code, like `ECONNREFUSED`.
11
11
  */
12
- export declare class RequestError extends Error {
12
+ export declare class RequestError<T = unknown> extends Error {
13
13
  input?: string;
14
14
  code: string;
15
15
  stack: string;
16
16
  readonly options: Options;
17
- readonly response?: Response;
17
+ readonly response?: Response<T>;
18
18
  readonly request?: Request;
19
19
  readonly timings?: Timings;
20
20
  constructor(message: string, error: Partial<Error & {
@@ -35,8 +35,8 @@ export declare class MaxRedirectsError extends RequestError {
35
35
  An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304.
36
36
  Includes a `response` property.
37
37
  */
38
- export declare class HTTPError extends RequestError {
39
- readonly response: Response;
38
+ export declare class HTTPError<T = any> extends RequestError<T> {
39
+ readonly response: Response<T>;
40
40
  readonly request: Request;
41
41
  readonly timings: Timings;
42
42
  constructor(response: PlainResponse);
@@ -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';
@@ -93,6 +63,7 @@ export class MaxRedirectsError extends RequestError {
93
63
  An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304.
94
64
  Includes a `response` property.
95
65
  */
66
+ // TODO: Change `HTTPError<T = any>` to `HTTPError<T = unknown>` in the next major version to enforce type usage.
96
67
  // eslint-disable-next-line @typescript-eslint/naming-convention
97
68
  export class HTTPError extends RequestError {
98
69
  constructor(response) {
@@ -127,20 +98,10 @@ An error to be thrown when the request is aborted due to a timeout.
127
98
  Includes an `event` and `timings` property.
128
99
  */
129
100
  export class TimeoutError extends RequestError {
101
+ timings;
102
+ event;
130
103
  constructor(error, timings, request) {
131
104
  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
105
  this.name = 'TimeoutError';
145
106
  this.event = error.event;
146
107
  this.timings = timings;
@@ -4,9 +4,9 @@
4
4
  /// <reference types="node" resolution-mode="require"/>
5
5
  /// <reference types="node" resolution-mode="require"/>
6
6
  import { Duplex } from 'node:stream';
7
- import type { ClientRequest } from 'node:http';
7
+ import { type ClientRequest } from 'node:http';
8
8
  import type { Socket } from 'node:net';
9
- import type { Timings } from '@szmarczak/http-timer';
9
+ import { type Timings } from '@szmarczak/http-timer';
10
10
  import Options from './options.js';
11
11
  import { type PlainResponse, type Response } from './response.js';
12
12
  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`.
@@ -611,6 +485,7 @@ export default class Request extends Duplex {
611
485
  if (is.object(options.cookieJar) && rawCookies) {
612
486
  let promises = rawCookies.map(async (rawCookie) => options.cookieJar.setCookie(rawCookie, url.toString()));
613
487
  if (options.ignoreInvalidCookies) {
488
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
614
489
  promises = promises.map(async (promise) => {
615
490
  try {
616
491
  await promise;
@@ -630,76 +505,79 @@ export default class Request extends Duplex {
630
505
  if (this.isAborted) {
631
506
  return;
632
507
  }
633
- if (options.followRedirect && response.headers.location && redirectCodes.has(statusCode)) {
508
+ if (response.headers.location && redirectCodes.has(statusCode)) {
634
509
  // We're being redirected, we don't care about the response.
635
510
  // It'd be best to abort the request, but we can't because
636
511
  // 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));
512
+ const shouldFollow = typeof options.followRedirect === 'function' ? options.followRedirect(typedResponse) : options.followRedirect;
513
+ if (shouldFollow) {
514
+ response.resume();
515
+ this._cancelTimeouts();
516
+ this._unproxyEvents();
517
+ if (this.redirectUrls.length >= options.maxRedirects) {
518
+ this._beforeError(new MaxRedirectsError(this));
662
519
  return;
663
520
  }
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;
521
+ this._request = undefined;
522
+ const updatedOptions = new Options(undefined, undefined, this.options);
523
+ const serverRequestedGet = statusCode === 303 && updatedOptions.method !== 'GET' && updatedOptions.method !== 'HEAD';
524
+ const canRewrite = statusCode !== 307 && statusCode !== 308;
525
+ const userRequestedGet = updatedOptions.methodRewriting && canRewrite;
526
+ if (serverRequestedGet || userRequestedGet) {
527
+ updatedOptions.method = 'GET';
528
+ updatedOptions.body = undefined;
529
+ updatedOptions.json = undefined;
530
+ updatedOptions.form = undefined;
531
+ delete updatedOptions.headers['content-length'];
532
+ }
533
+ try {
534
+ // We need this in order to support UTF-8
535
+ const redirectBuffer = Buffer.from(response.headers.location, 'binary').toString();
536
+ const redirectUrl = new URL(redirectBuffer, url);
537
+ if (!isUnixSocketURL(url) && isUnixSocketURL(redirectUrl)) {
538
+ this._beforeError(new RequestError('Cannot redirect to UNIX socket', {}, this));
539
+ return;
668
540
  }
669
- if ('cookie' in updatedOptions.headers) {
670
- delete updatedOptions.headers.cookie;
541
+ // Redirecting to a different site, clear sensitive data.
542
+ if (redirectUrl.hostname !== url.hostname || redirectUrl.port !== url.port) {
543
+ if ('host' in updatedOptions.headers) {
544
+ delete updatedOptions.headers.host;
545
+ }
546
+ if ('cookie' in updatedOptions.headers) {
547
+ delete updatedOptions.headers.cookie;
548
+ }
549
+ if ('authorization' in updatedOptions.headers) {
550
+ delete updatedOptions.headers.authorization;
551
+ }
552
+ if (updatedOptions.username || updatedOptions.password) {
553
+ updatedOptions.username = '';
554
+ updatedOptions.password = '';
555
+ }
671
556
  }
672
- if ('authorization' in updatedOptions.headers) {
673
- delete updatedOptions.headers.authorization;
557
+ else {
558
+ redirectUrl.username = updatedOptions.username;
559
+ redirectUrl.password = updatedOptions.password;
674
560
  }
675
- if (updatedOptions.username || updatedOptions.password) {
676
- updatedOptions.username = '';
677
- updatedOptions.password = '';
561
+ this.redirectUrls.push(redirectUrl);
562
+ updatedOptions.prefixUrl = '';
563
+ updatedOptions.url = redirectUrl;
564
+ for (const hook of updatedOptions.hooks.beforeRedirect) {
565
+ // eslint-disable-next-line no-await-in-loop
566
+ await hook(updatedOptions, typedResponse);
678
567
  }
568
+ this.emit('redirect', updatedOptions, typedResponse);
569
+ this.options = updatedOptions;
570
+ await this._makeRequest();
679
571
  }
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);
572
+ catch (error) {
573
+ this._beforeError(error);
574
+ return;
690
575
  }
691
- this.emit('redirect', updatedOptions, typedResponse);
692
- this.options = updatedOptions;
693
- await this._makeRequest();
694
- }
695
- catch (error) {
696
- this._beforeError(error);
697
576
  return;
698
577
  }
699
- return;
700
578
  }
701
579
  // `HTTPError`s always have `error.response.body` defined.
702
- // Therefore we cannot retry if `options.throwHttpErrors` is false.
580
+ // Therefore, we cannot retry if `options.throwHttpErrors` is false.
703
581
  // On the last retry, if `options.throwHttpErrors` is false, we would need to return the body,
704
582
  // but that wouldn't be possible since the body would be already read in `error.response.body`.
705
583
  if (options.isStream && options.throwHttpErrors && !isResponseOk(typedResponse)) {
@@ -6,19 +6,15 @@
6
6
  /// <reference types="node" resolution-mode="require"/>
7
7
  /// <reference types="node" resolution-mode="require"/>
8
8
  /// <reference types="node" resolution-mode="require"/>
9
- /// <reference types="node" resolution-mode="require"/>
10
9
  import type { Buffer } from 'node:buffer';
11
- import { checkServerIdentity } from 'node:tls';
12
- import http from 'node:http';
13
- import https from 'node:https';
10
+ import { checkServerIdentity, type SecureContextOptions, type DetailedPeerCertificate } from 'node:tls';
11
+ import https, { type RequestOptions as HttpsRequestOptions, type Agent as HttpsAgent } from 'node:https';
12
+ import http, { type Agent as HttpAgent, type ClientRequest } from 'node:http';
14
13
  import type { Readable } from 'node:stream';
15
14
  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
15
  import CacheableLookup from 'cacheable-lookup';
20
16
  import http2wrapper, { type ClientHttp2Session } from 'http2-wrapper';
21
- import type { FormDataLike } from 'form-data-encoder';
17
+ import { type FormDataLike } from 'form-data-encoder';
22
18
  import type { StorageAdapter } from 'cacheable-request';
23
19
  import type ResponseLike from 'responselike';
24
20
  import type { IncomingMessageWithTimings } from '@szmarczak/http-timer';
@@ -841,15 +837,17 @@ export default class Options {
841
837
  get hooks(): Hooks;
842
838
  set hooks(value: Hooks);
843
839
  /**
844
- Defines if redirect responses should be followed automatically.
840
+ Whether redirect responses should be followed automatically.
841
+
842
+ Optionally, pass a function to dynamically decide based on the response object.
845
843
 
846
844
  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
845
  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
846
 
849
847
  @default true
850
848
  */
851
- get followRedirect(): boolean;
852
- set followRedirect(value: boolean);
849
+ get followRedirect(): boolean | ((response: PlainResponse) => boolean);
850
+ set followRedirect(value: boolean | ((response: PlainResponse) => boolean));
853
851
  get followRedirects(): unknown;
854
852
  set followRedirects(_value: unknown);
855
853
  /**
@@ -1135,6 +1133,7 @@ export default class Options {
1135
1133
  username: string;
1136
1134
  password: string;
1137
1135
  json: unknown;
1136
+ followRedirect: boolean | ((response: PlainResponse) => boolean);
1138
1137
  retry: Partial<RetryOptions>;
1139
1138
  agent: Agents;
1140
1139
  h2session: http2wrapper.ClientHttp2Session | undefined;
@@ -1146,7 +1145,7 @@ export default class Options {
1146
1145
  cookieJar: PromiseCookieJar | ToughCookieJar | undefined;
1147
1146
  signal: AbortSignal | undefined;
1148
1147
  ignoreInvalidCookies: boolean;
1149
- searchParams: string | SearchParameters | URLSearchParams | undefined;
1148
+ searchParams: string | URLSearchParams | SearchParameters | undefined;
1150
1149
  dnsLookup: {
1151
1150
  (hostname: string, family: import("cacheable-lookup").IPFamily, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1152
1151
  (hostname: string, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
@@ -1158,7 +1157,6 @@ export default class Options {
1158
1157
  dnsCache: boolean | CacheableLookup | undefined;
1159
1158
  context: Record<string, unknown>;
1160
1159
  hooks: Hooks;
1161
- followRedirect: boolean;
1162
1160
  maxRedirects: number;
1163
1161
  cache: string | boolean | StorageAdapter | undefined;
1164
1162
  throwHttpErrors: boolean;
@@ -1209,7 +1207,7 @@ export default class Options {
1209
1207
  (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1210
1208
  } | undefined;
1211
1209
  family: DnsLookupIpVersion;
1212
- agent: false | Agents | http.Agent | undefined;
1210
+ agent: false | http.Agent | Agents | undefined;
1213
1211
  setHost: boolean;
1214
1212
  method: Method;
1215
1213
  maxHeaderSize: number | undefined;
@@ -1233,6 +1231,10 @@ export default class Options {
1233
1231
  socketPath?: string | undefined;
1234
1232
  uniqueHeaders?: (string | string[])[] | undefined;
1235
1233
  joinDuplicateHeaders?: boolean | undefined;
1234
+ ALPNCallback?: ((arg: {
1235
+ servername: string;
1236
+ protocols: string[];
1237
+ }) => string | undefined) | undefined;
1236
1238
  clientCertEngine?: string | undefined;
1237
1239
  privateKeyEngine?: string | undefined;
1238
1240
  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,5 +1,4 @@
1
1
  /// <reference types="node" resolution-mode="require"/>
2
- /// <reference types="node" resolution-mode="require"/>
3
2
  import type { Buffer } from 'node:buffer';
4
3
  import type { IncomingMessageWithTimings, Timings } from '@szmarczak/http-timer';
5
4
  import { RequestError } from './errors.js';
@@ -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,2 +1 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
1
  export default function isUnixSocketURL(url: URL): boolean;
@@ -1,4 +1,3 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
1
  export type URLOptions = {
3
2
  href?: string;
4
3
  protocol?: string;
@@ -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';
@@ -1,10 +1,9 @@
1
1
  /// <reference types="node" resolution-mode="require"/>
2
- /// <reference types="node" resolution-mode="require"/>
3
2
  import type { Buffer } from 'node:buffer';
4
3
  import type { CancelableRequest } from './as-promise/types.js';
5
4
  import type { Response } from './core/response.js';
6
5
  import type Options from './core/options.js';
7
- import type { PaginationOptions, OptionsInit } from './core/options.js';
6
+ import { type PaginationOptions, type OptionsInit } from './core/options.js';
8
7
  import type Request from './core/index.js';
9
8
  type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
10
9
  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.1.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)