@0xtld/tair-node
Version:
A Node.js package for Tair functionality with configuration, core, and helper modules.
91 lines (90 loc) • 3.28 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyHandler = void 0;
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const path_1 = tslib_1.__importDefault(require("path"));
const logger_1 = require("./logger");
const colors_1 = require("./colors");
const colors = new colors_1.ColorTheme();
class ProxyHandler {
constructor() {
this.proxies = [];
this.currentIndex = 0;
this.proxyFile = path_1.default.join(__dirname, 'proxies.txt');
}
loadProxies() {
try {
const content = fs_1.default.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_1.logger.warn(colors.style(`Invalid proxy format: ${proxy}`, 'warning'));
return null;
}
})
.filter((proxy) => proxy !== null);
logger_1.logger.info(colors.style(`Successfully loaded ${this.proxies.length} proxies`, 'info'));
return true;
}
catch (error) {
if (error.code === 'ENOENT') {
logger_1.logger.warn(colors.style('proxies.txt not found, will proceed without proxies', 'warning'));
return false;
}
logger_1.logger.error(colors.style(`Failed to load proxies: ${error.message}`, 'error'));
return false;
}
}
getNextProxy() {
if (this.proxies.length === 0)
return null;
const proxy = this.proxies[this.currentIndex];
this.currentIndex = (this.currentIndex + 1) % this.proxies.length;
return proxy;
}
getCurrentProxy() {
return this.proxies[this.currentIndex] || null;
}
getProxyUrl(proxy) {
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) {
if (!proxy)
return undefined;
return {
protocol: proxy.protocol,
host: proxy.host,
port: proxy.port,
auth: proxy.auth
};
}
getWeb3ProxyConfig(proxy) {
if (!proxy)
return undefined;
return this.getProxyUrl(proxy) || undefined;
}
}
exports.ProxyHandler = ProxyHandler;
exports.default = ProxyHandler;