import { URL } from 'url' ; import { proxies , auto } from 'http2-wrapper' ; import { Agents , Options } from 'got-cjs' ; import { HttpsProxyAgent , HttpRegularProxyAgent } from '../agent/h1-proxy-agent' ; import { TransformHeadersAgent } from '../agent/transform-headers-agent' ; const { HttpOverHttp2 , HttpsOverHttp2 , Http2OverHttp2 , Http2OverHttps , Http2OverHttp , } = proxies ; export async function proxyHook ( options ) { const { context : { proxyUrl } } = options ; if ( proxyUrl ) { const parsedProxy = new URL ( proxyUrl as string ) ; validateProxyProtocol ( parsedProxy . protocol ) ; options . agent = await getAgents ( parsedProxy , options . https . rejectUnauthorized ! ) ; } } function validateProxyProtocol ( protocol ) { const isSupported = protocol === 'http:' || protocol === 'https:' ; if ( ! isSupported ) { throw new Error ( `Proxy URL protocol "${ protocol }" is not supported. Please use HTTP or HTTPS.` ) ; } } async function getAgents ( parsedProxyUrl , rejectUnauthorized ) { const wrapperOptions = { proxyOptions : { url : parsedProxyUrl , rejectUnauthorized , } , maxFreeSockets : 0 , maxEmptySessions : 0 , } ; const nativeOptions = { proxy : parsedProxyUrl , maxFreeSockets : 0 , } ; let agent ; if ( parsedProxyUrl . protocol === 'https:' ) { let alpnProtocol = 'http/1.1' ; try { const result = await auto . resolveProtocol ( { host : parsedProxyUrl . hostname , port : parsedProxyUrl . port , rejectUnauthorized , ALPNProtocols : [ 'h2' , 'http/1.1' ] , servername : parsedProxyUrl . hostname , } ) ; alpnProtocol = result . alpnProtocol ; } catch { } const proxyIsHttp2 = alpnProtocol === 'h2' ; if ( proxyIsHttp2 ) { agent = { http : new TransformHeadersAgent ( new HttpOverHttp2 ( wrapperOptions ) ) , https : new TransformHeadersAgent ( new HttpsOverHttp2 ( wrapperOptions ) ) , http2 : new Http2OverHttp2 ( wrapperOptions ) , } ; } else { agent = { http : new TransformHeadersAgent ( new HttpRegularProxyAgent ( nativeOptions ) ) , https : new TransformHeadersAgent ( new HttpsProxyAgent ( nativeOptions ) ) , http2 : new Http2OverHttps ( wrapperOptions ) , } ; } } else { agent = { http : new TransformHeadersAgent ( new HttpRegularProxyAgent ( nativeOptions ) ) , https : new TransformHeadersAgent ( new HttpsProxyAgent ( nativeOptions ) ) , http2 : new Http2OverHttp ( wrapperOptions ) , } ; } return agent ; }