11import { HttpsProxyAgent } from 'https-proxy-agent' ;
2+ import { SocksProxyAgent } from 'socks-proxy-agent' ;
23
34type Proxy = {
45 host : string ;
@@ -8,9 +9,28 @@ type Proxy = {
89 username ?: string ;
910} ;
1011
11- export function makeProxyAgent ( proxy : Proxy | string ) {
12+ function selectProxyAgent ( proxyUrl : string ) : HttpsProxyAgent < string > | SocksProxyAgent {
13+ const url = new URL ( proxyUrl ) ;
14+
15+ // NOTE: The following constants are not used in the function but are defined for clarity.
16+ // When a proxy URL is used to build the URL object, the protocol returned by procotol's property contains a `:` at
17+ // the end so, we add the protocol constants without the `:` to avoid confusion.
18+ const PROXY_HTTP_PROTOCOL = 'http:' ;
19+ const PROXY_SOCKS_PROTOCOL = 'socks:' ;
20+
21+ switch ( url . protocol ) {
22+ case PROXY_HTTP_PROTOCOL :
23+ return new HttpsProxyAgent ( url ) ;
24+ case PROXY_SOCKS_PROTOCOL :
25+ return new SocksProxyAgent ( url ) ;
26+ default :
27+ throw new Error ( `Unsupported proxy protocol: ${ url . protocol } ` ) ;
28+ }
29+ }
30+
31+ export function makeProxyAgent ( proxy : Proxy | string ) : HttpsProxyAgent < string > | SocksProxyAgent {
1232 if ( typeof proxy === 'string' ) {
13- return new HttpsProxyAgent ( proxy ) ;
33+ return selectProxyAgent ( proxy ) ;
1434 }
1535
1636 const { host, password, port, protocol, username } = proxy ;
@@ -19,5 +39,6 @@ export function makeProxyAgent(proxy: Proxy | string) {
1939 if ( username && password ) {
2040 proxyUrl = `${ protocol } ://${ username } :${ password } @${ host } :${ port } ` ;
2141 }
22- return new HttpsProxyAgent ( proxyUrl ) ;
42+
43+ return selectProxyAgent ( proxyUrl ) ;
2344}
0 commit comments