UNPKG

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