-
Notifications
You must be signed in to change notification settings - Fork 301
Expand file tree
/
Copy pathhttp.d.ts
More file actions
1921 lines (1921 loc) · 83.7 KB
/
http.d.ts
File metadata and controls
1921 lines (1921 loc) · 83.7 KB
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
/**
* To use the HTTP server and client one must `require('node:http')`.
*
* The HTTP interfaces in Node.js are designed to support many features
* of the protocol which have been traditionally difficult to use.
* In particular, large, possibly chunk-encoded, messages. The interface is
* careful to never buffer entire requests or responses, so the
* user is able to stream data.
*
* HTTP message headers are represented by an object like this:
*
* ```json
* { "content-length": "123",
* "content-type": "text/plain",
* "connection": "keep-alive",
* "host": "example.com",
* "accept": "*" }
* ```
*
* Keys are lowercased. Values are not modified.
*
* In order to support the full spectrum of possible HTTP applications, the Node.js
* HTTP API is very low-level. It deals with stream handling and message
* parsing only. It parses a message into headers and body but it does not
* parse the actual headers or the body.
*
* See `message.headers` for details on how duplicate headers are handled.
*
* The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For
* example, the previous message header object might have a `rawHeaders` list like the following:
*
* ```js
* [ 'ConTent-Length', '123456',
* 'content-LENGTH', '123',
* 'content-type', 'text/plain',
* 'CONNECTION', 'keep-alive',
* 'Host', 'example.com',
* 'accepT', '*' ]
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/http.js)
*/
declare module "http" {
import * as stream from "node:stream";
import { URL } from "node:url";
import { LookupOptions } from "node:dns";
import { EventEmitter } from "node:events";
import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net";
// incoming headers will never contain number
interface IncomingHttpHeaders extends NodeJS.Dict<string | string[]> {
accept?: string | undefined;
"accept-language"?: string | undefined;
"accept-patch"?: string | undefined;
"accept-ranges"?: string | undefined;
"access-control-allow-credentials"?: string | undefined;
"access-control-allow-headers"?: string | undefined;
"access-control-allow-methods"?: string | undefined;
"access-control-allow-origin"?: string | undefined;
"access-control-expose-headers"?: string | undefined;
"access-control-max-age"?: string | undefined;
"access-control-request-headers"?: string | undefined;
"access-control-request-method"?: string | undefined;
age?: string | undefined;
allow?: string | undefined;
"alt-svc"?: string | undefined;
authorization?: string | undefined;
"cache-control"?: string | undefined;
connection?: string | undefined;
"content-disposition"?: string | undefined;
"content-encoding"?: string | undefined;
"content-language"?: string | undefined;
"content-length"?: string | undefined;
"content-location"?: string | undefined;
"content-range"?: string | undefined;
"content-type"?: string | undefined;
cookie?: string | undefined;
date?: string | undefined;
etag?: string | undefined;
expect?: string | undefined;
expires?: string | undefined;
forwarded?: string | undefined;
from?: string | undefined;
host?: string | undefined;
"if-match"?: string | undefined;
"if-modified-since"?: string | undefined;
"if-none-match"?: string | undefined;
"if-unmodified-since"?: string | undefined;
"last-modified"?: string | undefined;
location?: string | undefined;
origin?: string | undefined;
pragma?: string | undefined;
"proxy-authenticate"?: string | undefined;
"proxy-authorization"?: string | undefined;
"public-key-pins"?: string | undefined;
range?: string | undefined;
referer?: string | undefined;
"retry-after"?: string | undefined;
"sec-websocket-accept"?: string | undefined;
"sec-websocket-extensions"?: string | undefined;
"sec-websocket-key"?: string | undefined;
"sec-websocket-protocol"?: string | undefined;
"sec-websocket-version"?: string | undefined;
"set-cookie"?: string[] | undefined;
"strict-transport-security"?: string | undefined;
tk?: string | undefined;
trailer?: string | undefined;
"transfer-encoding"?: string | undefined;
upgrade?: string | undefined;
"user-agent"?: string | undefined;
vary?: string | undefined;
via?: string | undefined;
warning?: string | undefined;
"www-authenticate"?: string | undefined;
}
// outgoing headers allows numbers (as they are converted internally to strings)
type OutgoingHttpHeader = number | string | string[];
interface OutgoingHttpHeaders extends NodeJS.Dict<OutgoingHttpHeader> {
accept?: string | string[] | undefined;
"accept-charset"?: string | string[] | undefined;
"accept-encoding"?: string | string[] | undefined;
"accept-language"?: string | string[] | undefined;
"accept-ranges"?: string | undefined;
"access-control-allow-credentials"?: string | undefined;
"access-control-allow-headers"?: string | undefined;
"access-control-allow-methods"?: string | undefined;
"access-control-allow-origin"?: string | undefined;
"access-control-expose-headers"?: string | undefined;
"access-control-max-age"?: string | undefined;
"access-control-request-headers"?: string | undefined;
"access-control-request-method"?: string | undefined;
age?: string | undefined;
allow?: string | undefined;
authorization?: string | undefined;
"cache-control"?: string | undefined;
"cdn-cache-control"?: string | undefined;
connection?: string | string[] | undefined;
"content-disposition"?: string | undefined;
"content-encoding"?: string | undefined;
"content-language"?: string | undefined;
"content-length"?: string | number | undefined;
"content-location"?: string | undefined;
"content-range"?: string | undefined;
"content-security-policy"?: string | undefined;
"content-security-policy-report-only"?: string | undefined;
cookie?: string | string[] | undefined;
dav?: string | string[] | undefined;
dnt?: string | undefined;
date?: string | undefined;
etag?: string | undefined;
expect?: string | undefined;
expires?: string | undefined;
forwarded?: string | undefined;
from?: string | undefined;
host?: string | undefined;
"if-match"?: string | undefined;
"if-modified-since"?: string | undefined;
"if-none-match"?: string | undefined;
"if-range"?: string | undefined;
"if-unmodified-since"?: string | undefined;
"last-modified"?: string | undefined;
link?: string | string[] | undefined;
location?: string | undefined;
"max-forwards"?: string | undefined;
origin?: string | undefined;
prgama?: string | string[] | undefined;
"proxy-authenticate"?: string | string[] | undefined;
"proxy-authorization"?: string | undefined;
"public-key-pins"?: string | undefined;
"public-key-pins-report-only"?: string | undefined;
range?: string | undefined;
referer?: string | undefined;
"referrer-policy"?: string | undefined;
refresh?: string | undefined;
"retry-after"?: string | undefined;
"sec-websocket-accept"?: string | undefined;
"sec-websocket-extensions"?: string | string[] | undefined;
"sec-websocket-key"?: string | undefined;
"sec-websocket-protocol"?: string | string[] | undefined;
"sec-websocket-version"?: string | undefined;
server?: string | undefined;
"set-cookie"?: string | string[] | undefined;
"strict-transport-security"?: string | undefined;
te?: string | undefined;
trailer?: string | undefined;
"transfer-encoding"?: string | undefined;
"user-agent"?: string | undefined;
upgrade?: string | undefined;
"upgrade-insecure-requests"?: string | undefined;
vary?: string | undefined;
via?: string | string[] | undefined;
warning?: string | undefined;
"www-authenticate"?: string | string[] | undefined;
"x-content-type-options"?: string | undefined;
"x-dns-prefetch-control"?: string | undefined;
"x-frame-options"?: string | undefined;
"x-xss-protection"?: string | undefined;
}
interface ClientRequestArgs {
_defaultAgent?: Agent | undefined;
agent?: Agent | boolean | undefined;
auth?: string | null | undefined;
createConnection?:
| ((
options: ClientRequestArgs,
oncreate: (err: Error | null, socket: stream.Duplex) => void,
) => stream.Duplex | null | undefined)
| undefined;
defaultPort?: number | string | undefined;
family?: number | undefined;
headers?: OutgoingHttpHeaders | undefined;
hints?: LookupOptions["hints"];
host?: string | null | undefined;
hostname?: string | null | undefined;
insecureHTTPParser?: boolean | undefined;
localAddress?: string | undefined;
localPort?: number | undefined;
lookup?: LookupFunction | undefined;
/**
* @default 16384
*/
maxHeaderSize?: number | undefined;
method?: string | undefined;
path?: string | null | undefined;
port?: number | string | null | undefined;
protocol?: string | null | undefined;
setHost?: boolean | undefined;
signal?: AbortSignal | undefined;
socketPath?: string | undefined;
timeout?: number | undefined;
uniqueHeaders?: Array<string | string[]> | undefined;
joinDuplicateHeaders?: boolean;
}
interface ServerOptions<
Request extends typeof IncomingMessage = typeof IncomingMessage,
Response extends typeof ServerResponse = typeof ServerResponse,
> {
/**
* Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`.
*/
IncomingMessage?: Request | undefined;
/**
* Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`.
*/
ServerResponse?: Response | undefined;
/**
* Sets the timeout value in milliseconds for receiving the entire request from the client.
* @see Server.requestTimeout for more information.
* @default 300000
* @since v18.0.0
*/
requestTimeout?: number | undefined;
/**
* It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates.
* @default false
* @since v18.14.0
*/
joinDuplicateHeaders?: boolean;
/**
* The number of milliseconds of inactivity a server needs to wait for additional incoming data,
* after it has finished writing the last response, before a socket will be destroyed.
* @see Server.keepAliveTimeout for more information.
* @default 5000
* @since v18.0.0
*/
keepAliveTimeout?: number | undefined;
/**
* Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests.
* @default 30000
*/
connectionsCheckingInterval?: number | undefined;
/**
* Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`.
* This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`.
* Default: @see stream.getDefaultHighWaterMark().
* @since v20.1.0
*/
highWaterMark?: number | undefined;
/**
* Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.
* Using the insecure parser should be avoided.
* See --insecure-http-parser for more information.
* @default false
*/
insecureHTTPParser?: boolean | undefined;
/**
* Optionally overrides the value of `--max-http-header-size` for requests received by
* this server, i.e. the maximum length of request headers in bytes.
* @default 16384
* @since v13.3.0
*/
maxHeaderSize?: number | undefined;
/**
* If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received.
* @default true
* @since v16.5.0
*/
noDelay?: boolean | undefined;
/**
* If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received,
* similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`.
* @default false
* @since v16.5.0
*/
keepAlive?: boolean | undefined;
/**
* If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket.
* @default 0
* @since v16.5.0
*/
keepAliveInitialDelay?: number | undefined;
/**
* A list of response headers that should be sent only once.
* If the header's value is an array, the items will be joined using `; `.
*/
uniqueHeaders?: Array<string | string[]> | undefined;
}
type RequestListener<
Request extends typeof IncomingMessage = typeof IncomingMessage,
Response extends typeof ServerResponse = typeof ServerResponse,
> = (req: InstanceType<Request>, res: InstanceType<Response> & { req: InstanceType<Request> }) => void;
/**
* @since v0.1.17
*/
class Server<
Request extends typeof IncomingMessage = typeof IncomingMessage,
Response extends typeof ServerResponse = typeof ServerResponse,
> extends NetServer {
constructor(requestListener?: RequestListener<Request, Response>);
constructor(options: ServerOptions<Request, Response>, requestListener?: RequestListener<Request, Response>);
/**
* Sets the timeout value for sockets, and emits a `'timeout'` event on
* the Server object, passing the socket as an argument, if a timeout
* occurs.
*
* If there is a `'timeout'` event listener on the Server object, then it
* will be called with the timed-out socket as an argument.
*
* By default, the Server does not timeout sockets. However, if a callback
* is assigned to the Server's `'timeout'` event, timeouts must be handled
* explicitly.
* @since v0.9.12
* @param [msecs=0 (no timeout)]
*/
setTimeout(msecs?: number, callback?: () => void): this;
setTimeout(callback: () => void): this;
/**
* Limits maximum incoming headers count. If set to 0, no limit will be applied.
* @since v0.7.0
*/
maxHeadersCount: number | null;
/**
* The maximum number of requests socket can handle
* before closing keep alive connection.
*
* A value of `0` will disable the limit.
*
* When the limit is reached it will set the `Connection` header value to `close`,
* but will not actually close the connection, subsequent requests sent
* after the limit is reached will get `503 Service Unavailable` as a response.
* @since v16.10.0
*/
maxRequestsPerSocket: number | null;
/**
* The number of milliseconds of inactivity before a socket is presumed
* to have timed out.
*
* A value of `0` will disable the timeout behavior on incoming connections.
*
* The socket timeout logic is set up on connection, so changing this
* value only affects new connections to the server, not any existing connections.
* @since v0.9.12
*/
timeout: number;
/**
* Limit the amount of time the parser will wait to receive the complete HTTP
* headers.
*
* If the timeout expires, the server responds with status 408 without
* forwarding the request to the request listener and then closes the connection.
*
* It must be set to a non-zero value (e.g. 120 seconds) to protect against
* potential Denial-of-Service attacks in case the server is deployed without a
* reverse proxy in front.
* @since v11.3.0, v10.14.0
*/
headersTimeout: number;
/**
* The number of milliseconds of inactivity a server needs to wait for additional
* incoming data, after it has finished writing the last response, before a socket
* will be destroyed. If the server receives new data before the keep-alive
* timeout has fired, it will reset the regular inactivity timeout, i.e., `server.timeout`.
*
* A value of `0` will disable the keep-alive timeout behavior on incoming
* connections.
* A value of `0` makes the http server behave similarly to Node.js versions prior
* to 8.0.0, which did not have a keep-alive timeout.
*
* The socket timeout logic is set up on connection, so changing this value only
* affects new connections to the server, not any existing connections.
* @since v8.0.0
*/
keepAliveTimeout: number;
/**
* Sets the timeout value in milliseconds for receiving the entire request from
* the client.
*
* If the timeout expires, the server responds with status 408 without
* forwarding the request to the request listener and then closes the connection.
*
* It must be set to a non-zero value (e.g. 120 seconds) to protect against
* potential Denial-of-Service attacks in case the server is deployed without a
* reverse proxy in front.
* @since v14.11.0
*/
requestTimeout: number;
/**
* Closes all connections connected to this server.
* @since v18.2.0
*/
closeAllConnections(): void;
/**
* Closes all connections connected to this server which are not sending a request
* or waiting for a response.
* @since v18.2.0
*/
closeIdleConnections(): void;
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "connection", listener: (socket: Socket) => void): this;
addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "listening", listener: () => void): this;
addListener(event: "checkContinue", listener: RequestListener<Request, Response>): this;
addListener(event: "checkExpectation", listener: RequestListener<Request, Response>): this;
addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
addListener(
event: "connect",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void,
): this;
addListener(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this;
addListener(event: "request", listener: RequestListener<Request, Response>): this;
addListener(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void,
): this;
emit(event: string, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "connection", socket: Socket): boolean;
emit(event: "error", err: Error): boolean;
emit(event: "listening"): boolean;
emit(
event: "checkContinue",
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request> },
): boolean;
emit(
event: "checkExpectation",
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request> },
): boolean;
emit(event: "clientError", err: Error, socket: stream.Duplex): boolean;
emit(event: "connect", req: InstanceType<Request>, socket: stream.Duplex, head: Buffer): boolean;
emit(event: "dropRequest", req: InstanceType<Request>, socket: stream.Duplex): boolean;
emit(
event: "request",
req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request> },
): boolean;
emit(event: "upgrade", req: InstanceType<Request>, socket: stream.Duplex, head: Buffer): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "connection", listener: (socket: Socket) => void): this;
on(event: "error", listener: (err: Error) => void): this;
on(event: "listening", listener: () => void): this;
on(event: "checkContinue", listener: RequestListener<Request, Response>): this;
on(event: "checkExpectation", listener: RequestListener<Request, Response>): this;
on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
on(event: "connect", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void): this;
on(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this;
on(event: "request", listener: RequestListener<Request, Response>): this;
on(event: "upgrade", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "connection", listener: (socket: Socket) => void): this;
once(event: "error", listener: (err: Error) => void): this;
once(event: "listening", listener: () => void): this;
once(event: "checkContinue", listener: RequestListener<Request, Response>): this;
once(event: "checkExpectation", listener: RequestListener<Request, Response>): this;
once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
once(
event: "connect",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void,
): this;
once(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this;
once(event: "request", listener: RequestListener<Request, Response>): this;
once(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void,
): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "connection", listener: (socket: Socket) => void): this;
prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "listening", listener: () => void): this;
prependListener(event: "checkContinue", listener: RequestListener<Request, Response>): this;
prependListener(event: "checkExpectation", listener: RequestListener<Request, Response>): this;
prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
prependListener(
event: "connect",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void,
): this;
prependListener(
event: "dropRequest",
listener: (req: InstanceType<Request>, socket: stream.Duplex) => void,
): this;
prependListener(event: "request", listener: RequestListener<Request, Response>): this;
prependListener(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void,
): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "connection", listener: (socket: Socket) => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "listening", listener: () => void): this;
prependOnceListener(event: "checkContinue", listener: RequestListener<Request, Response>): this;
prependOnceListener(event: "checkExpectation", listener: RequestListener<Request, Response>): this;
prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
prependOnceListener(
event: "connect",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void,
): this;
prependOnceListener(
event: "dropRequest",
listener: (req: InstanceType<Request>, socket: stream.Duplex) => void,
): this;
prependOnceListener(event: "request", listener: RequestListener<Request, Response>): this;
prependOnceListener(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void,
): this;
}
/**
* This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from
* the perspective of the participants of an HTTP transaction.
* @since v0.1.17
*/
class OutgoingMessage<Request extends IncomingMessage = IncomingMessage> extends stream.Writable {
readonly req: Request;
chunkedEncoding: boolean;
shouldKeepAlive: boolean;
useChunkedEncodingByDefault: boolean;
sendDate: boolean;
/**
* @deprecated Use `writableEnded` instead.
*/
finished: boolean;
/**
* Read-only. `true` if the headers were sent, otherwise `false`.
* @since v0.9.3
*/
readonly headersSent: boolean;
/**
* Alias of `outgoingMessage.socket`.
* @since v0.3.0
* @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead.
*/
readonly connection: Socket | null;
/**
* Reference to the underlying socket. Usually, users will not want to access
* this property.
*
* After calling `outgoingMessage.end()`, this property will be nulled.
* @since v0.3.0
*/
readonly socket: Socket | null;
constructor();
/**
* Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter.
* @since v0.9.12
* @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event.
*/
setTimeout(msecs: number, callback?: () => void): this;
/**
* Sets a single header value. If the header already exists in the to-be-sent
* headers, its value will be replaced. Use an array of strings to send multiple
* headers with the same name.
* @since v0.4.0
* @param name Header name
* @param value Header value
*/
setHeader(name: string, value: number | string | readonly string[]): this;
/**
* Append a single header value to the header object.
*
* If the value is an array, this is equivalent to calling this method multiple
* times.
*
* If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`.
*
* Depending of the value of `options.uniqueHeaders` when the client request or the
* server were created, this will end up in the header being sent multiple times or
* a single time with values joined using `; `.
* @since v18.3.0, v16.17.0
* @param name Header name
* @param value Header value
*/
appendHeader(name: string, value: string | readonly string[]): this;
/**
* Gets the value of the HTTP header with the given name. If that header is not
* set, the returned value will be `undefined`.
* @since v0.4.0
* @param name Name of header
*/
getHeader(name: string): number | string | string[] | undefined;
/**
* Returns a shallow copy of the current outgoing headers. Since a shallow
* copy is used, array values may be mutated without additional calls to
* various header-related HTTP module methods. The keys of the returned
* object are the header names and the values are the respective header
* values. All header names are lowercase.
*
* The object returned by the `outgoingMessage.getHeaders()` method does
* not prototypically inherit from the JavaScript `Object`. This means that
* typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`,
* and others are not defined and will not work.
*
* ```js
* outgoingMessage.setHeader('Foo', 'bar');
* outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
*
* const headers = outgoingMessage.getHeaders();
* // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
* ```
* @since v7.7.0
*/
getHeaders(): OutgoingHttpHeaders;
/**
* Returns an array containing the unique names of the current outgoing headers.
* All names are lowercase.
* @since v7.7.0
*/
getHeaderNames(): string[];
/**
* Returns `true` if the header identified by `name` is currently set in the
* outgoing headers. The header name is case-insensitive.
*
* ```js
* const hasContentType = outgoingMessage.hasHeader('content-type');
* ```
* @since v7.7.0
*/
hasHeader(name: string): boolean;
/**
* Removes a header that is queued for implicit sending.
*
* ```js
* outgoingMessage.removeHeader('Content-Encoding');
* ```
* @since v0.4.0
* @param name Header name
*/
removeHeader(name: string): void;
/**
* Adds HTTP trailers (headers but at the end of the message) to the message.
*
* Trailers will **only** be emitted if the message is chunked encoded. If not,
* the trailers will be silently discarded.
*
* HTTP requires the `Trailer` header to be sent to emit trailers,
* with a list of header field names in its value, e.g.
*
* ```js
* message.writeHead(200, { 'Content-Type': 'text/plain',
* 'Trailer': 'Content-MD5' });
* message.write(fileData);
* message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
* message.end();
* ```
*
* Attempting to set a header field name or value that contains invalid characters
* will result in a `TypeError` being thrown.
* @since v0.3.0
*/
addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void;
/**
* Flushes the message headers.
*
* For efficiency reason, Node.js normally buffers the message headers
* until `outgoingMessage.end()` is called or the first chunk of message data
* is written. It then tries to pack the headers and data into a single TCP
* packet.
*
* It is usually desired (it saves a TCP round-trip), but not when the first
* data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message.
* @since v1.6.0
*/
flushHeaders(): void;
}
/**
* This object is created internally by an HTTP server, not by the user. It is
* passed as the second parameter to the `'request'` event.
* @since v0.1.17
*/
class ServerResponse<Request extends IncomingMessage = IncomingMessage> extends OutgoingMessage<Request> {
/**
* When using implicit headers (not calling `response.writeHead()` explicitly),
* this property controls the status code that will be sent to the client when
* the headers get flushed.
*
* ```js
* response.statusCode = 404;
* ```
*
* After response header was sent to the client, this property indicates the
* status code which was sent out.
* @since v0.4.0
*/
statusCode: number;
/**
* When using implicit headers (not calling `response.writeHead()` explicitly),
* this property controls the status message that will be sent to the client when
* the headers get flushed. If this is left as `undefined` then the standard
* message for the status code will be used.
*
* ```js
* response.statusMessage = 'Not found';
* ```
*
* After response header was sent to the client, this property indicates the
* status message which was sent out.
* @since v0.11.8
*/
statusMessage: string;
/**
* If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal.
* Mismatching the `Content-Length` header value will result
* in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`.
* @since v18.10.0, v16.18.0
*/
strictContentLength: boolean;
constructor(req: Request);
assignSocket(socket: Socket): void;
detachSocket(socket: Socket): void;
/**
* Sends an HTTP/1.1 100 Continue message to the client, indicating that
* the request body should be sent. See the `'checkContinue'` event on `Server`.
* @since v0.3.0
*/
writeContinue(callback?: () => void): void;
/**
* Sends an HTTP/1.1 103 Early Hints message to the client with a Link header,
* indicating that the user agent can preload/preconnect the linked resources.
* The `hints` is an object containing the values of headers to be sent with
* early hints message. The optional `callback` argument will be called when
* the response message has been written.
*
* **Example**
*
* ```js
* const earlyHintsLink = '</styles.css>; rel=preload; as=style';
* response.writeEarlyHints({
* 'link': earlyHintsLink,
* });
*
* const earlyHintsLinks = [
* '</styles.css>; rel=preload; as=style',
* '</scripts.js>; rel=preload; as=script',
* ];
* response.writeEarlyHints({
* 'link': earlyHintsLinks,
* 'x-trace-id': 'id for diagnostics',
* });
*
* const earlyHintsCallback = () => console.log('early hints message sent');
* response.writeEarlyHints({
* 'link': earlyHintsLinks,
* }, earlyHintsCallback);
* ```
* @since v18.11.0
* @param hints An object containing the values of headers
* @param callback Will be called when the response message has been written
*/
writeEarlyHints(hints: Record<string, string | string[]>, callback?: () => void): void;
/**
* Sends a response header to the request. The status code is a 3-digit HTTP
* status code, like `404`. The last argument, `headers`, are the response headers.
* Optionally one can give a human-readable `statusMessage` as the second
* argument.
*
* `headers` may be an `Array` where the keys and values are in the same list.
* It is _not_ a list of tuples. So, the even-numbered offsets are key values,
* and the odd-numbered offsets are the associated values. The array is in the same
* format as `request.rawHeaders`.
*
* Returns a reference to the `ServerResponse`, so that calls can be chained.
*
* ```js
* const body = 'hello world';
* response
* .writeHead(200, {
* 'Content-Length': Buffer.byteLength(body),
* 'Content-Type': 'text/plain',
* })
* .end(body);
* ```
*
* This method must only be called once on a message and it must
* be called before `response.end()` is called.
*
* If `response.write()` or `response.end()` are called before calling
* this, the implicit/mutable headers will be calculated and call this function.
*
* When headers have been set with `response.setHeader()`, they will be merged
* with any headers passed to `response.writeHead()`, with the headers passed
* to `response.writeHead()` given precedence.
*
* If this method is called and `response.setHeader()` has not been called,
* it will directly write the supplied header values onto the network channel
* without caching internally, and the `response.getHeader()` on the header
* will not yield the expected result. If progressive population of headers is
* desired with potential future retrieval and modification, use `response.setHeader()` instead.
*
* ```js
* // Returns content-type = text/plain
* const server = http.createServer((req, res) => {
* res.setHeader('Content-Type', 'text/html');
* res.setHeader('X-Foo', 'bar');
* res.writeHead(200, { 'Content-Type': 'text/plain' });
* res.end('ok');
* });
* ```
*
* `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js
* will check whether `Content-Length` and the length of the body which has
* been transmitted are equal or not.
*
* Attempting to set a header field name or value that contains invalid characters
* will result in a \[`Error`\]\[\] being thrown.
* @since v0.1.30
*/
writeHead(
statusCode: number,
statusMessage?: string,
headers?: OutgoingHttpHeaders | OutgoingHttpHeader[],
): this;
writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this;
/**
* Sends a HTTP/1.1 102 Processing message to the client, indicating that
* the request body should be sent.
* @since v10.0.0
*/
writeProcessing(): void;
}
interface InformationEvent {
statusCode: number;
statusMessage: string;
httpVersion: string;
httpVersionMajor: number;
httpVersionMinor: number;
headers: IncomingHttpHeaders;
rawHeaders: string[];
}
/**
* This object is created internally and returned from {@link request}. It
* represents an _in-progress_ request whose header has already been queued. The
* header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will
* be sent along with the first data chunk or when calling `request.end()`.
*
* To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response
* headers have been received. The `'response'` event is executed with one
* argument which is an instance of {@link IncomingMessage}.
*
* During the `'response'` event, one can add listeners to the
* response object; particularly to listen for the `'data'` event.
*
* If no `'response'` handler is added, then the response will be
* entirely discarded. However, if a `'response'` event handler is added,
* then the data from the response object **must** be consumed, either by
* calling `response.read()` whenever there is a `'readable'` event, or
* by adding a `'data'` handler, or by calling the `.resume()` method.
* Until the data is consumed, the `'end'` event will not fire. Also, until
* the data is read it will consume memory that can eventually lead to a
* 'process out of memory' error.
*
* For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered.
*
* Set `Content-Length` header to limit the response body size.
* If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown,
* identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`.
*
* `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes.
* @since v0.1.17
*/
class ClientRequest extends OutgoingMessage {
/**
* The `request.aborted` property will be `true` if the request has
* been aborted.
* @since v0.11.14
* @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead.
*/
aborted: boolean;
/**
* The request host.
* @since v14.5.0, v12.19.0
*/
host: string;
/**
* The request protocol.
* @since v14.5.0, v12.19.0
*/
protocol: string;
/**
* When sending request through a keep-alive enabled agent, the underlying socket
* might be reused. But if server closes connection at unfortunate time, client
* may run into a 'ECONNRESET' error.
*
* ```js
* import http from 'node:http';
*
* // Server has a 5 seconds keep-alive timeout by default
* http
* .createServer((req, res) => {
* res.write('hello\n');
* res.end();
* })
* .listen(3000);
*
* setInterval(() => {
* // Adapting a keep-alive agent
* http.get('http://localhost:3000', { agent }, (res) => {
* res.on('data', (data) => {
* // Do nothing
* });
* });
* }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
* ```
*
* By marking a request whether it reused socket or not, we can do
* automatic error retry base on it.
*
* ```js
* import http from 'node:http';
* const agent = new http.Agent({ keepAlive: true });
*
* function retriableRequest() {
* const req = http
* .get('http://localhost:3000', { agent }, (res) => {
* // ...
* })
* .on('error', (err) => {
* // Check if retry is needed
* if (req.reusedSocket && err.code === 'ECONNRESET') {
* retriableRequest();
* }
* });
* }
*
* retriableRequest();
* ```
* @since v13.0.0, v12.16.0
*/
reusedSocket: boolean;
/**
* Limits maximum response headers count. If set to 0, no limit will be applied.
*/
maxHeadersCount: number;
constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void);
/**
* The request method.
* @since v0.1.97
*/
method: string;
/**
* The request path.
* @since v0.4.0
*/
path: string;
/**
* Marks the request as aborting. Calling this will cause remaining data
* in the response to be dropped and the socket to be destroyed.
* @since v0.3.8
* @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead.
*/
abort(): void;
onSocket(socket: Socket): void;
/**
* Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called.
* @since v0.5.9
* @param timeout Milliseconds before a request times out.
* @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event.
*/
setTimeout(timeout: number, callback?: () => void): this;
/**
* Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called.
* @since v0.5.9
*/
setNoDelay(noDelay?: boolean): void;
/**
* Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called.
* @since v0.5.9
*/