forked from sindresorhus/got
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
1846 lines (1500 loc) 路 52.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {promisify} from 'util';
import {Duplex, Writable, Readable} from 'stream';
import {ReadStream} from 'fs';
import {URL, URLSearchParams} from 'url';
import {Socket} from 'net';
import {SecureContextOptions, DetailedPeerCertificate} from 'tls';
import http = require('http');
import {ClientRequest, RequestOptions, IncomingMessage, ServerResponse, request as httpRequest} from 'http';
import https = require('https');
import timer, {ClientRequestWithTimings, Timings, IncomingMessageWithTimings} from '@szmarczak/http-timer';
import CacheableLookup from 'cacheable-lookup';
import CacheableRequest = require('cacheable-request');
import decompressResponse = require('decompress-response');
// @ts-expect-error Missing types
import http2wrapper = require('http2-wrapper');
import lowercaseKeys = require('lowercase-keys');
import ResponseLike = require('responselike');
import is, {assert} from '@sindresorhus/is';
import getBodySize from './utils/get-body-size';
import isFormData from './utils/is-form-data';
import proxyEvents from './utils/proxy-events';
import timedOut, {Delays, TimeoutError as TimedOutTimeoutError} from './utils/timed-out';
import urlToOptions from './utils/url-to-options';
import optionsToUrl, {URLOptions} from './utils/options-to-url';
import WeakableMap from './utils/weakable-map';
import getBuffer from './utils/get-buffer';
import {DnsLookupIpVersion, isDnsLookupIpVersion, dnsLookupIpVersionToFamily} from './utils/dns-ip-version';
import deprecationWarning from '../utils/deprecation-warning';
import {PromiseOnly} from '../as-promise/types';
const globalDnsCache = new CacheableLookup();
type HttpRequestFunction = typeof httpRequest;
type Error = NodeJS.ErrnoException;
const kRequest = Symbol('request');
const kResponse = Symbol('response');
const kResponseSize = Symbol('responseSize');
const kDownloadedSize = Symbol('downloadedSize');
const kBodySize = Symbol('bodySize');
const kUploadedSize = Symbol('uploadedSize');
const kServerResponsesPiped = Symbol('serverResponsesPiped');
const kUnproxyEvents = Symbol('unproxyEvents');
const kIsFromCache = Symbol('isFromCache');
const kCancelTimeouts = Symbol('cancelTimeouts');
const kStartedReading = Symbol('startedReading');
const kStopReading = Symbol('stopReading');
const kTriggerRead = Symbol('triggerRead');
const kBody = Symbol('body');
const kJobs = Symbol('jobs');
const kOriginalResponse = Symbol('originalResponse');
export const kIsNormalizedAlready = Symbol('isNormalizedAlready');
const supportsBrotli = is.string((process.versions as any).brotli);
export interface Agents {
http?: http.Agent;
https?: https.Agent;
http2?: unknown;
}
export const withoutBody: ReadonlySet<string> = new Set(['GET', 'HEAD']);
export interface ToughCookieJar {
getCookieString: ((currentUrl: string, options: {[key: string]: unknown}, cb: (err: Error | null, cookies: string) => void) => void)
& ((url: string, callback: (error: Error | null, cookieHeader: string) => void) => void);
setCookie: ((cookieOrString: unknown, currentUrl: string, options: {[key: string]: unknown}, cb: (err: Error | null, cookie: unknown) => void) => void)
& ((rawCookie: string, url: string, callback: (error: Error | null, result: unknown) => void) => void);
}
export interface PromiseCookieJar {
getCookieString: (url: string) => Promise<string>;
setCookie: (rawCookie: string, url: string) => Promise<unknown>;
}
export type Method =
| 'GET'
| 'POST'
| 'PUT'
| 'PATCH'
| 'HEAD'
| 'DELETE'
| 'OPTIONS'
| 'TRACE'
| 'get'
| 'post'
| 'put'
| 'patch'
| 'head'
| 'delete'
| 'options'
| 'trace';
type Promisable<T> = T | Promise<T>;
export type InitHook = (options: Options) => void;
export type BeforeRequestHook = (options: NormalizedOptions) => Promisable<void | Response | ResponseLike>;
export type BeforeRedirectHook = (options: NormalizedOptions, response: Response) => Promisable<void>;
export type BeforeErrorHook = (error: RequestError) => Promisable<RequestError>;
interface PlainHooks {
init?: InitHook[];
beforeRequest?: BeforeRequestHook[];
beforeRedirect?: BeforeRedirectHook[];
beforeError?: BeforeErrorHook[];
}
export interface Hooks extends PromiseOnly.Hooks, PlainHooks {}
type PlainHookEvent = 'init' | 'beforeRequest' | 'beforeRedirect' | 'beforeError';
export type HookEvent = PromiseOnly.HookEvent | PlainHookEvent;
export const knownHookEvents: HookEvent[] = ['init', 'beforeRequest', 'beforeRedirect', 'beforeError'];
type AcceptableResponse = IncomingMessageWithTimings | ResponseLike;
type AcceptableRequestResult = AcceptableResponse | ClientRequest | Promise<AcceptableResponse | ClientRequest> | undefined;
export type RequestFunction = (url: URL, options: RequestOptions, callback?: (response: AcceptableResponse) => void) => AcceptableRequestResult;
export type Headers = Record<string, string | string[] | undefined>;
type CacheableRequestFunction = (
opts: string | URL | RequestOptions,
cb?: (response: ServerResponse | ResponseLike) => void
) => CacheableRequest.Emitter;
type CheckServerIdentityFunction = (hostname: string, certificate: DetailedPeerCertificate) => Error | void;
export type ParseJsonFunction = (text: string) => unknown;
export type StringifyJsonFunction = (object: unknown) => string;
interface RealRequestOptions extends https.RequestOptions {
checkServerIdentity: CheckServerIdentityFunction;
}
interface PlainOptions extends URLOptions {
request?: RequestFunction;
agent?: Agents | false;
decompress?: boolean;
timeout?: Delays | number;
prefixUrl?: string | URL;
body?: string | Buffer | Readable;
form?: {[key: string]: any};
json?: {[key: string]: any};
url?: string | URL;
cookieJar?: PromiseCookieJar | ToughCookieJar;
ignoreInvalidCookies?: boolean;
searchParams?: string | {[key: string]: string | number | boolean | null | undefined} | URLSearchParams;
dnsCache?: CacheableLookup | boolean;
context?: Record<string, unknown>;
hooks?: Hooks;
followRedirect?: boolean;
maxRedirects?: number;
cache?: string | CacheableRequest.StorageAdapter | false;
throwHttpErrors?: boolean;
username?: string;
password?: string;
http2?: boolean;
allowGetBody?: boolean;
lookup?: CacheableLookup['lookup'];
headers?: Headers;
methodRewriting?: boolean;
dnsLookupIpVersion?: DnsLookupIpVersion;
parseJson?: ParseJsonFunction;
stringifyJson?: StringifyJsonFunction;
// From `http.RequestOptions`
localAddress?: string;
socketPath?: string;
method?: Method;
createConnection?: (options: http.RequestOptions, oncreate: (error: Error, socket: Socket) => void) => Socket;
// TODO: remove when Got 12 gets released
rejectUnauthorized?: boolean; // Here for backwards compatibility
https?: HTTPSOptions;
}
export interface Options extends PromiseOnly.Options, PlainOptions {}
export interface HTTPSOptions {
// From `http.RequestOptions` and `tls.CommonConnectionOptions`
rejectUnauthorized?: https.RequestOptions['rejectUnauthorized'];
// From `tls.ConnectionOptions`
checkServerIdentity?: CheckServerIdentityFunction;
// From `tls.SecureContextOptions`
certificateAuthority?: SecureContextOptions['ca'];
key?: SecureContextOptions['key'];
certificate?: SecureContextOptions['cert'];
passphrase?: SecureContextOptions['passphrase'];
pfx?: SecureContextOptions['pfx'];
}
interface NormalizedPlainOptions extends PlainOptions {
method: Method;
url: URL;
timeout: Delays;
prefixUrl: string;
ignoreInvalidCookies: boolean;
decompress: boolean;
searchParams?: URLSearchParams;
cookieJar?: PromiseCookieJar;
headers: Headers;
context: Record<string, unknown>;
hooks: Required<Hooks>;
followRedirect: boolean;
maxRedirects: number;
cache?: string | CacheableRequest.StorageAdapter;
throwHttpErrors: boolean;
dnsCache?: CacheableLookup;
http2: boolean;
allowGetBody: boolean;
rejectUnauthorized: boolean;
lookup?: CacheableLookup['lookup'];
methodRewriting: boolean;
username: string;
password: string;
parseJson: ParseJsonFunction;
stringifyJson: StringifyJsonFunction;
[kRequest]: HttpRequestFunction;
[kIsNormalizedAlready]?: boolean;
}
export interface NormalizedOptions extends PromiseOnly.NormalizedOptions, NormalizedPlainOptions {}
interface PlainDefaults {
timeout: Delays;
prefixUrl: string;
method: Method;
ignoreInvalidCookies: boolean;
decompress: boolean;
context: Record<string, unknown>;
cookieJar?: PromiseCookieJar | ToughCookieJar;
dnsCache?: CacheableLookup;
headers: Headers;
hooks: Required<Hooks>;
followRedirect: boolean;
maxRedirects: number;
cache?: string | CacheableRequest.StorageAdapter;
throwHttpErrors: boolean;
http2: boolean;
allowGetBody: boolean;
https?: HTTPSOptions;
methodRewriting: boolean;
parseJson: ParseJsonFunction;
stringifyJson: StringifyJsonFunction;
// Optional
agent?: Agents | false;
request?: RequestFunction;
searchParams?: URLSearchParams;
lookup?: CacheableLookup['lookup'];
localAddress?: string;
createConnection?: Options['createConnection'];
}
export interface Defaults extends PromiseOnly.Defaults, PlainDefaults {}
export interface Progress {
percent: number;
transferred: number;
total?: number;
}
export interface PlainResponse extends IncomingMessageWithTimings {
requestUrl: string;
redirectUrls: string[];
request: Request;
ip?: string;
isFromCache: boolean;
statusCode: number;
url: string;
timings: Timings;
}
// For Promise support
export interface Response<T = unknown> extends PlainResponse {
body: T;
rawBody: Buffer;
retryCount: number;
}
export interface RequestEvents<T> {
on: ((name: 'request', listener: (request: http.ClientRequest) => void) => T)
& (<R extends Response>(name: 'response', listener: (response: R) => void) => T)
& (<R extends Response, N extends NormalizedOptions>(name: 'redirect', listener: (response: R, nextOptions: N) => void) => T)
& ((name: 'uploadProgress' | 'downloadProgress', listener: (progress: Progress) => void) => T);
}
function validateSearchParameters(searchParameters: Record<string, unknown>): asserts searchParameters is Record<string, string | number | boolean | null | undefined> {
// eslint-disable-next-line guard-for-in
for (const key in searchParameters) {
const value = searchParameters[key];
if (!is.string(value) && !is.number(value) && !is.boolean(value) && !is.null_(value) && !is.undefined(value)) {
throw new TypeError(`The \`searchParams\` value '${String(value)}' must be a string, number, boolean or null`);
}
}
}
function isClientRequest(clientRequest: unknown): clientRequest is ClientRequest {
return is.object(clientRequest) && !('statusCode' in clientRequest);
}
const cacheableStore = new WeakableMap<string | CacheableRequest.StorageAdapter, CacheableRequestFunction>();
const waitForOpenFile = async (file: ReadStream): Promise<void> => new Promise((resolve, reject) => {
const onError = (error: Error): void => {
reject(error);
};
// Node.js 12 has incomplete types
if (!(file as any).pending) {
resolve();
}
file.once('error', onError);
file.once('ready', () => {
file.off('error', onError);
resolve();
});
});
const redirectCodes: ReadonlySet<number> = new Set([300, 301, 302, 303, 304, 307, 308]);
type NonEnumerableProperty = 'context' | 'body' | 'json' | 'form';
const nonEnumerableProperties: NonEnumerableProperty[] = [
'context',
'body',
'json',
'form'
];
export const setNonEnumerableProperties = (sources: Array<Options | Defaults | undefined>, to: Options): void => {
// Non enumerable properties shall not be merged
const properties: Partial<{[Key in NonEnumerableProperty]: any}> = {};
for (const source of sources) {
if (!source) {
continue;
}
for (const name of nonEnumerableProperties) {
if (!(name in source)) {
continue;
}
properties[name] = {
writable: true,
configurable: true,
enumerable: false,
// @ts-expect-error TS doesn't see the check above
value: source[name]
};
}
}
Object.defineProperties(to, properties);
};
export class RequestError extends Error {
code?: string;
stack!: string;
declare readonly options: NormalizedOptions;
readonly response?: Response;
readonly request?: Request;
readonly timings?: Timings;
constructor(message: string, error: Partial<Error & {code?: string}>, self: Request | NormalizedOptions) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = 'RequestError';
this.code = error.code;
if (self instanceof Request) {
Object.defineProperty(this, 'request', {
enumerable: false,
value: self
});
Object.defineProperty(this, 'response', {
enumerable: false,
value: self[kResponse]
});
Object.defineProperty(this, 'options', {
// This fails because of TS 3.7.2 useDefineForClassFields
// Ref: https://github.com/microsoft/TypeScript/issues/34972
enumerable: false,
value: self.options
});
} else {
Object.defineProperty(this, 'options', {
// This fails because of TS 3.7.2 useDefineForClassFields
// Ref: https://github.com/microsoft/TypeScript/issues/34972
enumerable: false,
value: self
});
}
this.timings = this.request?.timings;
// Recover the original stacktrace
if (!is.undefined(error.stack)) {
const indexOfMessage = this.stack.indexOf(this.message) + this.message.length;
const thisStackTrace = this.stack.slice(indexOfMessage).split('\n').reverse();
const errorStackTrace = error.stack.slice(error.stack.indexOf(error.message!) + error.message!.length).split('\n').reverse();
// Remove duplicated traces
while (errorStackTrace.length !== 0 && errorStackTrace[0] === thisStackTrace[0]) {
thisStackTrace.shift();
}
this.stack = `${this.stack.slice(0, indexOfMessage)}${thisStackTrace.reverse().join('\n')}${errorStackTrace.reverse().join('\n')}`;
}
}
}
export class MaxRedirectsError extends RequestError {
declare readonly response: Response;
declare readonly request: Request;
declare readonly timings: Timings;
constructor(request: Request) {
super(`Redirected ${request.options.maxRedirects} times. Aborting.`, {}, request);
this.name = 'MaxRedirectsError';
}
}
export class HTTPError extends RequestError {
declare readonly response: Response;
declare readonly request: Request;
declare readonly timings: Timings;
constructor(response: Response) {
super(`Response code ${response.statusCode} (${response.statusMessage!})`, {}, response.request);
this.name = 'HTTPError';
}
}
export class CacheError extends RequestError {
declare readonly request: Request;
constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'CacheError';
}
}
export class UploadError extends RequestError {
declare readonly request: Request;
constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'UploadError';
}
}
export class TimeoutError extends RequestError {
declare readonly request: Request;
readonly timings: Timings;
readonly event: string;
constructor(error: TimedOutTimeoutError, timings: Timings, request: Request) {
super(error.message, error, request);
this.name = 'TimeoutError';
this.event = error.event;
this.timings = timings;
}
}
export class ReadError extends RequestError {
declare readonly request: Request;
declare readonly response: Response;
declare readonly timings: Timings;
constructor(error: Error, request: Request) {
super(error.message, error, request);
this.name = 'ReadError';
}
}
export class UnsupportedProtocolError extends RequestError {
constructor(options: NormalizedOptions) {
super(`Unsupported protocol "${options.url.protocol}"`, {}, options);
this.name = 'UnsupportedProtocolError';
}
}
const proxiedRequestEvents = [
'socket',
'connect',
'continue',
'information',
'upgrade',
'timeout'
];
export default class Request extends Duplex implements RequestEvents<Request> {
['constructor']: typeof Request;
declare [kUnproxyEvents]: () => void;
declare _cannotHaveBody: boolean;
[kDownloadedSize]: number;
[kUploadedSize]: number;
[kStopReading]: boolean;
[kTriggerRead]: boolean;
[kBody]: Options['body'];
[kJobs]: Array<() => void>;
[kBodySize]?: number;
[kServerResponsesPiped]: Set<ServerResponse>;
[kIsFromCache]?: boolean;
[kStartedReading]?: boolean;
[kCancelTimeouts]?: () => void;
[kResponseSize]?: number;
[kResponse]?: IncomingMessageWithTimings;
[kOriginalResponse]?: IncomingMessageWithTimings;
[kRequest]?: ClientRequest;
_noPipe?: boolean;
_progressCallbacks: Array<() => void>;
declare options: NormalizedOptions;
declare requestUrl: string;
requestInitialized: boolean;
redirects: string[];
constructor(url: string | URL, options: Options = {}, defaults?: Defaults) {
super({
// It needs to be zero because we're just proxying the data to another stream
highWaterMark: 0
});
this[kDownloadedSize] = 0;
this[kUploadedSize] = 0;
this.requestInitialized = false;
this[kServerResponsesPiped] = new Set<ServerResponse>();
this.redirects = [];
this[kStopReading] = false;
this[kTriggerRead] = false;
this[kJobs] = [];
// TODO: Remove this when targeting Node.js >= 12
this._progressCallbacks = [];
const unlockWrite = (): void => this._unlockWrite();
const lockWrite = (): void => this._lockWrite();
this.on('pipe', (source: Writable) => {
source.prependListener('data', unlockWrite);
source.on('data', lockWrite);
source.prependListener('end', unlockWrite);
source.on('end', lockWrite);
});
this.on('unpipe', (source: Writable) => {
source.off('data', unlockWrite);
source.off('data', lockWrite);
source.off('end', unlockWrite);
source.off('end', lockWrite);
});
this.on('pipe', source => {
if (source instanceof IncomingMessage) {
this.options.headers = {
...source.headers,
...this.options.headers
};
}
});
const {json, body, form} = options;
if (json || body || form) {
this._lockWrite();
}
(async (nonNormalizedOptions: Options) => {
try {
if (nonNormalizedOptions.body instanceof ReadStream) {
await waitForOpenFile(nonNormalizedOptions.body);
}
if (kIsNormalizedAlready in nonNormalizedOptions) {
this.options = nonNormalizedOptions as NormalizedOptions;
} else {
// @ts-expect-error Common TypeScript bug saying that `this.constructor` is not accessible
this.options = this.constructor.normalizeArguments(url, nonNormalizedOptions, defaults);
}
const {url: normalizedURL} = this.options;
if (!normalizedURL) {
throw new TypeError('Missing `url` property');
}
this.requestUrl = normalizedURL.toString();
decodeURI(this.requestUrl);
await this._finalizeBody();
await this._makeRequest();
if (this.destroyed) {
this[kRequest]?.destroy();
return;
}
// Queued writes etc.
for (const job of this[kJobs]) {
job();
}
this.requestInitialized = true;
} catch (error) {
if (error instanceof RequestError) {
this._beforeError(error);
return;
}
// This is a workaround for https://github.com/nodejs/node/issues/33335
if (!this.destroyed) {
this.destroy(error);
}
}
})(options);
}
static normalizeArguments(url?: string | URL, options?: Options, defaults?: Defaults): NormalizedOptions {
const rawOptions = options;
if (is.object(url) && !is.urlInstance(url)) {
options = {...defaults, ...(url as Options), ...options};
} else {
if (url && options && options.url !== undefined) {
throw new TypeError('The `url` option is mutually exclusive with the `input` argument');
}
options = {...defaults, ...options};
if (url !== undefined) {
options.url = url;
}
if (is.urlInstance(options.url)) {
options.url = new URL(options.url.toString());
}
}
// TODO: Deprecate URL options in Got 12.
// Support extend-specific options
if (options.cache === false) {
options.cache = undefined;
}
if (options.dnsCache === false) {
options.dnsCache = undefined;
}
// Nice type assertions
assert.any([is.string, is.undefined], options.method);
assert.any([is.object, is.undefined], options.headers);
assert.any([is.string, is.urlInstance, is.undefined], options.prefixUrl);
assert.any([is.object, is.undefined], options.cookieJar);
assert.any([is.object, is.string, is.undefined], options.searchParams);
assert.any([is.object, is.string, is.undefined], options.cache);
assert.any([is.object, is.number, is.undefined], options.timeout);
assert.any([is.object, is.undefined], options.context);
assert.any([is.object, is.undefined], options.hooks);
assert.any([is.boolean, is.undefined], options.decompress);
assert.any([is.boolean, is.undefined], options.ignoreInvalidCookies);
assert.any([is.boolean, is.undefined], options.followRedirect);
assert.any([is.number, is.undefined], options.maxRedirects);
assert.any([is.boolean, is.undefined], options.throwHttpErrors);
assert.any([is.boolean, is.undefined], options.http2);
assert.any([is.boolean, is.undefined], options.allowGetBody);
assert.any([is.string, is.undefined], options.localAddress);
assert.any([isDnsLookupIpVersion, is.undefined], options.dnsLookupIpVersion);
assert.any([is.object, is.undefined], options.https);
assert.any([is.boolean, is.undefined], options.rejectUnauthorized);
if (options.https) {
assert.any([is.boolean, is.undefined], options.https.rejectUnauthorized);
assert.any([is.function_, is.undefined], options.https.checkServerIdentity);
assert.any([is.string, is.object, is.array, is.undefined], options.https.certificateAuthority);
assert.any([is.string, is.object, is.array, is.undefined], options.https.key);
assert.any([is.string, is.object, is.array, is.undefined], options.https.certificate);
assert.any([is.string, is.undefined], options.https.passphrase);
assert.any([is.string, is.buffer, is.array, is.undefined], options.https.pfx);
}
// `options.method`
if (is.string(options.method)) {
options.method = options.method.toUpperCase() as Method;
} else {
options.method = 'GET';
}
// `options.headers`
if (options.headers === defaults?.headers) {
options.headers = {...options.headers};
} else {
options.headers = lowercaseKeys({...(defaults?.headers), ...options.headers});
}
// Disallow legacy `url.Url`
if ('slashes' in options) {
throw new TypeError('The legacy `url.Url` has been deprecated. Use `URL` instead.');
}
// `options.auth`
if ('auth' in options) {
throw new TypeError('Parameter `auth` is deprecated. Use `username` / `password` instead.');
}
// `options.searchParams`
if ('searchParams' in options) {
if (options.searchParams && options.searchParams !== defaults?.searchParams) {
let searchParameters: URLSearchParams;
if (is.string(options.searchParams) || (options.searchParams instanceof URLSearchParams)) {
searchParameters = new URLSearchParams(options.searchParams);
} else {
validateSearchParameters(options.searchParams);
searchParameters = new URLSearchParams();
// eslint-disable-next-line guard-for-in
for (const key in options.searchParams) {
const value = options.searchParams[key];
if (value === null) {
searchParameters.append(key, '');
} else if (value !== undefined) {
searchParameters.append(key, value as string);
}
}
}
// `normalizeArguments()` is also used to merge options
defaults?.searchParams?.forEach((value, key) => {
// Only use default if one isn't already defined
if (!searchParameters.has(key)) {
searchParameters.append(key, value);
}
});
options.searchParams = searchParameters;
}
}
// `options.username` & `options.password`
options.username = options.username ?? '';
options.password = options.password ?? '';
// `options.prefixUrl` & `options.url`
if (options.prefixUrl) {
options.prefixUrl = options.prefixUrl.toString();
if (options.prefixUrl !== '' && !options.prefixUrl.endsWith('/')) {
options.prefixUrl += '/';
}
} else {
options.prefixUrl = '';
}
if (is.string(options.url)) {
if (options.url.startsWith('/')) {
throw new Error('`input` must not start with a slash when using `prefixUrl`');
}
options.url = optionsToUrl(options.prefixUrl + options.url, options as Options & {searchParams?: URLSearchParams});
} else if ((is.undefined(options.url) && options.prefixUrl !== '') || options.protocol) {
options.url = optionsToUrl(options.prefixUrl, options as Options & {searchParams?: URLSearchParams});
}
if (options.url) {
// Make it possible to change `options.prefixUrl`
let {prefixUrl} = options;
Object.defineProperty(options, 'prefixUrl', {
set: (value: string) => {
const url = options!.url as URL;
if (!url.href.startsWith(value)) {
throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${url.href}`);
}
options!.url = new URL(value + url.href.slice(prefixUrl.length));
prefixUrl = value;
},
get: () => prefixUrl
});
// Support UNIX sockets
let {protocol} = options.url;
if (protocol === 'unix:') {
protocol = 'http:';
options.url = new URL(`http://unix${options.url.pathname}${options.url.search}`);
}
// Set search params
if (options.searchParams) {
// eslint-disable-next-line @typescript-eslint/no-base-to-string
options.url.search = options.searchParams.toString();
}
// Protocol check
if (protocol !== 'http:' && protocol !== 'https:') {
throw new UnsupportedProtocolError(options as NormalizedOptions);
}
// Update `username`
if (options.username === '') {
options.username = options.url.username;
} else {
options.url.username = options.username;
}
// Update `password`
if (options.password === '') {
options.password = options.url.password;
} else {
options.url.password = options.password;
}
}
// `options.cookieJar`
const {cookieJar} = options;
if (cookieJar) {
let {setCookie, getCookieString} = cookieJar;
assert.function_(setCookie);
assert.function_(getCookieString);
/* istanbul ignore next: Horrible `tough-cookie` v3 check */
if (setCookie.length === 4 && getCookieString.length === 0) {
setCookie = promisify(setCookie.bind(options.cookieJar));
getCookieString = promisify(getCookieString.bind(options.cookieJar));
options.cookieJar = {
setCookie,
// TODO: Fix this when upgrading to TypeScript 4.
// @ts-expect-error TypeScript thinks that promisifying callback(error, string) will result in Promise<void>
getCookieString
};
}
}
// `options.cache`
const {cache} = options;
if (cache) {
if (!cacheableStore.has(cache)) {
cacheableStore.set(cache, new CacheableRequest(
((requestOptions: RequestOptions, handler?: (response: IncomingMessageWithTimings) => void): ClientRequest => {
const result = (requestOptions as Pick<NormalizedOptions, typeof kRequest>)[kRequest](requestOptions, handler);
// TODO: remove this when `cacheable-request` supports async request functions.
if (is.promise(result)) {
// @ts-expect-error
// We only need to implement the error handler in order to support HTTP2 caching.
// The result will be a promise anyway.
result.once = (event: string, handler: (reason: unknown) => void) => {
if (event === 'error') {
result.catch(handler);
} else if (event === 'abort') {
// The empty catch is needed here in case when
// it rejects before it's `await`ed in `_makeRequest`.
(async () => {
try {
const request = (await result) as ClientRequest;
request.once('abort', handler);
} catch {}
})();
} else {
/* istanbul ignore next: safety check */
throw new Error(`Unknown HTTP2 promise event: ${event}`);
}
return result;
};
}
return result;
}) as HttpRequestFunction,
cache as CacheableRequest.StorageAdapter
));
}
}
// `options.dnsCache`
if (options.dnsCache === true) {
options.dnsCache = globalDnsCache;
} else if (!is.undefined(options.dnsCache) && !options.dnsCache.lookup) {
throw new TypeError(`Parameter \`dnsCache\` must be a CacheableLookup instance or a boolean, got ${is(options.dnsCache)}`);
}
// `options.timeout`
if (is.number(options.timeout)) {
options.timeout = {request: options.timeout};
} else if (defaults && options.timeout !== defaults.timeout) {
options.timeout = {
...defaults.timeout,
...options.timeout
};
} else {
options.timeout = {...options.timeout};
}
// `options.context`
if (!options.context) {
options.context = {};
}
// `options.hooks`
const areHooksDefault = options.hooks === defaults?.hooks;
options.hooks = {...options.hooks};
for (const event of knownHookEvents) {
if (event in options.hooks) {
if (is.array(options.hooks[event])) {
// See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044
(options.hooks as any)[event] = [...options.hooks[event]!];
} else {
throw new TypeError(`Parameter \`${event}\` must be an Array, got ${is(options.hooks[event])}`);
}
} else {
options.hooks[event] = [];
}
}
if (defaults && !areHooksDefault) {
for (const event of knownHookEvents) {
const defaultHooks = defaults.hooks[event];
if (defaultHooks.length !== 0) {
// See https://github.com/microsoft/TypeScript/issues/31445#issuecomment-576929044
(options.hooks as any)[event] = [
...defaults.hooks[event],
...options.hooks[event]!
];
}
}
}
// DNS options
if ('family' in options) {
deprecationWarning('"options.family" was never documented, please use "options.dnsLookupIpVersion"');
}
// HTTPS options
if (defaults?.https) {
options.https = {...defaults.https, ...options.https};
}
if ('rejectUnauthorized' in options) {
deprecationWarning('"options.rejectUnauthorized" is now deprecated, please use "options.https.rejectUnauthorized"');
}
if ('checkServerIdentity' in options) {
deprecationWarning('"options.checkServerIdentity" was never documented, please use "options.https.checkServerIdentity"');
}
if ('ca' in options) {
deprecationWarning('"options.ca" was never documented, please use "options.https.certificateAuthority"');
}
if ('key' in options) {
deprecationWarning('"options.key" was never documented, please use "options.https.key"');
}
if ('cert' in options) {
deprecationWarning('"options.cert" was never documented, please use "options.https.certificate"');
}
if ('passphrase' in options) {
deprecationWarning('"options.passphrase" was never documented, please use "options.https.passphrase"');
}
if ('pfx' in options) {
deprecationWarning('"options.pfx" was never documented, please use "options.https.pfx"');
}
// Other options
if ('followRedirects' in options) {
throw new TypeError('The `followRedirects` option does not exist. Use `followRedirect` instead.');
}
if (options.agent) {
for (const key in options.agent) {
if (key !== 'http' && key !== 'https' && key !== 'http2') {
throw new TypeError(`Expected the \`options.agent\` properties to be \`http\`, \`https\` or \`http2\`, got \`${key}\``);
}
}
}
options.maxRedirects = options.maxRedirects ?? 0;