UNPKG

49.7 kBTypeScriptView Raw
1import type { Buffer } from 'node:buffer';
2import { checkServerIdentity, type SecureContextOptions, type DetailedPeerCertificate } from 'node:tls';
3import https, { type RequestOptions as HttpsRequestOptions, type Agent as HttpsAgent } from 'node:https';
4import http, { type Agent as HttpAgent, type ClientRequest } from 'node:http';
5import type { Readable } from 'node:stream';
6import type { Socket } from 'node:net';
7import CacheableLookup from 'cacheable-lookup';
8import http2wrapper, { type ClientHttp2Session } from 'http2-wrapper';
9import { type FormDataLike } from 'form-data-encoder';
10import type { StorageAdapter } from 'cacheable-request';
11import type ResponseLike from 'responselike';
12import type { IncomingMessageWithTimings } from '@szmarczak/http-timer';
13import type { CancelableRequest } from '../as-promise/types.js';
14import type { PlainResponse, Response } from './response.js';
15import type { RequestError } from './errors.js';
16import type { Delays } from './timed-out.js';
17type Promisable<T> = T | Promise<T>;
18export type DnsLookupIpVersion = undefined | 4 | 6;
19type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
20export type NativeRequestOptions = HttpsRequestOptions & CacheOptions & {
21 checkServerIdentity?: CheckServerIdentityFunction;
22};
23type AcceptableResponse = IncomingMessageWithTimings | ResponseLike;
24type AcceptableRequestResult = Promisable<AcceptableResponse | ClientRequest> | undefined;
25export type RequestFunction = (url: URL, options: NativeRequestOptions, callback?: (response: AcceptableResponse) => void) => AcceptableRequestResult;
26export type Agents = {
27 http?: HttpAgent | false;
28 https?: HttpsAgent | false;
29 http2?: unknown | false;
30};
31export type Headers = Record<string, string | string[] | undefined>;
32export type ToughCookieJar = {
33 getCookieString: ((currentUrl: string, options: Record<string, unknown>, callback: (error: Error | null, cookies: string) => void) => void) & ((url: string, callback: (error: Error | null, cookieHeader: string) => void) => void);
34 setCookie: ((cookieOrString: unknown, currentUrl: string, options: Record<string, unknown>, callback: (error: Error | null, cookie: unknown) => void) => void) & ((rawCookie: string, url: string, callback: (error: Error | null, result: unknown) => void) => void);
35};
36export type PromiseCookieJar = {
37 getCookieString: (url: string) => Promise<string>;
38 setCookie: (rawCookie: string, url: string) => Promise<unknown>;
39};
40export type InitHook = (init: OptionsInit, self: Options) => void;
41export type BeforeRequestHook = (options: Options) => Promisable<void | Response | ResponseLike>;
42export type BeforeRedirectHook = (updatedOptions: Options, plainResponse: PlainResponse) => Promisable<void>;
43export type BeforeErrorHook = (error: RequestError) => Promisable<RequestError>;
44export type BeforeRetryHook = (error: RequestError, retryCount: number) => Promisable<void>;
45export type AfterResponseHook<ResponseType = unknown> = (response: Response<ResponseType>, retryWithMergedOptions: (options: OptionsInit) => never) => Promisable<Response | CancelableRequest<Response>>;
46/**
47All available hooks of Got.
48*/
49export type Hooks = {
50 /**
51 Called with the plain request options, right before their normalization.
52
53 The second argument represents the current `Options` instance.
54
55 @default []
56
57 **Note:**
58 > - This hook must be synchronous.
59
60 **Note:**
61 > - This is called every time options are merged.
62
63 **Note:**
64 > - The `options` object may not have the `url` property. To modify it, use a `beforeRequest` hook instead.
65
66 **Note:**
67 > - This hook is called when a new instance of `Options` is created.
68 > - Do not confuse this with the creation of `Request` or `got(…)`.
69
70 **Note:**
71 > - When using `got(url)` or `got(url, undefined, defaults)` this hook will **not** be called.
72
73 This is especially useful in conjunction with `got.extend()` when the input needs custom handling.
74
75 For example, this can be used to fix typos to migrate from older versions faster.
76
77 @example
78 ```
79 import got from 'got';
80
81 const instance = got.extend({
82 hooks: {
83 init: [
84 plain => {
85 if ('followRedirects' in plain) {
86 plain.followRedirect = plain.followRedirects;
87 delete plain.followRedirects;
88 }
89 }
90 ]
91 }
92 });
93
94 // Normally, the following would throw:
95 const response = await instance(
96 'https://example.com',
97 {
98 followRedirects: true
99 }
100 );
101
102 // There is no option named `followRedirects`, but we correct it in an `init` hook.
103 ```
104
105 Or you can create your own option and store it in a context:
106
107 ```
108 import got from 'got';
109
110 const instance = got.extend({
111 hooks: {
112 init: [
113 (plain, options) => {
114 if ('secret' in plain) {
115 options.context.secret = plain.secret;
116 delete plain.secret;
117 }
118 }
119 ],
120 beforeRequest: [
121 options => {
122 options.headers.secret = options.context.secret;
123 }
124 ]
125 }
126 });
127
128 const {headers} = await instance(
129 'https://httpbin.org/anything',
130 {
131 secret: 'passphrase'
132 }
133 ).json();
134
135 console.log(headers.Secret);
136 //=> 'passphrase'
137 ```
138 */
139 init: InitHook[];
140 /**
141 Called right before making the request with `options.createNativeRequestOptions()`.
142
143 This hook is especially useful in conjunction with `got.extend()` when you want to sign your request.
144
145 @default []
146
147 **Note:**
148 > - Got will make no further changes to the request before it is sent.
149
150 **Note:**
151 > - Changing `options.json` or `options.form` has no effect on the request. You should change `options.body` instead. If needed, update the `options.headers` accordingly.
152
153 @example
154 ```
155 import got from 'got';
156
157 const response = await got.post(
158 'https://httpbin.org/anything',
159 {
160 json: {payload: 'old'},
161 hooks: {
162 beforeRequest: [
163 options => {
164 options.body = JSON.stringify({payload: 'new'});
165 options.headers['content-length'] = options.body.length.toString();
166 }
167 ]
168 }
169 }
170 );
171 ```
172
173 **Tip:**
174 > - You can indirectly override the `request` function by early returning a [`ClientRequest`-like](https://nodejs.org/api/http.html#http_class_http_clientrequest) instance or a [`IncomingMessage`-like](https://nodejs.org/api/http.html#http_class_http_incomingmessage) instance. This is very useful when creating a custom cache mechanism.
175 > - [Read more about this tip](https://github.com/sindresorhus/got/blob/main/documentation/cache.md#advanced-caching-mechanisms).
176 */
177 beforeRequest: BeforeRequestHook[];
178 /**
179 The equivalent of `beforeRequest` but when redirecting.
180
181 @default []
182
183 **Tip:**
184 > - This is especially useful when you want to avoid dead sites.
185
186 @example
187 ```
188 import got from 'got';
189
190 const response = await got('https://example.com', {
191 hooks: {
192 beforeRedirect: [
193 (options, response) => {
194 if (options.hostname === 'deadSite') {
195 options.hostname = 'fallbackSite';
196 }
197 }
198 ]
199 }
200 });
201 ```
202 */
203 beforeRedirect: BeforeRedirectHook[];
204 /**
205 Called with a `RequestError` instance. The error is passed to the hook right before it's thrown.
206
207 This is especially useful when you want to have more detailed errors.
208
209 @default []
210
211 ```
212 import got from 'got';
213
214 await got('https://api.github.com/repos/sindresorhus/got/commits', {
215 responseType: 'json',
216 hooks: {
217 beforeError: [
218 error => {
219 const {response} = error;
220 if (response && response.body) {
221 error.name = 'GitHubError';
222 error.message = `${response.body.message} (${response.statusCode})`;
223 }
224
225 return error;
226 }
227 ]
228 }
229 });
230 ```
231 */
232 beforeError: BeforeErrorHook[];
233 /**
234 The equivalent of `beforeError` but when retrying. Additionally, there is a second argument `retryCount`, the current retry number.
235
236 @default []
237
238 **Note:**
239 > - When using the Stream API, this hook is ignored.
240
241 **Note:**
242 > - When retrying, the `beforeRequest` hook is called afterwards.
243
244 **Note:**
245 > - If no retry occurs, the `beforeError` hook is called instead.
246
247 This hook is especially useful when you want to retrieve the cause of a retry.
248
249 @example
250 ```
251 import got from 'got';
252
253 await got('https://httpbin.org/status/500', {
254 hooks: {
255 beforeRetry: [
256 (error, retryCount) => {
257 console.log(`Retrying [${retryCount}]: ${error.code}`);
258 // Retrying [1]: ERR_NON_2XX_3XX_RESPONSE
259 }
260 ]
261 }
262 });
263 ```
264 */
265 beforeRetry: BeforeRetryHook[];
266 /**
267 Each function should return the response. This is especially useful when you want to refresh an access token.
268
269 @default []
270
271 **Note:**
272 > - When using the Stream API, this hook is ignored.
273
274 **Note:**
275 > - Calling the `retryWithMergedOptions` function will trigger `beforeRetry` hooks. If the retry is successful, all remaining `afterResponse` hooks will be called. In case of an error, `beforeRetry` hooks will be called instead.
276 Meanwhile the `init`, `beforeRequest` , `beforeRedirect` as well as already executed `afterResponse` hooks will be skipped.
277
278 @example
279 ```
280 import got from 'got';
281
282 const instance = got.extend({
283 hooks: {
284 afterResponse: [
285 (response, retryWithMergedOptions) => {
286 // Unauthorized
287 if (response.statusCode === 401) {
288 // Refresh the access token
289 const updatedOptions = {
290 headers: {
291 token: getNewToken()
292 }
293 };
294
295 // Update the defaults
296 instance.defaults.options.merge(updatedOptions);
297
298 // Make a new retry
299 return retryWithMergedOptions(updatedOptions);
300 }
301
302 // No changes otherwise
303 return response;
304 }
305 ],
306 beforeRetry: [
307 error => {
308 // This will be called on `retryWithMergedOptions(...)`
309 }
310 ]
311 },
312 mutableDefaults: true
313 });
314 ```
315 */
316 afterResponse: AfterResponseHook[];
317};
318export type ParseJsonFunction = (text: string) => unknown;
319export type StringifyJsonFunction = (object: unknown) => string;
320/**
321All available HTTP request methods provided by Got.
322*/
323export type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD' | 'DELETE' | 'OPTIONS' | 'TRACE' | 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace';
324export type RetryObject = {
325 attemptCount: number;
326 retryOptions: RetryOptions;
327 error: RequestError;
328 computedValue: number;
329 retryAfter?: number;
330};
331export type RetryFunction = (retryObject: RetryObject) => Promisable<number>;
332/**
333An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
334
335Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
336
337The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value.
338The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
339
340By default, it retries *only* on the specified methods, status codes, and on these network errors:
341- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
342- `ECONNRESET`: Connection was forcibly closed by a peer.
343- `EADDRINUSE`: Could not bind to any free port.
344- `ECONNREFUSED`: Connection was refused by the server.
345- `EPIPE`: The remote side of the stream being written has been closed.
346- `ENOTFOUND`: Couldn't resolve the hostname to an IP address.
347- `ENETUNREACH`: No internet connection.
348- `EAI_AGAIN`: DNS lookup timed out.
349
350__Note:__ Got does not retry on `POST` by default.
351__Note:__ If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.
352__Note:__ If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
353*/
354export type RetryOptions = {
355 limit: number;
356 methods: Method[];
357 statusCodes: number[];
358 errorCodes: string[];
359 calculateDelay: RetryFunction;
360 backoffLimit: number;
361 noise: number;
362 maxRetryAfter?: number;
363};
364export type CreateConnectionFunction = (options: NativeRequestOptions, oncreate: (error: NodeJS.ErrnoException, socket: Socket) => void) => Socket;
365export type CheckServerIdentityFunction = (hostname: string, certificate: DetailedPeerCertificate) => NodeJS.ErrnoException | void;
366export type CacheOptions = {
367 shared?: boolean;
368 cacheHeuristic?: number;
369 immutableMinTimeToLive?: number;
370 ignoreCargoCult?: boolean;
371};
372type PfxObject = {
373 buffer: string | Buffer;
374 passphrase?: string | undefined;
375};
376type PfxType = string | Buffer | Array<string | Buffer | PfxObject> | undefined;
377export type HttpsOptions = {
378 alpnProtocols?: string[];
379 rejectUnauthorized?: NativeRequestOptions['rejectUnauthorized'];
380 checkServerIdentity?: CheckServerIdentityFunction;
381 /**
382 Override the default Certificate Authorities ([from Mozilla](https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReport)).
383
384 @example
385 ```
386 // Single Certificate Authority
387 await got('https://example.com', {
388 https: {
389 certificateAuthority: fs.readFileSync('./my_ca.pem')
390 }
391 });
392 ```
393 */
394 certificateAuthority?: SecureContextOptions['ca'];
395 /**
396 Private keys in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format.
397
398 [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) allows the option of private keys being encrypted.
399 Encrypted keys will be decrypted with `options.https.passphrase`.
400
401 Multiple keys with different passphrases can be provided as an array of `{pem: <string | Buffer>, passphrase: <string>}`
402 */
403 key?: SecureContextOptions['key'];
404 /**
405 [Certificate chains](https://en.wikipedia.org/wiki/X.509#Certificate_chains_and_cross-certification) in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format.
406
407 One cert chain should be provided per private key (`options.https.key`).
408
409 When providing multiple cert chains, they do not have to be in the same order as their private keys in `options.https.key`.
410
411 If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.
412 */
413 certificate?: SecureContextOptions['cert'];
414 /**
415 The passphrase to decrypt the `options.https.key` (if different keys have different passphrases refer to `options.https.key` documentation).
416 */
417 passphrase?: SecureContextOptions['passphrase'];
418 pfx?: PfxType;
419 ciphers?: SecureContextOptions['ciphers'];
420 honorCipherOrder?: SecureContextOptions['honorCipherOrder'];
421 minVersion?: SecureContextOptions['minVersion'];
422 maxVersion?: SecureContextOptions['maxVersion'];
423 signatureAlgorithms?: SecureContextOptions['sigalgs'];
424 tlsSessionLifetime?: SecureContextOptions['sessionTimeout'];
425 dhparam?: SecureContextOptions['dhparam'];
426 ecdhCurve?: SecureContextOptions['ecdhCurve'];
427 certificateRevocationLists?: SecureContextOptions['crl'];
428};
429export type PaginateData<BodyType, ElementType> = {
430 response: Response<BodyType>;
431 currentItems: ElementType[];
432 allItems: ElementType[];
433};
434export type FilterData<ElementType> = {
435 item: ElementType;
436 currentItems: ElementType[];
437 allItems: ElementType[];
438};
439/**
440All options accepted by `got.paginate()`.
441*/
442export type PaginationOptions<ElementType, BodyType> = {
443 /**
444 A function that transform [`Response`](#response) into an array of items.
445 This is where you should do the parsing.
446
447 @default response => JSON.parse(response.body)
448 */
449 transform?: (response: Response<BodyType>) => Promise<ElementType[]> | ElementType[];
450 /**
451 Checks whether the item should be emitted or not.
452
453 @default ({item, currentItems, allItems}) => true
454 */
455 filter?: (data: FilterData<ElementType>) => boolean;
456 /**
457 The function takes an object with the following properties:
458 - `response` - The current response object.
459 - `currentItems` - Items from the current response.
460 - `allItems` - An empty array, unless `pagination.stackAllItems` is set to `true`, in which case, it's an array of the emitted items.
461
462 It should return an object representing Got options pointing to the next page. The options are merged automatically with the previous request, therefore the options returned `pagination.paginate(...)` must reflect changes only. If there are no more pages, `false` should be returned.
463
464 @example
465 ```
466 import got from 'got';
467
468 const limit = 10;
469
470 const items = got.paginate('https://example.com/items', {
471 searchParams: {
472 limit,
473 offset: 0
474 },
475 pagination: {
476 paginate: ({response, currentItems}) => {
477 const previousSearchParams = response.request.options.searchParams;
478 const previousOffset = previousSearchParams.get('offset');
479
480 if (currentItems.length < limit) {
481 return false;
482 }
483
484 return {
485 searchParams: {
486 ...previousSearchParams,
487 offset: Number(previousOffset) + limit,
488 }
489 };
490 }
491 }
492 });
493
494 console.log('Items from all pages:', items);
495 ```
496 */
497 paginate?: (data: PaginateData<BodyType, ElementType>) => OptionsInit | false;
498 /**
499 Checks whether the pagination should continue.
500
501 For example, if you need to stop **before** emitting an entry with some flag, you should use `({item}) => !item.flag`.
502
503 If you want to stop **after** emitting the entry, you should use
504 `({item, allItems}) => allItems.some(item => item.flag)` instead.
505
506 @default ({item, currentItems, allItems}) => true
507 */
508 shouldContinue?: (data: FilterData<ElementType>) => boolean;
509 /**
510 The maximum amount of items that should be emitted.
511
512 @default Infinity
513 */
514 countLimit?: number;
515 /**
516 Milliseconds to wait before the next request is triggered.
517
518 @default 0
519 */
520 backoff?: number;
521 /**
522 The maximum amount of request that should be triggered.
523 Retries on failure are not counted towards this limit.
524
525 For example, it can be helpful during development to avoid an infinite number of requests.
526
527 @default 10000
528 */
529 requestLimit?: number;
530 /**
531 Defines how the property `allItems` in `pagination.paginate`, `pagination.filter` and `pagination.shouldContinue` is managed.
532
533 By default, the property `allItems` is always an empty array. This setting can be helpful to save on memory usage when working with a large dataset.
534
535 When set to `true`, the property `allItems` is an array of the emitted items.
536
537 @default false
538 */
539 stackAllItems?: boolean;
540};
541export type SearchParameters = Record<string, string | number | boolean | null | undefined>;
542/**
543All parsing methods supported by Got.
544*/
545export type ResponseType = 'json' | 'buffer' | 'text';
546type OptionsToSkip = 'searchParameters' | 'followRedirects' | 'auth' | 'toJSON' | 'merge' | 'createNativeRequestOptions' | 'getRequestFunction' | 'getFallbackRequestFunction' | 'freeze';
547export type InternalsType = Except<Options, OptionsToSkip>;
548export type OptionsError = NodeJS.ErrnoException & {
549 options?: Options;
550};
551export type OptionsInit = Except<Partial<InternalsType>, 'hooks' | 'retry'> & {
552 hooks?: Partial<Hooks>;
553 retry?: Partial<RetryOptions>;
554};
555export default class Options {
556 private _unixOptions?;
557 private readonly _internals;
558 private _merging;
559 private readonly _init;
560 constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options);
561 merge(options?: OptionsInit | Options): void;
562 /**
563 Custom request function.
564 The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper).
565
566 @default http.request | https.request
567 */
568 get request(): RequestFunction | undefined;
569 set request(value: RequestFunction | undefined);
570 /**
571 An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance.
572 This is necessary because a request to one protocol might redirect to another.
573 In such a scenario, Got will switch over to the right protocol agent for you.
574
575 If a key is not present, it will default to a global agent.
576
577 @example
578 ```
579 import got from 'got';
580 import HttpAgent from 'agentkeepalive';
581
582 const {HttpsAgent} = HttpAgent;
583
584 await got('https://sindresorhus.com', {
585 agent: {
586 http: new HttpAgent(),
587 https: new HttpsAgent()
588 }
589 });
590 ```
591 */
592 get agent(): Agents;
593 set agent(value: Agents);
594 get h2session(): ClientHttp2Session | undefined;
595 set h2session(value: ClientHttp2Session | undefined);
596 /**
597 Decompress the response automatically.
598
599 This will set the `accept-encoding` header to `gzip, deflate, br` unless you set it yourself.
600
601 If this is disabled, a compressed response is returned as a `Buffer`.
602 This may be useful if you want to handle decompression yourself or stream the raw compressed data.
603
604 @default true
605 */
606 get decompress(): boolean;
607 set decompress(value: boolean);
608 /**
609 Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property).
610 By default, there's no timeout.
611
612 This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
613
614 - `lookup` starts when a socket is assigned and ends when the hostname has been resolved.
615 Does not apply when using a Unix domain socket.
616 - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected.
617 - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
618 - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
619 - `response` starts when the request has been written to the socket and ends when the response headers are received.
620 - `send` starts when the socket is connected and ends with the request has been written to the socket.
621 - `request` starts when the request is initiated and ends when the response's end event fires.
622 */
623 get timeout(): Delays;
624 set timeout(value: Delays);
625 /**
626 When specified, `prefixUrl` will be prepended to `url`.
627 The prefix can be any valid URL, either relative or absolute.
628 A trailing slash `/` is optional - one will be added automatically.
629
630 __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance.
631
632 __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion.
633 For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`.
634 The latter is used by browsers.
635
636 __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances.
637
638 __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`.
639 If the URL doesn't include it anymore, it will throw.
640
641 @example
642 ```
643 import got from 'got';
644
645 await got('unicorn', {prefixUrl: 'https://cats.com'});
646 //=> 'https://cats.com/unicorn'
647
648 const instance = got.extend({
649 prefixUrl: 'https://google.com'
650 });
651
652 await instance('unicorn', {
653 hooks: {
654 beforeRequest: [
655 options => {
656 options.prefixUrl = 'https://cats.com';
657 }
658 ]
659 }
660 });
661 //=> 'https://cats.com/unicorn'
662 ```
663 */
664 get prefixUrl(): string | URL;
665 set prefixUrl(value: string | URL);
666 /**
667 __Note #1__: The `body` option cannot be used with the `json` or `form` option.
668
669 __Note #2__: If you provide this option, `got.stream()` will be read-only.
670
671 __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`.
672
673 __Note #4__: This option is not enumerable and will not be merged with the instance defaults.
674
675 The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
676
677 Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`.
678 */
679 get body(): string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined;
680 set body(value: string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined);
681 /**
682 The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj).
683
684 If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`.
685
686 __Note #1__: If you provide this option, `got.stream()` will be read-only.
687
688 __Note #2__: This option is not enumerable and will not be merged with the instance defaults.
689 */
690 get form(): Record<string, any> | undefined;
691 set form(value: Record<string, any> | undefined);
692 /**
693 JSON body. If the `Content-Type` header is not set, it will be set to `application/json`.
694
695 __Note #1__: If you provide this option, `got.stream()` will be read-only.
696
697 __Note #2__: This option is not enumerable and will not be merged with the instance defaults.
698 */
699 get json(): unknown;
700 set json(value: unknown);
701 /**
702 The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
703
704 Properties from `options` will override properties in the parsed `url`.
705
706 If no protocol is specified, it will throw a `TypeError`.
707
708 __Note__: The query string is **not** parsed as search params.
709
710 @example
711 ```
712 await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b
713 await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
714
715 // The query string is overridden by `searchParams`
716 await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
717 ```
718 */
719 get url(): string | URL | undefined;
720 set url(value: string | URL | undefined);
721 /**
722 Cookie support. You don't have to care about parsing or how to store them.
723
724 __Note__: If you provide this option, `options.headers.cookie` will be overridden.
725 */
726 get cookieJar(): PromiseCookieJar | ToughCookieJar | undefined;
727 set cookieJar(value: PromiseCookieJar | ToughCookieJar | undefined);
728 /**
729 You can abort the `request` using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
730
731 @example
732 ```
733 import got from 'got';
734
735 const abortController = new AbortController();
736
737 const request = got('https://httpbin.org/anything', {
738 signal: abortController.signal
739 });
740
741 setTimeout(() => {
742 abortController.abort();
743 }, 100);
744 ```
745 */
746 get signal(): AbortSignal | undefined;
747 set signal(value: AbortSignal | undefined);
748 /**
749 Ignore invalid cookies instead of throwing an error.
750 Only useful when the `cookieJar` option has been set. Not recommended.
751
752 @default false
753 */
754 get ignoreInvalidCookies(): boolean;
755 set ignoreInvalidCookies(value: boolean);
756 /**
757 Query string that will be added to the request URL.
758 This will override the query string in `url`.
759
760 If you need to pass in an array, you can do it using a `URLSearchParams` instance.
761
762 @example
763 ```
764 import got from 'got';
765
766 const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]);
767
768 await got('https://example.com', {searchParams});
769
770 console.log(searchParams.toString());
771 //=> 'key=a&key=b'
772 ```
773 */
774 get searchParams(): string | SearchParameters | URLSearchParams | undefined;
775 set searchParams(value: string | SearchParameters | URLSearchParams | undefined);
776 get searchParameters(): unknown;
777 set searchParameters(_value: unknown);
778 get dnsLookup(): CacheableLookup['lookup'] | undefined;
779 set dnsLookup(value: CacheableLookup['lookup'] | undefined);
780 /**
781 An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups.
782 Useful when making lots of requests to different *public* hostnames.
783
784 `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay.
785
786 __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc.
787
788 @default false
789 */
790 get dnsCache(): CacheableLookup | boolean | undefined;
791 set dnsCache(value: CacheableLookup | boolean | undefined);
792 /**
793 User data. `context` is shallow merged and enumerable. If it contains non-enumerable properties they will NOT be merged.
794
795 @example
796 ```
797 import got from 'got';
798
799 const instance = got.extend({
800 hooks: {
801 beforeRequest: [
802 options => {
803 if (!options.context || !options.context.token) {
804 throw new Error('Token required');
805 }
806
807 options.headers.token = options.context.token;
808 }
809 ]
810 }
811 });
812
813 const context = {
814 token: 'secret'
815 };
816
817 const response = await instance('https://httpbin.org/headers', {context});
818
819 // Let's see the headers
820 console.log(response.body);
821 ```
822 */
823 get context(): Record<string, unknown>;
824 set context(value: Record<string, unknown>);
825 /**
826 Hooks allow modifications during the request lifecycle.
827 Hook functions may be async and are run serially.
828 */
829 get hooks(): Hooks;
830 set hooks(value: Hooks);
831 /**
832 Whether redirect responses should be followed automatically.
833
834 Optionally, pass a function to dynamically decide based on the response object.
835
836 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`.
837 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`.
838
839 @default true
840 */
841 get followRedirect(): boolean | ((response: PlainResponse) => boolean);
842 set followRedirect(value: boolean | ((response: PlainResponse) => boolean));
843 get followRedirects(): unknown;
844 set followRedirects(_value: unknown);
845 /**
846 If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown.
847
848 @default 10
849 */
850 get maxRedirects(): number;
851 set maxRedirects(value: number);
852 /**
853 A cache adapter instance for storing cached response data.
854
855 @default false
856 */
857 get cache(): string | StorageAdapter | boolean | undefined;
858 set cache(value: string | StorageAdapter | boolean | undefined);
859 /**
860 Determines if a `got.HTTPError` is thrown for unsuccessful responses.
861
862 If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing.
863 This may be useful if you are checking for resource availability and are expecting error responses.
864
865 @default true
866 */
867 get throwHttpErrors(): boolean;
868 set throwHttpErrors(value: boolean);
869 get username(): string;
870 set username(value: string);
871 get password(): string;
872 set password(value: string);
873 /**
874 If set to `true`, Got will additionally accept HTTP2 requests.
875
876 It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol.
877
878 __Note__: This option requires Node.js 15.10.0 or newer as HTTP/2 support on older Node.js versions is very buggy.
879
880 __Note__: Overriding `options.request` will disable HTTP2 support.
881
882 @default false
883
884 @example
885 ```
886 import got from 'got';
887
888 const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true});
889
890 console.log(headers.via);
891 //=> '2 nghttpx'
892 ```
893 */
894 get http2(): boolean;
895 set http2(value: boolean);
896 /**
897 Set this to `true` to allow sending body for the `GET` method.
898 However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect.
899 This option is only meant to interact with non-compliant servers when you have no other choice.
900
901 __Note__: The [RFC 7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__.
902
903 @default false
904 */
905 get allowGetBody(): boolean;
906 set allowGetBody(value: boolean);
907 /**
908 Request headers.
909
910 Existing headers will be overwritten. Headers set to `undefined` will be omitted.
911
912 @default {}
913 */
914 get headers(): Headers;
915 set headers(value: Headers);
916 /**
917 Specifies if the HTTP request method should be [rewritten as `GET`](https://tools.ietf.org/html/rfc7231#section-6.4) on redirects.
918
919 As the [specification](https://tools.ietf.org/html/rfc7231#section-6.4) prefers to rewrite the HTTP method only on `303` responses, this is Got's default behavior.
920 Setting `methodRewriting` to `true` will also rewrite `301` and `302` responses, as allowed by the spec. This is the behavior followed by `curl` and browsers.
921
922 __Note__: Got never performs method rewriting on `307` and `308` responses, as this is [explicitly prohibited by the specification](https://www.rfc-editor.org/rfc/rfc7231#section-6.4.7).
923
924 @default false
925 */
926 get methodRewriting(): boolean;
927 set methodRewriting(value: boolean);
928 /**
929 Indicates which DNS record family to use.
930
931 Values:
932 - `undefined`: IPv4 (if present) or IPv6
933 - `4`: Only IPv4
934 - `6`: Only IPv6
935
936 @default undefined
937 */
938 get dnsLookupIpVersion(): DnsLookupIpVersion;
939 set dnsLookupIpVersion(value: DnsLookupIpVersion);
940 /**
941 A function used to parse JSON responses.
942
943 @example
944 ```
945 import got from 'got';
946 import Bourne from '@hapi/bourne';
947
948 const parsed = await got('https://example.com', {
949 parseJson: text => Bourne.parse(text)
950 }).json();
951
952 console.log(parsed);
953 ```
954 */
955 get parseJson(): ParseJsonFunction;
956 set parseJson(value: ParseJsonFunction);
957 /**
958 A function used to stringify the body of JSON requests.
959
960 @example
961 ```
962 import got from 'got';
963
964 await got.post('https://example.com', {
965 stringifyJson: object => JSON.stringify(object, (key, value) => {
966 if (key.startsWith('_')) {
967 return;
968 }
969
970 return value;
971 }),
972 json: {
973 some: 'payload',
974 _ignoreMe: 1234
975 }
976 });
977 ```
978
979 @example
980 ```
981 import got from 'got';
982
983 await got.post('https://example.com', {
984 stringifyJson: object => JSON.stringify(object, (key, value) => {
985 if (typeof value === 'number') {
986 return value.toString();
987 }
988
989 return value;
990 }),
991 json: {
992 some: 'payload',
993 number: 1
994 }
995 });
996 ```
997 */
998 get stringifyJson(): StringifyJsonFunction;
999 set stringifyJson(value: StringifyJsonFunction);
1000 /**
1001 An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
1002
1003 Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
1004
1005 The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value.
1006 The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
1007
1008 By default, it retries *only* on the specified methods, status codes, and on these network errors:
1009
1010 - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
1011 - `ECONNRESET`: Connection was forcibly closed by a peer.
1012 - `EADDRINUSE`: Could not bind to any free port.
1013 - `ECONNREFUSED`: Connection was refused by the server.
1014 - `EPIPE`: The remote side of the stream being written has been closed.
1015 - `ENOTFOUND`: Couldn't resolve the hostname to an IP address.
1016 - `ENETUNREACH`: No internet connection.
1017 - `EAI_AGAIN`: DNS lookup timed out.
1018
1019 __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.
1020 __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
1021 */
1022 get retry(): Partial<RetryOptions>;
1023 set retry(value: Partial<RetryOptions>);
1024 /**
1025 From `http.RequestOptions`.
1026
1027 The IP address used to send the request from.
1028 */
1029 get localAddress(): string | undefined;
1030 set localAddress(value: string | undefined);
1031 /**
1032 The HTTP method used to make the request.
1033
1034 @default 'GET'
1035 */
1036 get method(): Method;
1037 set method(value: Method);
1038 get createConnection(): CreateConnectionFunction | undefined;
1039 set createConnection(value: CreateConnectionFunction | undefined);
1040 /**
1041 From `http-cache-semantics`
1042
1043 @default {}
1044 */
1045 get cacheOptions(): CacheOptions;
1046 set cacheOptions(value: CacheOptions);
1047 /**
1048 Options for the advanced HTTPS API.
1049 */
1050 get https(): HttpsOptions;
1051 set https(value: HttpsOptions);
1052 /**
1053 [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data.
1054
1055 To get a [`Buffer`](https://nodejs.org/api/buffer.html), you need to set `responseType` to `buffer` instead.
1056 Don't set this option to `null`.
1057
1058 __Note__: This doesn't affect streams! Instead, you need to do `got.stream(...).setEncoding(encoding)`.
1059
1060 @default 'utf-8'
1061 */
1062 get encoding(): BufferEncoding | undefined;
1063 set encoding(value: BufferEncoding | undefined);
1064 /**
1065 When set to `true` the promise will return the Response body instead of the Response object.
1066
1067 @default false
1068 */
1069 get resolveBodyOnly(): boolean;
1070 set resolveBodyOnly(value: boolean);
1071 /**
1072 Returns a `Stream` instead of a `Promise`.
1073 This is equivalent to calling `got.stream(url, options?)`.
1074
1075 @default false
1076 */
1077 get isStream(): boolean;
1078 set isStream(value: boolean);
1079 /**
1080 The parsing method.
1081
1082 The promise also has `.text()`, `.json()` and `.buffer()` methods which return another Got promise for the parsed body.
1083
1084 It's like setting the options to `{responseType: 'json', resolveBodyOnly: true}` but without affecting the main Got promise.
1085
1086 __Note__: When using streams, this option is ignored.
1087
1088 @example
1089 ```
1090 const responsePromise = got(url);
1091 const bufferPromise = responsePromise.buffer();
1092 const jsonPromise = responsePromise.json();
1093
1094 const [response, buffer, json] = Promise.all([responsePromise, bufferPromise, jsonPromise]);
1095 // `response` is an instance of Got Response
1096 // `buffer` is an instance of Buffer
1097 // `json` is an object
1098 ```
1099
1100 @example
1101 ```
1102 // This
1103 const body = await got(url).json();
1104
1105 // is semantically the same as this
1106 const body = await got(url, {responseType: 'json', resolveBodyOnly: true});
1107 ```
1108 */
1109 get responseType(): ResponseType;
1110 set responseType(value: ResponseType);
1111 get pagination(): PaginationOptions<unknown, unknown>;
1112 set pagination(value: PaginationOptions<unknown, unknown>);
1113 get auth(): unknown;
1114 set auth(_value: unknown);
1115 get setHost(): boolean;
1116 set setHost(value: boolean);
1117 get maxHeaderSize(): number | undefined;
1118 set maxHeaderSize(value: number | undefined);
1119 get enableUnixSockets(): boolean;
1120 set enableUnixSockets(value: boolean);
1121 toJSON(): {
1122 headers: Headers;
1123 timeout: Delays;
1124 request: RequestFunction | undefined;
1125 username: string;
1126 password: string;
1127 json: unknown;
1128 followRedirect: boolean | ((response: PlainResponse) => boolean);
1129 retry: Partial<RetryOptions>;
1130 agent: Agents;
1131 h2session: http2wrapper.ClientHttp2Session | undefined;
1132 decompress: boolean;
1133 prefixUrl: string | URL;
1134 body: string | Readable | Buffer | Generator<unknown, any, any> | AsyncGenerator<unknown, any, any> | FormDataLike | undefined;
1135 form: Record<string, any> | undefined;
1136 url: string | URL | undefined;
1137 cookieJar: PromiseCookieJar | ToughCookieJar | undefined;
1138 signal: AbortSignal | undefined;
1139 ignoreInvalidCookies: boolean;
1140 searchParams: string | URLSearchParams | SearchParameters | undefined;
1141 dnsLookup: {
1142 (hostname: string, family: import("cacheable-lookup").IPFamily, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1143 (hostname: string, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1144 (hostname: string, options: import("cacheable-lookup").LookupOptions & {
1145 all: true;
1146 }, callback: (error: NodeJS.ErrnoException | null, result: ReadonlyArray<import("cacheable-lookup").EntryObject>) => void): void;
1147 (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1148 } | undefined;
1149 dnsCache: boolean | CacheableLookup | undefined;
1150 context: Record<string, unknown>;
1151 hooks: Hooks;
1152 maxRedirects: number;
1153 cache: string | boolean | StorageAdapter | undefined;
1154 throwHttpErrors: boolean;
1155 http2: boolean;
1156 allowGetBody: boolean;
1157 methodRewriting: boolean;
1158 dnsLookupIpVersion: DnsLookupIpVersion;
1159 parseJson: ParseJsonFunction;
1160 stringifyJson: StringifyJsonFunction;
1161 localAddress: string | undefined;
1162 method: Method;
1163 createConnection: CreateConnectionFunction | undefined;
1164 cacheOptions: CacheOptions;
1165 https: HttpsOptions;
1166 encoding: BufferEncoding | undefined;
1167 resolveBodyOnly: boolean;
1168 isStream: boolean;
1169 responseType: ResponseType;
1170 pagination: PaginationOptions<unknown, unknown>;
1171 setHost: boolean;
1172 maxHeaderSize: number | undefined;
1173 enableUnixSockets: boolean;
1174 };
1175 createNativeRequestOptions(): {
1176 ALPNProtocols: string[] | undefined;
1177 ca: string | Buffer | (string | Buffer)[] | undefined;
1178 cert: string | Buffer | (string | Buffer)[] | undefined;
1179 key: string | Buffer | (string | Buffer | import("tls").KeyObject)[] | undefined;
1180 passphrase: string | undefined;
1181 pfx: PfxType;
1182 rejectUnauthorized: boolean | undefined;
1183 checkServerIdentity: typeof checkServerIdentity | CheckServerIdentityFunction;
1184 ciphers: string | undefined;
1185 honorCipherOrder: boolean | undefined;
1186 minVersion: import("tls").SecureVersion | undefined;
1187 maxVersion: import("tls").SecureVersion | undefined;
1188 sigalgs: string | undefined;
1189 sessionTimeout: number | undefined;
1190 dhparam: string | Buffer | undefined;
1191 ecdhCurve: string | undefined;
1192 crl: string | Buffer | (string | Buffer)[] | undefined;
1193 lookup: {
1194 (hostname: string, family: import("cacheable-lookup").IPFamily, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1195 (hostname: string, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1196 (hostname: string, options: import("cacheable-lookup").LookupOptions & {
1197 all: true;
1198 }, callback: (error: NodeJS.ErrnoException | null, result: ReadonlyArray<import("cacheable-lookup").EntryObject>) => void): void;
1199 (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1200 } | undefined;
1201 family: DnsLookupIpVersion;
1202 agent: false | http.Agent | Agents | undefined;
1203 setHost: boolean;
1204 method: Method;
1205 maxHeaderSize: number | undefined;
1206 localAddress: string | undefined;
1207 headers: Headers;
1208 createConnection: CreateConnectionFunction | undefined;
1209 timeout: number | undefined;
1210 h2session: http2wrapper.ClientHttp2Session | undefined;
1211 _defaultAgent?: http.Agent | undefined;
1212 auth?: string | null | undefined;
1213 defaultPort?: number | string | undefined;
1214 hints?: import("dns").LookupOptions["hints"];
1215 host?: string | null | undefined;
1216 hostname?: string | null | undefined;
1217 insecureHTTPParser?: boolean | undefined;
1218 localPort?: number | undefined;
1219 path?: string | null | undefined;
1220 port?: number | string | null | undefined;
1221 protocol?: string | null | undefined;
1222 signal?: AbortSignal | undefined;
1223 socketPath?: string | undefined;
1224 uniqueHeaders?: Array<string | string[]> | undefined;
1225 joinDuplicateHeaders?: boolean;
1226 ALPNCallback?: ((arg: {
1227 servername: string;
1228 protocols: string[];
1229 }) => string | undefined) | undefined;
1230 clientCertEngine?: string | undefined;
1231 privateKeyEngine?: string | undefined;
1232 privateKeyIdentifier?: string | undefined;
1233 secureOptions?: number | undefined;
1234 secureProtocol?: string | undefined;
1235 sessionIdContext?: string | undefined;
1236 ticketKeys?: Buffer | undefined;
1237 servername?: string | undefined;
1238 shared?: boolean;
1239 cacheHeuristic?: number;
1240 immutableMinTimeToLive?: number;
1241 ignoreCargoCult?: boolean;
1242 };
1243 getRequestFunction(): RequestFunction | typeof https.request | undefined;
1244 getFallbackRequestFunction(): RequestFunction | typeof https.request | undefined;
1245 freeze(): void;
1246}
1247export {};
1248
\No newline at end of file