proxy-pool-manager 1.0.6 → 1.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/proxyManager.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";var e={171:e=>{e.exports=require("winston-daily-rotate-file")},298:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFormattedDate=function(e=!1){const t=new Date,r=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return e?`${r}-${s}-${n} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`:`${r}-${s}-${n}`},t.getMainDirectory=function(){const e=r(928);return r.c[r.s]?e.dirname(r.c[r.s].filename):process.cwd()}},306:e=>{e.exports=require("winston")},330:e=>{e.exports=JSON.parse('{"name":"proxy-pool-manager","version":"1.0.6","description":"proxy manager","main":"./dist/index.js","types":"./dist/index.d.ts","files":["dist","package.json"],"scripts":{"build":"webpack --mode=production && tsc --emitDeclarationOnly --outDir dist","dev":"webpack --mode=development","watch":"webpack --watch --mode=development","build:analyze":"webpack --mode=production --analyze","prepublishOnly":"npm run build"},"author":"memeak","license":"ISC","devDependencies":{"@types/node":"^22.5.4","@webpack-cli/generators":"^3.0.7","clean-webpack-plugin":"^4.0.0","ts-loader":"^9.5.1","typescript":"^5.6.2","webpack":"^5.94.0","webpack-cli":"^5.1.4"},"dependencies":{"async":"^3.2.6","mongoose":"^7.8.7","node-fetch":"^2.7.0","winston":"^3.18.3","winston-daily-rotate-file":"^5.0.0"},"packageManager":"pnpm@10.18.2+sha512.9fb969fa749b3ade6035e0f109f0b8a60b5d08a1a87fdf72e337da90dcc93336e2280ca4e44f2358a649b83c17959e9993e777c2080879f3801e6f0d999ad3dd"}')},331:e=>{e.exports=require("mongoose")},378:function(e,t,r){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Request=void 0;const n=s(r(867)),o=r(388);class i{constructor(e={}){if(this.proxyManager=null,this.hasProxyManager=!1,void 0!==e.maxRetries&&(e.maxRetries<0||!Number.isInteger(e.maxRetries)))throw new Error("maxRetries 必须是非负整数");if(void 0!==e.timeout&&e.timeout<=0)throw new Error("timeout 必须是正数");if(void 0!==e.retryDelay&&e.retryDelay<0)throw new Error("retryDelay 必须是非负数");if(void 0!==e.retryDelayBase&&e.retryDelayBase<=0)throw new Error("retryDelayBase 必须是正数");if(void 0!==e.retryDelayMultiplier&&e.retryDelayMultiplier<=0)throw new Error("retryDelayMultiplier 必须是正数");this.maxRetries=e.maxRetries??3,this.timeout=e.timeout??30,this.logLevel=e.logLevel||"none",this.proxyStrategy=e.proxyStrategy||"sequential",this.retryDelay=e.retryDelay??null,this.retryDelayBase=e.retryDelayBase??1e3,this.retryDelayMultiplier=e.retryDelayMultiplier??2;try{const t=e.instanceId||"default";this.proxyManager=o.ServiceLocator.get(`ProxyManager-${t}`),this.hasProxyManager=!0,this.log("info","成功获取 ProxyManager 实例",{instanceId:t})}catch(t){this.hasProxyManager=!1,this.log("info","ProxyManager 未初始化,将以轻量级模式运行(不使用代理管理功能)",{instanceId:e.instanceId||"default"})}}setLogLevel(e){try{o.ServiceLocator.get("DebugManager").setLogLevel(e),this.log("info",`设置日志等级: ${e}`)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}}getLogLevel(){try{return o.ServiceLocator.get("DebugManager").getLogLevel()}catch(e){return"info"}}log(e,t,r){try{const s=o.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[Request] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [Request] ${t}`,r||"")}}async selectProxy(e){if(e.options.proxy){const t=e.options.proxy;return this.hasProxyManager&&this.proxyManager&&await this.proxyManager.addProxy(t).catch(()=>{}),this.log("info","使用请求级别代理",{proxy:t}),t}if(!this.hasProxyManager||!this.proxyManager)return null;const t=this.proxyManager.getProxiesCount();if(0===t)return null;const r=this.proxyManager.getAvailableProxy();return r&&this.log("info","使用策略选择代理",{proxy:r,strategy:this.proxyManager.getProxyStrategy(),index:this.proxyManager.getCurrentProxyIndex()+1,total:t}),r}async executeSingleRequest(e,t){const r=e.options.timeout||this.timeout,s=1e3*r;try{const o=await this.selectProxy(e),i={method:e.method,headers:{},signal:AbortSignal.timeout(s)},a=e.options?{...e.options}:{};o&&(a.proxy=o),Object.keys(a).length>0&&(i.body=JSON.stringify(a),i.headers["Content-Type"]="application/json"),this.log("info",`开始请求 ${e.url} (尝试 ${t}/${this.maxRetries})`,{method:e.method,timeout:r,hasProxy:!!o});const c=Date.now(),l=await(0,n.default)(e.url,i),h=Date.now()-c;if(!l.ok)throw new Error(`HTTP Error: ${l.status} ${l.statusText}`);const u=await l.text();let g;try{g=JSON.parse(u)}catch{g=u}const y={status_code:l.status,success:l.ok,headers:Object.fromEntries(l.headers.entries()),data:g,error:l.ok?void 0:u,timestamp:(new Date).toISOString()};if(this.hasProxyManager&&this.proxyManager){const e=this.proxyManager.getCurrentProxy();e&&await this.proxyManager.recordProxyUsage(e,y.success,h).catch(()=>{})}return y}catch(s){if("TimeoutError"===s.name||"AbortError"===s.name)throw this.log("warn",`请求超时 (${r}s)`,{url:e.url,attempt:t}),new Error(`请求超时: ${r}秒`);if(this.hasProxyManager&&this.proxyManager){const e=this.proxyManager.getCurrentProxy();e&&this.proxyManager.shouldRotateProxy(s)&&(this.log("error",`代理 ${e} 出现问题,尝试轮换`,{error:s.message}),await this.proxyManager.rotateProxy().catch(()=>{}))}throw s}}isValidStatusCode(e){return e>=200&&e<300}async get(e,t={}){let r=e;return t.params&&Object.keys(t.params).length>0&&(r=`${e}?${new URLSearchParams(t.params).toString()}`),this.request({url:r,method:"GET",options:t})}async post(e,t={}){return this.request({url:e,method:"POST",options:t})}async put(e,t={}){return this.request({url:e,method:"PUT",options:t})}async delete(e,t={}){return this.request({url:e,method:"DELETE",options:t})}async patch(e,t={}){return this.request({url:e,method:"PATCH",options:t})}async request(e){const t={url:e.url,method:e.method,options:{...e.options,timeout:e.options.timeout||this.timeout}};for(let e=1;e<=this.maxRetries;e++)try{const r=await this.executeSingleRequest(t,e),s={status:r.status_code,statusText:this.getStatusText(r.status_code),headers:r.headers||{},error:r.error?String(r.error):null,errors:[],data:r.data,text:()=>"string"==typeof r.data?r.data:JSON.stringify(r.data),json:()=>r.data,buffer:()=>Buffer.from("string"==typeof r.data?r.data:JSON.stringify(r.data||{}))};return this.log("info","请求成功",{url:t.url,status:s.status,attempt:e}),s}catch(r){const s=r.message;if(this.log("error","请求失败",{attempt:e,maxRetries:this.maxRetries,url:t.url,error:s}),(s.includes("超时")||"TimeoutError"===r.name)&&this.log("warn",`请求超时,尝试 ${e}/${this.maxRetries}`),this.hasProxyManager&&this.proxyManager&&e<this.maxRetries){if(0===this.proxyManager.getAvailableProxiesList().length){this.log("warn","无可用代理,停止重试");break}if(!t.options.proxy&&this.proxyManager.shouldRotateProxy(r)){const e=await this.proxyManager.rotateProxy().catch(()=>null);e&&this.log("info",`代理轮换成功,使用新代理: ${e}`)}}if(e<this.maxRetries){let t;null!==this.retryDelay?(t=this.retryDelay,this.log("info",`等待 ${t}ms 后重试(固定间隔)`)):(t=this.retryDelayBase*Math.pow(this.retryDelayMultiplier,e-1),this.log("info",`等待 ${t}ms 后重试(指数退避:基础 ${this.retryDelayBase}ms,倍数 ${this.retryDelayMultiplier})`)),await new Promise(e=>setTimeout(e,t))}}throw new Error(`${e.options.url} 请求失败,已尝试 ${this.maxRetries} 次都失败了`)}getStatusText(e){return{200:"OK",201:"Created",202:"Accepted",204:"No Content",400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable"}[e]||`Status ${e}`}getCurrentProxy(){return this.hasProxyManager&&this.proxyManager?this.proxyManager.getCurrentProxy():null}async rotateProxy(){if(!this.hasProxyManager||!this.proxyManager)throw new Error("ProxyManager 未初始化,无法轮换代理");return await this.proxyManager.rotateProxy()}resetProxyUsage(){this.hasProxyManager&&this.proxyManager&&this.proxyManager.resetProxyUsage()}setProxyStrategy(e){if(!this.hasProxyManager||!this.proxyManager)throw new Error("ProxyManager 未初始化,无法设置代理策略");this.proxyManager.setProxyStrategy(e)}async checkProxy(e){if(!this.hasProxyManager||!this.proxyManager)throw new Error("ProxyManager 未初始化,无法检查代理");return this.proxyManager.checkProxy(e)}getAvailableProxiesList(){return this.hasProxyManager&&this.proxyManager?this.proxyManager.getAvailableProxiesList():[]}hasProxyManagement(){return this.hasProxyManager}}t.Request=i,t.default=i},388:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceLocator=void 0;class r{static shouldLog(e){try{if(this.services.has("DebugManager")){const t=this.services.get("DebugManager");if(t&&"function"==typeof t.getLogLevel){const r=t.getLogLevel(),s={none:0,error:1,warn:2,info:3,debug:4,verbose:5},n=s[r]||0;return(s[e]||0)<=n}}}catch(e){}return"error"===e||"warn"===e}static shouldLogForService(e,t){if(["DebugManager","AsyncQueue"].includes(e)&&("debug"===t||"verbose"===t)){try{if(this.services.has("DebugManager")){const e=this.services.get("DebugManager");if(e&&"function"==typeof e.getLogLevel)return"verbose"===e.getLogLevel()}}catch(e){}return!1}return this.shouldLog(t)}static get(e){if(this.services.has(e)){const t=this.services.get(e);return this.shouldLogForService(e,"debug")&&this.log("debug",`返回已注册的服务实例: ${e}`,{serviceType:this.getServiceType(t)}),t}if(this.dependencies.has(e)){this.shouldLogForService(e,"debug")&&this.log("debug",`通过工厂创建服务: ${e}`);const t=this.dependencies.get(e)();return this.services.set(e,t),this.shouldLogForService(e,"debug")&&this.log("debug",`工厂创建服务完成: ${e}`,{serviceType:this.getServiceType(t)}),t}const t=new Error(`[ServiceLocator] 服务未注册: ${e}`);throw this.log("error","服务未注册",{serviceName:e,availableServices:this.getAvailableServiceNames(),error:t.message}),t}static has(e){const t=this.services.has(e)||this.dependencies.has(e);return this.shouldLogForService(e,"debug")&&this.log("debug",`检查服务存在性: ${e}`,{exists:t,hasInstance:this.services.has(e),hasFactory:this.dependencies.has(e)}),t}static register(e,t){this.services.set(e,t),this.shouldLogForService(e,"info")&&this.log("info",`注册服务: ${e}`,{serviceType:this.getServiceType(t),hasFactory:this.dependencies.has(e)})}static registerFactory(e,t){this.dependencies.set(e,t),this.shouldLogForService(e,"info")&&this.log("info",`注册服务工厂: ${e}`,{hasExistingInstance:this.services.has(e)})}static log(e,t,r){if(!this.shouldLog(e))return;try{if(this.services.has("DebugManager")){const s=this.services.get("DebugManager");if(s&&"function"==typeof s.log)return e.toUpperCase(),void s.log(e,`[ServiceLocator] ${t}`,r)}}catch(e){}const s=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${s} [ServiceLocator] ${t}`,r||"")}static getAvailableServiceNames(){const e=Array.from(this.services.keys()),t=Array.from(this.dependencies.keys()),r=[...new Set([...e,...t])];return this.shouldLog("debug")&&this.log("debug","获取可用服务名称",{total:r.length,services:e,factories:t}),r}static getStats(){const e=Array.from(this.services.keys()),t=Array.from(this.dependencies.keys()),r={totalServices:e.length,totalFactories:t.length,serviceNames:e,factoryNames:t};return this.shouldLog("debug")&&this.log("debug","服务统计",r),r}static isInitialized(){const e=this.has("DebugManager");return this.shouldLog("debug")&&this.log("debug","检查服务定位器初始化状态",{hasDebugManager:e,totalServices:this.services.size,totalFactories:this.dependencies.size}),e}static getServiceType(e){return e?e.constructor&&e.constructor.name?e.constructor.name:"function"==typeof e?"Function":Array.isArray(e)?"Array":"object"==typeof e?"Object":typeof e:"null"}static registerMultiple(e){const t=Object.keys(e);this.log("info","批量注册服务",{count:t.length,services:t}),Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}static safeGet(e,t){try{return this.get(e)}catch(r){return this.log("warn",`安全获取服务失败: ${e}`,{error:r.message,usingDefault:void 0!==t}),t}}static reset(){this.services.clear(),this.dependencies.clear(),this.log("info","服务定位器已重置")}static initialize(){this.log("info","服务定位器初始化",{nodeEnv:"production"})}static clear(){const e=this.services.size,t=this.dependencies.size;this.services.clear(),this.dependencies.clear(),this.log("info","所有服务已清除",{clearedServices:e,clearedFactories:t})}static removeService(e){const t=this.services.has(e),r=this.dependencies.has(e);return this.services.delete(e),this.dependencies.delete(e),!(!t&&!r||(this.log("info",`移除服务: ${e}`,{hadService:t,hadFactory:r}),0))}static getExistingInstance(e){if(this.services.has(e))return this.services.get(e)}static hasOnlyFactory(e){return!this.services.has(e)&&this.dependencies.has(e)}static getCounts(){const e=this.services.size,t=this.dependencies.size,r=e+t;return this.shouldLog("debug")&&this.log("debug","服务数量统计",{instances:e,factories:t,total:r}),{instances:e,factories:t,total:r}}}t.ServiceLocator=r,r.services=new Map,r.dependencies=new Map},392:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyUrlBulkInsertManager=void 0;const s=r(388);t.ProxyUrlBulkInsertManager=class{constructor(e,t=500,r=4,s){this.mongoManager=e,this.batchSize=t,this.concurrency=r,s&&this.setLogLevel(s)}setLogLevel(e){try{s.ServiceLocator.get("DebugManager").setLogLevel(e),this.debug="debug"===e||"verbose"===e,this.log("info",`设置日志等级: ${e}`)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}}getLogLevel(){try{return s.ServiceLocator.get("DebugManager").getLogLevel()}catch(e){return this.debug?"debug":"info"}}setDebugMode(e){if(this.debug=e,this.debug)try{let t;try{t=s.ServiceLocator.get("DebugManager")}catch(e){const{DebugManager:n}=r(577);t=n.getInstance(),s.ServiceLocator.register("DebugManager",t),this.log("info","自动注册 DebugManager")}t.setLogLevel(e?"debug":"info"),this.log("info","ProxyUrlBulkInsertManager debug 模式已开启")}catch(e){console.warn("[ProxyUrlBulkInsertManager] DebugManager 自动注册失败,使用本地 debug 模式")}}log(e,t,r){try{const n=s.ServiceLocator.get("DebugManager");e.toUpperCase(),n.log(e,`[ProxyUrlBulkInsertManager] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [ProxyUrlBulkInsertManager] ${t}`,r||"")}}chunkArray(e,t){const r=[];for(let s=0;s<e.length;s+=t)r.push(e.slice(s,s+t));return r}async processInBatches(e,t){let r=0;const s=[];for(const n of e){s.length>=this.concurrency&&await Promise.race(s);const o=t(n).then(t=>{r+=t;const s=Math.round(r/e.flat().length*100);return this.debug&&this.log("info",`已处理 ${r} 条记录 (${s}%)`),t}).catch(e=>{throw this.debug&&this.log("error",`批次处理失败: ${e.message}`),e});s.push(o),s.forEach((e,t)=>{e.then(()=>s.splice(t,1))})}return await Promise.all(s),r}async bulkInsertFromUrls(e){if(0===e.length)return 0;const t=[...new Set(e)];t.length!==e.length&&this.debug&&this.log("info",`检测到 ${e.length-t.length} 个重复URL,已自动去重`),this.debug&&this.log("info",`开始处理 ${t.length} 个代理URL,仅插入不存在的记录`);const r=this.chunkArray(t,this.batchSize);return this.debug&&this.log("info",`拆分为 ${r.length} 个批次,每批 ${this.batchSize} 条`),this.processInBatches(r,e=>this.processUrlBatch(e))}async processUrlBatch(e){if(0===e.length)return 0;const t=await this.mongoManager.findAll({url:{$in:e}}),r=new Set(t.map(e=>e.url)),s=e.filter(e=>!r.has(e));if(0===s.length)return this.debug&&this.log("info",`批次中所有 ${e.length} 个代理已存在,无需插入`),0;const n=s.map(e=>({url:e,totalRequests:0,failCount:0,avgResponseTime:0,lastCheckTime:Date.now(),consecutiveFails:0,status:"valid"}));try{const e=await this.mongoManager.bulkInsert(n);return this.debug&&this.log("info",`批次插入完成,新增 ${e.insertedCount} 个代理`),e.insertedCount}catch(e){throw this.debug&&this.log("error",`批次插入失败: ${e.message}`),e}}}},435:function(e,t,r){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getMainDirectory=t.getFormattedDate=t.VERSION=t.ProxyRequestSDK=t.AsyncQueueSingleton=t.DebugManager=t.ServiceLocator=t.MongoProxyManager=t.ProxyManager=t.Request=t.ProxyUrlBulkInsertManager=void 0,t.initializeServices=y,t.createProxyRequest=async function(e){return await y(e)},t.registerCoreServices=function(e){const t=e.instanceId||`core-${Date.now()}`,r=h.DebugManager.getInstance();e.logLevel&&r.setLogLevel(e.logLevel),l.ServiceLocator.register("DebugManager",r);const s=u.AsyncQueueSingleton.getInstance(t,{logLevel:e.logLevel});l.ServiceLocator.register(`AsyncQueue-${t}`,s);const n=a.ProxyManager.getInstance({mongoUri:e.mongoUri,logLevel:e.logLevel,instanceId:t});l.ServiceLocator.register(`ProxyManager-${t}`,n);const o=new i.Request({mongoUri:e.mongoUri,logLevel:e.logLevel,instanceId:t});l.ServiceLocator.register(`Request-${t}`,o)},t.registerRequestFactory=function(e,t){const r=t||`factory-${Date.now()}`;l.ServiceLocator.registerFactory(`Request-${r}`,e)},t.registerProxyManagerFactory=function(e,t){const r=t||`factory-${Date.now()}`;l.ServiceLocator.registerFactory(`ProxyManager-${r}`,e)},t.bulkInsertProxyUrls=async function(e){const t=new o.ProxyUrlBulkInsertManager(c.MongoProxyManager.getInstance({uri:e.mongoUri,logLevel:e.logLevel}),e.batchSize||500,e.concurrency||4,e.logLevel);return await t.bulkInsertFromUrls(e.proxyUrls)},t.getStandaloneServices=function(e){const t=e.instanceId||`standalone-${Date.now()}`,r=c.MongoProxyManager.getInstance({uri:e.mongoUri,logLevel:e.logLevel}),s=u.AsyncQueueSingleton.getInstance(`standalone-${t}`,{logLevel:e.logLevel});return{proxyManager:a.ProxyManager.getInstance({mongoUri:e.mongoUri,logLevel:e.logLevel,instanceId:t}),request:new i.Request({mongoUri:e.mongoUri,logLevel:e.logLevel,instanceId:t}),mongoManager:r,asyncQueue:s}},t.cleanupServices=function(){l.ServiceLocator.clear(),u.AsyncQueueSingleton.destroyAllInstances(),a.ProxyManager.resetInstance()},t.checkServicesHealth=async function(e,t){try{const r=c.MongoProxyManager.getInstance({uri:e}),s=await r.checkConnection(),n=t||"default",o={DebugManager:l.ServiceLocator.has("DebugManager"),[`ProxyManager-${n}`]:l.ServiceLocator.has(`ProxyManager-${n}`),[`Request-${n}`]:l.ServiceLocator.has(`Request-${n}`),[`AsyncQueue-${n}`]:l.ServiceLocator.has(`AsyncQueue-${n}`)},i=u.AsyncQueueSingleton.getInstanceNames();return{mongo:s,proxyManager:l.ServiceLocator.has(`ProxyManager-${n}`),asyncQueues:i,services:o}}catch(e){return{mongo:!1,proxyManager:!1,asyncQueues:[],services:{}}}};const n=s(r(330)),o=r(392);Object.defineProperty(t,"ProxyUrlBulkInsertManager",{enumerable:!0,get:function(){return o.ProxyUrlBulkInsertManager}});const i=r(378);Object.defineProperty(t,"Request",{enumerable:!0,get:function(){return i.Request}});const a=r(696);Object.defineProperty(t,"ProxyManager",{enumerable:!0,get:function(){return a.ProxyManager}});const c=r(862);Object.defineProperty(t,"MongoProxyManager",{enumerable:!0,get:function(){return c.MongoProxyManager}});const l=r(388);Object.defineProperty(t,"ServiceLocator",{enumerable:!0,get:function(){return l.ServiceLocator}});const h=r(577);Object.defineProperty(t,"DebugManager",{enumerable:!0,get:function(){return h.DebugManager}});const u=r(892);Object.defineProperty(t,"AsyncQueueSingleton",{enumerable:!0,get:function(){return u.AsyncQueueSingleton}});class g{constructor(e){this.proxyManagerInstance=null,this.bulkInsertManager=null,this.isInitialized=!1,this.instanceId=e.instanceId||`sdk-${Date.now()}`,e.logLevel&&this.setLogLevel(e.logLevel);const t=!!(e.proxies&&e.proxies.length>0)||!!e.proxy;if((e.mongoUri||e.proxyCheckOptions||t)&&!t&&!e.proxyCheckOptions?.mainUrl&&!1!==e.proxyCheckEnabled)throw new Error("启用代理管理功能时,proxyCheckOptions.mainUrl 必须设置(除非 proxyCheckEnabled 为 false 或提供了代理数组)");if(!l.ServiceLocator.has("DebugManager")){const t=h.DebugManager.getInstance();e.logLevel&&t.setLogLevel(e.logLevel),l.ServiceLocator.register("DebugManager",t),this.log("info","注册 DebugManager")}if(!l.ServiceLocator.has(`AsyncQueue-${this.instanceId}`)){const t=u.AsyncQueueSingleton.getInstance(this.instanceId,{logLevel:e.logLevel});l.ServiceLocator.register(`AsyncQueue-${this.instanceId}`,t),this.log("info","注册 AsyncQueue",{instanceId:this.instanceId})}try{if(!l.ServiceLocator.has(`Request-${this.instanceId}`))throw new Error("Request 服务未注册。请使用 createProxyRequest() 或 initializeServices() 创建 SDK 实例,不要直接 new ProxyRequestSDK()。");this.requestInstance=l.ServiceLocator.get(`Request-${this.instanceId}`),l.ServiceLocator.has(`ProxyManager-${this.instanceId}`)?(this.proxyManagerInstance=l.ServiceLocator.get(`ProxyManager-${this.instanceId}`),this.log("info","使用已注册的服务实例(包含代理管理)",{instanceId:this.instanceId})):(this.proxyManagerInstance=null,this.log("info","使用已注册的服务实例(轻量级模式,无代理管理)",{instanceId:this.instanceId}))}catch(e){const t=e?.message||String(e);if(t.includes("请使用 createProxyRequest"))throw e;throw this.log("error","服务未正确初始化",{error:t}),new Error(`服务初始化失败: ${t}。请使用 createProxyRequest() 或 initializeServices() 创建实例。`)}e.mongoUri&&(this.bulkInsertManager=new o.ProxyUrlBulkInsertManager(c.MongoProxyManager.getInstance({uri:e.mongoUri}),500,4,e.logLevel)),this.initializeAsync(e).catch(e=>{console.error("SDK初始化失败:",e)})}log(e,t,r){try{const s=l.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[ProxyRequestSDK:${this.instanceId}] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e?console.debug:console.info)(`${n} [ProxyRequestSDK:${this.instanceId}] ${t}`,r||"")}}async initializeAsync(e){try{this.proxyManagerInstance&&await this.proxyManagerInstance.waitForInitialization(),this.isInitialized=!0,this.log("info","初始化完成",{hasProxyManagement:!!this.proxyManagerInstance})}catch(e){throw this.log("error","初始化失败:",e),e}}async waitForReady(){for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}setLogLevel(e){try{l.ServiceLocator.get("DebugManager").setLogLevel(e),this.log("info",`设置日志等级: ${e}`)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}}getLogLevel(){try{return l.ServiceLocator.get("DebugManager").getLogLevel()}catch(e){return"info"}}getServiceInfo(){const e=["DebugManager",`ProxyManager-${this.instanceId}`,`Request-${this.instanceId}`,`AsyncQueue-${this.instanceId}`],t={};return e.forEach(e=>{t[e]=l.ServiceLocator.has(e)}),u.AsyncQueueSingleton.getInstanceNames().forEach(e=>{t[`AsyncQueue:${e}`]=!0}),t.hasProxyManagement=this.hasProxyManagement(),t}async get(e,t,r){await this.waitForReady();const s={...r,params:t?{...r?.params,...t}:r?.params};return this.requestInstance.get(e,s)}async post(e,t){return await this.waitForReady(),this.requestInstance.post(e,t)}async put(e,t){return await this.waitForReady(),this.requestInstance.put(e,t)}async delete(e,t){return await this.waitForReady(),this.requestInstance.delete(e,t)}async patch(e,t){return await this.waitForReady(),this.requestInstance.patch(e,t)}async request(e){return await this.waitForReady(),this.requestInstance.request({url:e.url,method:e.method||"GET",options:e.options||{}})}async addProxy(e){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.addProxy(e)}async deleteProxy(e){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.deleteProxy(e)}getAvailableProxies(){return this.proxyManagerInstance?this.proxyManagerInstance.getAvailableProxiesList():[]}getCurrentProxy(){return this.proxyManagerInstance?this.proxyManagerInstance.getCurrentProxy():null}async rotateProxy(){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.rotateProxy()}setProxyStrategy(e){if(!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");this.proxyManagerInstance.setProxyStrategy(e)}async checkProxy(e){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.checkProxy(e)}async triggerProxyCheck(){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.triggerProxyCheck()}hasProxyManagement(){return!!this.proxyManagerInstance}async bulkInsertProxies(e){if(await this.waitForReady(),!this.bulkInsertManager)throw new Error("批量插入功能需要提供 mongoUri");return this.bulkInsertManager.bulkInsertFromUrls(e)}async getProxyStats(){if(await this.waitForReady(),!this.proxyManagerInstance)return{total:0,valid:0,invalid:0,available:0};const e=this.getAvailableProxies(),t=this.proxyManagerInstance?this.proxyManagerInstance.getProxiesCount():0;return{total:t,valid:e.length,invalid:t-e.length,available:e.length}}getProxyDetails(e){if(this.proxyManagerInstance)return this.proxyManagerInstance.getProxyDetails(e)}getQueueStats(){if(!this.proxyManagerInstance)throw new Error("代理管理功能未启用,无法获取队列统计");return this.proxyManagerInstance.getQueueStats()}getInstanceId(){return this.instanceId}async destroy(){this.log("info","开始清理资源"),this.bulkInsertManager&&("function"==typeof this.bulkInsertManager.destroy&&await this.bulkInsertManager.destroy(),this.bulkInsertManager=null),[`ProxyManager-${this.instanceId}`,`Request-${this.instanceId}`,`AsyncQueue-${this.instanceId}`].forEach(e=>{l.ServiceLocator.has(e)&&(l.ServiceLocator.removeService(e),this.log("info",`清理服务: ${e}`))}),u.AsyncQueueSingleton.destroyInstance(this.instanceId),this.proxyManagerInstance&&(await this.proxyManagerInstance.destroy(),this.proxyManagerInstance=null),this.isInitialized=!1,this.log("info","资源清理完成")}}async function y(e){const t=e.instanceId||`instance-${Date.now()}`,r=!!(e.proxies&&e.proxies.length>0)||!!e.proxy,s=!!(e.mongoUri||e.proxyCheckOptions||r);if(s&&!r&&void 0===e.proxyCheckOptions?.mainUrl&&!1!==e.proxyCheckEnabled)throw new Error("启用代理管理功能时,proxyCheckOptions.mainUrl 必须设置(除非 proxyCheckEnabled 为 false 或提供了代理数组)");let n;[`ProxyManager-${t}`,`Request-${t}`,`AsyncQueue-${t}`].forEach(e=>{if(l.ServiceLocator.has(e)){if(e.startsWith("ProxyManager-"))try{const t=l.ServiceLocator.get(e);t&&"function"==typeof t.destroy&&t.destroy().catch(e=>{console.warn(`清理 ProxyManager 失败: ${e.message}`)})}catch(e){console.warn(`获取 ProxyManager 服务失败: ${e.message}`)}if(e.startsWith("AsyncQueue-")){const t=e.replace("AsyncQueue-","");u.AsyncQueueSingleton.destroyInstance(t)}l.ServiceLocator.removeService(e)}}),l.ServiceLocator.initialize(),l.ServiceLocator.has("DebugManager")?(n=l.ServiceLocator.get("DebugManager"),e.logLevel&&n.setLogLevel(e.logLevel)):(n=h.DebugManager.getInstance(),e.logLevel&&n.setLogLevel(e.logLevel),l.ServiceLocator.register("DebugManager",n));const o=`AsyncQueue-${t}`;let c;if(u.AsyncQueueSingleton.hasInstance(t)){if(c=u.AsyncQueueSingleton.getExistingInstance(t),c&&void 0!==e.logLevel)try{const t=l.ServiceLocator.get("DebugManager");e.logLevel&&t.setLogLevel(e.logLevel)}catch(e){console.warn("DebugManager未注册,无法更新debug状态")}}else c=u.AsyncQueueSingleton.getInstance(t,{logLevel:e.logLevel});l.ServiceLocator.register(o,c);let y=null;const d=`ProxyManager-${t}`;if(s)l.ServiceLocator.has(d)?(y=l.ServiceLocator.get(d),e.proxyStrategy&&y.setProxyStrategy(e.proxyStrategy),e.maxConcurrentChecks&&y.setMaxConcurrentChecks(e.maxConcurrentChecks)):y=a.ProxyManager.getInstance({mongoUri:e.mongoUri,proxies:e.proxies,proxy:e.proxy,proxyLimit:e.proxyLimit,proxyStrategy:e.proxyStrategy,maxConcurrentChecks:e.maxConcurrentChecks,logLevel:e.logLevel,proxyCheckOptions:e.proxyCheckOptions,proxyCheckEnabled:e.proxyCheckEnabled,instanceId:t}),await y.waitForInitialization(),l.ServiceLocator.register(d,y);else try{l.ServiceLocator.get("DebugManager").log("info","以轻量级模式运行(不使用代理管理功能)",{instanceId:t})}catch(e){console.info("以轻量级模式运行(不使用代理管理功能)",{instanceId:t})}const p=`Request-${t}`;let x;if(x=l.ServiceLocator.has(p)?l.ServiceLocator.get(p):new i.Request({maxRetries:e.maxRetries,timeout:e.timeout,logLevel:e.logLevel,retryDelay:e.retryDelay,retryDelayBase:e.retryDelayBase,retryDelayMultiplier:e.retryDelayMultiplier,instanceId:t}),l.ServiceLocator.register(p,x),e.logLevel&&"none"!==e.logLevel&&"error"!==e.logLevel)try{l.ServiceLocator.get("DebugManager").log("info","服务初始化完成",{instanceId:t,mongoUri:e.mongoUri,hasProxyManagement:s,proxyCount:y?y.getProxiesCount():0})}catch(r){console.info("服务初始化完成",{instanceId:t,mongoUri:e.mongoUri,hasProxyManagement:s,proxyCount:y?y.getProxiesCount():0})}return new g({...e,instanceId:t})}t.ProxyRequestSDK=g,t.default=g,t.VERSION=n.default.version;var d=r(298);Object.defineProperty(t,"getFormattedDate",{enumerable:!0,get:function(){return d.getFormattedDate}}),Object.defineProperty(t,"getMainDirectory",{enumerable:!0,get:function(){return d.getMainDirectory}})},577:function(e,t,r){var s,n=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,n)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(s=function(e){return s=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},s(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=s(e),i=0;i<r.length;i++)"default"!==r[i]&&n(t,e,r[i]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.safeLog=t.debugManager=t.DebugManager=void 0;const a=i(r(896)),c=i(r(928)),l=i(r(306));r(171);class h{constructor(){this.logLevel="info",this.logLevelPriority={none:0,error:1,warn:2,info:3,debug:4,verbose:5},this.initializeLogger()}static getInstance(){return h.instance||(h.instance=new h),h.instance}initializeLogger(){const e=c.join(process.cwd(),"logs");a.existsSync(e)||a.mkdirSync(e,{recursive:!0});const t=l.format.combine(l.format.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),l.format.printf(({timestamp:e,level:t,message:r,...s})=>{let n=`${e} [${t.toUpperCase()}] ${r}`;if(Object.keys(s).length>0){const{timestamp:e,level:t,message:r,...o}=s;if(Object.keys(o).length>0)try{n+=` | ${JSON.stringify(o)}`}catch{n+=` | ${String(o)}`}}return n}));this.logger=l.createLogger({level:this.getWinstonLevel(this.logLevel),format:t,transports:[new l.transports.Console({format:t}),new l.transports.DailyRotateFile({filename:c.join(e,"%DATE%.log"),format:t,datePattern:"YYYY/MM/DD",maxFiles:null})]})}getWinstonLevel(e){return{none:"error",error:"error",warn:"warn",info:"info",debug:"debug",verbose:"verbose"}[e]}setLogLevel(e){this.logLevel=e,this.logger.level=this.getWinstonLevel(e)}getLogLevel(){return this.logLevel}logInternal(e,t,r){const s=`[${e.toUpperCase()}]`;this.logger.log(this.getWinstonLevel(e),`${s} [DebugManager] ${t}`,r)}log(e,t,r){this.logger.log(this.getWinstonLevel(e),t,r)}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}verbose(e,t){this.log("verbose",e,t)}}t.DebugManager=h,t.debugManager=h.getInstance(),t.safeLog=t.debugManager.log.bind(t.debugManager)},626:e=>{e.exports=require("async")},696:function(e,t,r){var s,n=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,n)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(s=function(e){return s=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},s(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=s(e),i=0;i<r.length;i++)"default"!==r[i]&&n(t,e,r[i]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyManager=void 0;const a=r(862),c=r(892),l=r(388);class h{constructor(e={}){this.mongoClient=null,this.isInitialized=!1,this.initializationPromise=null,this.needsMongoDB=!0,this.currentPage=0,this.pageSize=2e3,this.hasMorePages=!0,this.totalLoaded=0,this.instanceId=e.instanceId||`proxy-pool-manager-${Date.now()}`,this.logLevel=e.logLevel||"none",this.proxyCheckEnabled=e.proxyCheckEnabled??!0,this.proxyStrategy=e.proxyStrategy??"sequential",this.availableProxies=new Set,this.checkInProgress=new Set,this.maxConcurrentChecks=e.maxConcurrentChecks??5,this.proxyLimit=e.proxyLimit??0;const t=Array.isArray(e.proxies)&&e.proxies.length>0||!!e.proxy,r=0!==this.proxyLimit||t||this.proxyCheckEnabled;if(!e.mongoUri&&r&&0!==this.proxyLimit&&!t)throw new Error("ProxyManager实例化时,mongoUri 未设置(需要从数据库加载代理)");e.mongoUri?(this.mongoClient=a.MongoProxyManager.getInstance({uri:e.mongoUri}),this.needsMongoDB=!0):(this.needsMongoDB=!1,this.log("info","未提供 mongoUri,将跳过 MongoDB 连接(仅使用内存中的代理)")),this.asyncQueue=c.AsyncQueueSingleton.getInstance(this.instanceId,{concurrency:this.maxConcurrentChecks,autoStart:!0,logLevel:this.logLevel,onDrain:()=>{this.log("info","所有代理检测任务完成")},onError:e=>{this.log("error","代理检测任务出错:",e)},onSuccess:e=>{},taskHandler:async e=>(await new Promise(e=>setTimeout(e,1e3)),await this.taskHandler(e))}),this.proxies=[],Array.isArray(e.proxies)?e.proxies.forEach(e=>{this.addProxySync(e)}):e.proxy&&this.addProxySync(e.proxy),this.proxyCheckOptions={mainUrl:e.proxyCheckOptions?.mainUrl||"",testUrls:e.proxyCheckOptions?.testUrls??["http://httpbin.org/ip","http://api.ipify.org?format=json","http://ipinfo.io/json"],timeout:e.proxyCheckOptions?.timeout??5,successStatusCodes:e.proxyCheckOptions?.successStatusCodes??[200],checkInterval:e.proxyCheckOptions?.checkInterval??6e4,maxConsecutiveFails:e.proxyCheckOptions?.maxConsecutiveFails??3,maxResponseTime:e.proxyCheckOptions?.maxResponseTime??2e3},this.currentProxyIndex=0,this.usedProxies=new Set,this.initializationPromise=this.initializeAsync()}async initializeAsync(){try{this.needsMongoDB&&this.mongoClient?(await this.mongoClient.ensureConnected(),0!==this.proxyLimit?await this.loadProxiesFromDB():this.log("info","proxyLimit 设置为 0,跳过从数据库加载代理")):this.log("info","跳过 MongoDB 连接(不需要代理管理功能)"),this.isInitialized=!0,this.log("info",`ProxyManager初始化完成,加载了 ${this.proxies.length} 个代理`)}catch(e){throw this.log("error","ProxyManager初始化失败:",e),e}}async waitForInitialization(){if(!this.isInitialized){if(!this.initializationPromise)throw new Error("ProxyManager未正确初始化");await this.initializationPromise}}addProxySync(e){if(!this.proxies.find(t=>t.url===e)){const t={url:e,totalRequests:0,failCount:0,avgResponseTime:0,lastCheckTime:Date.now(),consecutiveFails:0,status:"valid"};this.proxies.push(t),this.availableProxies.add(e),this.mongoClient&&this.mongoClient.upsert(t).catch(t=>{this.log("error",`保存代理到数据库失败: ${e}`,t)})}}static getInstance(e={}){const t=e.instanceId||`proxy-pool-manager-${Date.now()}`;if(h.instances.has(t))return h.instances.get(t);h.instanceLock=!0;try{if(h.instances.has(t))return h.instances.get(t);const r=new h({...e,instanceId:t});return h.instances.set(t,r),r}finally{h.instanceLock=!1}}static resetInstance(e){if(void 0!==e){const t=h.instances.get(e);t&&(t.destroy(),h.instances.delete(e))}else h.instances.forEach(e=>e.destroy()),h.instances.clear()}log(e,t,r){try{const s=l.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[ProxyManager] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [ProxyManager] ${t}`,r||"")}}setLogLevel(e){try{l.ServiceLocator.get("DebugManager").setLogLevel(e),this.log("info",`设置日志等级: ${e}`)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}}getLogLevel(){try{return l.ServiceLocator.get("DebugManager").getLogLevel()}catch(e){return"info"}}async loadProxiesFromDB(e={},t=!1){try{if(t&&(this.currentPage=0,this.totalLoaded=0,this.hasMorePages=!0,this.proxies=[],this.log("info","重置分页查询状态")),!this.hasMorePages&&!t)return void this.log("info","没有更多代理可加载");const r={status:"valid",...e};if(!this.mongoClient)return this.log("info","MongoDB 客户端未初始化,跳过代理加载"),void(this.hasMorePages=!1);if(0===this.proxyLimit)return this.log("info","proxyLimit 为 0,跳过代理加载"),void(this.hasMorePages=!1);const s=this.currentPage*this.pageSize,n=this.proxyLimit>0?Math.min(this.proxyLimit,this.pageSize):this.pageSize;this.log("debug","分页查询代理",{page:this.currentPage+1,pageSize:n,skip:s,query:r});const o=await this.mongoClient.findLimited(r,n,s);if(o.length<n?(this.hasMorePages=!1,this.log("info",`已加载最后一页,共 ${o.length} 个代理`)):(this.hasMorePages=!0,this.currentPage++,this.log("info",`加载第 ${this.currentPage} 页,共 ${o.length} 个代理`)),this.totalLoaded+=o.length,1===this.currentPage||t)this.proxies=o;else{const e=new Set(this.proxies.map(e=>e.url)),t=o.filter(t=>!e.has(t.url));this.proxies.push(...t)}this.availableProxies.clear(),this.proxies.forEach(e=>this.availableProxies.add(e.url)),this.log("info","从数据库加载代理完成",{totalInMemory:this.proxies.length,available:this.availableProxies.size,currentPage:this.currentPage,hasMorePages:this.hasMorePages,totalLoaded:this.totalLoaded})}catch(e){throw this.log("error","从数据库加载代理失败:",e.message),e}}async loadNextPage(){if(await this.waitForInitialization(),!this.hasMorePages)return this.log("info","没有更多代理页面,返回第一页"),await this.loadProxiesFromDB({},!0),this.proxies.length;const e=this.proxies.length;return await this.loadProxiesFromDB({},!1),this.proxies.length-e}async resetPagination(){await this.waitForInitialization(),await this.loadProxiesFromDB({},!0)}getPaginationInfo(){return{currentPage:this.currentPage,pageSize:this.pageSize,hasMorePages:this.hasMorePages,totalLoaded:this.totalLoaded,totalInMemory:this.proxies.length}}async addProxy(e){if(!e?.trim())throw new Error("代理URL不能为空");await this.waitForInitialization();let t=this.proxies.find(t=>t.url===e);if(t)return this.log("info","代理已存在于内存中",{proxy:e}),t;if(this.mongoClient&&(t=await this.mongoClient.findByUrl(e),t))return"valid"===t.status&&(this.proxies.push(t),this.availableProxies.add(e),this.log("info","从数据库加载现有代理",{proxy:e,status:t.status})),t;const r={url:e,totalRequests:0,failCount:0,avgResponseTime:0,lastCheckTime:Date.now(),consecutiveFails:0,status:"valid"},s=this.mongoClient?await this.mongoClient.upsert(r):r;return this.proxies.push(s),this.availableProxies.add(e),this.log("info","添加新代理到数据库",{proxy:e}),s}async deleteProxy(e){if(await this.waitForInitialization(),!this.mongoClient){const t=this.proxies.findIndex(t=>t.url===e);return-1!==t&&(this.proxies.splice(t,1),this.availableProxies.delete(e),this.log("info","从内存中删除代理",{proxy:e}),!0)}const t=await this.mongoClient.delete(e);return t&&(this.proxies=this.proxies.filter(t=>t.url!==e),this.availableProxies.delete(e),this.log("info","删除代理",{proxy:e})),t}async deleteInvalidProxies(){if(await this.waitForInitialization(),!this.mongoClient){const e=this.proxies.filter(e=>"invalid"===e.status).length;return this.proxies=this.proxies.filter(e=>"valid"===e.status),this.availableProxies.clear(),this.proxies.forEach(e=>this.availableProxies.add(e.url)),this.log("info","从内存中删除无效代理",{count:e}),e}const e=await this.mongoClient.deleteInvalidProxies();return this.log("info","删除无效代理完成",{count:e}),e}async standaloneProxyCheck(e,t,s,n){const{default:o}=await Promise.resolve().then(()=>i(r(867)));try{const r=new AbortController,i=setTimeout(()=>r.abort(),1e3*n),a={method:"POST",headers:{"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"}};let c={url:s,method:"GET"};e&&(c.proxy=e,c.impersonate="chrome",c.timeout=n,a.body=JSON.stringify(c),a.headers["Content-Type"]="application/json");const l=await o(t,a),h=await l.text();let u;clearTimeout(i);try{u=JSON.parse(h)}catch{u=h}const g={status_code:l.status,success:l.ok,headers:Object.fromEntries(l.headers.entries()),data:u,error:l.ok?void 0:h,timestamp:(new Date).toISOString()},y=l.ok&&this.proxyCheckOptions.successStatusCodes.includes(g.status_code);return y?this.log("info","代理检测成功",{proxy:e,status:g.status_code,result:JSON.stringify(g.data)}):this.log("error","代理检测状态码不符",{proxy:e,statusCode:g.status_code,expected:this.proxyCheckOptions.successStatusCodes}),y}catch(t){return this.log("error","代理检测请求失败",{proxy:e,error:t.message}),!1}}async taskHandler(e){const t=Date.now();try{const r=this.proxyCheckOptions.testUrls[Math.floor(Math.random()*this.proxyCheckOptions.testUrls.length)],s=await this.standaloneProxyCheck(e.url,this.proxyCheckOptions.mainUrl,r,this.proxyCheckOptions.timeout),n=Date.now()-t;return e.totalRequests++,e.lastCheckTime=Date.now(),s?(e.avgResponseTime=(e.avgResponseTime*(e.totalRequests-1)+n)/e.totalRequests,e.consecutiveFails=0):(e.failCount++,e.consecutiveFails++),{proxy:e,isAvailable:s,responseTime:n}}catch(r){return this.log("error","代理检测出错",{proxy:e.url,error:r.message}),e.totalRequests++,e.failCount++,e.consecutiveFails++,e.lastCheckTime=Date.now(),{proxy:e,isAvailable:!1,responseTime:Date.now()-t}}}async checkAllProxies(){this.mongoClient||this.log("info","MongoDB 客户端未初始化,使用内存中的代理进行检测");let e=this.mongoClient?await this.mongoClient.findAll({status:"valid"}):this.proxies.filter(e=>"valid"===e.status);this.log("info",`开始批量检测代理,共 ${e.length} 个代理,最大并发数: ${this.maxConcurrentChecks}`),this.asyncQueue.updateConcurrency(this.maxConcurrentChecks);const t=[];try{const r=await this.asyncQueue.addBatch(e);t.push(...r),t.forEach(e=>{e.proxy.totalRequests>=2&&(e.proxy.failCount,e.proxy.totalRequests),e.proxy.failCount||e.proxy.avgResponseTime>this.proxyCheckOptions.maxResponseTime?(e.proxy.status="invalid",this.availableProxies.delete(e.proxy.url)):e.proxy.status="valid"}),this.mongoClient&&await this.mongoClient.bulkUpsert(e);const s=e.filter(e=>"valid"===e.status).length,n=e.length-s;this.log("info","批量代理检测完成",{total:e.length,valid:s,invalid:n})}catch(e){this.log("error","批量代理检测失败",{error:e.message})}}getCurrentProxy(){return 0===this.proxies.length?null:this.proxies[this.currentProxyIndex].url}selectProxy(){const e=this.proxies.filter(e=>"valid"===e.status);if(0===e.length)return null;let t;switch(this.proxyStrategy){case"sequential":t=this.currentProxyIndex%e.length,this.currentProxyIndex=(t+1)%e.length;break;case"random":this.usedProxies.size>=e.length&&this.usedProxies.clear();const r=Array.from({length:e.length},(e,t)=>t).filter(e=>!this.usedProxies.has(e));t=r.length>0?r[Math.floor(Math.random()*r.length)]:Math.floor(Math.random()*e.length),this.usedProxies.add(t),this.currentProxyIndex=t;break;case"failover":const s=[...e].sort((e,t)=>{if(e.consecutiveFails!==t.consecutiveFails)return e.consecutiveFails-t.consecutiveFails;const r=e.totalRequests>0?e.failCount/e.totalRequests:0,s=t.totalRequests>0?t.failCount/t.totalRequests:0;return r!==s?r-s:e.avgResponseTime-t.avgResponseTime});t=this.proxies.findIndex(e=>e.url===s[0].url),this.currentProxyIndex=t;break;default:t=this.currentProxyIndex%e.length}return e[t].url}async rotateProxy(){if(0===this.proxies.filter(e=>"valid"===e.status).length)return null;const e=this.proxies[this.currentProxyIndex];e.failCount++,e.totalRequests++,e.consecutiveFails++,e.consecutiveFails>=this.proxyCheckOptions.maxConsecutiveFails&&(e.status="invalid",this.availableProxies.delete(e.url)),this.mongoClient&&await this.mongoClient.upsert(e);const t=this.proxies.filter(e=>"valid"===e.status);if(0===t.length)return null;this.currentProxyIndex=(this.currentProxyIndex+1)%t.length;const r=t[this.currentProxyIndex];return this.log("info","轮换代理",{from:e.url,to:r.url,consecutiveFails:e.consecutiveFails}),r.url}async recordProxyUsage(e,t,r){const s=this.proxies.find(t=>t.url===e);s&&(s.totalRequests++,t?(s.avgResponseTime=(s.avgResponseTime*(s.totalRequests-1)+r)/s.totalRequests,s.consecutiveFails=0):(s.failCount++,s.consecutiveFails++),s.lastCheckTime=Date.now(),t&&"invalid"===s.status&&(s.status="valid",this.availableProxies.add(s.url)),this.mongoClient&&await this.mongoClient.upsert(s))}resetProxyUsage(){this.usedProxies.clear(),this.log("info","重置代理使用记录")}setProxyStrategy(e){this.proxyStrategy=e,this.resetProxyUsage(),this.log("info","设置代理策略",{strategy:e})}async enhancedProxyCheck(e){if(!this.proxyCheckEnabled)return!0;if(this.checkInProgress.has(e))return!0;try{this.checkInProgress.add(e);const t=this.proxyCheckOptions.testUrls[Math.floor(Math.random()*this.proxyCheckOptions.testUrls.length)],r=Date.now(),s=await this.standaloneProxyCheck(e,this.proxyCheckOptions.mainUrl,t,this.proxyCheckOptions.timeout),n=Date.now()-r;return s&&n>this.proxyCheckOptions.maxResponseTime?(this.log("error","代理响应时间过长",{proxy:e,responseTime:n,threshold:this.proxyCheckOptions.maxResponseTime}),!1):s}catch(t){return this.log("error","代理检测异常",{proxy:e,error:t.message}),!1}finally{this.checkInProgress.delete(e)}}setMaxConcurrentChecks(e){e>0&&(this.maxConcurrentChecks=e,this.asyncQueue.updateConcurrency(e),this.log("info","更新最大并发检查数",{maxConcurrentChecks:e}))}getQueueStats(){return this.asyncQueue.stats}pauseProxyChecks(){this.asyncQueue.pause(),this.log("info","代理检测队列已暂停")}resumeProxyChecks(){this.asyncQueue.resume(),this.log("info","代理检测队列已恢复")}async checkProxy(e){const t=e||this.getCurrentProxy();if(!t)return!1;const r=await this.enhancedProxyCheck(t),s=this.proxies.find(e=>e.url===t);return s&&(s.status=r?"valid":"invalid",r?this.availableProxies.add(t):this.availableProxies.delete(t),this.mongoClient&&await this.mongoClient.upsert(s)),this.log("info","代理检查完成",{proxy:t,result:r}),r}getAvailableProxy(){const e=this.proxies.filter(e=>"valid"===e.status);if(0===e.length)return null;const t=this.selectProxy();return this.log("info","获取代理",{proxy:t,strategy:this.proxyStrategy,available:e.length}),t}shouldRotateProxy(e){if(0===this.proxies.filter(e=>"valid"===e.status).length)return!1;if(!e||!e.message)return!1;const t=e.message.toLowerCase();return["proxy","connect","connection","timeout","socket","网络","连接","ETIMEDOUT","ECONNREFUSED"].some(e=>t.includes(e))}async triggerProxyCheck(){await this.waitForInitialization(),this.log("info","手动触发代理检测"),await this.checkAllProxies()}getAvailableProxiesList(){return this.proxies.filter(e=>"valid"===e.status).map(e=>e.url)}getProxyDetails(e){return this.proxies.find(t=>t.url===e)}getProxiesCount(){return this.proxies.length}getProxyStrategy(){return this.proxyStrategy}getCurrentProxyIndex(){return this.currentProxyIndex}async destroy(){if(this.checkInProgress.clear(),this.usedProxies.clear(),this.proxies=[],this.availableProxies.clear(),this.asyncQueue){const e=this.asyncQueue.getName();this.asyncQueue.pause(),c.AsyncQueueSingleton.destroyInstance(e)}this.mongoClient&&this.needsMongoDB&&await this.mongoClient.disconnect(),this.isInitialized=!1,this.initializationPromise=null,h.instances.delete(this.instanceId),this.log("info","ProxyManager 已完全销毁")}}t.ProxyManager=h,h.instances=new Map,h.instanceLock=!1},862:function(e,t,r){var s,n=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,n)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(s=function(e){return s=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},s(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=s(e),i=0;i<r.length;i++)"default"!==r[i]&&n(t,e,r[i]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.MongoProxyManager=void 0;const a=r(388),c=i(r(331)),l=new c.Schema({url:{type:String,required:!0,unique:!0},totalRequests:{type:Number,default:0},failCount:{type:Number,default:0},avgResponseTime:{type:Number,default:0},lastCheckTime:{type:Number,default:Date.now},consecutiveFails:{type:Number,default:0},status:{type:String,enum:["valid","invalid"],default:"valid"}});l.index({status:1}),l.index({url:1}),l.index({status:1,totalRequests:1});class h{constructor(e){this.isConnected=!1,this.connectPromise=null,this.connectionAttempts=0,this.maxConnectionAttempts=3,this.config=e,this.logLevel=e.logLevel||"none",this.ProxyModel=c.default.model("Proxy",l)}async connectWithRetry(){if(!this.isConnected){if(this.connectPromise)return await this.connectPromise;this.connectPromise=(async()=>{if(1===c.default.connection.readyState)return this.isConnected=!0,void this.log("info","使用现有MongoDB连接");for(;this.connectionAttempts<this.maxConnectionAttempts;)try{return this.connectionAttempts++,this.log("info",`尝试连接MongoDB (${this.connectionAttempts}/${this.maxConnectionAttempts})`),await c.default.connect(this.config.uri,{serverSelectionTimeoutMS:8e3,socketTimeoutMS:45e3,maxPoolSize:10}),this.isConnected=!0,this.connectionAttempts=0,void this.log("info",`MongoDB连接成功: ${this.config.uri}`)}catch(e){if(this.log("warn",`MongoDB连接尝试 ${this.connectionAttempts}/${this.maxConnectionAttempts} 失败: ${e.message}`),this.connectionAttempts>=this.maxConnectionAttempts){const t=new Error(`MongoDB连接失败,已尝试 ${this.maxConnectionAttempts} 次: ${e.message}`);throw this.connectPromise=null,t}await new Promise(e=>setTimeout(e,2e3*this.connectionAttempts))}})();try{await this.connectPromise}finally{this.connectPromise=null}}}static getInstance(e){const t=e.uri;return h.instances.has(t)||h.instances.set(t,new h(e)),h.instances.get(t)}log(e,t,r){try{const s=a.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[MongoProxyManager] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [MongoProxyManager] ${t}`,r||"")}}async ensureConnected(){this.isConnected||(this.connectPromise?await this.connectPromise:await this.connectWithRetry())}async connect(){if(!this.isConnected){if(this.connectPromise)return await this.connectPromise;this.connectPromise=(async()=>{try{await c.default.connect(this.config.uri,{serverSelectionTimeoutMS:5e3,socketTimeoutMS:45e3}),this.isConnected=!0,this.log("info",`MongoDB连接成功: ${this.config.uri}`)}catch(e){throw this.log("error",`MongoDB连接失败: ${e.message}`),e}finally{this.connectPromise=null}})(),await this.connectPromise}}async disconnect(){this.isConnected&&(await c.default.disconnect(),this.isConnected=!1,this.log("info","连接已关闭"))}async checkConnection(){try{return await c.default.connection.db.admin().ping(),!0}catch{return!1}}async findAll(e={}){return await this.ensureConnected(),await this.ProxyModel.find(e).lean()}async findByUrl(e){return await this.ensureConnected(),await this.ProxyModel.findOne({url:e}).lean()}async upsert(e){return await this.ensureConnected(),await this.ProxyModel.findOneAndUpdate({url:e.url},{$set:e},{upsert:!0,new:!0}).lean()}async updateByUrl(e,t){if(!e)throw new Error("代理URL不能为空");if(t.url&&t.url!==e)throw new Error("不能通过updateByUrl方法修改代理URL");await this.ensureConnected();const r={$set:t};return await this.ProxyModel.findOneAndUpdate({url:e},r,{new:!0,runValidators:!0}).lean()}async bulkUpsert(e){if(0===e.length)return;await this.ensureConnected();const t=e.map(e=>({updateOne:{filter:{url:e.url},update:{$set:e},upsert:!0}}));await this.ProxyModel.bulkWrite(t)}async bulkUpdateByUrl(e){if(0===e.length)return;await this.ensureConnected();const t=e.map(e=>({updateOne:{filter:{url:e.url},update:{$set:e.data},upsert:!1}}));await this.ProxyModel.bulkWrite(t)}async bulkInsert(e){if(0===e.length)return{insertedCount:0};await this.ensureConnected();try{return{insertedCount:(await this.ProxyModel.insertMany(e,{ordered:!1,rawResult:!0})).insertedCount}}catch(e){if(e.writeErrors&&e.insertedIds)return{insertedCount:e.insertedIds.length};throw e}}async delete(e){return await this.ensureConnected(),(await this.ProxyModel.deleteOne({url:e})).deletedCount>0}async clear(){await this.ensureConnected(),await this.ProxyModel.deleteMany({})}async updateMany(e,t){return await this.ensureConnected(),(await this.ProxyModel.updateMany(e,{$set:t},{runValidators:!0})).modifiedCount}async findLimited(e={},t=0,r=0){await this.ensureConnected();const s=this.ProxyModel.find(e).lean().skip(r);return t>0&&s.limit(t),await s}async deleteInvalidProxies(){await this.ensureConnected();const e=await this.ProxyModel.deleteMany({status:"invalid"});return this.log("info","删除无效代理",{deletedCount:e.deletedCount}),e.deletedCount}async deleteByCondition(e){await this.ensureConnected();const t=await this.ProxyModel.deleteMany(e);return this.log("info","根据条件删除代理",{filter:e,deletedCount:t.deletedCount}),t.deletedCount}async getStats(){return await this.ensureConnected(),(await this.ProxyModel.aggregate([{$group:{_id:null,total:{$sum:1},valid:{$sum:{$cond:[{$eq:["$status","valid"]},1,0]}},invalid:{$sum:{$cond:[{$eq:["$status","invalid"]},1,0]}},avgResponseTime:{$avg:"$avgResponseTime"}}}]))[0]||{total:0,valid:0,invalid:0,avgResponseTime:0}}}t.MongoProxyManager=h,h.instances=new Map},867:e=>{e.exports=require("node-fetch")},892:function(e,t,r){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncQueueSingleton=void 0;const n=s(r(626)),o=r(388);class i{constructor(e="default",t={}){this.queue=null,this.isInitialized=!1,this.logLevel="info",this.instanceName=e,this.logLevel=t.logLevel||"info",this.concurrency=t.concurrency||100,this.autoStart=!1!==t.autoStart,this.onDrain=t.onDrain||(()=>{this.log("info","所有任务完成")}),this.onError=t.onError||(e=>{this.log("error","任务错误:",e)}),this.onSuccess=t.onSuccess||(e=>{}),this.taskHandler=t.taskHandler||this.defaultTaskHandler,this.initializeQueue()}async defaultTaskHandler(e){return await new Promise(e=>setTimeout(e,1e3)),this.log("debug",`[${this.instanceName}] 剩余任务${this.queue?.length()} 运行任务数${this.queue?.running()}`),`运行成功 - ${this.instanceName}`}initializeQueue(){this.isInitialized||(this.queue=n.default.queue(async e=>await this.taskHandler(e),this.concurrency),this.queue.drain(()=>{this.onDrain()}),this.autoStart||this.queue.pause(),this.isInitialized=!0,this.log("info","队列初始化完成",{concurrency:this.concurrency,autoStart:this.autoStart}))}add(e,t=0){return new Promise((r,s)=>{if(!this.queue)return void s(new Error(`[${this.instanceName}] 队列未初始化`));const n=(t,n)=>{t?(this.log("error","任务执行失败",{task:e,error:t.message}),s(t)):(this.onSuccess(n),r(n))};t>0?this.queue.unshift(e,n):this.queue.push(e,n),this.log("debug","添加任务",{task:e,priority:t,queueLength:this.queue.length(),running:this.queue.running()})})}addBatch(e,t=0){return this.log("info","批量添加任务",{count:e.length,priority:t,instance:this.instanceName}),Promise.all(e.map(e=>this.add(e,t)))}updateConcurrency(e){if(e>0&&e!==this.concurrency&&this.queue){const t=this.concurrency;this.concurrency=e,this.queue.concurrency=e,this.log("info","更新并发数",{from:t,to:e,instance:this.instanceName})}}pause(){return this.queue?.pause(),this.log("info","队列暂停",{instance:this.instanceName}),this}resume(){return this.queue?.resume(),this.log("info","队列恢复",{instance:this.instanceName}),this}get length(){return this.queue?.length()||0}get running(){return this.queue?.running()||0}get workersList(){return this.queue?.workersList()||[]}get idle(){return this.queue?.idle()||!1}get stats(){return{length:this.length,running:this.running,concurrency:this.concurrency,idle:this.idle}}getName(){return this.instanceName}setTaskHandler(e){this.taskHandler=e,this.log("info","任务处理器已更新",{instance:this.instanceName})}destroy(){this.queue&&(this.queue.kill(),this.queue=null),this.isInitialized=!1,this.log("info","队列已销毁",{instance:this.instanceName})}log(e,t,r){try{const s=o.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[AsyncQueue:${this.instanceName}] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [AsyncQueue:${this.instanceName}] ${t}`,r||"")}}setLogLevel(e){this.logLevel=e;try{o.ServiceLocator.get("DebugManager").setLogLevel(e)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}this.log("info",`设置日志等级: ${e}`)}getLogLevel(){return this.logLevel}static getInstance(e="default",t={}){if(i.instances.has(e)){const r=i.instances.get(e);if(r.isInitialized&&r.queue)return void 0!==t.logLevel&&t.logLevel!==r.logLevel&&r.setLogLevel(t.logLevel),t.concurrency&&t.concurrency!==r.concurrency&&r.updateConcurrency(t.concurrency),r;i.instances.delete(e)}const r=new i(e,t);return i.instances.set(e,r),r}static getInstanceNames(){return Array.from(i.instances.keys())}static getAllInstancesStats(){const e={};return i.instances.forEach((t,r)=>{e[r]=t.stats}),e}static destroyInstance(e="default"){if(i.instances.has(e)){const t=i.instances.get(e);t?.isInitialized&&t.queue&&t.destroy(),i.instances.delete(e),console.log(`[AsyncQueue] 已销毁实例: ${e}`)}}static destroyAllInstances(){const e=Array.from(i.instances.keys());e.forEach(e=>{i.destroyInstance(e)}),console.log(`[AsyncQueue] 已销毁所有实例: ${e.join(", ")}`)}static hasInstance(e="default"){return i.instances.has(e)}static getExistingInstance(e="default"){return i.instances.get(e)||null}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}verbose(e,t){this.log("verbose",e,t)}}t.AsyncQueueSingleton=i,i.instances=new Map},896:e=>{e.exports=require("fs")},928:e=>{e.exports=require("path")}},t={};function r(s){var n=t[s];if(void 0!==n)return n.exports;var o=t[s]={exports:{}};return e[s].call(o.exports,o,o.exports,r),o.exports}r.c=t;var s=r(r.s=435);module.exports=s})();
|
|
1
|
+
(()=>{"use strict";var e={171:e=>{e.exports=require("winston-daily-rotate-file")},298:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getFormattedDate=function(e=!1){const t=new Date,r=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),n=String(t.getDate()).padStart(2,"0");return e?`${r}-${s}-${n} ${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`:`${r}-${s}-${n}`},t.getMainDirectory=function(){const e=r(928);return r.c[r.s]?e.dirname(r.c[r.s].filename):process.cwd()}},306:e=>{e.exports=require("winston")},330:e=>{e.exports=JSON.parse('{"name":"proxy-pool-manager","version":"1.0.7","description":"proxy manager","main":"./dist/index.js","types":"./dist/index.d.ts","files":["dist","package.json"],"scripts":{"build":"webpack --mode=production && tsc --emitDeclarationOnly --outDir dist","dev":"webpack --mode=development","watch":"webpack --watch --mode=development","build:analyze":"webpack --mode=production --analyze","prepublishOnly":"npm run build"},"author":"memeak","license":"ISC","devDependencies":{"@types/node":"^22.5.4","@webpack-cli/generators":"^3.0.7","clean-webpack-plugin":"^4.0.0","ts-loader":"^9.5.1","typescript":"^5.6.2","webpack":"^5.94.0","webpack-cli":"^5.1.4"},"dependencies":{"async":"^3.2.6","mongoose":"^7.8.7","node-fetch":"^2.7.0","winston":"^3.18.3","winston-daily-rotate-file":"^5.0.0"},"packageManager":"pnpm@10.18.2+sha512.9fb969fa749b3ade6035e0f109f0b8a60b5d08a1a87fdf72e337da90dcc93336e2280ca4e44f2358a649b83c17959e9993e777c2080879f3801e6f0d999ad3dd"}')},331:e=>{e.exports=require("mongoose")},378:function(e,t,r){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Request=void 0;const n=s(r(867)),o=r(388);class i{constructor(e={}){if(this.proxyManager=null,this.hasProxyManager=!1,void 0!==e.maxRetries&&(e.maxRetries<0||!Number.isInteger(e.maxRetries)))throw new Error("maxRetries 必须是非负整数");if(void 0!==e.timeout&&e.timeout<=0)throw new Error("timeout 必须是正数");if(void 0!==e.retryDelay&&e.retryDelay<0)throw new Error("retryDelay 必须是非负数");if(void 0!==e.retryDelayBase&&e.retryDelayBase<=0)throw new Error("retryDelayBase 必须是正数");if(void 0!==e.retryDelayMultiplier&&e.retryDelayMultiplier<=0)throw new Error("retryDelayMultiplier 必须是正数");this.maxRetries=e.maxRetries??3,this.timeout=e.timeout??30,this.logLevel=e.logLevel||"none",this.proxyStrategy=e.proxyStrategy||"sequential",this.retryDelay=e.retryDelay??null,this.retryDelayBase=e.retryDelayBase??1e3,this.retryDelayMultiplier=e.retryDelayMultiplier??2;try{const t=e.instanceId||"default";this.proxyManager=o.ServiceLocator.get(`ProxyManager-${t}`),this.hasProxyManager=!0,this.log("info","成功获取 ProxyManager 实例",{instanceId:t})}catch(t){this.hasProxyManager=!1,this.log("info","ProxyManager 未初始化,将以轻量级模式运行(不使用代理管理功能)",{instanceId:e.instanceId||"default"})}}setLogLevel(e){try{o.ServiceLocator.get("DebugManager").setLogLevel(e),this.log("info",`设置日志等级: ${e}`)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}}getLogLevel(){try{return o.ServiceLocator.get("DebugManager").getLogLevel()}catch(e){return"info"}}log(e,t,r){try{const s=o.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[Request] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [Request] ${t}`,r||"")}}async selectProxy(e){if(e.options.proxy){const t=e.options.proxy;return this.hasProxyManager&&this.proxyManager&&await this.proxyManager.addProxy(t).catch(()=>{}),this.log("info","使用请求级别代理",{proxy:t}),t}if(!this.hasProxyManager||!this.proxyManager)return null;const t=this.proxyManager.getProxiesCount();if(0===t)return null;const r=this.proxyManager.getAvailableProxy();return r&&this.log("info","使用策略选择代理",{proxy:r,strategy:this.proxyManager.getProxyStrategy(),index:this.proxyManager.getCurrentProxyIndex()+1,total:t}),r}async executeSingleRequest(e,t){const r=e.options.timeout||this.timeout,s=1e3*r;try{const o=await this.selectProxy(e),i={method:e.method,headers:{},signal:AbortSignal.timeout(s)},a=e.options?{...e.options}:{};o&&(a.proxy=o),Object.keys(a).length>0&&(i.body=JSON.stringify(a),i.headers["Content-Type"]="application/json"),this.log("info",`开始请求 ${e.url} (尝试 ${t}/${this.maxRetries})`,{method:e.method,timeout:r,hasProxy:!!o});const c=Date.now(),l=await(0,n.default)(e.url,i),h=Date.now()-c;if(!l.ok)throw new Error(`HTTP Error: ${l.status} ${l.statusText}`);const u=await l.text();let g;try{g=JSON.parse(u)}catch{g=u}const y={status_code:l.status,success:l.ok,headers:Object.fromEntries(l.headers.entries()),data:g,error:l.ok?void 0:u,timestamp:(new Date).toISOString()};if(this.hasProxyManager&&this.proxyManager){const e=this.proxyManager.getCurrentProxy();e&&await this.proxyManager.recordProxyUsage(e,y.success,h).catch(()=>{})}return y}catch(s){if("TimeoutError"===s.name||"AbortError"===s.name)throw this.log("warn",`请求超时 (${r}s)`,{url:e.url,attempt:t}),new Error(`请求超时: ${r}秒`);if(this.hasProxyManager&&this.proxyManager){const e=this.proxyManager.getCurrentProxy();e&&this.proxyManager.shouldRotateProxy(s)&&(this.log("error",`代理 ${e} 出现问题,尝试轮换`,{error:s.message}),await this.proxyManager.rotateProxy().catch(()=>{}))}throw s}}isValidStatusCode(e){return e>=200&&e<300}async get(e,t={}){let r=e;return t.params&&Object.keys(t.params).length>0&&(r=`${e}?${new URLSearchParams(t.params).toString()}`),this.request({url:r,method:"GET",options:t})}async post(e,t={}){return this.request({url:e,method:"POST",options:t})}async put(e,t={}){return this.request({url:e,method:"PUT",options:t})}async delete(e,t={}){return this.request({url:e,method:"DELETE",options:t})}async patch(e,t={}){return this.request({url:e,method:"PATCH",options:t})}async request(e){const t={url:e.url,method:e.method,options:{...e.options,timeout:e.options.timeout||this.timeout}};for(let e=1;e<=this.maxRetries;e++)try{const r=await this.executeSingleRequest(t,e),s={status:r.status_code,statusText:this.getStatusText(r.status_code),headers:r.headers||{},error:r.error?String(r.error):null,errors:[],data:r.data,text:()=>"string"==typeof r.data?r.data:JSON.stringify(r.data),json:()=>r.data,buffer:()=>Buffer.from("string"==typeof r.data?r.data:JSON.stringify(r.data||{}))};return this.log("info","请求成功",{url:t.url,status:s.status,attempt:e}),s}catch(r){const s=r.message;if(this.log("error","请求失败",{attempt:e,maxRetries:this.maxRetries,url:t.url,error:s}),(s.includes("超时")||"TimeoutError"===r.name)&&this.log("warn",`请求超时,尝试 ${e}/${this.maxRetries}`),this.hasProxyManager&&this.proxyManager&&e<this.maxRetries){if(0===this.proxyManager.getAvailableProxiesList().length){this.log("warn","无可用代理,停止重试");break}if(!t.options.proxy&&this.proxyManager.shouldRotateProxy(r)){const e=await this.proxyManager.rotateProxy().catch(()=>null);e&&this.log("info",`代理轮换成功,使用新代理: ${e}`)}}if(e<this.maxRetries){let t;null!==this.retryDelay?(t=this.retryDelay,this.log("info",`等待 ${t}ms 后重试(固定间隔)`)):(t=this.retryDelayBase*Math.pow(this.retryDelayMultiplier,e-1),this.log("info",`等待 ${t}ms 后重试(指数退避:基础 ${this.retryDelayBase}ms,倍数 ${this.retryDelayMultiplier})`)),await new Promise(e=>setTimeout(e,t))}}throw new Error(`${e.options.url} 请求失败,已尝试 ${this.maxRetries} 次都失败了`)}getStatusText(e){return{200:"OK",201:"Created",202:"Accepted",204:"No Content",400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable"}[e]||`Status ${e}`}getCurrentProxy(){return this.hasProxyManager&&this.proxyManager?this.proxyManager.getCurrentProxy():null}async rotateProxy(){if(!this.hasProxyManager||!this.proxyManager)throw new Error("ProxyManager 未初始化,无法轮换代理");return await this.proxyManager.rotateProxy()}resetProxyUsage(){this.hasProxyManager&&this.proxyManager&&this.proxyManager.resetProxyUsage()}setProxyStrategy(e){if(!this.hasProxyManager||!this.proxyManager)throw new Error("ProxyManager 未初始化,无法设置代理策略");this.proxyManager.setProxyStrategy(e)}async checkProxy(e){if(!this.hasProxyManager||!this.proxyManager)throw new Error("ProxyManager 未初始化,无法检查代理");return this.proxyManager.checkProxy(e)}getAvailableProxiesList(){return this.hasProxyManager&&this.proxyManager?this.proxyManager.getAvailableProxiesList():[]}hasProxyManagement(){return this.hasProxyManager}}t.Request=i,t.default=i},388:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ServiceLocator=void 0;class r{static shouldLog(e){try{if(this.services.has("DebugManager")){const t=this.services.get("DebugManager");if(t&&"function"==typeof t.getLogLevel){const r=t.getLogLevel(),s={none:0,error:1,warn:2,info:3,debug:4,verbose:5},n=s[r]||0;return(s[e]||0)<=n}}}catch(e){}return"error"===e||"warn"===e}static shouldLogForService(e,t){if(["DebugManager","AsyncQueue"].includes(e)&&("debug"===t||"verbose"===t)){try{if(this.services.has("DebugManager")){const e=this.services.get("DebugManager");if(e&&"function"==typeof e.getLogLevel)return"verbose"===e.getLogLevel()}}catch(e){}return!1}return this.shouldLog(t)}static get(e){if(this.services.has(e)){const t=this.services.get(e);return this.shouldLogForService(e,"debug")&&this.log("debug",`返回已注册的服务实例: ${e}`,{serviceType:this.getServiceType(t)}),t}if(this.dependencies.has(e)){this.shouldLogForService(e,"debug")&&this.log("debug",`通过工厂创建服务: ${e}`);const t=this.dependencies.get(e)();return this.services.set(e,t),this.shouldLogForService(e,"debug")&&this.log("debug",`工厂创建服务完成: ${e}`,{serviceType:this.getServiceType(t)}),t}const t=new Error(`[ServiceLocator] 服务未注册: ${e}`);throw this.log("error","服务未注册",{serviceName:e,availableServices:this.getAvailableServiceNames(),error:t.message}),t}static has(e){const t=this.services.has(e)||this.dependencies.has(e);return this.shouldLogForService(e,"debug")&&this.log("debug",`检查服务存在性: ${e}`,{exists:t,hasInstance:this.services.has(e),hasFactory:this.dependencies.has(e)}),t}static register(e,t){this.services.set(e,t),this.shouldLogForService(e,"info")&&this.log("info",`注册服务: ${e}`,{serviceType:this.getServiceType(t),hasFactory:this.dependencies.has(e)})}static registerFactory(e,t){this.dependencies.set(e,t),this.shouldLogForService(e,"info")&&this.log("info",`注册服务工厂: ${e}`,{hasExistingInstance:this.services.has(e)})}static log(e,t,r){if(!this.shouldLog(e))return;try{if(this.services.has("DebugManager")){const s=this.services.get("DebugManager");if(s&&"function"==typeof s.log)return e.toUpperCase(),void s.log(e,`[ServiceLocator] ${t}`,r)}}catch(e){}const s=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${s} [ServiceLocator] ${t}`,r||"")}static getAvailableServiceNames(){const e=Array.from(this.services.keys()),t=Array.from(this.dependencies.keys()),r=[...new Set([...e,...t])];return this.shouldLog("debug")&&this.log("debug","获取可用服务名称",{total:r.length,services:e,factories:t}),r}static getStats(){const e=Array.from(this.services.keys()),t=Array.from(this.dependencies.keys()),r={totalServices:e.length,totalFactories:t.length,serviceNames:e,factoryNames:t};return this.shouldLog("debug")&&this.log("debug","服务统计",r),r}static isInitialized(){const e=this.has("DebugManager");return this.shouldLog("debug")&&this.log("debug","检查服务定位器初始化状态",{hasDebugManager:e,totalServices:this.services.size,totalFactories:this.dependencies.size}),e}static getServiceType(e){return e?e.constructor&&e.constructor.name?e.constructor.name:"function"==typeof e?"Function":Array.isArray(e)?"Array":"object"==typeof e?"Object":typeof e:"null"}static registerMultiple(e){const t=Object.keys(e);this.log("info","批量注册服务",{count:t.length,services:t}),Object.entries(e).forEach(([e,t])=>{this.register(e,t)})}static safeGet(e,t){try{return this.get(e)}catch(r){return this.log("warn",`安全获取服务失败: ${e}`,{error:r.message,usingDefault:void 0!==t}),t}}static reset(){this.services.clear(),this.dependencies.clear(),this.log("info","服务定位器已重置")}static initialize(){this.log("info","服务定位器初始化",{nodeEnv:"production"})}static clear(){const e=this.services.size,t=this.dependencies.size;this.services.clear(),this.dependencies.clear(),this.log("info","所有服务已清除",{clearedServices:e,clearedFactories:t})}static removeService(e){const t=this.services.has(e),r=this.dependencies.has(e);return this.services.delete(e),this.dependencies.delete(e),!(!t&&!r||(this.log("info",`移除服务: ${e}`,{hadService:t,hadFactory:r}),0))}static getExistingInstance(e){if(this.services.has(e))return this.services.get(e)}static hasOnlyFactory(e){return!this.services.has(e)&&this.dependencies.has(e)}static getCounts(){const e=this.services.size,t=this.dependencies.size,r=e+t;return this.shouldLog("debug")&&this.log("debug","服务数量统计",{instances:e,factories:t,total:r}),{instances:e,factories:t,total:r}}}t.ServiceLocator=r,r.services=new Map,r.dependencies=new Map},392:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyUrlBulkInsertManager=void 0;const s=r(388);t.ProxyUrlBulkInsertManager=class{constructor(e,t=500,r=4,s){this.mongoManager=e,this.batchSize=t,this.concurrency=r,s&&this.setLogLevel(s)}setLogLevel(e){try{s.ServiceLocator.get("DebugManager").setLogLevel(e),this.debug="debug"===e||"verbose"===e,this.log("info",`设置日志等级: ${e}`)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}}getLogLevel(){try{return s.ServiceLocator.get("DebugManager").getLogLevel()}catch(e){return this.debug?"debug":"info"}}setDebugMode(e){if(this.debug=e,this.debug)try{let t;try{t=s.ServiceLocator.get("DebugManager")}catch(e){const{DebugManager:n}=r(577);t=n.getInstance(),s.ServiceLocator.register("DebugManager",t),this.log("info","自动注册 DebugManager")}t.setLogLevel(e?"debug":"info"),this.log("info","ProxyUrlBulkInsertManager debug 模式已开启")}catch(e){console.warn("[ProxyUrlBulkInsertManager] DebugManager 自动注册失败,使用本地 debug 模式")}}log(e,t,r){try{const n=s.ServiceLocator.get("DebugManager");e.toUpperCase(),n.log(e,`[ProxyUrlBulkInsertManager] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [ProxyUrlBulkInsertManager] ${t}`,r||"")}}chunkArray(e,t){const r=[];for(let s=0;s<e.length;s+=t)r.push(e.slice(s,s+t));return r}async processInBatches(e,t){let r=0;const s=[];for(const n of e){s.length>=this.concurrency&&await Promise.race(s);const o=t(n).then(t=>{r+=t;const s=Math.round(r/e.flat().length*100);return this.debug&&this.log("info",`已处理 ${r} 条记录 (${s}%)`),t}).catch(e=>{throw this.debug&&this.log("error",`批次处理失败: ${e.message}`),e});s.push(o),s.forEach((e,t)=>{e.then(()=>s.splice(t,1))})}return await Promise.all(s),r}async bulkInsertFromUrls(e){if(0===e.length)return 0;const t=[...new Set(e)];t.length!==e.length&&this.debug&&this.log("info",`检测到 ${e.length-t.length} 个重复URL,已自动去重`),this.debug&&this.log("info",`开始处理 ${t.length} 个代理URL,仅插入不存在的记录`);const r=this.chunkArray(t,this.batchSize);return this.debug&&this.log("info",`拆分为 ${r.length} 个批次,每批 ${this.batchSize} 条`),this.processInBatches(r,e=>this.processUrlBatch(e))}async processUrlBatch(e){if(0===e.length)return 0;const t=await this.mongoManager.findAll({url:{$in:e}}),r=new Set(t.map(e=>e.url)),s=e.filter(e=>!r.has(e));if(0===s.length)return this.debug&&this.log("info",`批次中所有 ${e.length} 个代理已存在,无需插入`),0;const n=s.map(e=>({url:e,totalRequests:0,failCount:0,avgResponseTime:0,lastCheckTime:Date.now(),consecutiveFails:0,status:"valid"}));try{const e=await this.mongoManager.bulkInsert(n);return this.debug&&this.log("info",`批次插入完成,新增 ${e.insertedCount} 个代理`),e.insertedCount}catch(e){throw this.debug&&this.log("error",`批次插入失败: ${e.message}`),e}}}},435:function(e,t,r){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getMainDirectory=t.getFormattedDate=t.VERSION=t.ProxyRequestSDK=t.AsyncQueueSingleton=t.DebugManager=t.ServiceLocator=t.MongoProxyManager=t.ProxyManager=t.Request=t.ProxyUrlBulkInsertManager=void 0,t.initializeServices=y,t.createProxyRequest=async function(e){return await y(e)},t.registerCoreServices=function(e){const t=e.instanceId||`core-${Date.now()}`,r=h.DebugManager.getInstance();e.logLevel&&r.setLogLevel(e.logLevel),l.ServiceLocator.register("DebugManager",r);const s=u.AsyncQueueSingleton.getInstance(t,{logLevel:e.logLevel});l.ServiceLocator.register(`AsyncQueue-${t}`,s);const n=a.ProxyManager.getInstance({mongoUri:e.mongoUri,logLevel:e.logLevel,instanceId:t});l.ServiceLocator.register(`ProxyManager-${t}`,n);const o=new i.Request({mongoUri:e.mongoUri,logLevel:e.logLevel,instanceId:t});l.ServiceLocator.register(`Request-${t}`,o)},t.registerRequestFactory=function(e,t){const r=t||`factory-${Date.now()}`;l.ServiceLocator.registerFactory(`Request-${r}`,e)},t.registerProxyManagerFactory=function(e,t){const r=t||`factory-${Date.now()}`;l.ServiceLocator.registerFactory(`ProxyManager-${r}`,e)},t.bulkInsertProxyUrls=async function(e){const t=new o.ProxyUrlBulkInsertManager(c.MongoProxyManager.getInstance({uri:e.mongoUri,logLevel:e.logLevel}),e.batchSize||500,e.concurrency||4,e.logLevel);return await t.bulkInsertFromUrls(e.proxyUrls)},t.getStandaloneServices=function(e){const t=e.instanceId||`standalone-${Date.now()}`,r=c.MongoProxyManager.getInstance({uri:e.mongoUri,logLevel:e.logLevel}),s=u.AsyncQueueSingleton.getInstance(`standalone-${t}`,{logLevel:e.logLevel});return{proxyManager:a.ProxyManager.getInstance({mongoUri:e.mongoUri,logLevel:e.logLevel,instanceId:t}),request:new i.Request({mongoUri:e.mongoUri,logLevel:e.logLevel,instanceId:t}),mongoManager:r,asyncQueue:s}},t.cleanupServices=function(){l.ServiceLocator.clear(),u.AsyncQueueSingleton.destroyAllInstances(),a.ProxyManager.resetInstance()},t.checkServicesHealth=async function(e,t){try{const r=c.MongoProxyManager.getInstance({uri:e}),s=await r.checkConnection(),n=t||"default",o={DebugManager:l.ServiceLocator.has("DebugManager"),[`ProxyManager-${n}`]:l.ServiceLocator.has(`ProxyManager-${n}`),[`Request-${n}`]:l.ServiceLocator.has(`Request-${n}`),[`AsyncQueue-${n}`]:l.ServiceLocator.has(`AsyncQueue-${n}`)},i=u.AsyncQueueSingleton.getInstanceNames();return{mongo:s,proxyManager:l.ServiceLocator.has(`ProxyManager-${n}`),asyncQueues:i,services:o}}catch(e){return{mongo:!1,proxyManager:!1,asyncQueues:[],services:{}}}};const n=s(r(330)),o=r(392);Object.defineProperty(t,"ProxyUrlBulkInsertManager",{enumerable:!0,get:function(){return o.ProxyUrlBulkInsertManager}});const i=r(378);Object.defineProperty(t,"Request",{enumerable:!0,get:function(){return i.Request}});const a=r(696);Object.defineProperty(t,"ProxyManager",{enumerable:!0,get:function(){return a.ProxyManager}});const c=r(862);Object.defineProperty(t,"MongoProxyManager",{enumerable:!0,get:function(){return c.MongoProxyManager}});const l=r(388);Object.defineProperty(t,"ServiceLocator",{enumerable:!0,get:function(){return l.ServiceLocator}});const h=r(577);Object.defineProperty(t,"DebugManager",{enumerable:!0,get:function(){return h.DebugManager}});const u=r(892);Object.defineProperty(t,"AsyncQueueSingleton",{enumerable:!0,get:function(){return u.AsyncQueueSingleton}});class g{constructor(e){this.proxyManagerInstance=null,this.bulkInsertManager=null,this.isInitialized=!1,this.instanceId=e.instanceId||`sdk-${Date.now()}`,e.logLevel&&this.setLogLevel(e.logLevel);const t=!!(e.proxies&&e.proxies.length>0)||!!e.proxy;if((e.mongoUri||e.proxyCheckOptions||t)&&!t&&!e.proxyCheckOptions?.mainUrl&&!1!==e.proxyCheckEnabled)throw new Error("启用代理管理功能时,proxyCheckOptions.mainUrl 必须设置(除非 proxyCheckEnabled 为 false 或提供了代理数组)");if(!l.ServiceLocator.has("DebugManager")){const t=h.DebugManager.getInstance();e.logLevel&&t.setLogLevel(e.logLevel),l.ServiceLocator.register("DebugManager",t),this.log("info","注册 DebugManager")}if(!l.ServiceLocator.has(`AsyncQueue-${this.instanceId}`)){const t=u.AsyncQueueSingleton.getInstance(this.instanceId,{logLevel:e.logLevel});l.ServiceLocator.register(`AsyncQueue-${this.instanceId}`,t),this.log("info","注册 AsyncQueue",{instanceId:this.instanceId})}try{if(!l.ServiceLocator.has(`Request-${this.instanceId}`))throw new Error("Request 服务未注册。请使用 createProxyRequest() 或 initializeServices() 创建 SDK 实例,不要直接 new ProxyRequestSDK()。");this.requestInstance=l.ServiceLocator.get(`Request-${this.instanceId}`),l.ServiceLocator.has(`ProxyManager-${this.instanceId}`)?(this.proxyManagerInstance=l.ServiceLocator.get(`ProxyManager-${this.instanceId}`),this.log("info","使用已注册的服务实例(包含代理管理)",{instanceId:this.instanceId})):(this.proxyManagerInstance=null,this.log("info","使用已注册的服务实例(轻量级模式,无代理管理)",{instanceId:this.instanceId}))}catch(e){const t=e?.message||String(e);if(t.includes("请使用 createProxyRequest"))throw e;throw this.log("error","服务未正确初始化",{error:t}),new Error(`服务初始化失败: ${t}。请使用 createProxyRequest() 或 initializeServices() 创建实例。`)}e.mongoUri&&(this.bulkInsertManager=new o.ProxyUrlBulkInsertManager(c.MongoProxyManager.getInstance({uri:e.mongoUri}),500,4,e.logLevel)),this.initializeAsync(e).catch(e=>{console.error("SDK初始化失败:",e)})}log(e,t,r){try{const s=l.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[ProxyRequestSDK:${this.instanceId}] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e?console.debug:console.info)(`${n} [ProxyRequestSDK:${this.instanceId}] ${t}`,r||"")}}async initializeAsync(e){try{this.proxyManagerInstance&&await this.proxyManagerInstance.waitForInitialization(),this.isInitialized=!0,this.log("info","初始化完成",{hasProxyManagement:!!this.proxyManagerInstance})}catch(e){throw this.log("error","初始化失败:",e),e}}async waitForReady(){for(;!this.isInitialized;)await new Promise(e=>setTimeout(e,100))}setLogLevel(e){try{l.ServiceLocator.get("DebugManager").setLogLevel(e),this.log("info",`设置日志等级: ${e}`)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}}getLogLevel(){try{return l.ServiceLocator.get("DebugManager").getLogLevel()}catch(e){return"info"}}getServiceInfo(){const e=["DebugManager",`ProxyManager-${this.instanceId}`,`Request-${this.instanceId}`,`AsyncQueue-${this.instanceId}`],t={};return e.forEach(e=>{t[e]=l.ServiceLocator.has(e)}),u.AsyncQueueSingleton.getInstanceNames().forEach(e=>{t[`AsyncQueue:${e}`]=!0}),t.hasProxyManagement=this.hasProxyManagement(),t}async get(e,t,r){await this.waitForReady();const s={...r,params:t?{...r?.params,...t}:r?.params};return this.requestInstance.get(e,s)}async post(e,t){return await this.waitForReady(),this.requestInstance.post(e,t)}async put(e,t){return await this.waitForReady(),this.requestInstance.put(e,t)}async delete(e,t){return await this.waitForReady(),this.requestInstance.delete(e,t)}async patch(e,t){return await this.waitForReady(),this.requestInstance.patch(e,t)}async request(e){return await this.waitForReady(),this.requestInstance.request({url:e.url,method:e.method||"GET",options:e.options||{}})}async addProxy(e){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.addProxy(e)}async deleteProxy(e){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.deleteProxy(e)}getAvailableProxies(){return this.proxyManagerInstance?this.proxyManagerInstance.getAvailableProxiesList():[]}getCurrentProxy(){return this.proxyManagerInstance?this.proxyManagerInstance.getCurrentProxy():null}async rotateProxy(){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.rotateProxy()}setProxyStrategy(e){if(!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");this.proxyManagerInstance.setProxyStrategy(e)}async checkProxy(e){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.checkProxy(e)}async triggerProxyCheck(){if(await this.waitForReady(),!this.proxyManagerInstance)throw new Error("代理管理功能未启用,请提供 mongoUri 或 proxyCheckOptions 来启用此功能");return this.proxyManagerInstance.triggerProxyCheck()}hasProxyManagement(){return!!this.proxyManagerInstance}async bulkInsertProxies(e){if(await this.waitForReady(),!this.bulkInsertManager)throw new Error("批量插入功能需要提供 mongoUri");return this.bulkInsertManager.bulkInsertFromUrls(e)}async getProxyStats(){if(await this.waitForReady(),!this.proxyManagerInstance)return{total:0,valid:0,invalid:0,available:0};const e=this.getAvailableProxies(),t=this.proxyManagerInstance?this.proxyManagerInstance.getProxiesCount():0;return{total:t,valid:e.length,invalid:t-e.length,available:e.length}}getProxyDetails(e){if(this.proxyManagerInstance)return this.proxyManagerInstance.getProxyDetails(e)}getQueueStats(){if(!this.proxyManagerInstance)throw new Error("代理管理功能未启用,无法获取队列统计");return this.proxyManagerInstance.getQueueStats()}getInstanceId(){return this.instanceId}async destroy(){this.log("info","开始清理资源"),this.bulkInsertManager&&("function"==typeof this.bulkInsertManager.destroy&&await this.bulkInsertManager.destroy(),this.bulkInsertManager=null),[`ProxyManager-${this.instanceId}`,`Request-${this.instanceId}`,`AsyncQueue-${this.instanceId}`].forEach(e=>{l.ServiceLocator.has(e)&&(l.ServiceLocator.removeService(e),this.log("info",`清理服务: ${e}`))}),u.AsyncQueueSingleton.destroyInstance(this.instanceId),this.proxyManagerInstance&&(await this.proxyManagerInstance.destroy(),this.proxyManagerInstance=null),this.isInitialized=!1,this.log("info","资源清理完成")}}async function y(e){const t=e.instanceId||`instance-${Date.now()}`,r=!!(e.proxies&&e.proxies.length>0)||!!e.proxy,s=!!(e.mongoUri||e.proxyCheckOptions||r);if(s&&!r&&void 0===e.proxyCheckOptions?.mainUrl&&!1!==e.proxyCheckEnabled)throw new Error("启用代理管理功能时,proxyCheckOptions.mainUrl 必须设置(除非 proxyCheckEnabled 为 false 或提供了代理数组)");let n;[`ProxyManager-${t}`,`Request-${t}`,`AsyncQueue-${t}`].forEach(e=>{if(l.ServiceLocator.has(e)){if(e.startsWith("ProxyManager-"))try{const t=l.ServiceLocator.get(e);t&&"function"==typeof t.destroy&&t.destroy().catch(e=>{console.warn(`清理 ProxyManager 失败: ${e.message}`)})}catch(e){console.warn(`获取 ProxyManager 服务失败: ${e.message}`)}if(e.startsWith("AsyncQueue-")){const t=e.replace("AsyncQueue-","");u.AsyncQueueSingleton.destroyInstance(t)}l.ServiceLocator.removeService(e)}}),l.ServiceLocator.initialize(),l.ServiceLocator.has("DebugManager")?(n=l.ServiceLocator.get("DebugManager"),e.logLevel&&n.setLogLevel(e.logLevel)):(n=h.DebugManager.getInstance(),e.logLevel&&n.setLogLevel(e.logLevel),l.ServiceLocator.register("DebugManager",n));const o=`AsyncQueue-${t}`;let c;if(u.AsyncQueueSingleton.hasInstance(t)){if(c=u.AsyncQueueSingleton.getExistingInstance(t),c&&void 0!==e.logLevel)try{const t=l.ServiceLocator.get("DebugManager");e.logLevel&&t.setLogLevel(e.logLevel)}catch(e){console.warn("DebugManager未注册,无法更新debug状态")}}else c=u.AsyncQueueSingleton.getInstance(t,{logLevel:e.logLevel});l.ServiceLocator.register(o,c);let y=null;const d=`ProxyManager-${t}`;if(s)l.ServiceLocator.has(d)?(y=l.ServiceLocator.get(d),e.proxyStrategy&&y.setProxyStrategy(e.proxyStrategy),e.maxConcurrentChecks&&y.setMaxConcurrentChecks(e.maxConcurrentChecks)):y=a.ProxyManager.getInstance({mongoUri:e.mongoUri,proxies:e.proxies,proxy:e.proxy,proxyLimit:e.proxyLimit,proxyStrategy:e.proxyStrategy,maxConcurrentChecks:e.maxConcurrentChecks,logLevel:e.logLevel,proxyCheckOptions:e.proxyCheckOptions,proxyCheckEnabled:e.proxyCheckEnabled,instanceId:t}),await y.waitForInitialization(),l.ServiceLocator.register(d,y);else try{l.ServiceLocator.get("DebugManager").log("info","以轻量级模式运行(不使用代理管理功能)",{instanceId:t})}catch(e){console.info("以轻量级模式运行(不使用代理管理功能)",{instanceId:t})}const p=`Request-${t}`;let x;if(x=l.ServiceLocator.has(p)?l.ServiceLocator.get(p):new i.Request({maxRetries:e.maxRetries,timeout:e.timeout,logLevel:e.logLevel,retryDelay:e.retryDelay,retryDelayBase:e.retryDelayBase,retryDelayMultiplier:e.retryDelayMultiplier,instanceId:t}),l.ServiceLocator.register(p,x),e.logLevel&&"none"!==e.logLevel&&"error"!==e.logLevel)try{l.ServiceLocator.get("DebugManager").log("info","服务初始化完成",{instanceId:t,mongoUri:e.mongoUri,hasProxyManagement:s,proxyCount:y?y.getProxiesCount():0})}catch(r){console.info("服务初始化完成",{instanceId:t,mongoUri:e.mongoUri,hasProxyManagement:s,proxyCount:y?y.getProxiesCount():0})}return new g({...e,instanceId:t})}t.ProxyRequestSDK=g,t.default=g,t.VERSION=n.default.version;var d=r(298);Object.defineProperty(t,"getFormattedDate",{enumerable:!0,get:function(){return d.getFormattedDate}}),Object.defineProperty(t,"getMainDirectory",{enumerable:!0,get:function(){return d.getMainDirectory}})},577:function(e,t,r){var s,n=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,n)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(s=function(e){return s=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},s(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=s(e),i=0;i<r.length;i++)"default"!==r[i]&&n(t,e,r[i]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.safeLog=t.debugManager=t.DebugManager=void 0;const a=i(r(896)),c=i(r(928)),l=i(r(306));r(171);class h{constructor(){this.logLevel="info",this.logLevelPriority={none:0,error:1,warn:2,info:3,debug:4,verbose:5},this.initializeLogger()}static getInstance(){return h.instance||(h.instance=new h),h.instance}initializeLogger(){const e=c.join(process.cwd(),"logs");a.existsSync(e)||a.mkdirSync(e,{recursive:!0});const t=l.format.combine(l.format.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),l.format.printf(({timestamp:e,level:t,message:r,...s})=>{let n=`${e} [${t.toUpperCase()}] ${r}`;if(Object.keys(s).length>0){const{timestamp:e,level:t,message:r,...o}=s;if(Object.keys(o).length>0)try{n+=` | ${JSON.stringify(o)}`}catch{n+=` | ${String(o)}`}}return n}));this.logger=l.createLogger({level:this.getWinstonLevel(this.logLevel),format:t,transports:[new l.transports.Console({format:t}),new l.transports.DailyRotateFile({filename:c.join(e,"%DATE%.log"),format:t,datePattern:"YYYY/MM/DD",maxFiles:null})]})}getWinstonLevel(e){return{none:"error",error:"error",warn:"warn",info:"info",debug:"debug",verbose:"verbose"}[e]}setLogLevel(e){this.logLevel=e,this.logger.level=this.getWinstonLevel(e)}getLogLevel(){return this.logLevel}logInternal(e,t,r){const s=`[${e.toUpperCase()}]`;this.logger.log(this.getWinstonLevel(e),`${s} [DebugManager] ${t}`,r)}log(e,t,r){this.logger.log(this.getWinstonLevel(e),t,r)}error(e,t){this.log("error",e,t)}warn(e,t){this.log("warn",e,t)}info(e,t){this.log("info",e,t)}debug(e,t){this.log("debug",e,t)}verbose(e,t){this.log("verbose",e,t)}}t.DebugManager=h,t.debugManager=h.getInstance(),t.safeLog=t.debugManager.log.bind(t.debugManager)},626:e=>{e.exports=require("async")},696:function(e,t,r){var s,n=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,n)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(s=function(e){return s=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},s(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=s(e),i=0;i<r.length;i++)"default"!==r[i]&&n(t,e,r[i]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.ProxyManager=void 0;const a=r(862),c=r(892),l=r(388);class h{constructor(e={}){this.mongoClient=null,this.isInitialized=!1,this.initializationPromise=null,this.needsMongoDB=!0,this.currentPage=0,this.pageSize=2e3,this.hasMorePages=!0,this.totalLoaded=0,this.instanceId=e.instanceId||`proxy-pool-manager-${Date.now()}`,this.logLevel=e.logLevel||"none",this.proxyCheckEnabled=e.proxyCheckEnabled??!0,this.proxyStrategy=e.proxyStrategy??"sequential",this.availableProxies=new Set,this.checkInProgress=new Set,this.maxConcurrentChecks=e.maxConcurrentChecks??5,this.proxyLimit=e.proxyLimit??0;const t=Array.isArray(e.proxies)&&e.proxies.length>0||!!e.proxy,r=0!==this.proxyLimit||t||this.proxyCheckEnabled;if(!e.mongoUri&&r&&0!==this.proxyLimit&&!t)throw new Error("ProxyManager实例化时,mongoUri 未设置(需要从数据库加载代理)");e.mongoUri?(this.mongoClient=a.MongoProxyManager.getInstance({uri:e.mongoUri}),this.needsMongoDB=!0):(this.needsMongoDB=!1,this.log("info","未提供 mongoUri,将跳过 MongoDB 连接(仅使用内存中的代理)")),this.asyncQueue=c.AsyncQueueSingleton.getInstance(this.instanceId,{concurrency:this.maxConcurrentChecks,autoStart:!0,logLevel:this.logLevel,onDrain:()=>{this.log("info","所有代理检测任务完成")},onError:e=>{this.log("error","代理检测任务出错:",e)},onSuccess:e=>{},taskHandler:async e=>(await new Promise(e=>setTimeout(e,1e3)),await this.taskHandler(e))}),this.proxies=[],Array.isArray(e.proxies)?e.proxies.forEach(e=>{this.addProxySync(e)}):e.proxy&&this.addProxySync(e.proxy),this.proxyCheckOptions={mainUrl:e.proxyCheckOptions?.mainUrl||"",testUrls:e.proxyCheckOptions?.testUrls??["http://httpbin.org/ip","http://api.ipify.org?format=json","http://ipinfo.io/json"],timeout:e.proxyCheckOptions?.timeout??5,successStatusCodes:e.proxyCheckOptions?.successStatusCodes??[200],checkInterval:e.proxyCheckOptions?.checkInterval??6e4,maxConsecutiveFails:e.proxyCheckOptions?.maxConsecutiveFails??3,maxResponseTime:e.proxyCheckOptions?.maxResponseTime??2e3},this.currentProxyIndex=0,this.usedProxies=new Set,this.initializationPromise=this.initializeAsync()}async initializeAsync(){try{this.needsMongoDB&&this.mongoClient?(await this.mongoClient.ensureConnected(),0!==this.proxyLimit?await this.loadProxiesFromDB():this.log("info","proxyLimit 设置为 0,跳过从数据库加载代理")):this.log("info","跳过 MongoDB 连接(不需要代理管理功能)"),this.isInitialized=!0,this.log("info",`ProxyManager初始化完成,加载了 ${this.proxies.length} 个代理`)}catch(e){throw this.log("error","ProxyManager初始化失败:",e),e}}async waitForInitialization(){if(!this.isInitialized){if(!this.initializationPromise)throw new Error("ProxyManager未正确初始化");await this.initializationPromise}}addProxySync(e){if(!this.proxies.find(t=>t.url===e)){const t={url:e,totalRequests:0,failCount:0,avgResponseTime:0,lastCheckTime:Date.now(),consecutiveFails:0,status:"valid"};this.proxies.push(t),this.availableProxies.add(e),this.mongoClient&&this.mongoClient.upsert(t).catch(t=>{this.log("error",`保存代理到数据库失败: ${e}`,t)})}}static getInstance(e={}){const t=e.instanceId||`proxy-pool-manager-${Date.now()}`;if(h.instances.has(t))return h.instances.get(t);h.instanceLock=!0;try{if(h.instances.has(t))return h.instances.get(t);const r=new h({...e,instanceId:t});return h.instances.set(t,r),r}finally{h.instanceLock=!1}}static resetInstance(e){if(void 0!==e){const t=h.instances.get(e);t&&(t.destroy(),h.instances.delete(e))}else h.instances.forEach(e=>e.destroy()),h.instances.clear()}log(e,t,r){try{const s=l.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[ProxyManager] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [ProxyManager] ${t}`,r||"")}}setLogLevel(e){try{l.ServiceLocator.get("DebugManager").setLogLevel(e),this.log("info",`设置日志等级: ${e}`)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}}getLogLevel(){try{return l.ServiceLocator.get("DebugManager").getLogLevel()}catch(e){return"info"}}async loadProxiesFromDB(e={},t=!1){try{if(t&&(this.currentPage=0,this.totalLoaded=0,this.hasMorePages=!0,this.proxies=[],this.log("info","重置分页查询状态")),!this.hasMorePages&&!t)return void this.log("info","没有更多代理可加载");const r={status:"valid",...e};if(!this.mongoClient)return this.log("info","MongoDB 客户端未初始化,跳过代理加载"),void(this.hasMorePages=!1);if(0===this.proxyLimit)return this.log("info","proxyLimit 为 0,跳过代理加载"),void(this.hasMorePages=!1);const s=this.currentPage*this.pageSize,n=this.proxyLimit>0?Math.min(this.proxyLimit,this.pageSize):this.pageSize;this.log("debug","分页查询代理",{page:this.currentPage+1,pageSize:n,skip:s,query:r});const o=await this.mongoClient.findLimited(r,n,s);if(o.length<n?(this.hasMorePages=!1,this.log("info",`已加载最后一页,共 ${o.length} 个代理`)):(this.hasMorePages=!0,this.currentPage++,this.log("info",`加载第 ${this.currentPage} 页,共 ${o.length} 个代理`)),this.totalLoaded+=o.length,1===this.currentPage||t)this.proxies=o;else{const e=new Set(this.proxies.map(e=>e.url)),t=o.filter(t=>!e.has(t.url));this.proxies.push(...t)}this.availableProxies.clear(),this.proxies.forEach(e=>this.availableProxies.add(e.url)),this.log("info","从数据库加载代理完成",{totalInMemory:this.proxies.length,available:this.availableProxies.size,currentPage:this.currentPage,hasMorePages:this.hasMorePages,totalLoaded:this.totalLoaded})}catch(e){throw this.log("error","从数据库加载代理失败:",e.message),e}}async loadNextPage(){if(await this.waitForInitialization(),!this.hasMorePages)return this.log("info","没有更多代理页面,返回第一页"),await this.loadProxiesFromDB({},!0),this.proxies.length;const e=this.proxies.length;return await this.loadProxiesFromDB({},!1),this.proxies.length-e}async resetPagination(){await this.waitForInitialization(),await this.loadProxiesFromDB({},!0)}getPaginationInfo(){return{currentPage:this.currentPage,pageSize:this.pageSize,hasMorePages:this.hasMorePages,totalLoaded:this.totalLoaded,totalInMemory:this.proxies.length}}async addProxy(e){if(!e?.trim())throw new Error("代理URL不能为空");await this.waitForInitialization();let t=this.proxies.find(t=>t.url===e);if(t)return this.log("info","代理已存在于内存中",{proxy:e}),t;if(this.mongoClient&&(t=await this.mongoClient.findByUrl(e),t))return"valid"===t.status&&(this.proxies.push(t),this.availableProxies.add(e),this.log("info","从数据库加载现有代理",{proxy:e,status:t.status})),t;const r={url:e,totalRequests:0,failCount:0,avgResponseTime:0,lastCheckTime:Date.now(),consecutiveFails:0,status:"valid"},s=this.mongoClient?await this.mongoClient.upsert(r):r;return this.proxies.push(s),this.availableProxies.add(e),this.log("info","添加新代理到数据库",{proxy:e}),s}async deleteProxy(e){if(await this.waitForInitialization(),!this.mongoClient){const t=this.proxies.findIndex(t=>t.url===e);return-1!==t&&(this.proxies.splice(t,1),this.availableProxies.delete(e),this.log("info","从内存中删除代理",{proxy:e}),!0)}const t=await this.mongoClient.delete(e);return t&&(this.proxies=this.proxies.filter(t=>t.url!==e),this.availableProxies.delete(e),this.log("info","删除代理",{proxy:e})),t}async deleteInvalidProxies(){if(await this.waitForInitialization(),!this.mongoClient){const e=this.proxies.filter(e=>"invalid"===e.status).length;return this.proxies=this.proxies.filter(e=>"valid"===e.status),this.availableProxies.clear(),this.proxies.forEach(e=>this.availableProxies.add(e.url)),this.log("info","从内存中删除无效代理",{count:e}),e}const e=await this.mongoClient.deleteInvalidProxies();return this.log("info","删除无效代理完成",{count:e}),e}async standaloneProxyCheck(e,t,s,n){const{default:o}=await Promise.resolve().then(()=>i(r(867)));try{const r=new AbortController,i=setTimeout(()=>r.abort(),1e3*n),a={method:"POST",headers:{"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"}};let c={url:s,method:"GET"};e&&(c.proxy=e,c.impersonate="chrome",c.timeout=n,a.body=JSON.stringify(c),a.headers["Content-Type"]="application/json");const l=await o(t,a),h=await l.text();let u;clearTimeout(i);try{u=JSON.parse(h)}catch{u=h}const g={status_code:l.status,success:l.ok,headers:Object.fromEntries(l.headers.entries()),data:u,error:l.ok?void 0:h,timestamp:(new Date).toISOString()},y=l.ok&&this.proxyCheckOptions.successStatusCodes.includes(g.status_code);return y?this.log("info","代理检测成功",{proxy:e,status:g.status_code,result:JSON.stringify(g.data)}):this.log("error","代理检测状态码不符",{proxy:e,statusCode:g.status_code,expected:this.proxyCheckOptions.successStatusCodes}),y}catch(t){return this.log("error","代理检测请求失败",{proxy:e,error:t.message}),!1}}async taskHandler(e){const t=Date.now();try{const r=this.proxyCheckOptions.testUrls[Math.floor(Math.random()*this.proxyCheckOptions.testUrls.length)],s=await this.standaloneProxyCheck(e.url,this.proxyCheckOptions.mainUrl,r,this.proxyCheckOptions.timeout),n=Date.now()-t;return e.totalRequests++,e.lastCheckTime=Date.now(),s?(e.avgResponseTime=(e.avgResponseTime*(e.totalRequests-1)+n)/e.totalRequests,e.consecutiveFails=0):(e.failCount++,e.consecutiveFails++),{proxy:e,isAvailable:s,responseTime:n}}catch(r){return this.log("error","代理检测出错",{proxy:e.url,error:r.message}),e.totalRequests++,e.failCount++,e.consecutiveFails++,e.lastCheckTime=Date.now(),{proxy:e,isAvailable:!1,responseTime:Date.now()-t}}}async checkAllProxies(){this.mongoClient||this.log("info","MongoDB 客户端未初始化,使用内存中的代理进行检测");let e=this.mongoClient?await this.mongoClient.findAll({status:"valid"}):this.proxies.filter(e=>"valid"===e.status);this.log("info",`开始批量检测代理,共 ${e.length} 个代理,最大并发数: ${this.maxConcurrentChecks}`),this.asyncQueue.updateConcurrency(this.maxConcurrentChecks);const t=[];try{const r=await this.asyncQueue.addBatch(e);t.push(...r),t.forEach(e=>{e.proxy.totalRequests>=2&&(e.proxy.failCount,e.proxy.totalRequests),e.proxy.failCount||e.proxy.avgResponseTime>this.proxyCheckOptions.maxResponseTime?(e.proxy.status="invalid",this.availableProxies.delete(e.proxy.url)):e.proxy.status="valid"}),this.mongoClient&&await this.mongoClient.bulkUpsert(e);const s=e.filter(e=>"valid"===e.status).length,n=e.length-s;this.log("info","批量代理检测完成",{total:e.length,valid:s,invalid:n})}catch(e){this.log("error","批量代理检测失败",{error:e.message})}}getCurrentProxy(){return 0===this.proxies.length?null:this.proxies[this.currentProxyIndex].url}selectProxy(){const e=this.proxies.filter(e=>"valid"===e.status);if(0===e.length)return this.proxies.length>0?(this.currentProxyIndex=0,this.proxies[0].url):null;let t;switch(this.proxyStrategy){case"sequential":t=this.currentProxyIndex%e.length,this.currentProxyIndex=(t+1)%e.length;break;case"random":this.usedProxies.size>=e.length&&this.usedProxies.clear();const r=Array.from({length:e.length},(e,t)=>t).filter(e=>!this.usedProxies.has(e));t=r.length>0?r[Math.floor(Math.random()*r.length)]:Math.floor(Math.random()*e.length),this.usedProxies.add(t),this.currentProxyIndex=t;break;case"failover":const s=[...e].sort((e,t)=>{if(e.consecutiveFails!==t.consecutiveFails)return e.consecutiveFails-t.consecutiveFails;const r=e.totalRequests>0?e.failCount/e.totalRequests:0,s=t.totalRequests>0?t.failCount/t.totalRequests:0;return r!==s?r-s:e.avgResponseTime-t.avgResponseTime});t=this.proxies.findIndex(e=>e.url===s[0].url),this.currentProxyIndex=t;break;default:t=this.currentProxyIndex%e.length}return e[t].url}async rotateProxy(){if(0===this.proxies.filter(e=>"valid"===e.status).length)return this.proxies.length>0?(this.currentProxyIndex=0,this.log("info","无有效代理,默认使用第一个代理",{proxy:this.proxies[0].url}),this.proxies[0].url):null;const e=this.proxies[this.currentProxyIndex];e.failCount++,e.totalRequests++,e.consecutiveFails++,e.consecutiveFails>=this.proxyCheckOptions.maxConsecutiveFails&&(e.status="invalid",this.availableProxies.delete(e.url)),this.mongoClient&&await this.mongoClient.upsert(e);const t=this.proxies.filter(e=>"valid"===e.status);if(0===t.length)return this.proxies.length>0?(this.currentProxyIndex=0,this.log("info","无有效代理,默认使用第一个代理",{proxy:this.proxies[0].url}),this.proxies[0].url):null;this.currentProxyIndex=(this.currentProxyIndex+1)%t.length;const r=t[this.currentProxyIndex];return this.log("info","轮换代理",{from:e.url,to:r.url,consecutiveFails:e.consecutiveFails}),r.url}async recordProxyUsage(e,t,r){const s=this.proxies.find(t=>t.url===e);s&&(s.totalRequests++,t?(s.avgResponseTime=(s.avgResponseTime*(s.totalRequests-1)+r)/s.totalRequests,s.consecutiveFails=0):(s.failCount++,s.consecutiveFails++),s.lastCheckTime=Date.now(),t&&"invalid"===s.status&&(s.status="valid",this.availableProxies.add(s.url)),this.mongoClient&&await this.mongoClient.upsert(s))}resetProxyUsage(){this.usedProxies.clear(),this.log("info","重置代理使用记录")}setProxyStrategy(e){this.proxyStrategy=e,this.resetProxyUsage(),this.log("info","设置代理策略",{strategy:e})}async enhancedProxyCheck(e){if(!this.proxyCheckEnabled)return!0;if(this.checkInProgress.has(e))return!0;try{this.checkInProgress.add(e);const t=this.proxyCheckOptions.testUrls[Math.floor(Math.random()*this.proxyCheckOptions.testUrls.length)],r=Date.now(),s=await this.standaloneProxyCheck(e,this.proxyCheckOptions.mainUrl,t,this.proxyCheckOptions.timeout),n=Date.now()-r;return s&&n>this.proxyCheckOptions.maxResponseTime?(this.log("error","代理响应时间过长",{proxy:e,responseTime:n,threshold:this.proxyCheckOptions.maxResponseTime}),!1):s}catch(t){return this.log("error","代理检测异常",{proxy:e,error:t.message}),!1}finally{this.checkInProgress.delete(e)}}setMaxConcurrentChecks(e){e>0&&(this.maxConcurrentChecks=e,this.asyncQueue.updateConcurrency(e),this.log("info","更新最大并发检查数",{maxConcurrentChecks:e}))}getQueueStats(){return this.asyncQueue.stats}pauseProxyChecks(){this.asyncQueue.pause(),this.log("info","代理检测队列已暂停")}resumeProxyChecks(){this.asyncQueue.resume(),this.log("info","代理检测队列已恢复")}async checkProxy(e){const t=e||this.getCurrentProxy();if(!t)return!1;const r=await this.enhancedProxyCheck(t),s=this.proxies.find(e=>e.url===t);return s&&(s.status=r?"valid":"invalid",r?this.availableProxies.add(t):this.availableProxies.delete(t),this.mongoClient&&await this.mongoClient.upsert(s)),this.log("info","代理检查完成",{proxy:t,result:r}),r}getAvailableProxy(){const e=this.proxies.filter(e=>"valid"===e.status);if(0===e.length)return this.proxies.length>0?(this.currentProxyIndex=0,this.log("info","所有代理均不可用,默认使用第一个代理",{proxy:this.proxies[0].url}),this.proxies[0].url):null;const t=this.selectProxy();return this.log("info","获取代理",{proxy:t,strategy:this.proxyStrategy,available:e.length}),t}shouldRotateProxy(e){if(0===this.proxies.filter(e=>"valid"===e.status).length)return!1;if(!e||!e.message)return!1;const t=e.message.toLowerCase();return["proxy","connect","connection","timeout","socket","网络","连接","ETIMEDOUT","ECONNREFUSED"].some(e=>t.includes(e))}async triggerProxyCheck(){await this.waitForInitialization(),this.log("info","手动触发代理检测"),await this.checkAllProxies()}getAvailableProxiesList(){const e=this.proxies.filter(e=>"valid"===e.status).map(e=>e.url);return 0===e.length&&this.proxies.length>0?[this.proxies[0].url]:e}getProxyDetails(e){return this.proxies.find(t=>t.url===e)}getProxiesCount(){return this.proxies.length}getProxyStrategy(){return this.proxyStrategy}getCurrentProxyIndex(){return this.currentProxyIndex}async destroy(){if(this.checkInProgress.clear(),this.usedProxies.clear(),this.proxies=[],this.availableProxies.clear(),this.asyncQueue){const e=this.asyncQueue.getName();this.asyncQueue.pause(),c.AsyncQueueSingleton.destroyInstance(e)}this.mongoClient&&this.needsMongoDB&&await this.mongoClient.disconnect(),this.isInitialized=!1,this.initializationPromise=null,h.instances.delete(this.instanceId),this.log("info","ProxyManager 已完全销毁")}}t.ProxyManager=h,h.instances=new Map,h.instanceLock=!1},862:function(e,t,r){var s,n=this&&this.__createBinding||(Object.create?function(e,t,r,s){void 0===s&&(s=r);var n=Object.getOwnPropertyDescriptor(t,r);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,s,n)}:function(e,t,r,s){void 0===s&&(s=r),e[s]=t[r]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||(s=function(e){return s=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},s(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=s(e),i=0;i<r.length;i++)"default"!==r[i]&&n(t,e,r[i]);return o(t,e),t});Object.defineProperty(t,"__esModule",{value:!0}),t.MongoProxyManager=void 0;const a=r(388),c=i(r(331)),l=new c.Schema({url:{type:String,required:!0,unique:!0},totalRequests:{type:Number,default:0},failCount:{type:Number,default:0},avgResponseTime:{type:Number,default:0},lastCheckTime:{type:Number,default:Date.now},consecutiveFails:{type:Number,default:0},status:{type:String,enum:["valid","invalid"],default:"valid"}});l.index({status:1}),l.index({url:1}),l.index({status:1,totalRequests:1});class h{constructor(e){this.isConnected=!1,this.connectPromise=null,this.connectionAttempts=0,this.maxConnectionAttempts=3,this.config=e,this.logLevel=e.logLevel||"none",this.ProxyModel=c.default.model("Proxy",l)}async connectWithRetry(){if(!this.isConnected){if(this.connectPromise)return await this.connectPromise;this.connectPromise=(async()=>{if(1===c.default.connection.readyState)return this.isConnected=!0,void this.log("info","使用现有MongoDB连接");for(;this.connectionAttempts<this.maxConnectionAttempts;)try{return this.connectionAttempts++,this.log("info",`尝试连接MongoDB (${this.connectionAttempts}/${this.maxConnectionAttempts})`),await c.default.connect(this.config.uri,{serverSelectionTimeoutMS:8e3,socketTimeoutMS:45e3,maxPoolSize:10}),this.isConnected=!0,this.connectionAttempts=0,void this.log("info",`MongoDB连接成功: ${this.config.uri}`)}catch(e){if(this.log("warn",`MongoDB连接尝试 ${this.connectionAttempts}/${this.maxConnectionAttempts} 失败: ${e.message}`),this.connectionAttempts>=this.maxConnectionAttempts){const t=new Error(`MongoDB连接失败,已尝试 ${this.maxConnectionAttempts} 次: ${e.message}`);throw this.connectPromise=null,t}await new Promise(e=>setTimeout(e,2e3*this.connectionAttempts))}})();try{await this.connectPromise}finally{this.connectPromise=null}}}static getInstance(e){const t=e.uri;return h.instances.has(t)||h.instances.set(t,new h(e)),h.instances.get(t)}log(e,t,r){try{const s=a.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[MongoProxyManager] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [MongoProxyManager] ${t}`,r||"")}}async ensureConnected(){this.isConnected||(this.connectPromise?await this.connectPromise:await this.connectWithRetry())}async connect(){if(!this.isConnected){if(this.connectPromise)return await this.connectPromise;this.connectPromise=(async()=>{try{await c.default.connect(this.config.uri,{serverSelectionTimeoutMS:5e3,socketTimeoutMS:45e3}),this.isConnected=!0,this.log("info",`MongoDB连接成功: ${this.config.uri}`)}catch(e){throw this.log("error",`MongoDB连接失败: ${e.message}`),e}finally{this.connectPromise=null}})(),await this.connectPromise}}async disconnect(){this.isConnected&&(await c.default.disconnect(),this.isConnected=!1,this.log("info","连接已关闭"))}async checkConnection(){try{return await c.default.connection.db.admin().ping(),!0}catch{return!1}}async findAll(e={}){return await this.ensureConnected(),await this.ProxyModel.find(e).lean()}async findByUrl(e){return await this.ensureConnected(),await this.ProxyModel.findOne({url:e}).lean()}async upsert(e){return await this.ensureConnected(),await this.ProxyModel.findOneAndUpdate({url:e.url},{$set:e},{upsert:!0,new:!0}).lean()}async updateByUrl(e,t){if(!e)throw new Error("代理URL不能为空");if(t.url&&t.url!==e)throw new Error("不能通过updateByUrl方法修改代理URL");await this.ensureConnected();const r={$set:t};return await this.ProxyModel.findOneAndUpdate({url:e},r,{new:!0,runValidators:!0}).lean()}async bulkUpsert(e){if(0===e.length)return;await this.ensureConnected();const t=e.map(e=>({updateOne:{filter:{url:e.url},update:{$set:e},upsert:!0}}));await this.ProxyModel.bulkWrite(t)}async bulkUpdateByUrl(e){if(0===e.length)return;await this.ensureConnected();const t=e.map(e=>({updateOne:{filter:{url:e.url},update:{$set:e.data},upsert:!1}}));await this.ProxyModel.bulkWrite(t)}async bulkInsert(e){if(0===e.length)return{insertedCount:0};await this.ensureConnected();try{return{insertedCount:(await this.ProxyModel.insertMany(e,{ordered:!1,rawResult:!0})).insertedCount}}catch(e){if(e.writeErrors&&e.insertedIds)return{insertedCount:e.insertedIds.length};throw e}}async delete(e){return await this.ensureConnected(),(await this.ProxyModel.deleteOne({url:e})).deletedCount>0}async clear(){await this.ensureConnected(),await this.ProxyModel.deleteMany({})}async updateMany(e,t){return await this.ensureConnected(),(await this.ProxyModel.updateMany(e,{$set:t},{runValidators:!0})).modifiedCount}async findLimited(e={},t=0,r=0){await this.ensureConnected();const s=this.ProxyModel.find(e).lean().skip(r);return t>0&&s.limit(t),await s}async deleteInvalidProxies(){await this.ensureConnected();const e=await this.ProxyModel.deleteMany({status:"invalid"});return this.log("info","删除无效代理",{deletedCount:e.deletedCount}),e.deletedCount}async deleteByCondition(e){await this.ensureConnected();const t=await this.ProxyModel.deleteMany(e);return this.log("info","根据条件删除代理",{filter:e,deletedCount:t.deletedCount}),t.deletedCount}async getStats(){return await this.ensureConnected(),(await this.ProxyModel.aggregate([{$group:{_id:null,total:{$sum:1},valid:{$sum:{$cond:[{$eq:["$status","valid"]},1,0]}},invalid:{$sum:{$cond:[{$eq:["$status","invalid"]},1,0]}},avgResponseTime:{$avg:"$avgResponseTime"}}}]))[0]||{total:0,valid:0,invalid:0,avgResponseTime:0}}}t.MongoProxyManager=h,h.instances=new Map},867:e=>{e.exports=require("node-fetch")},892:function(e,t,r){var s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncQueueSingleton=void 0;const n=s(r(626)),o=r(388);class i{constructor(e="default",t={}){this.queue=null,this.isInitialized=!1,this.logLevel="info",this.instanceName=e,this.logLevel=t.logLevel||"info",this.concurrency=t.concurrency||100,this.autoStart=!1!==t.autoStart,this.onDrain=t.onDrain||(()=>{this.log("info","所有任务完成")}),this.onError=t.onError||(e=>{this.log("error","任务错误:",e)}),this.onSuccess=t.onSuccess||(e=>{}),this.taskHandler=t.taskHandler||this.defaultTaskHandler,this.initializeQueue()}async defaultTaskHandler(e){return await new Promise(e=>setTimeout(e,1e3)),this.log("debug",`[${this.instanceName}] 剩余任务${this.queue?.length()} 运行任务数${this.queue?.running()}`),`运行成功 - ${this.instanceName}`}initializeQueue(){this.isInitialized||(this.queue=n.default.queue(async e=>await this.taskHandler(e),this.concurrency),this.queue.drain(()=>{this.onDrain()}),this.autoStart||this.queue.pause(),this.isInitialized=!0,this.log("info","队列初始化完成",{concurrency:this.concurrency,autoStart:this.autoStart}))}add(e,t=0){return new Promise((r,s)=>{if(!this.queue)return void s(new Error(`[${this.instanceName}] 队列未初始化`));const n=(t,n)=>{t?(this.log("error","任务执行失败",{task:e,error:t.message}),s(t)):(this.onSuccess(n),r(n))};t>0?this.queue.unshift(e,n):this.queue.push(e,n),this.log("debug","添加任务",{task:e,priority:t,queueLength:this.queue.length(),running:this.queue.running()})})}addBatch(e,t=0){return this.log("info","批量添加任务",{count:e.length,priority:t,instance:this.instanceName}),Promise.all(e.map(e=>this.add(e,t)))}updateConcurrency(e){if(e>0&&e!==this.concurrency&&this.queue){const t=this.concurrency;this.concurrency=e,this.queue.concurrency=e,this.log("info","更新并发数",{from:t,to:e,instance:this.instanceName})}}pause(){return this.queue?.pause(),this.log("info","队列暂停",{instance:this.instanceName}),this}resume(){return this.queue?.resume(),this.log("info","队列恢复",{instance:this.instanceName}),this}get length(){return this.queue?.length()||0}get running(){return this.queue?.running()||0}get workersList(){return this.queue?.workersList()||[]}get idle(){return this.queue?.idle()||!1}get stats(){return{length:this.length,running:this.running,concurrency:this.concurrency,idle:this.idle}}getName(){return this.instanceName}setTaskHandler(e){this.taskHandler=e,this.log("info","任务处理器已更新",{instance:this.instanceName})}destroy(){this.queue&&(this.queue.kill(),this.queue=null),this.isInitialized=!1,this.log("info","队列已销毁",{instance:this.instanceName})}log(e,t,r){try{const s=o.ServiceLocator.get("DebugManager");e.toUpperCase(),s.log(e,`[AsyncQueue:${this.instanceName}] ${t}`,r)}catch(s){const n=`[${e.toUpperCase()}]`;("error"===e?console.error:"warn"===e?console.warn:"debug"===e||"verbose"===e?console.debug:console.info)(`${n} [AsyncQueue:${this.instanceName}] ${t}`,r||"")}}setLogLevel(e){this.logLevel=e;try{o.ServiceLocator.get("DebugManager").setLogLevel(e)}catch(e){console.warn("DebugManager未注册,无法设置日志等级")}this.log("info",`设置日志等级: ${e}`)}getLogLevel(){return this.logLevel}static getInstance(e="default",t={}){if(i.instances.has(e)){const r=i.instances.get(e);if(r.isInitialized&&r.queue)return void 0!==t.logLevel&&t.logLevel!==r.logLevel&&r.setLogLevel(t.logLevel),t.concurrency&&t.concurrency!==r.concurrency&&r.updateConcurrency(t.concurrency),r;i.instances.delete(e)}const r=new i(e,t);return i.instances.set(e,r),r}static getInstanceNames(){return Array.from(i.instances.keys())}static getAllInstancesStats(){const e={};return i.instances.forEach((t,r)=>{e[r]=t.stats}),e}static destroyInstance(e="default"){if(i.instances.has(e)){const t=i.instances.get(e);t?.isInitialized&&t.queue&&t.destroy(),i.instances.delete(e),console.log(`[AsyncQueue] 已销毁实例: ${e}`)}}static destroyAllInstances(){const e=Array.from(i.instances.keys());e.forEach(e=>{i.destroyInstance(e)}),console.log(`[AsyncQueue] 已销毁所有实例: ${e.join(", ")}`)}static hasInstance(e="default"){return i.instances.has(e)}static getExistingInstance(e="default"){return i.instances.get(e)||null}debug(e,t){this.log("debug",e,t)}info(e,t){this.log("info",e,t)}warn(e,t){this.log("warn",e,t)}error(e,t){this.log("error",e,t)}verbose(e,t){this.log("verbose",e,t)}}t.AsyncQueueSingleton=i,i.instances=new Map},896:e=>{e.exports=require("fs")},928:e=>{e.exports=require("path")}},t={};function r(s){var n=t[s];if(void 0!==n)return n.exports;var o=t[s]={exports:{}};return e[s].call(o.exports,o,o.exports,r),o.exports}r.c=t;var s=r(r.s=435);module.exports=s})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"proxyManager.d.ts","sourceRoot":"","sources":["../src/proxyManager.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,aAAa,EACb,SAAS,EAET,mBAAmB,EAEnB,QAAQ,EACT,MAAM,SAAS,CAAC;AASjB,qBAAa,YAAY;IACvB,OAAO,CAAC,MAAM,CAAC,SAAS,CAAwC;IAChE,OAAO,CAAC,MAAM,CAAC,YAAY,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,OAAO,CAAc;IAC7B,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,iBAAiB,CAAU;IACnC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,iBAAiB,CAA8B;IACvD,OAAO,CAAC,gBAAgB,CAAc;IACtC,OAAO,CAAC,eAAe,CAAc;IACrC,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,WAAW,CAAkC;IACrD,OAAO,CAAC,UAAU,CAAsB;IACxC,OAAO,CAAC,aAAa,CAAkB;IACvC,OAAO,CAAC,qBAAqB,CAA8B;IAC3D,OAAO,CAAC,YAAY,CAAiB;IAErC,OAAO,CAAC,WAAW,CAAa;IAChC,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,YAAY,CAAiB;IACrC,OAAO,CAAC,WAAW,CAAa;IAChC,OAAO,CAAC,QAAQ,CAAW;IAE3B,OAAO;IA2FP;;OAEG;YACW,eAAe;IAyB7B;;KAEC;IACY,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC;IAUnD;;OAEG;IACH,OAAO,CAAC,YAAY;WAyBN,WAAW,CAAC,OAAO,GAAE,mBAAwB,GAAG,YAAY;IAkB1E,4BAA4B;WACd,aAAa,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;IActD,OAAO,CAAC,GAAG;IAgBX;;OAEG;IACI,WAAW,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI;IAUzC;;OAEG;IACI,WAAW,IAAI,QAAQ;IAU9B;;;;;OAKG;YACW,iBAAiB;IA8F/B;;OAEG;IACU,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC;IAc5C;;OAEG;IACU,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAK7C;;OAEG;IACI,iBAAiB,IAAI;QAC1B,WAAW,EAAE,MAAM,CAAC;QACpB,QAAQ,EAAE,MAAM,CAAC;QACjB,YAAY,EAAE,OAAO,CAAC;QACtB,WAAW,EAAE,MAAM,CAAC;QACpB,aAAa,EAAE,MAAM,CAAC;KACvB;IAUD;;OAEG;IACU,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;IAmDlE;;OAEG;IACU,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAsB5D;;KAEC;IACY,oBAAoB,IAAI,OAAO,CAAC,MAAM,CAAC;IAqBpD;;MAEE;YACY,oBAAoB;YAsEpB,WAAW;IAwCzB;;OAEG;YACW,eAAe;IAoD7B;;OAEG;IACI,eAAe,IAAI,MAAM,GAAG,IAAI;IAOvC;;OAEG;IACI,WAAW,IAAI,MAAM,GAAG,IAAI;
|
|
1
|
+
{"version":3,"file":"proxyManager.d.ts","sourceRoot":"","sources":["../src/proxyManager.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,aAAa,EACb,SAAS,EAET,mBAAmB,EAEnB,QAAQ,EACT,MAAM,SAAS,CAAC;AASjB,qBAAa,YAAY;IACvB,OAAO,CAAC,MAAM,CAAC,SAAS,CAAwC;IAChE,OAAO,CAAC,MAAM,CAAC,YAAY,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,OAAO,CAAc;IAC7B,OAAO,CAAC,iBAAiB,CAAS;IAClC,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,iBAAiB,CAAU;IACnC,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,iBAAiB,CAA8B;IACvD,OAAO,CAAC,gBAAgB,CAAc;IACtC,OAAO,CAAC,eAAe,CAAc;IACrC,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,WAAW,CAAkC;IACrD,OAAO,CAAC,UAAU,CAAsB;IACxC,OAAO,CAAC,aAAa,CAAkB;IACvC,OAAO,CAAC,qBAAqB,CAA8B;IAC3D,OAAO,CAAC,YAAY,CAAiB;IAErC,OAAO,CAAC,WAAW,CAAa;IAChC,OAAO,CAAC,QAAQ,CAAgB;IAChC,OAAO,CAAC,YAAY,CAAiB;IACrC,OAAO,CAAC,WAAW,CAAa;IAChC,OAAO,CAAC,QAAQ,CAAW;IAE3B,OAAO;IA2FP;;OAEG;YACW,eAAe;IAyB7B;;KAEC;IACY,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC;IAUnD;;OAEG;IACH,OAAO,CAAC,YAAY;WAyBN,WAAW,CAAC,OAAO,GAAE,mBAAwB,GAAG,YAAY;IAkB1E,4BAA4B;WACd,aAAa,CAAC,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI;IActD,OAAO,CAAC,GAAG;IAgBX;;OAEG;IACI,WAAW,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI;IAUzC;;OAEG;IACI,WAAW,IAAI,QAAQ;IAU9B;;;;;OAKG;YACW,iBAAiB;IA8F/B;;OAEG;IACU,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC;IAc5C;;OAEG;IACU,eAAe,IAAI,OAAO,CAAC,IAAI,CAAC;IAK7C;;OAEG;IACI,iBAAiB,IAAI;QAC1B,WAAW,EAAE,MAAM,CAAC;QACpB,QAAQ,EAAE,MAAM,CAAC;QACjB,YAAY,EAAE,OAAO,CAAC;QACtB,WAAW,EAAE,MAAM,CAAC;QACpB,aAAa,EAAE,MAAM,CAAC;KACvB;IAUD;;OAEG;IACU,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;IAmDlE;;OAEG;IACU,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAsB5D;;KAEC;IACY,oBAAoB,IAAI,OAAO,CAAC,MAAM,CAAC;IAqBpD;;MAEE;YACY,oBAAoB;YAsEpB,WAAW;IAwCzB;;OAEG;YACW,eAAe;IAoD7B;;OAEG;IACI,eAAe,IAAI,MAAM,GAAG,IAAI;IAOvC;;OAEG;IACI,WAAW,IAAI,MAAM,GAAG,IAAI;IAmEnC;;OAEG;IACU,WAAW,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAqDlD;;OAEG;IACU,gBAAgB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA2BtG;;OAEG;IACI,eAAe,IAAI,IAAI;IAK9B;;OAEG;IACI,gBAAgB,CAAC,QAAQ,EAAE,aAAa,GAAG,IAAI;IAMtD;;OAEG;IACU,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IA0ChE;;OAEG;IACI,sBAAsB,CAAC,mBAAmB,EAAE,MAAM,GAAG,IAAI;IAQhE;;OAEG;IACI,aAAa;IAIpB;;OAEG;IACI,gBAAgB,IAAI,IAAI;IAK/B;;OAEG;IACI,iBAAiB,IAAI,IAAI;IAKhC;;OAEG;IACU,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IA2BzD;;OAEG;IACI,iBAAiB,IAAI,MAAM,GAAG,IAAI;IAwBzC;;OAEG;IACI,iBAAiB,CAAC,KAAK,EAAE,GAAG,GAAG,OAAO;IAW7C;;OAEG;IACU,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC;IAM/C;;OAEG;IACI,uBAAuB,IAAI,MAAM,EAAE;IAS1C;;OAEG;IACI,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS;IAI/D;;OAEG;IACI,eAAe,IAAI,MAAM;IAIhC;;OAEG;IACI,gBAAgB,IAAI,aAAa;IAIxC;;OAEG;IACI,oBAAoB,IAAI,MAAM;IAIrC;;OAEG;IACU,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CA0BtC"}
|