|
| 1 | +import consola from "consola" |
| 2 | +import { getProxyForUrl } from "proxy-from-env" |
| 3 | +import { Agent, ProxyAgent, setGlobalDispatcher, type Dispatcher } from "undici" |
| 4 | + |
| 5 | +export function initProxyFromEnv(): void { |
| 6 | + if (typeof Bun !== "undefined") return |
| 7 | + |
| 8 | + try { |
| 9 | + const direct = new Agent() |
| 10 | + const proxies = new Map<string, ProxyAgent>() |
| 11 | + |
| 12 | + const dispatcher: Dispatcher = { |
| 13 | + dispatch( |
| 14 | + options: Dispatcher.RequestOptions, |
| 15 | + handler: Dispatcher.DispatchHandlers, |
| 16 | + ) { |
| 17 | + try { |
| 18 | + const origin = |
| 19 | + typeof options.origin === "string" ? |
| 20 | + new URL(options.origin) |
| 21 | + : (options.origin as URL) |
| 22 | + const get = getProxyForUrl as unknown as ( |
| 23 | + u: string, |
| 24 | + ) => string | undefined |
| 25 | + const raw = get(origin.toString()) |
| 26 | + const proxyUrl = raw && raw.length > 0 ? raw : undefined |
| 27 | + if (!proxyUrl) { |
| 28 | + consola.debug(`HTTP proxy bypass: ${origin.hostname}`) |
| 29 | + return (direct as unknown as Dispatcher).dispatch(options, handler) |
| 30 | + } |
| 31 | + let agent = proxies.get(proxyUrl) |
| 32 | + if (!agent) { |
| 33 | + agent = new ProxyAgent(proxyUrl) |
| 34 | + proxies.set(proxyUrl, agent) |
| 35 | + } |
| 36 | + let label = proxyUrl |
| 37 | + try { |
| 38 | + const u = new URL(proxyUrl) |
| 39 | + label = `${u.protocol}//${u.host}` |
| 40 | + } catch { |
| 41 | + /* noop */ |
| 42 | + } |
| 43 | + consola.debug(`HTTP proxy route: ${origin.hostname} via ${label}`) |
| 44 | + return (agent as unknown as Dispatcher).dispatch(options, handler) |
| 45 | + } catch { |
| 46 | + return (direct as unknown as Dispatcher).dispatch(options, handler) |
| 47 | + } |
| 48 | + }, |
| 49 | + close() { |
| 50 | + return direct.close() |
| 51 | + }, |
| 52 | + destroy() { |
| 53 | + return direct.destroy() |
| 54 | + }, |
| 55 | + } |
| 56 | + |
| 57 | + setGlobalDispatcher(dispatcher) |
| 58 | + consola.debug("HTTP proxy configured from environment (per-URL)") |
| 59 | + } catch (err) { |
| 60 | + consola.debug("Proxy setup skipped:", err) |
| 61 | + } |
| 62 | +} |
0 commit comments