-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-request.ts
More file actions
1960 lines (1843 loc) · 56.1 KB
/
http-request.ts
File metadata and controls
1960 lines (1843 loc) · 56.1 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
/**
* @fileoverview HTTP/HTTPS request utilities using Node.js built-in modules with retry logic, redirects, and download support.
*
* This module provides a fetch-like API built on top of Node.js native `http` and `https` modules.
* It supports automatic retries with exponential backoff, redirect following, streaming downloads,
* and provides a familiar fetch-style response interface.
*
* Key Features:
* - Automatic retries with exponential backoff for failed requests.
* - Redirect following with configurable max redirects.
* - Streaming downloads with progress callbacks.
* - Fetch-like response interface (`.json()`, `.text()`, `.arrayBuffer()`).
* - Timeout support for all operations.
* - Zero dependencies on external HTTP libraries.
*/
import { SOCKET_LIB_USER_AGENT } from './constants/socket'
import { safeDelete } from './fs'
import type { IncomingHttpHeaders, IncomingMessage } from 'node:http'
import type { Readable } from 'node:stream'
import type { Logger } from './logger'
/** IncomingMessage received as a response to a client request (http.request callback). */
export type IncomingResponse = IncomingMessage
/** IncomingMessage received as a request in a server handler (http.createServer callback). */
export type IncomingRequest = IncomingMessage
/**
* Information passed to the onRequest hook before each request attempt.
*/
export interface HttpHookRequestInfo {
headers: Record<string, string>
method: string
timeout: number
url: string
}
/**
* Information passed to the onResponse hook after each request attempt.
*/
export interface HttpHookResponseInfo {
duration: number
error?: Error | undefined
headers?: IncomingHttpHeaders | undefined
method: string
status?: number | undefined
statusText?: string | undefined
url: string
}
/**
* Lifecycle hooks for observing HTTP request/response events.
* Hooks fire per-attempt (retries produce multiple hook calls).
*/
export interface HttpHooks {
onRequest?: ((info: HttpHookRequestInfo) => void) | undefined
onResponse?: ((info: HttpHookResponseInfo) => void) | undefined
}
/**
* Configuration options for HTTP/HTTPS requests.
*/
export interface HttpRequestOptions {
/**
* Request body to send.
* Can be a string, Buffer, or Readable stream.
*
* When a Readable stream is provided, it is piped directly to the request.
* If the stream has a `getHeaders()` method (duck-typed, e.g., the `form-data`
* npm package), its headers (Content-Type with boundary) are automatically
* merged into the request headers.
*
* **Note:** Streaming bodies are one-shot — they cannot be replayed. Using a
* Readable body with `retries > 0` throws an error. Buffer the body as a
* string/Buffer if retries are needed. Redirects are also disabled for
* streaming bodies since the stream is consumed on the first request.
*
* @example
* ```ts
* // Send JSON data
* await httpRequest('https://api.example.com/data', {
* method: 'POST',
* body: JSON.stringify({ name: 'Alice' }),
* headers: { 'Content-Type': 'application/json' }
* })
*
* // Send binary data
* const buffer = Buffer.from([0x00, 0x01, 0x02])
* await httpRequest('https://api.example.com/upload', {
* method: 'POST',
* body: buffer
* })
*
* // Stream form-data (npm package, not native FormData)
* import FormData from 'form-data'
* const form = new FormData()
* form.append('file', createReadStream('data.json'))
* await httpRequest('https://api.example.com/upload', {
* method: 'POST',
* body: form // auto-merges form.getHeaders()
* })
* ```
*/
body?: Buffer | Readable | string | undefined
/**
* Custom CA certificates for TLS connections.
* When provided, these certificates are combined with the default trust
* store via an HTTPS agent. Useful when SSL_CERT_FILE is set but
* NODE_EXTRA_CA_CERTS was not available at process startup.
*
* @example
* ```ts
* import { rootCertificates } from 'node:tls'
* import { readFileSync } from 'node:fs'
*
* const extraCerts = readFileSync('/path/to/cert.pem', 'utf-8')
* await httpRequest('https://api.example.com', {
* ca: [...rootCertificates, extraCerts]
* })
* ```
*/
ca?: string[] | undefined
/**
* Whether to automatically follow HTTP redirects (3xx status codes).
*
* @default true
*
* @example
* ```ts
* // Follow redirects (default)
* await httpRequest('https://example.com/redirect')
*
* // Don't follow redirects
* const response = await httpRequest('https://example.com/redirect', {
* followRedirects: false
* })
* console.log(response.status) // 301 or 302
* ```
*/
followRedirects?: boolean | undefined
/**
* Lifecycle hooks for observing request/response events.
* Hooks fire per-attempt — retries and redirects each trigger separate hook calls.
*/
hooks?: HttpHooks | undefined
/**
* HTTP headers to send with the request.
* A `User-Agent` header is automatically added if not provided.
*
* @example
* ```ts
* await httpRequest('https://api.example.com/data', {
* headers: {
* 'Authorization': 'Bearer token123',
* 'Content-Type': 'application/json',
* 'Accept': 'application/json'
* }
* })
* ```
*/
headers?: Record<string, string> | undefined
/**
* Maximum number of redirects to follow before throwing an error.
* Only relevant when `followRedirects` is `true`.
*
* @default 5
*
* @example
* ```ts
* // Allow up to 10 redirects
* await httpRequest('https://example.com/many-redirects', {
* maxRedirects: 10
* })
* ```
*/
maxRedirects?: number | undefined
/**
* Maximum response body size in bytes. Responses exceeding this limit
* will be rejected with an error. Prevents memory exhaustion from
* unexpectedly large responses.
*
* @default undefined (no limit)
*/
maxResponseSize?: number | undefined
/**
* HTTP method to use for the request.
*
* @default 'GET'
*
* @example
* ```ts
* // GET request (default)
* await httpRequest('https://api.example.com/data')
*
* // POST request
* await httpRequest('https://api.example.com/data', {
* method: 'POST',
* body: JSON.stringify({ name: 'Alice' })
* })
*
* // DELETE request
* await httpRequest('https://api.example.com/data/123', {
* method: 'DELETE'
* })
* ```
*/
method?: string | undefined
/**
* Callback invoked before each retry attempt.
* Allows customizing retry behavior per-attempt (e.g., skip 4xx, honor Retry-After).
*
* @param attempt - Current retry attempt number (1-based)
* @param error - The error that triggered the retry (HttpResponseError for HTTP errors)
* @param delay - The calculated delay in ms before next retry
* @returns `false` to stop retrying and rethrow,
* a `number` to override the delay (ms),
* or `undefined` to use the calculated delay
*
* @example
* ```ts
* await httpRequest('https://api.example.com/data', {
* retries: 3,
* throwOnError: true,
* onRetry: (attempt, error, delay) => {
* // Don't retry client errors (except 429)
* if (error instanceof HttpResponseError) {
* if (error.response.status === 429) {
* const retryAfter = parseRetryAfterHeader(error.response.headers['retry-after'])
* return retryAfter ?? undefined
* }
* if (error.response.status >= 400 && error.response.status < 500) {
* return false
* }
* }
* }
* })
* ```
*/
onRetry?:
| ((
attempt: number,
error: unknown,
delay: number,
) => boolean | number | undefined)
| undefined
/**
* Number of retry attempts for failed requests.
* Uses exponential backoff: delay = `retryDelay` * 2^attempt.
*
* @default 0
*
* @example
* ```ts
* // Retry up to 3 times with exponential backoff
* await httpRequest('https://api.example.com/data', {
* retries: 3,
* retryDelay: 1000 // 1s, then 2s, then 4s
* })
* ```
*/
retries?: number | undefined
/**
* Initial delay in milliseconds before first retry.
* Subsequent retries use exponential backoff.
*
* @default 1000
*
* @example
* ```ts
* // Start with 2 second delay, then 4s, 8s, etc.
* await httpRequest('https://api.example.com/data', {
* retries: 3,
* retryDelay: 2000
* })
* ```
*/
retryDelay?: number | undefined
/**
* When true, non-2xx HTTP responses throw an `HttpResponseError` instead
* of resolving with `response.ok === false`. This makes HTTP error
* responses eligible for retry via the `retries` option.
*
* @default false
*
* @example
* ```ts
* // Throw on 4xx/5xx responses (enabling retry for 5xx)
* await httpRequest('https://api.example.com/data', {
* throwOnError: true,
* retries: 3
* })
* ```
*/
/**
* When true, resolve with an HttpResponse whose body is NOT buffered.
* The `rawResponse` property contains the unconsumed IncomingResponse
* stream for piping to files or other destinations.
*
* `body`, `text()`, `json()`, and `arrayBuffer()` return empty/zero
* values since the stream has not been read.
*
* Incompatible with `maxResponseSize` (size enforcement requires
* reading the body).
*
* @default false
*/
stream?: boolean | undefined
throwOnError?: boolean | undefined
/**
* Request timeout in milliseconds.
* If the request takes longer than this, it will be aborted.
*
* @default 30000
*
* @example
* ```ts
* // 60 second timeout
* await httpRequest('https://api.example.com/slow-endpoint', {
* timeout: 60000
* })
* ```
*/
timeout?: number | undefined
}
/**
* HTTP response object with fetch-like interface.
* Provides multiple ways to access the response body.
*/
export interface HttpResponse {
/**
* Get response body as ArrayBuffer.
* Useful for binary data or when you need compatibility with browser APIs.
*
* @returns The response body as an ArrayBuffer
*
* @example
* ```ts
* const response = await httpRequest('https://example.com/image.png')
* const arrayBuffer = response.arrayBuffer()
* console.log(arrayBuffer.byteLength)
* ```
*/
arrayBuffer(): ArrayBuffer
/**
* Raw response body as Buffer.
* Direct access to the underlying Node.js Buffer.
*
* @example
* ```ts
* const response = await httpRequest('https://example.com/data')
* console.log(response.body.length) // Size in bytes
* console.log(response.body.toString('hex')) // View as hex
* ```
*/
body: Buffer
/**
* HTTP response headers.
* Keys are lowercase header names, values can be strings or string arrays.
*
* @example
* ```ts
* const response = await httpRequest('https://example.com')
* console.log(response.headers['content-type'])
* console.log(response.headers['set-cookie']) // May be string[]
* ```
*/
headers: IncomingHttpHeaders
/**
* Parse response body as JSON.
* Type parameter `T` allows specifying the expected JSON structure.
*
* @template T - Expected JSON type (defaults to `unknown`)
* @returns Parsed JSON data
* @throws {SyntaxError} When response body is not valid JSON
*
* @example
* ```ts
* interface User { name: string; id: number }
* const response = await httpRequest('https://api.example.com/user')
* const user = response.json<User>()
* console.log(user.name, user.id)
* ```
*/
json<T = unknown>(): T
/**
* Whether the request was successful (status code 200-299).
*
* @example
* ```ts
* const response = await httpRequest('https://example.com/data')
* if (response.ok) {
* console.log('Success:', response.json())
* } else {
* console.error('Failed:', response.status, response.statusText)
* }
* ```
*/
ok: boolean
/**
* HTTP status code (e.g., 200, 404, 500).
*
* @example
* ```ts
* const response = await httpRequest('https://example.com')
* console.log(response.status) // 200, 404, etc.
* ```
*/
status: number
/**
* HTTP status message (e.g., "OK", "Not Found", "Internal Server Error").
*
* @example
* ```ts
* const response = await httpRequest('https://example.com')
* console.log(response.statusText) // "OK"
* ```
*/
statusText: string
/**
* Get response body as UTF-8 text string.
*
* @returns The response body as a string
*
* @example
* ```ts
* const response = await httpRequest('https://example.com')
* const html = response.text()
* console.log(html.includes('<html>'))
* ```
*/
text(): string
/**
* The underlying Node.js IncomingResponse for advanced use cases
* (e.g., streaming, custom header inspection). Only available when
* the response was not consumed by the convenience methods.
*/
rawResponse?: IncomingResponse | undefined
}
/**
* Error thrown when an HTTP response has a non-2xx status code
* and `throwOnError` is enabled. Carries the full `HttpResponse`
* so callers can inspect status, headers, and body.
*/
export class HttpResponseError extends Error {
response: HttpResponse
constructor(response: HttpResponse, message?: string | undefined) {
const statusCode = response.status ?? 'unknown'
const statusMessage = response.statusText || 'No status message'
super(message ?? `HTTP ${statusCode}: ${statusMessage}`)
this.name = 'HttpResponseError'
this.response = response
Error.captureStackTrace(this, HttpResponseError)
}
}
/**
* Configuration options for file downloads.
*/
export interface HttpDownloadOptions {
/**
* Custom CA certificates for TLS connections.
* When provided, these certificates are used for the download request.
* See `HttpRequestOptions.ca` for details.
*/
ca?: string[] | undefined
/**
* Whether to automatically follow HTTP redirects (3xx status codes).
* This is essential for downloading from services that use CDN redirects,
* such as GitHub release assets which return HTTP 302 to their CDN.
*
* @default true
*
* @example
* ```ts
* // Follow redirects (default) - works with GitHub releases
* await httpDownload(
* 'https://github.com/org/repo/releases/download/v1.0.0/file.zip',
* '/tmp/file.zip'
* )
*
* // Don't follow redirects
* await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {
* followRedirects: false
* })
* ```
*/
followRedirects?: boolean | undefined
/**
* HTTP headers to send with the download request.
* A `User-Agent` header is automatically added if not provided.
*
* @example
* ```ts
* await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {
* headers: {
* 'Authorization': 'Bearer token123'
* }
* })
* ```
*/
headers?: Record<string, string> | undefined
/**
* Logger instance for automatic progress logging.
* When provided with `progressInterval`, will automatically log download progress.
* If both `onProgress` and `logger` are provided, `onProgress` takes precedence.
*
* @example
* ```ts
* import { getDefaultLogger } from '@socketsecurity/lib/logger'
*
* const logger = getDefaultLogger()
* await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {
* logger,
* progressInterval: 10 // Log every 10%
* })
* // Output:
* // Progress: 10% (5.2 MB / 52.0 MB)
* // Progress: 20% (10.4 MB / 52.0 MB)
* // ...
* ```
*/
logger?: Logger | undefined
/**
* Maximum number of redirects to follow before throwing an error.
* Only relevant when `followRedirects` is `true`.
*
* @default 5
*
* @example
* ```ts
* // Allow up to 10 redirects
* await httpDownload('https://example.com/many-redirects/file.zip', '/tmp/file.zip', {
* maxRedirects: 10
* })
* ```
*/
maxRedirects?: number | undefined
/**
* Callback for tracking download progress.
* Called periodically as data is received.
* Takes precedence over `logger` if both are provided.
*
* @param downloaded - Number of bytes downloaded so far
* @param total - Total file size in bytes (from Content-Length header)
*
* @example
* ```ts
* await httpDownload('https://example.com/large-file.zip', '/tmp/file.zip', {
* onProgress: (downloaded, total) => {
* const percent = ((downloaded / total) * 100).toFixed(1)
* console.log(`Progress: ${percent}%`)
* }
* })
* ```
*/
onProgress?: ((downloaded: number, total: number) => void) | undefined
/**
* Progress reporting interval as a percentage (0-100).
* Only used when `logger` is provided.
* Progress will be logged each time the download advances by this percentage.
*
* @default 10
*
* @example
* ```ts
* // Log every 10%
* await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {
* logger: getDefaultLogger(),
* progressInterval: 10
* })
*
* // Log every 25%
* await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {
* logger: getDefaultLogger(),
* progressInterval: 25
* })
* ```
*/
progressInterval?: number | undefined
/**
* Number of retry attempts for failed downloads.
* Uses exponential backoff: delay = `retryDelay` * 2^attempt.
*
* @default 0
*
* @example
* ```ts
* // Retry up to 3 times for unreliable connections
* await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {
* retries: 3,
* retryDelay: 2000
* })
* ```
*/
retries?: number | undefined
/**
* Initial delay in milliseconds before first retry.
* Subsequent retries use exponential backoff.
*
* @default 1000
*/
retryDelay?: number | undefined
/**
* Download timeout in milliseconds.
* If the download takes longer than this, it will be aborted.
*
* @default 120000
*
* @example
* ```ts
* // 5 minute timeout for large files
* await httpDownload('https://example.com/huge-file.zip', '/tmp/file.zip', {
* timeout: 300000
* })
* ```
*/
timeout?: number | undefined
/**
* Expected SHA256 hash of the downloaded file.
* If provided, the download will fail if the computed hash doesn't match.
* The hash should be a lowercase hex string (64 characters).
*
* Use `fetchChecksums()` to fetch hashes from a checksums URL, then pass
* the specific hash here.
*
* @example
* ```ts
* // Verify download integrity with direct hash
* await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {
* sha256: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
* })
*
* // Verify using checksums from a URL
* const checksums = await fetchChecksums('https://example.com/checksums.txt')
* await httpDownload('https://example.com/file.zip', '/tmp/file.zip', {
* sha256: checksums['file.zip']
* })
* ```
*/
sha256?: string | undefined
}
/**
* Result of a successful file download.
*/
export interface HttpDownloadResult {
/** HTTP response headers from the final response (after redirects). */
headers: IncomingHttpHeaders
/** Whether the download succeeded (status 200-299). Always true on success (non-2xx throws). */
ok: true
/** Absolute path where the file was saved. */
path: string
/** Total size of downloaded file in bytes. */
size: number
/** HTTP status code from the final response (after redirects). */
status: number
/** HTTP status message from the final response (after redirects). */
statusText: string
}
/**
* Map of filenames to their SHA256 hashes.
* Keys are filenames (not paths), values are lowercase hex-encoded SHA256 hashes.
*
* @example
* ```ts
* const checksums: Checksums = {
* 'file.zip': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
* 'other.tar.gz': 'abc123...'
* }
* ```
*/
export type Checksums = Record<string, string>
/**
* Options for fetching checksums from a URL.
*/
export interface FetchChecksumsOptions {
/**
* Custom CA certificates for TLS connections.
* See `HttpRequestOptions.ca` for details.
*/
ca?: string[] | undefined
/**
* HTTP headers to send with the request.
*/
headers?: Record<string, string> | undefined
/**
* Request timeout in milliseconds.
* @default 30000
*/
timeout?: number | undefined
}
let _fs: typeof import('node:fs') | undefined
let _crypto: typeof import('node:crypto') | undefined
let _http: typeof import('node:http') | undefined
let _https: typeof import('node:https') | undefined
/**
* Lazily load the crypto module to avoid Webpack errors.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getCrypto() {
if (_crypto === undefined) {
_crypto = /*@__PURE__*/ require('node:crypto')
}
return _crypto as typeof import('node:crypto')
}
/**
* Lazily load the fs module to avoid Webpack errors.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getFs() {
if (_fs === undefined) {
_fs = /*@__PURE__*/ require('node:fs')
}
return _fs as typeof import('node:fs')
}
/**
* Lazily load http and https modules to avoid Webpack errors.
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getHttp() {
if (_http === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_http = /*@__PURE__*/ require('node:http')
}
return _http as typeof import('node:http')
}
/*@__NO_SIDE_EFFECTS__*/
function getHttps() {
if (_https === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_https = /*@__PURE__*/ require('node:https')
}
return _https as typeof import('node:https')
}
/**
* Single download attempt using httpRequestAttempt with stream: true.
* @private
*/
async function httpDownloadAttempt(
url: string,
destPath: string,
options: HttpDownloadOptions,
): Promise<HttpDownloadResult> {
const {
ca,
followRedirects = true,
headers = {},
maxRedirects = 5,
onProgress,
timeout = 120_000,
} = { __proto__: null, ...options } as HttpDownloadOptions
const response = await httpRequestAttempt(url, {
ca,
followRedirects,
headers,
maxRedirects,
method: 'GET',
stream: true,
timeout,
})
if (!response.ok) {
throw new HttpResponseError(
response,
`Download failed: HTTP ${response.status} ${response.statusText}`,
)
}
const res = response.rawResponse
if (!res) {
throw new Error('Stream response missing rawResponse')
}
const { createWriteStream } = getFs()
const totalSize = Number.parseInt(
(response.headers['content-length'] as string) || '0',
10,
)
return await new Promise((resolve, reject) => {
let downloadedSize = 0
const fileStream = createWriteStream(destPath)
const cleanupPartial = () => {
getFs()
.promises.unlink(destPath)
.catch(() => {})
}
fileStream.on('error', (error: Error) => {
fileStream.destroy()
cleanupPartial()
reject(
new Error(`Failed to write file: ${error.message}`, { cause: error }),
)
})
res.on('data', (chunk: Buffer) => {
downloadedSize += chunk.length
if (onProgress && totalSize > 0) {
onProgress(downloadedSize, totalSize)
}
})
res.on('end', () => {
fileStream.close(() => {
resolve({
headers: response.headers,
ok: true,
path: destPath,
size: downloadedSize,
status: response.status,
statusText: response.statusText,
})
})
})
res.on('error', (error: Error) => {
fileStream.destroy()
cleanupPartial()
reject(error)
})
res.pipe(fileStream)
})
}
/**
* Single HTTP request attempt (used internally by httpRequest with retry logic).
* Supports hooks (fire per-attempt), maxResponseSize, and rawResponse.
* @private
*/
async function httpRequestAttempt(
url: string,
options: HttpRequestOptions,
): Promise<HttpResponse> {
const {
body,
ca,
followRedirects = true,
headers = {},
hooks,
maxRedirects = 5,
maxResponseSize,
method = 'GET',
stream = false,
timeout = 30_000,
} = { __proto__: null, ...options } as HttpRequestOptions
const startTime = Date.now()
// Auto-merge FormData headers (Content-Type with boundary).
const streamHeaders =
body &&
typeof body === 'object' &&
'getHeaders' in body &&
typeof (body as { getHeaders?: unknown }).getHeaders === 'function'
? (body as { getHeaders: () => Record<string, string> }).getHeaders()
: undefined
const mergedHeaders = {
'User-Agent': SOCKET_LIB_USER_AGENT,
...streamHeaders,
...headers,
}
hooks?.onRequest?.({ method, url, headers: mergedHeaders, timeout })
return await new Promise((resolve, reject) => {
// Settled flag guards all resolve/reject paths so that at most one
// fires, even when destroy() cascades multiple events.
let settled = false
const resolveOnce = (response: HttpResponse) => {
if (settled) {
return
}
settled = true
resolve(response)
}
const rejectOnce = (err: Error) => {
if (settled) {
return
}
settled = true
// Clean up streaming body if still active to avoid leaked descriptors.
if (
body &&
typeof body === 'object' &&
typeof (body as { destroy?: unknown }).destroy === 'function'
) {
;(body as { destroy: () => void }).destroy()
}
emitResponse({ error: err })
reject(err)
}
const parsedUrl = new URL(url)
const isHttps = parsedUrl.protocol === 'https:'
const httpModule = isHttps ? getHttps() : getHttp()
const requestOptions: Record<string, unknown> = {
headers: mergedHeaders,
hostname: parsedUrl.hostname,
method,
path: parsedUrl.pathname + parsedUrl.search,
port: parsedUrl.port,
timeout,
}
if (ca && isHttps) {
requestOptions['ca'] = ca
}
const emitResponse = (info: Partial<HttpHookResponseInfo>) => {
try {
hooks?.onResponse?.({
duration: Date.now() - startTime,
method,
url,
...info,
})
} catch {
// User-provided hook threw — swallow to avoid leaving the promise pending.
}
}
/* c8 ignore start - External HTTP/HTTPS request */
const request = httpModule.request(
requestOptions,
(res: IncomingResponse) => {
if (
followRedirects &&
res.statusCode &&
res.statusCode >= 300 &&
res.statusCode < 400 &&
res.headers.location
) {
// Drain the redirect response body to free the socket.
res.resume()
emitResponse({
headers: res.headers,
status: res.statusCode,
statusText: res.statusMessage,
})
if (maxRedirects <= 0) {
// Hook already emitted above — reject directly to avoid double-fire.
settled = true
reject(
new Error(
`Too many redirects (exceeded maximum: ${maxRedirects})`,
),
)
return
}
const redirectUrl = res.headers.location.startsWith('http')
? res.headers.location
: new URL(res.headers.location, url).toString()
const redirectParsed = new URL(redirectUrl)
if (isHttps && redirectParsed.protocol !== 'https:') {
// Hook already emitted above — reject directly to avoid double-fire.
settled = true
reject(
new Error(
`Redirect from HTTPS to HTTP is not allowed: ${redirectUrl}`,
),
)
return
}
// Strip auth/session headers on cross-origin redirects to prevent
// leaking credentials to third-party hosts (e.g., GitHub -> S3).
let redirectHeaders = headers
if (new URL(url).origin !== redirectParsed.origin) {
redirectHeaders = { __proto__: null } as unknown as typeof headers
const stripped = new Set([
'authorization',
'cookie',