|
| 1 | +import { getEnvVar } from './api/metadata' |
| 2 | +import { runtime } from './utils' |
| 3 | + |
| 4 | +function getProxyUrl(): string | undefined { |
| 5 | + return ( |
| 6 | + getEnvVar('HTTPS_PROXY') || |
| 7 | + getEnvVar('https_proxy') || |
| 8 | + getEnvVar('HTTP_PROXY') || |
| 9 | + getEnvVar('http_proxy') || |
| 10 | + getEnvVar('ALL_PROXY') || |
| 11 | + getEnvVar('all_proxy') || |
| 12 | + undefined |
| 13 | + ) |
| 14 | +} |
| 15 | + |
| 16 | +let cachedProxyFetch: typeof fetch | null = null |
| 17 | +let proxyResolved = false |
| 18 | + |
| 19 | +/** |
| 20 | + * Returns a proxy-aware fetch function if HTTPS_PROXY/HTTP_PROXY/ALL_PROXY |
| 21 | + * env vars are set. In browser environments, returns undefined (browsers |
| 22 | + * handle proxies natively via OS settings). |
| 23 | + * |
| 24 | + * Uses undici's ProxyAgent, which is built into Node.js 20+. |
| 25 | + */ |
| 26 | +export function getProxyFetch(): typeof fetch | undefined { |
| 27 | + if (proxyResolved) return cachedProxyFetch ?? undefined |
| 28 | + proxyResolved = true |
| 29 | + |
| 30 | + if (runtime === 'browser') return undefined |
| 31 | + |
| 32 | + const proxyUrl = getProxyUrl() |
| 33 | + if (!proxyUrl) return undefined |
| 34 | + |
| 35 | + try { |
| 36 | + // eslint-disable-next-line @typescript-eslint/no-var-requires |
| 37 | + const { ProxyAgent } = require('undici') |
| 38 | + const agent = new ProxyAgent(proxyUrl) |
| 39 | + cachedProxyFetch = ((input: any, init?: any) => |
| 40 | + fetch(input, { ...init, dispatcher: agent })) as typeof fetch |
| 41 | + return cachedProxyFetch |
| 42 | + } catch { |
| 43 | + // undici not available (e.g. edge runtimes, older Node.js) — fall back to default fetch |
| 44 | + return undefined |
| 45 | + } |
| 46 | +} |
0 commit comments