simplify http-client and switch to bun fetch + undeci

This commit is contained in:
Bojan Kucera 2025-06-06 23:24:22 -04:00
parent 08bb21cee7
commit 7eeccfe8f2
7 changed files with 43 additions and 740 deletions

View file

@ -1,47 +1,51 @@
import { HttpsProxyAgent } from 'https-proxy-agent';
import { SocksProxyAgent } from 'socks-proxy-agent';
import { ProxyAgent } from 'undici';
import type { ProxyConfig } from './types.js';
import { validateProxyConfig } from './types.js';
import { HttpProxyAgent } from 'http-proxy-agent';
export class ProxyManager {
/**
* Create appropriate proxy agent based on configuration
* Determine if we should use Bun fetch (HTTP/HTTPS) or Undici (SOCKS)
*/
static createAgent(proxy: ProxyConfig): HttpsProxyAgent<string> | SocksProxyAgent {
const { protocol, host, port, username, password } = proxy;
static shouldUseBunFetch(proxy: ProxyConfig): boolean {
return proxy.protocol === 'http' || proxy.protocol === 'https';
}
/**
* Create Bun fetch proxy URL for HTTP/HTTPS proxies
*/
static createBunProxyUrl(proxy: ProxyConfig): string {
const { protocol, host, port, username, password } = proxy;
if (username && password) {
return `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}`;
}
return `${protocol}://${host}:${port}`;
}
/**
* Create Undici proxy agent for SOCKS proxies
*/
static createUndiciAgent(proxy: ProxyConfig): ProxyAgent {
const { protocol, host, port, username, password } = proxy;
let proxyUrl: string;
console.log('Creating proxy agent with config:', {
protocol,
host,
port,
username,
password
});
if (username && password) {
proxyUrl = `${protocol}://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${port}`;
} else {
proxyUrl = `${protocol}://${host}:${port}`;
}
switch (protocol) {
case 'http':
return new HttpProxyAgent(proxyUrl);
case 'https':
return new HttpsProxyAgent(proxyUrl);
case 'socks4':
case 'socks5':
return new SocksProxyAgent(proxyUrl);
default:
throw new Error(`Unsupported proxy protocol: ${protocol}`);
}
return new ProxyAgent(proxyUrl);
}
/**
* Validate proxy configuration
* Simple proxy config validation
*/
static validateConfig(proxy: ProxyConfig): void {
// Use the centralized validation function
validateProxyConfig(proxy);
if (!proxy.host || !proxy.port) {
throw new Error('Proxy host and port are required');
}
if (!['http', 'https', 'socks4', 'socks5'].includes(proxy.protocol)) {
throw new Error(`Unsupported proxy protocol: ${proxy.protocol}`);
}
}
}