@0xtld/tair-node
Version:
A Node.js package for Tair functionality with configuration, core, and helper modules.
113 lines (93 loc) • 3 kB
text/typescript
import fs from 'fs';
import path from 'path';
import { logger } from './logger';
import { ColorTheme } from './colors';
const colors = new ColorTheme();
interface ProxyAuth {
username: string;
password: string;
}
interface Proxy {
protocol: string;
host: string;
port?: string;
auth?: ProxyAuth;
}
class ProxyHandler {
private proxies: Array<Proxy | null>;
private currentIndex: number;
private proxyFile: string;
constructor() {
this.proxies = [];
this.currentIndex = 0;
this.proxyFile = path.join(__dirname, 'proxies.txt');
}
loadProxies(): boolean {
try {
const content = fs.readFileSync(this.proxyFile, 'utf8');
this.proxies = content
.replace(/\r/g, '')
.split('\n')
.map(line => line.trim())
.filter(Boolean)
.map(proxy => {
try {
const url = new URL(proxy);
return {
protocol: url.protocol.replace(':', ''),
host: url.hostname,
port: url.port,
auth: url.username && url.password ? {
username: decodeURIComponent(url.username),
password: decodeURIComponent(url.password)
} : undefined
};
} catch (error) {
logger.warn(colors.style(`Invalid proxy format: ${proxy}`, 'warning'));
return null;
}
})
.filter((proxy) => proxy !== null);
logger.info(colors.style(`Successfully loaded ${this.proxies.length} proxies`, 'info'));
return true;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
logger.warn(colors.style('proxies.txt not found, will proceed without proxies', 'warning'));
return false;
}
logger.error(colors.style(`Failed to load proxies: ${(error as Error).message}`, 'error'));
return false;
}
}
getNextProxy(): Proxy | null {
if (this.proxies.length === 0) return null;
const proxy = this.proxies[this.currentIndex];
this.currentIndex = (this.currentIndex + 1) % this.proxies.length;
return proxy;
}
getCurrentProxy(): Proxy | null {
return this.proxies[this.currentIndex] || null;
}
getProxyUrl(proxy: Proxy | null): string | null {
if (!proxy) return null;
const auth = proxy.auth ?
`${encodeURIComponent(proxy.auth.username)}:${encodeURIComponent(proxy.auth.password)}@` :
'';
return `${proxy.protocol}://${auth}${proxy.host}${proxy.port ? `:${proxy.port}` : ''}`;
}
getAxiosProxyConfig(proxy: Proxy | null): object | undefined {
if (!proxy) return undefined;
return {
protocol: proxy.protocol,
host: proxy.host,
port: proxy.port,
auth: proxy.auth
};
}
getWeb3ProxyConfig(proxy: Proxy | null): string | undefined {
if (!proxy) return undefined;
return this.getProxyUrl(proxy) || undefined;
}
}
export { Proxy, ProxyAuth, ProxyHandler };
export default ProxyHandler;