| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| import { ProxyAgent, fetch as undiciFetch, type RequestInit as UndiciRequestInit } from 'undici'; |
| import { createLogger } from '@/lib/logger'; |
|
|
| const log = createLogger('ProxyFetch'); |
|
|
| function getProxyUrl(): string | undefined { |
| return ( |
| process.env.https_proxy || |
| process.env.HTTPS_PROXY || |
| process.env.http_proxy || |
| process.env.HTTP_PROXY || |
| undefined |
| ); |
| } |
|
|
| let cachedAgent: ProxyAgent | null = null; |
| let cachedProxyUrl: string | undefined; |
|
|
| function getProxyAgent(): ProxyAgent | undefined { |
| const proxyUrl = getProxyUrl(); |
| if (!proxyUrl) return undefined; |
|
|
| |
| if (cachedAgent && cachedProxyUrl === proxyUrl) { |
| return cachedAgent; |
| } |
|
|
| cachedAgent = new ProxyAgent(proxyUrl); |
| cachedProxyUrl = proxyUrl; |
| return cachedAgent; |
| } |
|
|
| |
| |
| |
| |
| export async function proxyFetch(input: string | URL, init?: RequestInit): Promise<Response> { |
| const agent = getProxyAgent(); |
| const url = typeof input === 'string' ? input : input.toString(); |
|
|
| if (!agent) { |
| log.info('No proxy configured, using direct fetch for:', url.slice(0, 80)); |
| return fetch(input, init); |
| } |
|
|
| log.info('Using proxy', cachedProxyUrl, 'for:', url.slice(0, 80)); |
| |
| const res = await undiciFetch(input, { |
| ...(init as UndiciRequestInit), |
| dispatcher: agent, |
| }); |
|
|
| |
| return res as unknown as Response; |
| } |
|
|