renamed http-client to http and fixed tests

This commit is contained in:
Bojan Kucera 2025-06-07 13:20:58 -04:00
parent e87acb5e18
commit 3d9afd711e
26 changed files with 472 additions and 496 deletions

View file

@ -0,0 +1,91 @@
import got from 'got';
import { SocksProxyAgent } from 'socks-proxy-agent';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { HttpProxyAgent } from 'http-proxy-agent';
import type { ProxyConfig } from './types.js';
export class ProxyManager {
/**
* Determine if we should use Bun fetch (HTTP/HTTPS) or Got (SOCKS)
*/
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 appropriate agent for Got based on proxy type
*/
static createGotAgent(proxy: ProxyConfig) {
this.validateConfig(proxy);
const proxyUrl = this.buildProxyUrl(proxy);
switch (proxy.protocol) {
case 'socks4':
case 'socks5':
return new SocksProxyAgent(proxyUrl);
case 'http':
return new HttpProxyAgent(proxyUrl);
case 'https':
return new HttpsProxyAgent(proxyUrl);
default:
throw new Error(`Unsupported proxy protocol: ${proxy.protocol}`);
}
}
/**
* Create Got instance with proxy configuration
*/
static createGotInstance(proxy: ProxyConfig) {
const agent = this.createGotAgent(proxy);
return got.extend({
agent: {
http: agent,
https: agent
},
timeout: {
request: 30000,
connect: 10000
},
retry: {
limit: 3,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']
},
throwHttpErrors: false // We'll handle errors ourselves
});
}
private static buildProxyUrl(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}`;
}
/**
* Simple proxy config validation
*/
static validateConfig(proxy: ProxyConfig): void {
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}`);
}
}
}