@stackone/transport 2.40.0 → 2.40.1
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.cjs +9 -9
- package/dist/index.d.cts +9 -5
- package/dist/index.d.mts +10 -6
- package/dist/index.mjs +9 -9
- package/package.json +2 -2
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInMS as n,generateRequestId as r,getContentHash as i,isFunction as a,isFutureUnixTimestamp as o,isMissing as s,isNumber as c,isObject as l,isString as u,notMissing as d,z as f,zStrictObject as p}from"@stackone/utils";import*as m from"redis";import{ConnectionTimeoutError as h,SocketClosedUnexpectedlyError as g}from"redis";import{evaluate as _,safeEvaluate as v}from"@stackone/expressions";import y,{AxiosError as b,isAxiosError as x}from"axios";import S from"node:https";import{createHash as C,createHmac as w,randomUUID as T}from"crypto";import{clearTimeout as ee}from"node:timers";import{hasNumericValue as E,isString as te}from"mathjs";import{JSONPath as D}from"jsonpath-plus";import{redactFields as ne,redactUrl as O}from"@stackone/redaction";import k from"qs";import{Readable as re}from"node:stream";import{Client as ie,SdkHttpError as ae,StreamableHTTPClientTransport as oe,UnauthorizedError as se,discoverAuthorizationServerMetadata as ce,discoverOAuthProtectedResourceMetadata as le,extractWWWAuthenticateParams as ue}from"@modelcontextprotocol/client";import{getDomain as de}from"tldts";import{randomUUID as fe}from"node:crypto";import{XMLBuilder as pe,XMLParser as me,XMLValidator as A}from"fast-xml-parser";const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return await t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);r&&i?(i.push({lock:n,unlock:t}),await i[i.length-2].lock):this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const j=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}setLogger(e){this.config={...this.config,logger:e},this.logger=e}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.ttlMap=new Map,this.slidingExpiration=e?.slidingExpiration??!1,this.hashStore=new Map,this.hashExpiryMap=new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let t=this.dataStore.get(e)??null;return t!==null&&this.slideExpiry(e),t})}slideExpiry(e){let t=this.ttlMap.get(e);this.slidingExpiration&&t!==void 0&&this.expiryMap.set(e,Date.now()+t)}async getDataBatch(e){return e.length===0?[]:Promise.all(e.map(e=>this.getData(e)))}async getDataKeysFromGroup(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.getLiveGroup(e)??[])}async deleteDataKeyFromGroup(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let n=this.getLiveGroup(e);if(s(n))return!1;let r=n.delete(t);return n.size===0&&(this.groupMap.delete(e),this.groupExpiryMap.delete(e)),r}getLiveGroup(e){let t=this.groupExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),null):this.groupMap.get(e)??null}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),d(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*j,o=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{(d(this.typeGuard)&&this.typeGuard(t)||s(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,o),this.slidingExpiration&&this.ttlMap.set(e,a)}),d(r)&&r.length>0){let t=d(i)&&Number.isFinite(i)&&i>0?i*j:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),d(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let{removed:n,value:r}=await this.lockManager.withLock(e,async()=>{let n=this.dataStore.get(e);if(d(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.ttlMap.delete(e),{removed:this.dataStore.delete(e),value:n}});return n&&this.dispose&&await this.dispose(e,r),n}async pruneExpiredKeys(){this.pruneExpiredHashes();let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0,a=0;this.dataStore.forEach((e,o)=>{let s=Date.now(),c=this.expiryMap.get(o)??0,l=this.truncateThreshold*this.truncationPercentage/100,u=c<=s,d=t&&i>=0&&i<=l;(u||d)&&(u||a++,r.push(o),n.push(this.lockManager.withLock(o,async()=>!d&&(this.expiryMap.get(o)??0)>Date.now()?!1:(this.expiryMap.delete(o),this.ttlMap.delete(o),this.dataStore.delete(o))).then(async t=>(t&&this.dispose&&await this.dispose(o,e),t)))),i++});let o=await Promise.all(n);this.removeKeysFromGroups(r.filter((e,t)=>o[t]));let s=this.dataStore.size;return a>0&&this.logger?.warning({message:`Truncated ${a} unexpired keys because the store held ${e}, at or above its limit of ${this.truncateThreshold}.`,category:`MemoryStore`,context:{instantiator:this.instantiator,dataStoreSize:e,truncateThreshold:this.truncateThreshold,truncatedUnexpiredKeys:a}}),{dataStoreSize:e,prunedDataStoreSize:s}}removeKeysFromGroups(e){if(e.length===0)return;let t=new Set(e);for(let e of this.groupMap.values())for(let n of e)t.has(n)&&!this.dataStore.has(n)&&e.delete(n)}startEvictionTask(){if(d(this.evictionInterval))return;let executePrune=async()=>{let e;try{if(this.lastAccessedAt+this.staleDataThreshold<Date.now()){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),await this.close();return}e=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}catch(e){e instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:e,code:`MemoryStorePruneError`}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if(d(e?.dataStoreSize)&&d(e?.prunedDataStoreSize)){let{dataStoreSize:t,prunedDataStoreSize:n}=e,r=t-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&=(clearTimeout(this.evictionInterval),void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return d(this.evictionInterval)&&d(this.dataStore)&&d(this.expiryMap)&&d(this.lockManager)}isAvailable(){return this.isReady()}async setTTL(e,t){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),!this.dataStore.has(e)||!Number.isFinite(t)||t<=0)return!1;let n=t*j;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n),this.slidingExpiration&&this.ttlMap.set(e,n)}),!0}pruneExpiredHashes(){let e=Date.now();for(let[t,n]of this.hashExpiryMap)n<=e&&(this.hashStore.delete(t),this.hashExpiryMap.delete(t))}getLiveHash(e){let t=this.hashExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.hashStore.delete(e),this.hashExpiryMap.delete(e),null):this.hashStore.get(e)??null}async setHashData({key:e,entries:t,cacheTTL:n}){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),!Number.isFinite(n)||n<=0||Object.keys(t).length===0?!1:this.lockManager.withLock(e,async()=>{let r=this.getLiveHash(e)??new Map;return Object.entries(t).forEach(([e,t])=>{r.set(e,t)}),this.hashStore.set(e,r),this.hashExpiryMap.set(e,Date.now()+n*j),!0})}async getHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.getLiveHash(e)?.get(t)??null)}async getAllHashData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let t=this.getLiveHash(e);return s(t)||t.size===0?null:Object.fromEntries(t)})}async deleteHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let n=this.getLiveHash(e);if(s(n))return 0;let r=t.filter(e=>n.delete(e)).length;return n.size===0&&(this.hashStore.delete(e),this.hashExpiryMap.delete(e)),r})}async close(){this.stopEvictionTask(),this.dispose&&await Promise.all(Array.from(this.dataStore,async([e,t])=>{try{await this.dispose?.(e,t)}catch(t){this.logger?.error({message:`Failed to dispose entry "${e}" during close`,category:`MemoryStore`,error:t,code:`MemoryStoreDisposeError`})}})),this.dataStore.clear(),this.expiryMap.clear(),this.ttlMap.clear(),this.hashStore.clear(),this.hashExpiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}},EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.defaultExecutorMethodDispose=async(e,t)=>{d(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):d(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))},this.defaultPendingPromiseDispose=async(e,t)=>{t instanceof Promise&&t?.finally(()=>{})},this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return d(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);s(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:`EventClientResolveError`})}}async close(){let e=this.executorMethodStore,t=this.promiseStore;this.executorMethodStore=null,this.promiseStore=null,await e?.close(),await t?.close()}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(s(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,s(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}},LogThrottle=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t=128){this.#e=e,this.#t=t}consume(e,t=Date.now()){let n=this.#n.get(e);if(n!==void 0&&t-n<this.#e)return this.#r.set(e,(this.#r.get(e)??0)+1),null;let r=this.#r.get(e)??0;return this.#r.delete(e),this.#n.delete(e),this.#n.set(e,t),this.#i(),{suppressed:r}}clear(){this.#n.clear(),this.#r.clear()}#i(){for(;this.#n.size>this.#t;){let e=this.#n.keys().next().value;if(e===void 0)return;this.#n.delete(e),this.#r.delete(e)}}};const he=1e4,ge=6e4,_e=new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof h||e instanceof g)return!0;let t=e.code;return t!==void 0&&_e.has(t)};var RedisConnectionHealth=class{#e;#t=null;#n=null;#r=0;#i=!1;constructor(e){this.#e=e}recordAttemptStart(e=Date.now()){this.#t=e,this.#n??=e}recordReady(){this.#t=null,this.#n=null,this.#r=0,this.#i=!0}assess(e,t=Date.now()){this.#r+=1,this.#n??=t;let n=this.#t===null?null:t-this.#t,r=e instanceof h&&n!==null&&n>this.#e*2,i=this.#n===null?null:t-this.#n;return{severity:this.#a(e,r,i),isFreezeArtifact:r,consecutiveFailures:this.#r,unhealthyForMs:i,attemptElapsedMs:n}}isHealthy(){return this.#i&&this.#n===null}#a(e,t,n){return t?`transient`:!isTransientError(e)||this.#r>=5||n!==null&&n>=3e4?`sustained`:`degraded`}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await ve.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:`RedisClientError`,category:n??`buildRedisClientInstance`});return}};var ve=class RedisClient{#e;#t;static async build({getRedisClient:e=m.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o,connectTimeout:s=he,initialConnectTimeout:c=15e3,pingInterval:l},u,f){let p=new RedisClient,h=f??`RedisClient`;p.#t=u;try{p.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:i,connectTimeout:s,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0,...d(l)?{pingInterval:l}:{}});let u=new RedisConnectionHealth(s),f=getDefaultRedisListeners(h,p.#t,u);return addRedisEventHandlers(p.#e,f),u.recordAttemptStart(),await connectWithinBudget(p.#e,c,h,p.#t)?p:(p.#t?.error({message:`Redis client did not connect within its ${c}ms budget, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:h}),await teardownUnusableClient(p.#e),null)}catch(e){let t=e;return p.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:h}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}#r(e){let t=this.#n(e);return u(t)?e:t}async getData(e){if(!this.#a())return null;try{let t=await this.#e.get(e);return d(t)?this.#r(t):null}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataBatch(e){if(e.length===0)return[];if(!this.#a())return e.map(()=>null);try{return(await this.#e.mGet(e)).map(e=>d(e)?this.#r(e):null)}catch(t){let n=t;return this.#t?.error({message:`Error getting batch data`,error:n,code:`RedisClientReadError`,category:RedisClient.name}),e.map(()=>null)}}async getDataKeysFromGroup(e){if(!this.#a())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#a())return!1;try{let a=u(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),d(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),d(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#a())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#a())return null;try{return await this.#e.evalSha(e,{keys:t,arguments:n})}catch(e){let t=e;throw this.#t?.error({message:`Error executing script`,error:t,code:`RedisClientScriptExecuteError`,category:RedisClient.name}),t}}async loadScript(e){if(!this.#a())return null;try{return await this.#e.scriptLoad(e)}catch(e){let t=e;return this.#t?.error({message:`Error loading script`,error:t,code:`RedisClientScriptLoadError`,category:RedisClient.name}),null}}async scriptExists(e){if(!this.#a())return e.map(()=>!1);try{return(await this.#e.scriptExists(e)).map(e=>!!e)}catch(t){let n=t;return this.#t?.error({message:`Error checking script existence`,error:n,code:`RedisClientScriptError`,category:RedisClient.name}),e.map(()=>!1)}}async#i(e,t,n){if(!this.#a())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#i(`incr`,e,t)}async decrement(e,t){return this.#i(`decr`,e,t)}async subscribe(e,t){if(!this.#a())return!1;try{return await this.#e.pSubscribe(e,t),!0}catch(t){let n=t;return this.#t?.error({message:`Error subscribing to ${e}`,error:n,code:`RedisClientSubscribeError`,category:RedisClient.name}),!1}}async unsubscribe(e){if(!this.#a())return!1;try{return await this.#e.pUnsubscribe(e),!0}catch(t){let n=t;return this.#t?.error({message:`Error unsubscribing from ${e}`,error:n,code:`RedisClientUnsubscribeError`,category:RedisClient.name}),!1}}async publish(e,t){if(!this.#a())return null;try{let n=await this.#e.publish(e,t);return n===0&&this.#t?.debug({message:`No subscribers found for channel ${e}`,category:RedisClient.name}),n}catch(t){let n=t;return this.#t?.error({message:`Error publishing to ${e}`,error:n,code:`RedisClientPublishError`,category:RedisClient.name}),null}}getClient(){return this.#a()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){try{this.#e.isOpen&&await this.#e.quit()}catch(e){try{await this.#e.disconnect()}catch{}this.#t?.error({message:`Error gracefully closing Redis client, forced disconnect`,error:e,code:`RedisClientError`,category:RedisClient.name})}}#a(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);d(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#a())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),d(t)&&t.length>0&&(await Promise.allSettled(t.map(t=>this.#e.sRem(t,e)))).forEach((e,n)=>{e.status===`rejected`&&this.#t?.error({message:`Error removing key from group set ${t[n]}`,error:e.reason,code:`RedisClientDeleteError`,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async deleteDataKeyFromGroup(e,t){if(!this.#a())return!1;try{let n=await this.#e.sRem(e,t);return n===0&&this.#t?.debug({message:`No keys removed from group ${e}`,category:RedisClient.name}),n>0}catch(t){let n=t;return this.#t?.error({message:`Error removing key from group set ${e}`,error:n,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async setHashData({key:e,entries:t,cacheTTL:n}){if(!this.#a())return!1;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;let r=Object.entries(t);if(r.length===0)return!1;try{let t=r.flatMap(([e,t])=>[e,u(t)?t:JSON.stringify(t)]);return await this.#e.multiExecutor([{args:[`hset`,e,...t]},{args:[`expire`,e,n.toString()]}]),!0}catch(e){let t=e;return this.#t?.error({message:`Error setting hash data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async getHashData(e,t){if(!this.#a())return null;try{let n=await this.#e.hGet(e,t);return n!==``&&s(n)?null:this.#r(n)}catch(e){let t=e;return this.#t?.error({message:`Error getting hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getAllHashData(e){if(!this.#a())return null;try{let t=await this.#e.hGetAll(e);return Object.keys(t).length===0?null:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,this.#r(t)]))}catch(e){let t=e;return this.#t?.error({message:`Error getting all hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async deleteHashData(e,t){if(!this.#a())return null;if(t.length===0)return 0;try{return await this.#e.hDel(e,t)}catch(e){let t=e;return this.#t?.error({message:`Error deleting hash data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),null}}};const computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},connectWithinBudget=async(e,t,n,r)=>{let i=Promise.resolve(e.connect());i.catch(()=>void 0);let a=i.then(()=>!0),o=0,s=0;for(;o<t;){let e=Math.min(1e3,t-o),i=Date.now(),c,l=new Promise(t=>{c=setTimeout(()=>t(!1),e)}),u;try{u=await Promise.race([a,l])}finally{clearTimeout(c)}if(u)return!0;o+=e;let d=Date.now()-i-e;d<=250||(s+=d,r?.debug({message:`Redis connect budget did not advance for ${d}ms because the runtime was suspended; only executed time is charged against the ${t}ms budget`,category:n,context:{budgetMs:t,sliceMs:e,overrunMs:d,suspendedMs:s,chargedMs:o}}))}return!1},teardownUnusableClient=async e=>{e.removeAllListeners(),e.on(`error`,()=>void 0);try{await e.disconnect()}catch{}},addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t,n=new RedisConnectionHealth(he))=>{let r=new LogThrottle(ge);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),o=n.assess(a),c={consecutiveFailures:o.consecutiveFailures,unhealthyForMs:o.unhealthyForMs,attemptElapsedMs:o.attemptElapsedMs,isFreezeArtifact:o.isFreezeArtifact};if(o.severity===`transient`){t?.debug({message:o.isFreezeArtifact?`Redis connect timeout reported after ${o.attemptElapsedMs}ms, far beyond its budget; runtime was suspended mid-handshake`:`Redis client error ${a.message}`,category:e,context:{...c,error:a.message}});return}let l=r.consume(`${e}:${o.severity}:${a.name}`);if(s(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};if(o.severity===`sustained`){t?.error(u);return}t?.warning(u)}},{eventName:`ready`,listener:()=>{n.recordReady(),r.clear(),t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.debug({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{n.recordAttemptStart(),t?.debug({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.debug({message:`Redis client disconnected`,category:e})}}]};var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0,this.ownsCacheClient=!1,this.unavailableLogThrottle=new LogThrottle(ge)}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=s(t),c=t??await buildRedisClientInstance(e,i,this.name);if(s(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),o&&this.closeCacheClient(),e}return this}closeCacheClient(){if(!this.ownsCacheClient)return;let e=this.cacheClient;this.cacheClient=void 0,this.ownsCacheClient=!1,(async()=>{try{await e?.close?.()}catch(e){this.logger?.error({message:`Failed to close Redis client`,category:this.name,error:e,code:`ScriptManagerCloseError`})}})()}releaseAdditionalResources(){}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.setMaxListeners(20),e.on(`ready`,async()=>{this.unavailableLogThrottle.clear(),this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(d(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(s(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if(d(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(d),i=new Map;if(r.length>0&&d(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(d(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);d(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,n,r){if(!this.isRedisReady()){let t=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return d(t)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r,suppressedSinceLastLog:t.suppressed}}),null}let i=this.scriptMap?.get(e);if(s(i))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:`ScriptManagerExecutionError`}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}catch(a){if(a instanceof Error&&a.message.includes(`NOSCRIPT`)){let a=Date.now()-this.lastReloadTime;if(a<1500){let n=1500-a;this.logger?.info({message:`Script ${e} not found, reload occurred ${a}ms ago. Waiting ${n}ms before reloading`,category:this.name}),await t(n)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),i=this.scriptMap?.get(e),s(i))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}throw a instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${a.message}`,category:this.name,context:{keys:n,args:r},error:a,code:`ScriptManagerExecutionError`}),a}}isRedisReady(){let e=this.cacheClient?.getClient?.();if(d(this.cacheClient)&&s(e))return this.logger?.warning({message:`Cache client exists but getClient() returned null - cannot verify Redis readiness`,category:this.name}),!1;let t=e?.isReady&&e?.isOpen;return this.isReady()&&d(this.cacheClient)&&(t??!1)}},SubscriptionManager=class{constructor(e){this.options={getCacheClient:buildRedisClientInstance},this.subscriptionMap=null,this.subscriptionClient=null,this.name=`SubscriptionManager`,this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new MemoryStore({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),d(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=i(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return d(this.subscriptionClient)&&d(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const M=15e3,ye=15e3,N=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if(s(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:6e4,truncateThreshold:N,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:ye,truncateThreshold:N,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ye,truncateThreshold:N,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=M,o){try{let s=`${e}:${t}`;await this.subscriptionManager?.subscribe(s,async(n,r)=>{if(r.includes(s)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let c=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1,l=!i||!c?await this.waitForTurnOrAbort(s,a,o):o?.aborted===!0;return await this.eventClient?.deleteEvent(s),l||o?.aborted===!0?null:await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:`QueueManagerJoinAndWaitTurnError`,context:{queueName:e,value:t}}),n}}async waitForTurnOrAbort(e,t,n){if(d(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return s(n)?(await r,!1):await new Promise((e,t)=>{let onAbort=()=>{n.removeEventListener(`abort`,onAbort),e(!0)};n.addEventListener(`abort`,onAbort,{once:!0}),n.aborted&&onAbort(),Promise.resolve(r).then(()=>{n.removeEventListener(`abort`,onAbort),e(!1)},e=>{n.removeEventListener(`abort`,onAbort),t(e)})})}async remove(e,t){try{return(await this.executeScript(`remove`,[e],[t])??0)>0}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error removing item from queue`,category:this.name,error:n,code:`QueueManagerRemoveError`,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(`lPop`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:`QueueManagerPopError`,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(`llen`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:`QueueManagerLengthError`,context:{queueName:e}}),t}}isReady(){return d(this.subscriptionManager)&&d(this.cacheClient)&&d(this.scriptMap)&&this.scriptMap.size>0}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null;let e=this.eventClient;this.eventClient=null,e?.close().catch(e=>{this.logger?.error({message:`Failed to close the event client`,category:this.name,error:e,code:`QueueManagerCloseError`})})}close(){this.releaseAdditionalResources(),this.scriptMap?.clear(),this.closeCacheClient()}};const P=`__keyevent@0__:`,F=`${P}set`,be=`${P}expire`,I=`${P}expired`,xe=`${P}srem`,Se=[F,be,I],Ce={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,we={tryConcurrency:`
|
|
1
|
+
import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInMS as n,generateRequestId as r,getContentHash as i,isFunction as a,isFutureUnixTimestamp as o,isMissing as s,isNumber as c,isObject as l,isString as u,notMissing as d,z as f,zStrictObject as p}from"@stackone/utils";import*as m from"redis";import{ConnectionTimeoutError as h,SocketClosedUnexpectedlyError as g}from"redis";import{evaluate as _,safeEvaluate as v}from"@stackone/expressions";import y,{AxiosError as b,isAxiosError as x}from"axios";import S from"node:https";import{createHash as C,createHmac as w,randomUUID as T}from"crypto";import{clearTimeout as ee}from"node:timers";import{hasNumericValue as E,isString as D}from"mathjs";import{JSONPath as O}from"jsonpath-plus";import{redactFields as te,redactUrl as k}from"@stackone/redaction";import ne from"node:http";import A from"qs";import{Readable as re}from"node:stream";import{Client as ie,SdkHttpError as ae,StreamableHTTPClientTransport as oe,UnauthorizedError as se,discoverAuthorizationServerMetadata as ce,discoverOAuthProtectedResourceMetadata as le,extractWWWAuthenticateParams as ue}from"@modelcontextprotocol/client";import{getDomain as de}from"tldts";import{randomUUID as fe}from"node:crypto";import{XMLBuilder as pe,XMLParser as me,XMLValidator as j}from"fast-xml-parser";const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return await t()}finally{this.unlock(e)}}async lock(e){let t,n=new Promise(e=>t=e),r=this.locks.has(e),i=this.locks.get(e);r&&i?(i.push({lock:n,unlock:t}),await i[i.length-2].lock):this.locks.set(e,[{lock:n,unlock:t}])}unlock(e){let t=this.locks.has(e),n=this.locks.get(e);if(t&&n&&n.length>0){let e=n.shift()?.unlock;e?.()}this.queueLength(e)===0&&this.locks.delete(e)}queueLength(e){return this.locks.get(e)?.length}close(){this.locks.clear()}};const M=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}setLogger(e){this.config={...this.config,logger:e},this.logger=e}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.ttlMap=new Map,this.slidingExpiration=e?.slidingExpiration??!1,this.hashStore=new Map,this.hashExpiryMap=new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let t=this.dataStore.get(e)??null;return t!==null&&this.slideExpiry(e),t})}slideExpiry(e){let t=this.ttlMap.get(e);this.slidingExpiration&&t!==void 0&&this.expiryMap.set(e,Date.now()+t)}async getDataBatch(e){return e.length===0?[]:Promise.all(e.map(e=>this.getData(e)))}async getDataKeysFromGroup(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.getLiveGroup(e)??[])}async deleteDataKeyFromGroup(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let n=this.getLiveGroup(e);if(s(n))return!1;let r=n.delete(t);return n.size===0&&(this.groupMap.delete(e),this.groupExpiryMap.delete(e)),r}getLiveGroup(e){let t=this.groupExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),null):this.groupMap.get(e)??null}async setData({key:e,value:t,cacheTTL:n=60,groupKeys:r,groupKeyTTL:i}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),d(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*M,o=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{(d(this.typeGuard)&&this.typeGuard(t)||s(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,o),this.slidingExpiration&&this.ttlMap.set(e,a)}),d(r)&&r.length>0){let t=d(i)&&Number.isFinite(i)&&i>0?i*M:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),d(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let{removed:n,value:r}=await this.lockManager.withLock(e,async()=>{let n=this.dataStore.get(e);if(d(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.ttlMap.delete(e),{removed:this.dataStore.delete(e),value:n}});return n&&this.dispose&&await this.dispose(e,r),n}async pruneExpiredKeys(){this.pruneExpiredHashes();let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0,a=0;this.dataStore.forEach((e,o)=>{let s=Date.now(),c=this.expiryMap.get(o)??0,l=this.truncateThreshold*this.truncationPercentage/100,u=c<=s,d=t&&i>=0&&i<=l;(u||d)&&(u||a++,r.push(o),n.push(this.lockManager.withLock(o,async()=>!d&&(this.expiryMap.get(o)??0)>Date.now()?!1:(this.expiryMap.delete(o),this.ttlMap.delete(o),this.dataStore.delete(o))).then(async t=>(t&&this.dispose&&await this.dispose(o,e),t)))),i++});let o=await Promise.all(n);this.removeKeysFromGroups(r.filter((e,t)=>o[t]));let s=this.dataStore.size;return a>0&&this.logger?.warning({message:`Truncated ${a} unexpired keys because the store held ${e}, at or above its limit of ${this.truncateThreshold}.`,category:`MemoryStore`,context:{instantiator:this.instantiator,dataStoreSize:e,truncateThreshold:this.truncateThreshold,truncatedUnexpiredKeys:a}}),{dataStoreSize:e,prunedDataStoreSize:s}}removeKeysFromGroups(e){if(e.length===0)return;let t=new Set(e);for(let e of this.groupMap.values())for(let n of e)t.has(n)&&!this.dataStore.has(n)&&e.delete(n)}startEvictionTask(){if(d(this.evictionInterval))return;let executePrune=async()=>{let e;try{if(this.lastAccessedAt+this.staleDataThreshold<Date.now()){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),await this.close();return}e=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}catch(e){e instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:e,code:`MemoryStorePruneError`}),this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}finally{if(d(e?.dataStoreSize)&&d(e?.prunedDataStoreSize)){let{dataStoreSize:t,prunedDataStoreSize:n}=e,r=t-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(executePrune,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&=(clearTimeout(this.evictionInterval),void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return d(this.evictionInterval)&&d(this.dataStore)&&d(this.expiryMap)&&d(this.lockManager)}isAvailable(){return this.isReady()}async setTTL(e,t){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),!this.dataStore.has(e)||!Number.isFinite(t)||t<=0)return!1;let n=t*M;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n),this.slidingExpiration&&this.ttlMap.set(e,n)}),!0}pruneExpiredHashes(){let e=Date.now();for(let[t,n]of this.hashExpiryMap)n<=e&&(this.hashStore.delete(t),this.hashExpiryMap.delete(t))}getLiveHash(e){let t=this.hashExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.hashStore.delete(e),this.hashExpiryMap.delete(e),null):this.hashStore.get(e)??null}async setHashData({key:e,entries:t,cacheTTL:n}){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),!Number.isFinite(n)||n<=0||Object.keys(t).length===0?!1:this.lockManager.withLock(e,async()=>{let r=this.getLiveHash(e)??new Map;return Object.entries(t).forEach(([e,t])=>{r.set(e,t)}),this.hashStore.set(e,r),this.hashExpiryMap.set(e,Date.now()+n*M),!0})}async getHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.getLiveHash(e)?.get(t)??null)}async getAllHashData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let t=this.getLiveHash(e);return s(t)||t.size===0?null:Object.fromEntries(t)})}async deleteHashData(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{let n=this.getLiveHash(e);if(s(n))return 0;let r=t.filter(e=>n.delete(e)).length;return n.size===0&&(this.hashStore.delete(e),this.hashExpiryMap.delete(e)),r})}async close(){this.stopEvictionTask(),this.dispose&&await Promise.all(Array.from(this.dataStore,async([e,t])=>{try{await this.dispose?.(e,t)}catch(t){this.logger?.error({message:`Failed to dispose entry "${e}" during close`,category:`MemoryStore`,error:t,code:`MemoryStoreDisposeError`})}})),this.dataStore.clear(),this.expiryMap.clear(),this.ttlMap.clear(),this.hashStore.clear(),this.hashExpiryMap.clear(),this.groupMap.clear(),this.groupExpiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()).filter(t=>t.includes(e)),i=[],a=t?parseInt(t,10):0;for(let e=a;e<n+a;e++){let t=r[e];if(!t)break;let a=await this.getData(t);if(a&&i.push(a),i.length>=n)break}return{items:i,cursor:i.length<n?void 0:(a+n).toString()}}},EventClient=class{constructor(e,t,n){this.executorMethodStore=null,this.promiseStore=null,this.eventClientConfig=null,this.executorMethodStoreConfig=null,this.pendingPromiseStoreConfig=null,this.defaultExecutorMethodDispose=async(e,t)=>{d(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):d(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))},this.defaultPendingPromiseDispose=async(e,t)=>{t instanceof Promise&&t?.finally(()=>{})},this.eventClientConfig=e,this.executorMethodStoreConfig=t,this.pendingPromiseStoreConfig=n;let r=e?.instantiator?`${e?.instantiator}(${this.constructor.name})`:this.constructor.name,i={logger:this.logger,dispose:this.defaultExecutorMethodDispose,typeGuard:this.defaultExecutorMethodTypeGuard,...this.executorMethodStoreConfig??{},instantiator:r},a={logger:this.logger,dispose:this.defaultPendingPromiseDispose,typeGuard:this.defaultPendingPromiseTypeGuard,...this.pendingPromiseStoreConfig??{},instantiator:r};this.executorMethodStore=new MemoryStore(i),this.promiseStore=new MemoryStore(a)}async setPendingEvent(e,t){let n={resolve:void 0,reject:void 0},r=new Promise((e,t)=>{n.resolve=e,n.reject=t}),i=t/1e3;await this.executorMethodStore?.setData({key:e,value:n,cacheTTL:i}),await this.promiseStore?.setData({key:e,value:r,cacheTTL:i})}async waitForEvent(e,t){let n=await this.promiseStore?.getData(e);return d(n)?n:(await this.setPendingEvent(e,t),this.getPendingEvent(e))}async getPendingEvent(e){return this.promiseStore?.getData(e)??null}async deleteEvent(e){return(await Promise.all([this.promiseStore?.delete(e),this.executorMethodStore?.delete(e)])).every(Boolean)}async resolveEvent(e,t){try{let n=await this.executorMethodStore?.getData(e);s(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??6e4),n=await this.executorMethodStore?.getData(e)),n?.resolve?.(t)}catch(t){t instanceof Error&&this.logger.error({message:`Error handling event for key ${e}: ${t.message}`,category:this.constructor.name,context:{eventKey:e},error:t,code:`EventClientResolveError`})}}async close(){let e=this.executorMethodStore,t=this.promiseStore;this.executorMethodStore=null,this.promiseStore=null,await e?.close(),await t?.close()}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(s(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,s(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}},LogThrottle=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t=128){this.#e=e,this.#t=t}consume(e,t=Date.now()){let n=this.#n.get(e);if(n!==void 0&&t-n<this.#e)return this.#r.set(e,(this.#r.get(e)??0)+1),null;let r=this.#r.get(e)??0;return this.#r.delete(e),this.#n.delete(e),this.#n.set(e,t),this.#i(),{suppressed:r}}clear(){this.#n.clear(),this.#r.clear()}#i(){for(;this.#n.size>this.#t;){let e=this.#n.keys().next().value;if(e===void 0)return;this.#n.delete(e),this.#r.delete(e)}}};const he=1e4,ge=6e4,_e=new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof h||e instanceof g)return!0;let t=e.code;return t!==void 0&&_e.has(t)};var RedisConnectionHealth=class{#e;#t=null;#n=null;#r=0;#i=!1;constructor(e){this.#e=e}recordAttemptStart(e=Date.now()){this.#t=e,this.#n??=e}recordReady(){this.#t=null,this.#n=null,this.#r=0,this.#i=!0}assess(e,t=Date.now()){this.#r+=1,this.#n??=t;let n=this.#t===null?null:t-this.#t,r=e instanceof h&&n!==null&&n>this.#e*2,i=this.#n===null?null:t-this.#n;return{severity:this.#a(e,r,i),isFreezeArtifact:r,consecutiveFailures:this.#r,unhealthyForMs:i,attemptElapsedMs:n}}isHealthy(){return this.#i&&this.#n===null}#a(e,t,n){return t?`transient`:!isTransientError(e)||this.#r>=5||n!==null&&n>=3e4?`sustained`:`degraded`}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await ve.build(e,t,n)??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:`RedisClientError`,category:n??`buildRedisClientInstance`});return}};var ve=class RedisClient{#e;#t;static async build({getRedisClient:e=m.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o,connectTimeout:s=he,initialConnectTimeout:c=15e3,pingInterval:l},u,f){let p=new RedisClient,h=f??`RedisClient`;p.#t=u;try{p.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:i,connectTimeout:s,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0,...d(l)?{pingInterval:l}:{}});let u=new RedisConnectionHealth(s),f=getDefaultRedisListeners(h,p.#t,u);return addRedisEventHandlers(p.#e,f),u.recordAttemptStart(),await connectWithinBudget(p.#e,c,h,p.#t)?p:(p.#t?.error({message:`Redis client did not connect within its ${c}ms budget, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:h}),await teardownUnusableClient(p.#e),null)}catch(e){let t=e;return p.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:h}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}#r(e){let t=this.#n(e);return u(t)?e:t}async getData(e){if(!this.#a())return null;try{let t=await this.#e.get(e);return d(t)?this.#r(t):null}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataBatch(e){if(e.length===0)return[];if(!this.#a())return e.map(()=>null);try{return(await this.#e.mGet(e)).map(e=>d(e)?this.#r(e):null)}catch(t){let n=t;return this.#t?.error({message:`Error getting batch data`,error:n,code:`RedisClientReadError`,category:RedisClient.name}),e.map(()=>null)}}async getDataKeysFromGroup(e){if(!this.#a())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#a())return!1;try{let a=u(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),d(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),d(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#a())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#a())return null;try{return await this.#e.evalSha(e,{keys:t,arguments:n})}catch(e){let t=e;throw this.#t?.error({message:`Error executing script`,error:t,code:`RedisClientScriptExecuteError`,category:RedisClient.name}),t}}async loadScript(e){if(!this.#a())return null;try{return await this.#e.scriptLoad(e)}catch(e){let t=e;return this.#t?.error({message:`Error loading script`,error:t,code:`RedisClientScriptLoadError`,category:RedisClient.name}),null}}async scriptExists(e){if(!this.#a())return e.map(()=>!1);try{return(await this.#e.scriptExists(e)).map(e=>!!e)}catch(t){let n=t;return this.#t?.error({message:`Error checking script existence`,error:n,code:`RedisClientScriptError`,category:RedisClient.name}),e.map(()=>!1)}}async#i(e,t,n){if(!this.#a())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#i(`incr`,e,t)}async decrement(e,t){return this.#i(`decr`,e,t)}async subscribe(e,t){if(!this.#a())return!1;try{return await this.#e.pSubscribe(e,t),!0}catch(t){let n=t;return this.#t?.error({message:`Error subscribing to ${e}`,error:n,code:`RedisClientSubscribeError`,category:RedisClient.name}),!1}}async unsubscribe(e){if(!this.#a())return!1;try{return await this.#e.pUnsubscribe(e),!0}catch(t){let n=t;return this.#t?.error({message:`Error unsubscribing from ${e}`,error:n,code:`RedisClientUnsubscribeError`,category:RedisClient.name}),!1}}async publish(e,t){if(!this.#a())return null;try{let n=await this.#e.publish(e,t);return n===0&&this.#t?.debug({message:`No subscribers found for channel ${e}`,category:RedisClient.name}),n}catch(t){let n=t;return this.#t?.error({message:`Error publishing to ${e}`,error:n,code:`RedisClientPublishError`,category:RedisClient.name}),null}}getClient(){return this.#a()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){try{this.#e.isOpen&&await this.#e.quit()}catch(e){try{await this.#e.disconnect()}catch{}this.#t?.error({message:`Error gracefully closing Redis client, forced disconnect`,error:e,code:`RedisClientError`,category:RedisClient.name})}}#a(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);d(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#a())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),d(t)&&t.length>0&&(await Promise.allSettled(t.map(t=>this.#e.sRem(t,e)))).forEach((e,n)=>{e.status===`rejected`&&this.#t?.error({message:`Error removing key from group set ${t[n]}`,error:e.reason,code:`RedisClientDeleteError`,category:RedisClient.name})}),n>0}catch(e){let t=e;return this.#t?.error({message:`Error deleting data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async deleteDataKeyFromGroup(e,t){if(!this.#a())return!1;try{let n=await this.#e.sRem(e,t);return n===0&&this.#t?.debug({message:`No keys removed from group ${e}`,category:RedisClient.name}),n>0}catch(t){let n=t;return this.#t?.error({message:`Error removing key from group set ${e}`,error:n,code:`RedisClientDeleteError`,category:RedisClient.name}),!1}}async setHashData({key:e,entries:t,cacheTTL:n}){if(!this.#a())return!1;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;let r=Object.entries(t);if(r.length===0)return!1;try{let t=r.flatMap(([e,t])=>[e,u(t)?t:JSON.stringify(t)]);return await this.#e.multiExecutor([{args:[`hset`,e,...t]},{args:[`expire`,e,n.toString()]}]),!0}catch(e){let t=e;return this.#t?.error({message:`Error setting hash data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async getHashData(e,t){if(!this.#a())return null;try{let n=await this.#e.hGet(e,t);return n!==``&&s(n)?null:this.#r(n)}catch(e){let t=e;return this.#t?.error({message:`Error getting hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getAllHashData(e){if(!this.#a())return null;try{let t=await this.#e.hGetAll(e);return Object.keys(t).length===0?null:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,this.#r(t)]))}catch(e){let t=e;return this.#t?.error({message:`Error getting all hash data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async deleteHashData(e,t){if(!this.#a())return null;if(t.length===0)return 0;try{return await this.#e.hDel(e,t)}catch(e){let t=e;return this.#t?.error({message:`Error deleting hash data`,error:t,code:`RedisClientDeleteError`,category:RedisClient.name}),null}}};const computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},connectWithinBudget=async(e,t,n,r)=>{let i=Promise.resolve(e.connect());i.catch(()=>void 0);let a=i.then(()=>!0),o=0,s=0;for(;o<t;){let e=Math.min(1e3,t-o),i=Date.now(),c,l=new Promise(t=>{c=setTimeout(()=>t(!1),e)}),u;try{u=await Promise.race([a,l])}finally{clearTimeout(c)}if(u)return!0;o+=e;let d=Date.now()-i-e;d<=250||(s+=d,r?.debug({message:`Redis connect budget did not advance for ${d}ms because the runtime was suspended; only executed time is charged against the ${t}ms budget`,category:n,context:{budgetMs:t,sliceMs:e,overrunMs:d,suspendedMs:s,chargedMs:o}}))}return!1},teardownUnusableClient=async e=>{e.removeAllListeners(),e.on(`error`,()=>void 0);try{await e.disconnect()}catch{}},addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t,n=new RedisConnectionHealth(he))=>{let r=new LogThrottle(ge);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),o=n.assess(a),c={consecutiveFailures:o.consecutiveFailures,unhealthyForMs:o.unhealthyForMs,attemptElapsedMs:o.attemptElapsedMs,isFreezeArtifact:o.isFreezeArtifact};if(o.severity===`transient`){t?.debug({message:o.isFreezeArtifact?`Redis connect timeout reported after ${o.attemptElapsedMs}ms, far beyond its budget; runtime was suspended mid-handshake`:`Redis client error ${a.message}`,category:e,context:{...c,error:a.message}});return}let l=r.consume(`${e}:${o.severity}:${a.name}`);if(s(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};if(o.severity===`sustained`){t?.error(u);return}t?.warning(u)}},{eventName:`ready`,listener:()=>{n.recordReady(),r.clear(),t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.debug({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{n.recordAttemptStart(),t?.debug({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.debug({message:`Redis client disconnected`,category:e})}}]};var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0,this.ownsCacheClient=!1,this.unavailableLogThrottle=new LogThrottle(ge)}async initInstance({redisClientConfig:e=this.redisClientConfig,cacheClient:t=this.cacheClient,scripts:n=this.scripts,scriptMap:r=this.scriptMap,logger:i=this.logger,additionalArgs:a=this.additionalArgs}){let o=s(t),c=t??await buildRedisClientInstance(e,i,this.name);if(s(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),o&&this.closeCacheClient(),e}return this}closeCacheClient(){if(!this.ownsCacheClient)return;let e=this.cacheClient;this.cacheClient=void 0,this.ownsCacheClient=!1,(async()=>{try{await e?.close?.()}catch(e){this.logger?.error({message:`Failed to close Redis client`,category:this.name,error:e,code:`ScriptManagerCloseError`})}})()}releaseAdditionalResources(){}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.setMaxListeners(20),e.on(`ready`,async()=>{this.unavailableLogThrottle.clear(),this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(d(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(s(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if(d(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(d),i=new Map;if(r.length>0&&d(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(d(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);d(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,n,r){if(!this.isRedisReady()){let t=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return d(t)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r,suppressedSinceLastLog:t.suppressed}}),null}let i=this.scriptMap?.get(e);if(s(i))throw this.logger?.error({message:`Script for ${e} not found in script map`,category:this.name,code:`ScriptManagerExecutionError`}),Error(`Script for ${e} not found`);try{return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}catch(a){if(a instanceof Error&&a.message.includes(`NOSCRIPT`)){let a=Date.now()-this.lastReloadTime;if(a<1500){let n=1500-a;this.logger?.info({message:`Script ${e} not found, reload occurred ${a}ms ago. Waiting ${n}ms before reloading`,category:this.name}),await t(n)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),i=this.scriptMap?.get(e),s(i))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:i,keys:n,args:r})??null}throw a instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${a.message}`,category:this.name,context:{keys:n,args:r},error:a,code:`ScriptManagerExecutionError`}),a}}isRedisReady(){let e=this.cacheClient?.getClient?.();if(d(this.cacheClient)&&s(e))return this.logger?.warning({message:`Cache client exists but getClient() returned null - cannot verify Redis readiness`,category:this.name}),!1;let t=e?.isReady&&e?.isOpen;return this.isReady()&&d(this.cacheClient)&&(t??!1)}},SubscriptionManager=class{constructor(e){this.options={getCacheClient:buildRedisClientInstance},this.subscriptionMap=null,this.subscriptionClient=null,this.name=`SubscriptionManager`,this.options={...this.options,...e}}async initialize(e=this.options){let{config:t,getCacheClient:n,logger:r}=e;if(this.logger=r,this.subscriptionMap=new MemoryStore({instantiator:`${e?.instantiator}(${this.name})`,evictionFrequency:e?.subscriptionTTL,staleDataThreshold:e?.staleSubscriptionsThreshold,truncateThreshold:e?.truncateThreshold,truncationPercentage:e?.truncationPercentage,typeGuard:e=>typeof e==`string`,dispose:async e=>{await this.subscriptionClient?.unsubscribe?.(e)}}),d(t))this.subscriptionClient=await n?.(t,this.logger,e?.instantiator)??null,this.logger?.info({message:`${this.name} initialized for ${e.instantiator}.`,category:this.name});else throw Error(`SubscriptionManager requires a Redis client configuration.`)}async subscribe(e,t){this.isReady()||await this.initialize(this.options);let n=await this.subscriptionMap?.getData(e),r=i(t.toString());return await this.subscriptionMap?.setData({key:e,value:r}),n===r?!0:await this.subscriptionClient?.subscribe?.(e,t)??!1}async unsubscribe(e){return this.isReady()||await this.initialize(this.options),this.subscriptionClient?.unsubscribe?.(e)??!1}isReady(){return d(this.subscriptionClient)&&d(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const N=15e3,ye=15e3,P=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if(s(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:6e4,truncateThreshold:P,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:ye,truncateThreshold:P,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ye,truncateThreshold:P,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=N,o){try{let s=`${e}:${t}`;await this.subscriptionManager?.subscribe(s,async(n,r)=>{if(r.includes(s)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let c=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1,l=!i||!c?await this.waitForTurnOrAbort(s,a,o):o?.aborted===!0;return await this.eventClient?.deleteEvent(s),l||o?.aborted===!0?null:await r(e,t)}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error in joinAndWaitTurn`,category:this.name,error:n,code:`QueueManagerJoinAndWaitTurnError`,context:{queueName:e,value:t}}),n}}async waitForTurnOrAbort(e,t,n){if(d(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return s(n)?(await r,!1):await new Promise((e,t)=>{let onAbort=()=>{n.removeEventListener(`abort`,onAbort),e(!0)};n.addEventListener(`abort`,onAbort,{once:!0}),n.aborted&&onAbort(),Promise.resolve(r).then(()=>{n.removeEventListener(`abort`,onAbort),e(!1)},e=>{n.removeEventListener(`abort`,onAbort),t(e)})})}async remove(e,t){try{return(await this.executeScript(`remove`,[e],[t])??0)>0}catch(n){throw n instanceof Error&&this.logger?.error({message:`Error removing item from queue`,category:this.name,error:n,code:`QueueManagerRemoveError`,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(`lPop`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:`QueueManagerPopError`,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(`llen`,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:`QueueManagerLengthError`,context:{queueName:e}}),t}}isReady(){return d(this.subscriptionManager)&&d(this.cacheClient)&&d(this.scriptMap)&&this.scriptMap.size>0}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null;let e=this.eventClient;this.eventClient=null,e?.close().catch(e=>{this.logger?.error({message:`Failed to close the event client`,category:this.name,error:e,code:`QueueManagerCloseError`})})}close(){this.releaseAdditionalResources(),this.scriptMap?.clear(),this.closeCacheClient()}};const F=`__keyevent@0__:`,I=`${F}set`,be=`${F}expire`,L=`${F}expired`,xe=`${F}srem`,Se=[I,be,L],Ce={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,we={tryConcurrency:`
|
|
2
2
|
local requestId = KEYS[1]
|
|
3
3
|
local targetKey = KEYS[2]
|
|
4
4
|
local queueKey = KEYS[3]
|
|
@@ -94,14 +94,14 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInM
|
|
|
94
94
|
|
|
95
95
|
redis.call('publish', nextItemKey, nextItem)
|
|
96
96
|
end
|
|
97
|
-
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==I)return;let n=this.leaseRegistry.get(e);if(!s(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==xe)return;let n=this.setRemovalRegistry.get(e);if(!s(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??r,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.debug({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(s(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return s(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(F)&&n.includes(be)&&n.includes(I)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,confirmedEvents:[...e],redisHost:this.redisClientConfig.host,redisPort:this.redisClientConfig.port,redisDatabase:this.redisClientConfig.database}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(Se.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(I,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(xe,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=M*5,s){let c=`concurrency:${e}`,l=`queue:${e}`,u=r.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,f=d(u)?`${c}-${u}`:c,{mainMaxConcurrency:p,subPools:m}=r,h=[{key:c,maxConcurrency:p},...m?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${c}-${t}`,maxConcurrency:n}})??[]],g=h.map(e=>e.key),_=h.map(e=>e.maxConcurrency),[v,y]=await Promise.all([this.subscribeToLeaseExpiry(i,f),this.subscribeToSetRemoval(f,l)]),b={requestId:i,targetConcurrencyKey:f,leaseSubscription:v,setRemovalSubscription:y,queueKey:l,acquired:!1},x=!1,S=!1;try{let e=await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]);if(d(e)&&e[0])return x=!0,{...b,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let r=d(e)?e[1]:``,a=0,c=o,u=[],isAborted=()=>s?.aborted===!0;for(;c>0&&a<5&&!isAborted();){let e=a>1,r=Math.min(M,c),o=Date.now();S=!0;let m=await this.queueManager?.joinAndWaitTurn(l,i,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]),!1,r,s);c-=Math.max(Date.now()-o,0);let h=d(m)?m[0]:!1,v=d(m)?m[1]:``;if(d(v)&&v!==``&&u.push(v),a++,h)return x=!0,a>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${a} attempts.`,context:{...b,registerAttempts:a,joinCondition:`attempts`,failureMessages:u}}),{...b,joinCondition:`attempts`,acquired:!0};let y=n(a,100);if(c-=y,c<=0||isAborted())break;await t(y)}if(a===0){let e=isAborted()?`aborted`:`no-wait-budget`;return this.logger?.warning({category:this.name,message:isAborted()?`Request aborted before queueing for a concurrency slot.`:`No wait budget left to queue for a concurrency slot, proceeding fail-open.`,context:{...b,registerAttempts:a,joinCondition:e,maxWaitMs:o,optimisticFailureReason:r}}),{...b,joinCondition:e}}return this.logger?.error({category:this.name,message:`Failed to register request after ${a} attempts.`,context:{...b,registerAttempts:a,joinCondition:`failed`,failureMessages:u,optimisticFailureReason:r},code:`ConcurrencyManagerRegistrationFailed`}),{...b,joinCondition:`failed`}}finally{if(!x&&(this.leaseRegistry.delete(buildLeaseKey(f,i)),S))try{await this.queueManager?.remove(l,i)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...b,queueKey:l},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if(u(t)&&u(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null}close(){this.releaseAdditionalResources(),this.queueManager?.close(),this.scriptMap?.clear(),this.closeCacheClient(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const L={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if(s(t)||t?.length===0||s(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=v(r,n?{...e,credentials:n}:e)===!0;if(s(r)||i){let n=t?.message,r;return r=s(n)?L[t.targetStatus]??`Unknown error`:String(v(n,e)??L[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},Te=p({receivedStatus:f.number().meta({description:`Provider HTTP status code to match.`}),targetStatus:f.number().meta({description:`HTTP status code to return in place of the matched one.`}),message:f.string().optional().meta({description:`Error message to return in place of the provider's.`}),condition:f.string().optional().meta({description:`A JEXL expression that applies the remap only when it evaluates true.`})}).meta({description:`Remaps provider error responses to different statuses or messages. Useful for GraphQL APIs that return errors with a 200 status, normalizing provider-specific error formats, and giving AI agents clearer error messages.`});var R=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const Ee=[`client_disconnect`,`timeout`],De=`RequestAbortedError`,Oe={client_disconnect:`Client disconnected`,timeout:`Request timed out`};var RequestAbortedError=class extends Error{constructor(e){super(Oe[e]),this.name=De,this.reason=e}};const isRequestAbortedError=e=>e instanceof Error&&e.name===De&&Ee.includes(e.reason),isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet,n=0)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(n>=64)return`[Max Depth Exceeded]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let r=e.map(e=>safeSerialize(e,t,n+1));return t.delete(e),r}let r=e,i={};t.add(r);for(let[e,a]of Object.entries(r))i[e]=safeSerialize(a,t,n+1);return t.delete(r),i},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}},z=`http-transport`,countSocketsInUse=e=>Object.values(e.sockets).reduce((e,t)=>e+(t?.length??0),0),listHostsInUse=e=>{let t=Object.values(e.sockets).flatMap(e=>e??[]).map(e=>e.servername||e.remoteAddress).filter(e=>typeof e==`string`&&e!==``);return[...new Set(t)]},closeAgentWhenIdle=(e,{pollIntervalMs:t=1e3,maxWaitMs:n=21e5,logger:r,logContext:i}={})=>{let a=countSocketsInUse(e);if(a===0){e.destroy();return}r?.info({category:z,message:`Closing a transport instance with ${a} requests still running, waiting for them to finish.`,context:{...i,busyRequestsAtClose:a,hosts:listHostsInUse(e)}});for(let t of Object.values(e.freeSockets))for(let e of t??[])e.destroy();let o=Date.now(),s=setInterval(()=>{let t=Date.now()-o,c=countSocketsInUse(e);if(c===0)clearInterval(s),e.destroy(),r?.info({category:z,message:`The ${a} requests still running when a transport instance was closed have finished after ${t} ms.`,context:{...i,busyRequestsAtClose:a,waitedMs:t}});else if(t>=n){clearInterval(s);let n=listHostsInUse(e);e.destroy(),r?.warning({category:z,message:`Cut off ${c} requests still running ${t} ms after their transport instance was closed.`,context:{...i,busyRequestsAtClose:a,reapedRequests:c,waitedMs:t,hosts:n}})}},t);s.unref()};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new S.Agent(n),l=y.create({...t,httpsAgent:c});if(l.close=()=>{closeAgentWhenIdle(c,{logger:r,logContext:{accountSecureId:i?.accountSecureId,projectSecureId:i?.projectSecureId,provider:i?.provider,service:i?.service,resource:i?.resource,action:i?.action}})},e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return d(e)&&a(e)&&typeof e(t)==`function`?e(t):e??null}};const buildCloseEvictedInstance=(e,t)=>async(n,r)=>{try{await r?.close?.()}catch(r){e()?.error({message:`Failed to close evicted instance "${n}"`,category:t,error:r,code:`InstanceManagerDisposeError`})}},ke=3600*24*7*1e3;var B=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return s(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager({staleDataThreshold:ke,truncateThreshold:1e4,...e})),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,slidingExpiration:!0,typeGuard:e=>d(e),dispose:buildCloseEvictedInstance(()=>this.options.logger,InstanceManager.name)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}setLogger(e){this.options={...this.options,logger:e},InstanceManager.logger=e??null,this.dataStore?.setLogger?.(e)}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:d(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return d(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const Ae=B.getInstance(),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},je={mainRatelimit:25},V=1e3,Me=/^\d+(\.\d+)?$/,Ne=6e4,createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},H=e((e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&ee(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},`abortableDelay`),U=`checkConcurrencyInterceptor`,Pe=new LogThrottle(Ne),Fe=new LogThrottle(Ne),checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if(s(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:U,...a,httpsAgent:void 0,headers:void 0,hasContext:d(t),hasConfig:d(a)},code:`InterceptorContextNotPresent`});else if(s(i)||s(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:U,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:d(i),concurrencyManagerInitialized:d(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if(d(t.provider)&&d(t.accountSecureId)){let o=T(),{provider:l,accountSecureId:u}=t,f=n?.rateLimits??je,p=n?.concurrency??Ce,m=await i.getDynamicMaxWaitTime(f,p,a.url),h=a._waitDeadlineAt,g=c(h)&&Number.isFinite(h)?h:Date.now()+m*V,remainingBudgetMs=()=>Math.max(g-Date.now(),0),_=`${u}-${l}`,register=async()=>r.registerRequest(_,p,o,a.url,remainingBudgetMs(),a.signal),v=remainingBudgetMs()<=0,y;do{let t=await i.getWaitTime(_,f,a.url);if(s(t)){let t=Pe.consume(_);d(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${l} - Account: ${u}, proceeding without a limit`,context:{interceptor:U,provider:l,accountSecureId:u,suppressedSinceLastLog:t.suppressed},code:`InterceptorRateLimitUnavailable`})}let n=t??0;if(n<=0){y=await register();break}if(remainingBudgetMs()<=0)break;await H(Math.min(Math.max(n,50),remainingBudgetMs()),a)}while(remainingBudgetMs()>0);if(s(y)){y=await register();let n={...t,interceptor:U,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:m,joinCondition:y?.joinCondition};if(v){let t=Fe.consume(_);d(t)&&e?.warning({category:`HttpClient`,message:`Wait budget already spent by an earlier attempt for ${l} - Account: ${u}, proceeding without waiting`,context:{...n,suppressedSinceLastLog:t.suppressed},code:`InterceptorWaitBudgetAlreadySpent`})}else e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${l} - Account: ${u}`,context:n,code:`InterceptorMaxWaitTimeExceeded`})}return{...a,requestMetadata:y,_waitDeadlineAt:g}}return a};return checkConcurrencyInterceptor},adjustUnixTimestamp=e=>e<3250368e4?e*V:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&o(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*V},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=E(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:c}=e??{};return[t,n,r,o].some(s)?null:[t,n,r,i,a,o,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return o(e)||c(e)?evaluateRetryAfterNumber(Number(e),r,t,n):te(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/V);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Me.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/V);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i})=>{let retryErrorInterceptor=async a=>{let{response:o,config:s}=a;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,i,r,t);if(c===429&&d(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*V:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await H(d,s,o),e?.request(u)}return Promise.reject(a)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{status:i,headers:a,data:o}=e??{},{retryafter:s}=superNormalizeHeaders(a??{}),c=n?.rateLimits?.mappedRateLimitErrors;if(d(c)&&d(o))for(let e of c){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:c,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==i)continue;let f=n??`message`,p=testMessage(l(o)?D({path:f,json:o})[0]:o,r);if(t===i&&p){let e=convertRetryAfter(d??extractRetryAfter(a,c),u);return{status:429,retryAfter:s??e}}}return{status:i,retryAfter:s}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>d(t)&&d(e)?D({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>d(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/V;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},W=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i,concurrencyManager:a})=>{let rateLimitErrorInterceptor=async o=>{let{response:c,config:l}=o,u=l?.signal;if(s(i))return t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:W,...l,httpsAgent:void 0,headers:void 0},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(l))return Promise.reject(o);if(s(a))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:W,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(a)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(o);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h,acquired:g}=l?.requestMetadata??{},_=g!==!1&&d(f)&&d(p);if(!(_&&await a.releaseRequest(f,p))&&_&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:W,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:`RateLimiterReleaseRequestFailed`}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,l,`ERR_CANCELED`,c));let{status:v,retryAfter:y}=convertError(c,i,r,t);if(v===429&&d(l)){let r=getRetryAfterWaitTime(y);if(l._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:y,retryAfterAsNumber:r}}),Promise.reject(o);let a=l?._retryCount??0,s={...l,_retryCount:a+1},u=y?r*V:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:y,calculatedRetryAfter:u}}),await H(u,l,c),e?.request(s)}return Promise.reject(o)};return rateLimitErrorInterceptor},G=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if(s(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:G,...i,httpsAgent:void 0,headers:void 0}});else if(s(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:G,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if(d(t.provider)&&d(t.accountSecureId)){let t=r?.headers;if(d(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:G,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l,acquired:u}=i?.requestMetadata??{},f=u!==!1&&d(o)&&d(s);if(!(f&&await n.releaseRequest(o,s))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:G,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),Ie=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],Le=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],Re=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],ze=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=d(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),u=c.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.closeCacheClient(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(s(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(d(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&(r.reset?.(),this.instances.delete(e)),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}},TransportManagersUnavailableError=class extends Error{constructor(...e){super(...e),this.name=`TransportManagersUnavailableError`}};const Be=new LogThrottle(6e4),getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),s(n?.service)||s(n?.organizationId)||o===`test`||s(t)||s(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=l?.isReady(),p=u?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw new TransportManagersUnavailableError(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw new TransportManagersUnavailableError(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...Re),h.push(...ze)}let g=generateRequestKey(n);if(s(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:d(a)}}),a;let _=await Ae.get(g);if(d(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await Ae.set(g,y,600),y}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(a)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=Be.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);d(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);return d(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:Ie,responseConfigs:Le},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>y.create({maxBodyLength:1/0}),Ve=Symbol.for(`@stackone/transport/cancelledCallCount`),getCancelledCallCount=e=>{let t=Reflect.get(e,Ve);return typeof t==`number`?t:0},recordCancelledCall=e=>Reflect.set(e,Ve,getCancelledCallCount(e)+1),isCancelledByRequestAbort=(e,t)=>e?.aborted===!0&&`code`in t&&t.code===`ERR_CANCELED`&&isRequestAbortedError(e.reason),He=/^-?\d+$/,Ue=/(?:^|[-:,[\s])(?:\d{17,}|9\d{15})(?![\d.eE])/,reviveLargeIntegersAsStrings=(e,t,n)=>{let r=n?.source;return typeof t==`number`&&!Number.isSafeInteger(t)&&typeof r==`string`&&He.test(r)?r:t},parseJsonOrKeep=e=>{try{return JSON.parse(e)}catch{return e}},parseJsonExactly=(e,t,n)=>{if(typeof e!=`string`||t&&t!==`json`)return e;if(!Ue.test(e))return parseJsonOrKeep(e);try{return JSON.parse(e,reviveLargeIntegersAsStrings)}catch(t){return t instanceof RangeError?(n?.warning({category:`HttpClient`,message:`JSON body nested too deep to keep large integers exact, parsed without them.`,error:t}),parseJsonOrKeep(e)):e}},We=[`auth`,`token`,`key`,`secret`,`password`,`cookie`,`session`,`signature`,`credential`],isCredentialHeaderName=e=>{let t=e.toLowerCase();return We.some(e=>t.includes(e))},buildSafeRequestHeaders=e=>{let t=ne(e),n=Object.fromEntries(Object.entries(t??{}).filter(([t,n])=>n===e[t]&&!isCredentialHeaderName(t)));return Object.keys(n).length>0?n:void 0},byteLength=e=>e.reduce((e,t)=>e+t.length,0),readErrorBody=async(e,t,n)=>{let r=setTimeout(()=>e.destroy(Error(`Timed out reading the error body`)),n);try{let n=[];for await(let r of e)if(n.push(Buffer.from(r)),byteLength(n)>t)return;return Buffer.concat(n)}catch{return}finally{clearTimeout(r),e.destroy()}},toCallerSafeConfig=e=>s(e)?void 0:{url:O(e.url),method:e.method},toCallerSafeError=async(e,{maxBodyBytes:t=1048576,bodyReadTimeoutMs:n=5e3}={})=>{if(!x(e))return e;let r=e,i=toCallerSafeConfig(r.config);return r.config=i,r.request=void 0,d(r.response)&&(r.response.config=i,r.response.request=void 0,r.response.data instanceof re&&(r.response.data=await readErrorBody(r.response.data,t,n))),r},buildProxyConfig=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return{protocol:t,host:n,port:Number(r)}},Ge=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&Ge.has(e),toFailureCacheKey=e=>`${e}-error`,Ke=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&Ke in e,rebuildCachedFailure=(e,t)=>{let n={url:e.requestUrl,method:t},r={status:e.status,statusText:``,data:e.data,headers:e.headers,config:n},i=new b(e.message??`Request failed with status code ${e.status}`,b.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[Ke]:!0})};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?i(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getDataBatch([toFailureCacheKey(a),a]),s=o?.[0]??o?.[1]??null;return s?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),s):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async#l(e){if(!s(e))try{return(await B.getInstance().get(e))?.signal}catch(t){this.#n?.warning({category:this.name,message:`Could not look up the abort controller for trace [${e}], so the call cannot be cancelled.`,error:t instanceof Error?t:Error(String(t))});return}}#u({signal:e,error:t,message:n}){isCancelledByRequestAbort(e,t)&&recordCancelledCall(e)||this.#n?.warning({category:this.name,message:n,error:t})}async#d({url:e,payload:t,method:n,cacheTTL:r,context:i,error:a}){if(!this.#a||s(r)||r<=0||!x(a)||!isCacheableFailureStatus(a.response?.status))return!1;let o={data:a.response?.data,status:a.response?.status,headers:this.#p(a.response?.headers??{}),method:n,requestUrl:e,message:a.message,responseTime:new Date},c=this.#o({url:e,payload:t,method:n,context:i});if(!c)return!1;let l=toFailureCacheKey(c);return this.#n?.debug({category:this.name,message:`Caching ${o.status} for key [${l}].`}),this.#a.setData({key:l,value:o,cacheTTL:60})}async request({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,responseType:o,cacheTTL:c,context:l,traceId:u,payload:f,httpsAgent:p,httpAgent:m,requestConfig:h,httpsAgentConfig:g,timeoutMs:_,proxyUrl:v}){let y=await this.#l(u);try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let u=this.#x(t,r,i),b=this.#f(e),x=this.#v(f,e),S=await this.#s({url:u,payload:x,method:n,cacheTTL:c,context:l});if(S){if(isCacheableFailureStatus(S.status))throw rebuildCachedFailure(S,n);return{...S,responseTime:new Date}}let C=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:h,httpsAgentConfig:g})).request({headers:b,url:u,method:n,maxRedirects:a,responseType:o,data:x,httpsAgent:p,httpAgent:m,signal:y,...d(_)&&{timeout:_},...v&&{proxy:buildProxyConfig(v)},transformResponse:e=>parseJsonExactly(e,o,this.#n)}),w={data:C.data,status:C.status,body:x,method:n,headers:this.#p(C.headers),requestHeaders:buildSafeRequestHeaders(b),requestUrl:u,responseType:C?.config?.responseType,responseTime:new Date};return await this.#c({url:u,payload:x,method:n,cacheTTL:c,context:l,response:w}),w}catch(a){if(isReplayedFailure(a)){let e=await toCallerSafeError(a),t=this.#y(e);throw d(t)?t:e}let o=await toCallerSafeError(a);o.url=O(t),this.#u({signal:y,error:o,message:`Request error [${n?.toUpperCase()} ${o.url}]: ${o.message}.`}),await this.#d({url:this.#x(t,r,i),payload:this.#v(f,e),method:n,cacheTTL:c,context:l,error:o});let s=this.#y(o);throw d(s)?s:o}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s,proxyUrl:c}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s,proxyUrl:c})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s,proxyUrl:c}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s,proxyUrl:c})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,context:o,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:f,httpsAgentConfig:p,proxyUrl:m}){let h=await this.#l(s);try{let s=this.#x(t,r,i),d=this.#f(e),g=this.#v(c,e),_=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:o,requestConfig:f,httpsAgentConfig:p})).request({headers:d,url:s,method:n,maxRedirects:a,responseType:`stream`,data:g,httpsAgent:l,httpAgent:u,signal:h,...m&&{proxy:buildProxyConfig(m)}});return{status:_.status,headers:this.#p(_.headers),stream:_.data,requestUrl:t}}catch(e){let r=await toCallerSafeError(e);r.url=O(t),this.#u({signal:h,error:r,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`});let i=this.#y(r);throw d(i)?i:r}}#f(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#p(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#m(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#h(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#g(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#_(e){return Buffer.isBuffer(e)}#v(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#h(t)||this.#g(e)||this.#_(e)||typeof e==`string`?e:this.#m(t)?k.stringify(e):e}#y(e){if(x(e)&&this.#i)return this.#i(e)}#b(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#x(e,t,n){if(s(t)||Object.keys(t).length===0)return e;let r={},i={},a={},o={},c={};for(let[e,n]of Object.entries(t))if(this.#b(n)){let t=n.arrayFormat,s=n.value;t===`repeat`?i[e]=Array.isArray(s)?s:[s]:t===`brackets`?a[e]=Array.isArray(s)?s:[s]:t===`comma`?o[e]=Array.isArray(s)?s:[s]:t===`stringify`?c[e]=JSON.stringify(Array.isArray(s)?s:[s]):r[e]=s}else r[e]=n;let l=n===!1?{encode:!1}:{},u=[];Object.keys(r).length>0&&u.push(k.stringify(r,l)),Object.keys(i).length>0&&u.push(k.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(k.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(o).length>0&&u.push(k.stringify(o,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(k.stringify(c,l));let f=u.join(`&`);return d(f)?`${e}?${f}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const qe=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
97
|
+
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==L)return;let n=this.leaseRegistry.get(e);if(!s(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==xe)return;let n=this.setRemovalRegistry.get(e);if(!s(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??r,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.debug({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(s(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return s(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(I)&&n.includes(be)&&n.includes(L)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,confirmedEvents:[...e],redisHost:this.redisClientConfig.host,redisPort:this.redisClientConfig.port,redisDatabase:this.redisClientConfig.database}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(Se.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(L,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(xe,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=N*5,s){let c=`concurrency:${e}`,l=`queue:${e}`,u=r.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,f=d(u)?`${c}-${u}`:c,{mainMaxConcurrency:p,subPools:m}=r,h=[{key:c,maxConcurrency:p},...m?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${c}-${t}`,maxConcurrency:n}})??[]],g=h.map(e=>e.key),_=h.map(e=>e.maxConcurrency),[v,y]=await Promise.all([this.subscribeToLeaseExpiry(i,f),this.subscribeToSetRemoval(f,l)]),b={requestId:i,targetConcurrencyKey:f,leaseSubscription:v,setRemovalSubscription:y,queueKey:l,acquired:!1},x=!1,S=!1;try{let e=await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]);if(d(e)&&e[0])return x=!0,{...b,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let r=d(e)?e[1]:``,a=0,c=o,u=[],isAborted=()=>s?.aborted===!0;for(;c>0&&a<5&&!isAborted();){let e=a>1,r=Math.min(N,c),o=Date.now();S=!0;let m=await this.queueManager?.joinAndWaitTurn(l,i,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]),!1,r,s);c-=Math.max(Date.now()-o,0);let h=d(m)?m[0]:!1,v=d(m)?m[1]:``;if(d(v)&&v!==``&&u.push(v),a++,h)return x=!0,a>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${a} attempts.`,context:{...b,registerAttempts:a,joinCondition:`attempts`,failureMessages:u}}),{...b,joinCondition:`attempts`,acquired:!0};let y=n(a,100);if(c-=y,c<=0||isAborted())break;await t(y)}if(a===0){let e=isAborted()?`aborted`:`no-wait-budget`;return this.logger?.warning({category:this.name,message:isAborted()?`Request aborted before queueing for a concurrency slot.`:`No wait budget left to queue for a concurrency slot, proceeding fail-open.`,context:{...b,registerAttempts:a,joinCondition:e,maxWaitMs:o,optimisticFailureReason:r}}),{...b,joinCondition:e}}return this.logger?.error({category:this.name,message:`Failed to register request after ${a} attempts.`,context:{...b,registerAttempts:a,joinCondition:`failed`,failureMessages:u,optimisticFailureReason:r},code:`ConcurrencyManagerRegistrationFailed`}),{...b,joinCondition:`failed`}}finally{if(!x&&(this.leaseRegistry.delete(buildLeaseKey(f,i)),S))try{await this.queueManager?.remove(l,i)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...b,queueKey:l},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if(u(t)&&u(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}releaseAdditionalResources(){this.subscriptionManager?.close(),this.subscriptionManager=null}close(){this.releaseAdditionalResources(),this.queueManager?.close(),this.scriptMap?.clear(),this.closeCacheClient(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const R={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if(s(t)||t?.length===0||s(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=v(r,n?{...e,credentials:n}:e)===!0;if(s(r)||i){let n=t?.message,r;return r=s(n)?R[t.targetStatus]??`Unknown error`:String(v(n,e)??R[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},Te=p({receivedStatus:f.number().meta({description:`Provider HTTP status code to match.`}),targetStatus:f.number().meta({description:`HTTP status code to return in place of the matched one.`}),message:f.string().optional().meta({description:`Error message to return in place of the provider's.`}),condition:f.string().optional().meta({description:`A JEXL expression that applies the remap only when it evaluates true.`})}).meta({description:`Remaps provider error responses to different statuses or messages. Useful for GraphQL APIs that return errors with a 200 status, normalizing provider-specific error formats, and giving AI agents clearer error messages.`});var z=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const Ee=[`client_disconnect`,`timeout`],De=`RequestAbortedError`,Oe={client_disconnect:`Client disconnected`,timeout:`Request timed out`};var RequestAbortedError=class extends Error{constructor(e){super(Oe[e]),this.name=De,this.reason=e}};const isRequestAbortedError=e=>e instanceof Error&&e.name===De&&Ee.includes(e.reason),isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet,n=0)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(n>=64)return`[Max Depth Exceeded]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let r=e.map(e=>safeSerialize(e,t,n+1));return t.delete(e),r}let r=e,i={};t.add(r);for(let[e,a]of Object.entries(r))i[e]=safeSerialize(a,t,n+1);return t.delete(r),i},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}},ke={keepAlive:!0,maxFreeSockets:8,scheduling:`lifo`};var KeepAliveHttpsAgent=class extends S.Agent{keepSocketAlive(e){let t=this.options.timeout===void 0;t&&(this.options.timeout=4e3);try{return super.keepSocketAlive(e)}finally{t&&delete this.options.timeout}}};const B=`http-transport`,countSocketsInUse=e=>Object.values(e.sockets).reduce((e,t)=>e+(t?.length??0),0),listHostsInUse=e=>{let t=Object.values(e.sockets).flatMap(e=>e??[]).map(e=>e.servername||e.remoteAddress).filter(e=>typeof e==`string`&&e!==``);return[...new Set(t)]},closeAgentWhenIdle=(e,{pollIntervalMs:t=1e3,maxWaitMs:n=21e5,logger:r,logContext:i}={})=>{let a=countSocketsInUse(e);if(a===0){e.destroy();return}r?.info({category:B,message:`Closing a transport instance with ${a} requests still running, waiting for them to finish.`,context:{...i,busyRequestsAtClose:a,hosts:listHostsInUse(e)}});for(let t of Object.values(e.freeSockets))for(let e of t??[])e.destroy();let o=Date.now(),s=setInterval(()=>{let t=Date.now()-o,c=countSocketsInUse(e);if(c===0)clearInterval(s),e.destroy(),r?.info({category:B,message:`The ${a} requests still running when a transport instance was closed have finished after ${t} ms.`,context:{...i,busyRequestsAtClose:a,waitedMs:t}});else if(t>=n){clearInterval(s);let n=listHostsInUse(e);e.destroy(),r?.warning({category:B,message:`Cut off ${c} requests still running ${t} ms after their transport instance was closed.`,context:{...i,busyRequestsAtClose:a,reapedRequests:c,waitedMs:t,hosts:n}})}},t);s.unref()};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=n?.keepAlive?new KeepAliveHttpsAgent(n):new S.Agent(n),l=y.create({...t,httpsAgent:c});if(l.close=()=>{closeAgentWhenIdle(c,{logger:r,logContext:{accountSecureId:i?.accountSecureId,projectSecureId:i?.projectSecureId,provider:i?.provider,service:i?.service,resource:i?.resource,action:i?.action}})},e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return d(e)&&a(e)&&typeof e(t)==`function`?e(t):e??null}};const buildCloseEvictedInstance=(e,t)=>async(n,r)=>{try{await r?.close?.()}catch(r){e()?.error({message:`Failed to close evicted instance "${n}"`,category:t,error:r,code:`InstanceManagerDisposeError`})}},V=3600*24*7*1e3;var H=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return s(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager({staleDataThreshold:V,truncateThreshold:1e4,...e})),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,slidingExpiration:!0,typeGuard:e=>d(e),dispose:buildCloseEvictedInstance(()=>this.options.logger,InstanceManager.name)}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}setLogger(e){this.options={...this.options,logger:e},InstanceManager.logger=e??null,this.dataStore?.setLogger?.(e)}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:d(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return d(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const Ae=H.getInstance(),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},je={mainRatelimit:25},U=1e3,Me=/^\d+(\.\d+)?$/,Ne=6e4,createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},W=e((e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&ee(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},`abortableDelay`),G=`checkConcurrencyInterceptor`,Pe=new LogThrottle(Ne),Fe=new LogThrottle(Ne),checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if(s(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:G,...a,httpsAgent:void 0,headers:void 0,hasContext:d(t),hasConfig:d(a)},code:`InterceptorContextNotPresent`});else if(s(i)||s(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:G,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:d(i),concurrencyManagerInitialized:d(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if(d(t.provider)&&d(t.accountSecureId)){let o=T(),{provider:l,accountSecureId:u}=t,f=n?.rateLimits??je,p=n?.concurrency??Ce,m=await i.getDynamicMaxWaitTime(f,p,a.url),h=a._waitDeadlineAt,g=c(h)&&Number.isFinite(h)?h:Date.now()+m*U,remainingBudgetMs=()=>Math.max(g-Date.now(),0),_=`${u}-${l}`,register=async()=>r.registerRequest(_,p,o,a.url,remainingBudgetMs(),a.signal),v=remainingBudgetMs()<=0,y;do{let t=await i.getWaitTime(_,f,a.url);if(s(t)){let t=Pe.consume(_);d(t)&&e?.warning({category:`HttpClient`,message:`Rate limiter unavailable for ${l} - Account: ${u}, proceeding without a limit`,context:{interceptor:G,provider:l,accountSecureId:u,suppressedSinceLastLog:t.suppressed},code:`InterceptorRateLimitUnavailable`})}let n=t??0;if(n<=0){y=await register();break}if(remainingBudgetMs()<=0)break;await W(Math.min(Math.max(n,50),remainingBudgetMs()),a)}while(remainingBudgetMs()>0);if(s(y)){y=await register();let n={...t,interceptor:G,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:m,joinCondition:y?.joinCondition};if(v){let t=Fe.consume(_);d(t)&&e?.warning({category:`HttpClient`,message:`Wait budget already spent by an earlier attempt for ${l} - Account: ${u}, proceeding without waiting`,context:{...n,suppressedSinceLastLog:t.suppressed},code:`InterceptorWaitBudgetAlreadySpent`})}else e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${l} - Account: ${u}`,context:n,code:`InterceptorMaxWaitTimeExceeded`})}return{...a,requestMetadata:y,_waitDeadlineAt:g}}return a};return checkConcurrencyInterceptor},adjustUnixTimestamp=e=>e<3250368e4?e*U:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&o(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*U},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=E(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:c}=e??{};return[t,n,r,o].some(s)?null:[t,n,r,i,a,o,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return o(e)||c(e)?evaluateRetryAfterNumber(Number(e),r,t,n):D(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/U);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Me.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/U);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i})=>{let retryErrorInterceptor=async a=>{let{response:o,config:s}=a;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,i,r,t);if(c===429&&d(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*U:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await W(d,s,o),e?.request(u)}return Promise.reject(a)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{status:i,headers:a,data:o}=e??{},{retryafter:s}=superNormalizeHeaders(a??{}),c=n?.rateLimits?.mappedRateLimitErrors;if(d(c)&&d(o))for(let e of c){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:c,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==i)continue;let f=n??`message`,p=testMessage(l(o)?O({path:f,json:o})[0]:o,r);if(t===i&&p){let e=convertRetryAfter(d??extractRetryAfter(a,c),u);return{status:429,retryAfter:s??e}}}return{status:i,retryAfter:s}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>d(t)&&d(e)?O({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>d(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/U;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},K=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i,concurrencyManager:a})=>{let rateLimitErrorInterceptor=async o=>{let{response:c,config:l}=o,u=l?.signal;if(s(i))return t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:K,...l,httpsAgent:void 0,headers:void 0},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(l))return Promise.reject(o);if(s(a))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:K,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(a)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(o);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h,acquired:g}=l?.requestMetadata??{},_=g!==!1&&d(f)&&d(p);if(!(_&&await a.releaseRequest(f,p))&&_&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:K,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:`RateLimiterReleaseRequestFailed`}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,l,`ERR_CANCELED`,c));let{status:v,retryAfter:y}=convertError(c,i,r,t);if(v===429&&d(l)){let r=getRetryAfterWaitTime(y);if(l._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:y,retryAfterAsNumber:r}}),Promise.reject(o);let a=l?._retryCount??0,s={...l,_retryCount:a+1},u=y?r*U:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:y,calculatedRetryAfter:u}}),await W(u,l,c),e?.request(s)}return Promise.reject(o)};return rateLimitErrorInterceptor},q=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if(s(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:q,...i,httpsAgent:void 0,headers:void 0}});else if(s(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:q,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if(d(t.provider)&&d(t.accountSecureId)){let t=r?.headers;if(d(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:q,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l,acquired:u}=i?.requestMetadata??{},f=u!==!1&&d(o)&&d(s);if(!(f&&await n.releaseRequest(o,s))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:q,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},Ie=new Set([`ECONNRESET`,`EPIPE`]),isResetOnReusedSocket=e=>{let t=e.request;return s(e.response)&&Ie.has(e.code??``)&&(t?._currentRequest??t)?.reusedSocket===!0},Le=[ne.Agent,S.Agent,KeepAliveHttpsAgent],isRebuildable=e=>Le.includes(e.constructor)&&!Object.prototype.hasOwnProperty.call(e,`createConnection`),unpooledCopy=(e,t)=>s(e)||isRebuildable(e)?new t({...e?.options,keepAlive:!1}):e,withFreshConnection=e=>({...e,_staleSocketRetried:!0,httpAgent:unpooledCopy(e.httpAgent,ne.Agent),httpsAgent:unpooledCopy(e.httpsAgent,S.Agent)}),withoutQuery=(e=``)=>k(e.split(`?`)[0]),staleSocketRetryInterceptor=({axiosInstance:e,logger:t,context:n})=>{let staleSocketRetryInterceptor=async r=>{let{config:i}=r;if(s(i)||!isResetOnReusedSocket(r))return Promise.reject(r);let a=(i.method??`get`).toUpperCase(),o=a===`GET`&&i._staleSocketRetried!==!0&&i.signal?.aborted!==!0&&d(e);return t?.info({category:`http-transport`,message:`Provider closed a reused connection [${a} ${withoutQuery(i.url)}]: ${r.code}. ${o?`Retrying once on a new connection.`:`Not retried.`}`,context:{...n??{},method:a,errorCode:r.code,retried:o}}),o?e?.request(withFreshConnection(i)):Promise.reject(r)};return staleSocketRetryInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),Re=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ze=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],Be=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],Ve=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:staleSocketRetryInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=d(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),u=c.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.closeCacheClient(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(s(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(d(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&(r.reset?.(),this.instances.delete(e)),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}},TransportManagersUnavailableError=class extends Error{constructor(...e){super(...e),this.name=`TransportManagersUnavailableError`}};const He=new LogThrottle(6e4),getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),s(n?.service)||s(n?.organizationId)||o===`test`||s(t)||s(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=l?.isReady(),p=u?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw new TransportManagersUnavailableError(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw new TransportManagersUnavailableError(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...Be),h.push(...Ve)}let g=generateRequestKey(n);if(s(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:d(a)}}),a;let _=await Ae.get(g);if(d(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:c.includes(`CONCURRENCY`)?{...ke,...i}:i,concurrencyManager:u,rateLimitManager:l},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await Ae.set(g,y,600),y}catch(t){let r={category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(a)},error:t,code:`HttpTransportInstanceCreateError`};if(t instanceof TransportManagersUnavailableError){let t=He.consume(`${n?.service??`unknown`}:${n?.organizationId??`unknown`}`);d(t)&&e?.warning({...r,context:{...r.context,suppressedSinceLastLog:t.suppressed}})}else e?.error(r);return d(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:Re,responseConfigs:ze},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>y.create({maxBodyLength:1/0}),Ue=Symbol.for(`@stackone/transport/cancelledCallCount`),getCancelledCallCount=e=>{let t=Reflect.get(e,Ue);return typeof t==`number`?t:0},recordCancelledCall=e=>Reflect.set(e,Ue,getCancelledCallCount(e)+1),isCancelledByRequestAbort=(e,t)=>e?.aborted===!0&&`code`in t&&t.code===`ERR_CANCELED`&&isRequestAbortedError(e.reason),We=/^-?\d+$/,Ge=/(?:^|[-:,[\s])(?:\d{17,}|9\d{15})(?![\d.eE])/,reviveLargeIntegersAsStrings=(e,t,n)=>{let r=n?.source;return typeof t==`number`&&!Number.isSafeInteger(t)&&typeof r==`string`&&We.test(r)?r:t},parseJsonOrKeep=e=>{try{return JSON.parse(e)}catch{return e}},parseJsonExactly=(e,t,n)=>{if(typeof e!=`string`||t&&t!==`json`)return e;if(!Ge.test(e))return parseJsonOrKeep(e);try{return JSON.parse(e,reviveLargeIntegersAsStrings)}catch(t){return t instanceof RangeError?(n?.warning({category:`HttpClient`,message:`JSON body nested too deep to keep large integers exact, parsed without them.`,error:t}),parseJsonOrKeep(e)):e}},Ke=[`auth`,`token`,`key`,`secret`,`password`,`cookie`,`session`,`signature`,`credential`],isCredentialHeaderName=e=>{let t=e.toLowerCase();return Ke.some(e=>t.includes(e))},buildSafeRequestHeaders=e=>{let t=te(e),n=Object.fromEntries(Object.entries(t??{}).filter(([t,n])=>n===e[t]&&!isCredentialHeaderName(t)));return Object.keys(n).length>0?n:void 0},byteLength=e=>e.reduce((e,t)=>e+t.length,0),readErrorBody=async(e,t,n)=>{let r=setTimeout(()=>e.destroy(Error(`Timed out reading the error body`)),n);try{let n=[];for await(let r of e)if(n.push(Buffer.from(r)),byteLength(n)>t)return;return Buffer.concat(n)}catch{return}finally{clearTimeout(r),e.destroy()}},toCallerSafeConfig=e=>s(e)?void 0:{url:k(e.url),method:e.method},toCallerSafeError=async(e,{maxBodyBytes:t=1048576,bodyReadTimeoutMs:n=5e3}={})=>{if(!x(e))return e;let r=e,i=toCallerSafeConfig(r.config);return r.config=i,r.request=void 0,d(r.response)&&(r.response.config=i,r.response.request=void 0,r.response.data instanceof re&&(r.response.data=await readErrorBody(r.response.data,t,n))),r},buildProxyConfig=e=>{let{protocol:t,hostname:n,port:r}=new URL(e);return{protocol:t,host:n,port:Number(r)}},qe=new Set([404]),isCacheableFailureStatus=e=>e!==void 0&&qe.has(e),toFailureCacheKey=e=>`${e}-error`,Je=Symbol(`replayedCachedFailure`),isReplayedFailure=e=>typeof e==`object`&&!!e&&Je in e,rebuildCachedFailure=(e,t)=>{let n={url:e.requestUrl,method:t},r={status:e.status,statusText:``,data:e.data,headers:e.headers,config:n},i=new b(e.message??`Request failed with status code ${e.status}`,b.ERR_BAD_REQUEST,n,void 0,r);return Object.assign(i,{[Je]:!0})};var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?i(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getDataBatch([toFailureCacheKey(a),a]),s=o?.[0]??o?.[1]??null;return s?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),s):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async#l(e){if(!s(e))try{return(await H.getInstance().get(e))?.signal}catch(t){this.#n?.warning({category:this.name,message:`Could not look up the abort controller for trace [${e}], so the call cannot be cancelled.`,error:t instanceof Error?t:Error(String(t))});return}}#u({signal:e,error:t,message:n}){isCancelledByRequestAbort(e,t)&&recordCancelledCall(e)||this.#n?.warning({category:this.name,message:n,error:t})}async#d({url:e,payload:t,method:n,cacheTTL:r,context:i,error:a}){if(!this.#a||s(r)||r<=0||!x(a)||!isCacheableFailureStatus(a.response?.status))return!1;let o={data:a.response?.data,status:a.response?.status,headers:this.#p(a.response?.headers??{}),method:n,requestUrl:e,message:a.message,responseTime:new Date},c=this.#o({url:e,payload:t,method:n,context:i});if(!c)return!1;let l=toFailureCacheKey(c);return this.#n?.debug({category:this.name,message:`Caching ${o.status} for key [${l}].`}),this.#a.setData({key:l,value:o,cacheTTL:60})}async request({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,responseType:o,cacheTTL:c,context:l,traceId:u,payload:f,httpsAgent:p,httpAgent:m,requestConfig:h,httpsAgentConfig:g,timeoutMs:_,proxyUrl:v}){let y=await this.#l(u);try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let u=this.#x(t,r,i),b=this.#f(e),x=this.#v(f,e),S=await this.#s({url:u,payload:x,method:n,cacheTTL:c,context:l});if(S){if(isCacheableFailureStatus(S.status))throw rebuildCachedFailure(S,n);return{...S,responseTime:new Date}}let C=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:h,httpsAgentConfig:g})).request({headers:b,url:u,method:n,maxRedirects:a,responseType:o,data:x,httpsAgent:p,httpAgent:m,signal:y,...d(_)&&{timeout:_},...v&&{proxy:buildProxyConfig(v)},transformResponse:e=>parseJsonExactly(e,o,this.#n)}),w={data:C.data,status:C.status,body:x,method:n,headers:this.#p(C.headers),requestHeaders:buildSafeRequestHeaders(b),requestUrl:u,responseType:C?.config?.responseType,responseTime:new Date};return await this.#c({url:u,payload:x,method:n,cacheTTL:c,context:l,response:w}),w}catch(a){if(isReplayedFailure(a)){let e=await toCallerSafeError(a),t=this.#y(e);throw d(t)?t:e}let o=await toCallerSafeError(a);o.url=k(t),this.#u({signal:y,error:o,message:`Request error [${n?.toUpperCase()} ${o.url}]: ${o.message}.`}),await this.#d({url:this.#x(t,r,i),payload:this.#v(f,e),method:n,cacheTTL:c,context:l,error:o});let s=this.#y(o);throw d(s)?s:o}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s,proxyUrl:c}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s,proxyUrl:c})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s,proxyUrl:c}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s,proxyUrl:c})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,context:o,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:f,httpsAgentConfig:p,proxyUrl:m}){let h=await this.#l(s);try{let s=this.#x(t,r,i),d=this.#f(e),g=this.#v(c,e),_=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:o,requestConfig:f,httpsAgentConfig:p})).request({headers:d,url:s,method:n,maxRedirects:a,responseType:`stream`,data:g,httpsAgent:l,httpAgent:u,signal:h,...m&&{proxy:buildProxyConfig(m)}});return{status:_.status,headers:this.#p(_.headers),stream:_.data,requestUrl:t}}catch(e){let r=await toCallerSafeError(e);r.url=k(t),this.#u({signal:h,error:r,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`});let i=this.#y(r);throw d(i)?i:r}}#f(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#p(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#m(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#h(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#g(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#_(e){return Buffer.isBuffer(e)}#v(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#h(t)||this.#g(e)||this.#_(e)||typeof e==`string`?e:this.#m(t)?A.stringify(e):e}#y(e){if(x(e)&&this.#i)return this.#i(e)}#b(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#x(e,t,n){if(s(t)||Object.keys(t).length===0)return e;let r={},i={},a={},o={},c={};for(let[e,n]of Object.entries(t))if(this.#b(n)){let t=n.arrayFormat,s=n.value;t===`repeat`?i[e]=Array.isArray(s)?s:[s]:t===`brackets`?a[e]=Array.isArray(s)?s:[s]:t===`comma`?o[e]=Array.isArray(s)?s:[s]:t===`stringify`?c[e]=JSON.stringify(Array.isArray(s)?s:[s]):r[e]=s}else r[e]=n;let l=n===!1?{encode:!1}:{},u=[];Object.keys(r).length>0&&u.push(A.stringify(r,l)),Object.keys(i).length>0&&u.push(A.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(A.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(o).length>0&&u.push(A.stringify(o,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(A.stringify(c,l));let f=u.join(`&`);return d(f)?`${e}?${f}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const Ye=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
98
98
|
`).replace(/\r\n/g,`
|
|
99
99
|
`).replace(/\r/g,`
|
|
100
100
|
`).trim();t=t.replace(/(-----BEGIN [A-Z0-9 ]+-----) +/g,`$1
|
|
101
101
|
`),t=t.replace(/ +(-----END [A-Z0-9 ]+-----)/g,`
|
|
102
102
|
$1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+-----)/);if(n){let[,e,r,i]=n;if(!r.includes(`
|
|
103
103
|
`)&&r.includes(` `)){let n=r.replace(/ /g,``);t=`${e}\n${n.match(/.{1,64}/g)?.join(`
|
|
104
|
-
`)??n}\n${i}`}}return t},decodeCertOrKey=e=>{if(!e||e.length===0)return e;let t=normalizePem(e);if(isPemFormat(t))return t;try{let e=Buffer.from(t,`base64`).toString(`utf-8`);return isPemFormat(e)?normalizePem(e):t}catch{return t}},buildHttpsAgent=e=>{if(!e)return;let{certs:t,keys:n}=e;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(e=>typeof e==`string`&&e.trim().length>0),i=n.filter(e=>typeof e==`string`&&e.trim().length>0);if(r.length===0||i.length===0)return;let a=r.map(decodeCertOrKey),o=i.map(decodeCertOrKey);return new S.Agent({cert:a,key:o})};var
|
|
104
|
+
`)??n}\n${i}`}}return t},decodeCertOrKey=e=>{if(!e||e.length===0)return e;let t=normalizePem(e);if(isPemFormat(t))return t;try{let e=Buffer.from(t,`base64`).toString(`utf-8`);return isPemFormat(e)?normalizePem(e):t}catch{return t}},buildHttpsAgent=e=>{if(!e)return;let{certs:t,keys:n}=e;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(e=>typeof e==`string`&&e.trim().length>0),i=n.filter(e=>typeof e==`string`&&e.trim().length>0);if(r.length===0||i.length===0)return;let a=r.map(decodeCertOrKey),o=i.map(decodeCertOrKey);return new S.Agent({cert:a,key:o})};var J=class PersistentInstanceManager{static{this.instance=null}constructor(e={}){this.dataStore=null,this.logger=e.logger,this.initialize()}static getInstance(e={}){return s(PersistentInstanceManager.instance)&&(PersistentInstanceManager.instance=new PersistentInstanceManager(e)),PersistentInstanceManager.instance}initialize(){this.dataStore=new MemoryStore({instantiator:PersistentInstanceManager.name,logger:this.logger,staleDataThreshold:V,truncateThreshold:1e3,slidingExpiration:!0,typeGuard:e=>d(e),dispose:buildCloseEvictedInstance(()=>this.logger,PersistentInstanceManager.name)})}setLogger(e){this.logger=e,this.dataStore?.setLogger?.(e)}static liveStore(){return PersistentInstanceManager.getInstance().dataStore}async get(e){return await PersistentInstanceManager.liveStore()?.getData(e)??null}async set(e,t,n){return await PersistentInstanceManager.liveStore()?.setData({key:e,value:t,cacheTTL:d(n)?n:604800})??!1}isReady(){return d(this.dataStore)&&this.dataStore.isAvailable()}close(){let e=this.dataStore;this.dataStore=null,PersistentInstanceManager.instance===this&&(PersistentInstanceManager.instance=null),e?.close?.()}};J.getInstance();const Xe={rPush:`
|
|
105
105
|
-- Drop any stale copy first so a retrying request holds at most one queue slot.
|
|
106
106
|
redis.call('LREM', KEYS[1], 0, ARGV[1])
|
|
107
107
|
|
|
@@ -126,7 +126,7 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
126
126
|
local queueKey = KEYS[1]
|
|
127
127
|
|
|
128
128
|
return redis.call("lpop", queueKey)
|
|
129
|
-
`,llen:`return redis.call("llen", KEYS[1])`},
|
|
129
|
+
`,llen:`return redis.call("llen", KEYS[1])`},Ze={incr:`
|
|
130
130
|
local targetKey = KEYS[1]
|
|
131
131
|
local totalLimit = tonumber(ARGV[1])
|
|
132
132
|
local windowMs = 1000
|
|
@@ -202,8 +202,8 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
202
202
|
-- open with a warning, so returning nil here would report the ordinary un-throttled path as
|
|
203
203
|
-- an outage. nil is reserved for the client genuinely being unavailable.
|
|
204
204
|
return 0
|
|
205
|
-
`};let q=null,J=null;const initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i,getCacheClient:a=buildRedisClientInstance}=e;d(n)&&(B.getInstance().setLogger(n),K.getInstance().setLogger(n));try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],o=await acquireSharedCacheClient(a,t,n);if(s(o))throw Error(`Failed to build the shared transport Redis client`);let[c,l]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,cacheClient:o,scripts:Je,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,cacheClient:o,scripts:Ye,logger:n})]),u=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,cacheClient:o,scripts:we,logger:n,additionalArgs:e}),d=[{name:`ConcurrencyManager`,ready:u.isReady()},{name:`QueueManager`,ready:c.isReady()},{name:`RateLimitManager`,ready:l.isReady()}],f=d.filter(e=>!e.ready);if(f.length>0){let e=f.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:d.map(e=>e.name)}}),{concurrencyManager:u,queueManager:c,rateLimitManager:l}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),closeAndResetManagers(n),await releaseSharedCacheClient(n),e}},acquireSharedCacheClient=async(e,t,n)=>{if(d(q))return q;J??=e(t,n,`TransportSystem`);try{return q=await J??null,q}finally{J=null}},releaseSharedCacheClient=async e=>{let t=q;if(q=null,J=null,!s(t))try{await t.close?.()}catch(t){e?.error({category:`TransportInitialization`,message:`Error closing the shared transport Redis client`,code:`TRANSPORT_CLIENT_CLOSE_ERROR`,error:t})}},closeAndResetManagers=e=>{let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);for(let[i,a]of[[`ConcurrencyManager`,t],[`QueueManager`,n],[`RateLimitManager`,r]])try{a?.close()}catch(t){e?.error({category:`TransportInitialization`,message:`Error closing ${i}`,code:`TRANSPORT_MANAGER_CLOSE_ERROR`,error:t})}SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager)},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`}),closeAndResetManagers(e),releaseSharedCacheClient(e),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},Xe=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/x-icon`,`image/vnd.microsoft.icon`]),startsWith=(e,t,n=0)=>t.every((t,r)=>e[n+r]===t),isRasterImage=e=>startsWith(e,[137,80,78,71,13,10,26,10])||startsWith(e,[255,216,255])||startsWith(e,[71,73,70,56])||startsWith(e,[82,73,70,70])&&startsWith(e,[87,69,66,80],8)||startsWith(e,[0,0,1,0]),getSite=e=>de(e,{allowPrivateDomains:!0}),isSameSite=(e,t)=>{let n=getSite(t.hostname);return n?getSite(e.hostname)===n:e.origin===t.origin},getMediaType=e=>(e.headers.get(`content-type`)??``).split(`;`)[0].trim().toLowerCase(),fetchOnSite=async(e,t,n=3)=>{if(e.protocol!==`https:`||e.href.length>2048||e.username||e.password||!isSameSite(e,t.server))return;let r=await t.fetchFn(e,{redirect:`manual`,signal:t.signal}),i=r.headers.get(`location`);if(r.status>=300&&r.status<400&&i&&n>0)return await r.body?.cancel(),fetchOnSite(new URL(i,e),t,n-1);if(!r.ok){await r.body?.cancel();return}return{response:r,url:e}},readBytes=async(e,t)=>{let n=e.body?.getReader(),r=[],i=0;try{for(;n&&i<t;){let{done:e,value:t}=await n.read();if(e)break;r.push(t),i+=t.length}}finally{await n?.cancel()}return Buffer.concat(r).subarray(0,t)},verifyIcon=async(e,t)=>{let n=await fetchOnSite(e,t);if(!n)return;if(!Xe.has(getMediaType(n.response))){await n.response.body?.cancel();return}let r=await readBytes(n.response,262145);return r.length<=262144&&isRasterImage(r)?n.url.toString():void 0},readAttributes=e=>new Map(Array.from(e.matchAll(/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g),([,e,...t])=>[e.toLowerCase(),(t.find(e=>e!==void 0)??``).replaceAll(`&`,`&`)])),findDeclaredIcons=(e,t,n)=>{let r=e.search(/<\/head\b|<body\b/i),i=r===-1?e:e.slice(0,r);return Array.from(i.matchAll(/<link\b[^<>]*>/gi),([e])=>{let r=readAttributes(e),i=(r.get(`rel`)??``).toLowerCase().split(/\s+/),a=i.some(e=>e.startsWith(`apple-touch-icon`)),o=r.get(`href`)?.trim(),s=o?URL.parse(o,t.href):null;return!(i.includes(`icon`)||a)||r.get(`type`)?.toLowerCase()===`image/svg+xml`||r.get(`media`)?.toLowerCase().includes(`dark`)||s?.protocol!==`https:`||!isSameSite(s,n)||s.pathname.toLowerCase().endsWith(`.svg`)?[]:[{url:s,size:(r.get(`sizes`)??``).split(/\s+/).reduce((e,t)=>Math.max(e,Number.parseInt(t,10)||0),0)||(a?180:0)}]}).flat().sort((e,t)=>t.size-e.size).map(({url:e})=>e)},readHomePage=async(e,t)=>{let n=await fetchOnSite(e,t);return!n||getMediaType(n.response)!==`text/html`?(await n?.response.body?.cancel(),{icons:[],url:n?.url??e}):{icons:findDeclaredIcons((await readBytes(n.response,1048576)).toString(`utf8`),n.url,t.server),url:n.url}},findMcpIcon=async(e,t,n=fetch)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),5e3);try{let i=new URL(e),a=getSite(i.hostname);if(i.protocol!==`https:`||!a)return;let o={server:i,fetchFn:n,signal:r.signal},tryIcon=e=>e?verifyIcon(e,o).catch(()=>void 0):void 0,s=await tryIcon(t?URL.parse(t):void 0);if(s)return s;let c=new URL(`https://${a}/`),l=await readHomePage(c,o).catch(()=>({icons:[],url:c})),u=[...l.icons.slice(0,3),new URL(`/favicon.ico`,l.url)];for(let e of u){let t=await tryIcon(e);if(t)return t}return}catch{return}finally{clearTimeout(i)}},abortReason=e=>e.reason??new DOMException(`The operation was aborted`,`AbortError`),abortableDelay=(e,t)=>t?.aborted?Promise.reject(abortReason(t)):new Promise((n,r)=>{let i=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e),onAbort=()=>{clearTimeout(i),r(abortReason(t))};t?.addEventListener(`abort`,onAbort,{once:!0})}),Ze=e((e,t)=>fetch(e,t),`defaultBaseFetch`),createRetryingFetch=(e=Ze,{maxRetries:t=5,delay:r=abortableDelay}={})=>{let fetchWithRetry=async(i,a,o)=>{let s=await e(i,a);if(s.status!==429||o>=t)return s;let c=s.headers.get(`retry-after`),l=o+1,u=c?getRetryAfterWaitTime(c)*V:n(l);return await s.body?.cancel().catch(()=>void 0),await r(u,a?.signal),fetchWithRetry(i,a,l)};return(e,t)=>fetchWithRetry(e,t,0)},defaultBaseFetch=(e,t)=>fetch(e,t),createThrottledFetch=(e=defaultBaseFetch,{requestConfig:t,context:n,getManagers:r=getTransportManagers,delay:i=abortableDelay}={})=>async(a,o)=>{let c=r(),l=n?.provider,u=n?.accountSecureId;if(s(c)||s(l)||s(u))return e(a,o);let{rateLimitManager:f,concurrencyManager:p}=c,m=t?.rateLimits??je,h=t?.concurrency??Ce,g=`${u}-${l}`,_=a.toString(),v=f.getDynamicMaxWaitTime(m,h,_),y=Date.now()+v*V,remainingBudgetMs=()=>Math.max(y-Date.now(),0),registerRequest=()=>p.registerRequest(g,h,fe(),_,remainingBudgetMs(),o?.signal??void 0),acquireSlot=async()=>{let e=await f.getWaitTime(g,m,_)??0;return e<=0||remainingBudgetMs()<=0?registerRequest():(await i(Math.min(Math.max(e,50),remainingBudgetMs()),o?.signal),acquireSlot())},b=await acquireSlot();try{return await e(a,o)}finally{let{requestId:e,targetConcurrencyKey:t,acquired:n}=b??{};n!==!1&&d(e)&&d(t)&&await p.releaseRequest(e,t).catch(()=>void 0)}},Qe={name:`stackone-connect`,version:`1.0.0`},$e={mode:`auto`},et={createClient:(e,t)=>new ie(e,t),createTransport:(e,t)=>new oe(e,t)};var McpClient=class{constructor(e,t=et){this.config=e,this.sdk=t}async callTool({name:e,arguments:t}){let{content:n,structuredContent:r,isError:i}=await(await this.getConnectedClient()).callTool({name:e,arguments:t??{}},this.buildRequestOptions());return{content:n??[],structuredContent:r,isError:i===!0}}async listTools(e){let t=await(await this.getConnectedClient()).listTools(e?.cursor?{cursor:e.cursor}:void 0,this.buildRequestOptions());return{tools:t.tools,nextCursor:t.nextCursor}}async getServerInfo(){let e=await this.getConnectedClient(),t=e.getServerVersion();return{name:t?.name,title:t?.title,version:t?.version,description:t?.description,websiteUrl:t?.websiteUrl,instructions:e.getInstructions(),iconUrl:this.resolveIconUrl(t?.icons)}}resolveIconUrl(e){let t=(e??[]).flatMap(e=>{let t=this.toServerIconUrl(e.src);return t?[{theme:e.theme,url:t}]:[]});return(t.find(e=>e.theme!==`dark`)??t[0])?.url}toServerIconUrl(e){if(e.trim())try{let t=new URL(this.config.serverUrl);t.search=``,t.hash=``;let n=new URL(e,t);return n.username=``,n.password=``,n.protocol===`https:`&&isSameSite(n,t)?n.toString():void 0}catch{return}}async close(){let e=this.connectedClient;this.connectedClient=void 0,e&&await(await e.catch(()=>void 0))?.close()}getConnectedClient(){return this.connectedClient??=this.connect(),this.connectedClient.catch(e=>{throw this.connectedClient=void 0,e})}async connect(){let{serverUrl:e,headers:t,clientInfo:n,requestConfig:r,context:i}=this.config,a=this.sdk.createClient(n??Qe,{versionNegotiation:$e}),o=this.sdk.createTransport(new URL(e),{requestInit:t?{headers:t}:void 0,fetch:createRetryingFetch(createThrottledFetch(void 0,{requestConfig:r,context:i}))});return await a.connect(o,this.buildRequestOptions()),a}buildRequestOptions(){return this.config.timeout?{timeout:this.config.timeout}:void 0}};const fetchAuthorizationChallenge=async e=>{let t=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:`ping`})});if(await t.body?.cancel().catch(()=>void 0),t.status!==401)return;let{resourceMetadataUrl:n,scope:r}=ue(t);return{resourceMetadataUrl:n?.toString(),scope:r}},tt={createClient:e=>new McpClient({serverUrl:e}),fetchAuthorizationChallenge,discoverResourceMetadata:(e,t)=>le(e,t?{resourceMetadataUrl:t}:void 0),discoverAuthorizationServer:e=>ce(e)},isAuthorizationFailure=e=>e instanceof se||e instanceof ae&&e.status===401,buildOAuthProbe=async(e,t,n)=>{let r=e?.authorization_servers,i=r?.[0]?await n.discoverAuthorizationServer(r[0]).catch(()=>void 0):void 0,a=e?.resource_name||e?.resource_documentation?{name:e.resource_name,documentationUrl:e.resource_documentation}:void 0;return{oauth:{scopes:e?.scopes_supported??t?.scope?.split(` `)??i?.scopes_supported,authorizationServers:r,dynamicRegistration:d(i)?d(i.registration_endpoint):void 0,resourceMetadataUrl:t?.resourceMetadataUrl},...a?{resource:a}:{}}},probeProtectedServer=async(e,t)=>{let n=await t.fetchAuthorizationChallenge(e).catch(()=>void 0),r=await t.discoverResourceMetadata(e,n?.resourceMetadataUrl).catch(()=>void 0);return!r&&!n?.resourceMetadataUrl?{requiresAuthorization:!0}:{requiresAuthorization:!0,...await buildOAuthProbe(r,n,t)}},probeOpenServer=async(e,t,n)=>{let r=await t.getServerInfo().catch(()=>void 0),i=await n.discoverResourceMetadata(e).catch(()=>void 0);return i?{requiresAuthorization:!0,...await buildOAuthProbe(i,void 0,n),server:r}:{requiresAuthorization:!1,server:r}},probeMcpServer=async(e,t=tt)=>{let n=t.createClient(e);try{return await n.listTools(),await probeOpenServer(e,n,t)}catch(n){if(!isAuthorizationFailure(n))throw n;return probeProtectedServer(e,t)}finally{await n.close().catch(()=>void 0)}},nt=e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),Y=e(e=>Array.isArray(e)?e:[e],`toStringArray`),isNullish=e=>e==null,toQueryValue=e=>Array.isArray(e)?e.filter(e=>!isNullish(e)).map(String):String(e),hasValue=e=>e.in===`body`||!isNullish(e.value),mergeQueryValues=(e,t,n)=>{let r=Y(t);if(nt(e))return{value:[...Y(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...Y(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.filter(hasValue).reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.inline)e.body=t.value;else if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),rt=[`query`,`body`,`headers`],it=[`repeat`,`brackets`,`comma`,`stringify`],X={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},at=new pe(X),getContentType=e=>{let t=Object.entries(e).find(([e])=>e.toLowerCase()===`content-type`)?.[1];return typeof t==`string`?t.toLowerCase():``},isXmlContentTypeValue=e=>e.includes(`application/xml`)||e.includes(`text/xml`)||/application\/\S+\+xml/.test(e),isXmlContentType=e=>isXmlContentTypeValue(getContentType(e)),serializeBodyToXml=e=>{try{return at.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?k.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>d(e)&&e>=200&&e<=299,isFailedStatusCode=e=>d(e)&&e>=400&&e<=599,isInfoStatusCode=e=>d(e)&&e>=100&&e<=199,ot=[`arraybuffer`,`blob`,`document`,`text`];let st;const getXmlParser=()=>(st??=new me({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),st);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,httpsAgent:u,credentials:d,responseType:f,context:p,cacheTTL:m,timeoutMs:h}){let g,_=o;if(isXmlContentType(r))if(typeof o==`string`)_=o;else if(Array.isArray(o))throw Error(`Cannot serialize an array body to XML: XML requires a single root element. Wrap the array in an object with a root key.`);else o!=null&&(_=serializeBodyToXml(o));try{g=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:_,requestConfig:l,httpsAgent:u,responseType:f,context:p,cacheTTL:m,timeoutMs:h})}catch(e){if(s(e?.response))throw e;g=e.response}if(typeof g.data==`string`&&/\S/.test(g.data)&&g.headers&&isXmlContentType(g.headers)&&(!f||!ot.includes(f))){let e=A.validate(g.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);g={...g,data:getXmlParser().parse(g.data)}}let v=translateCustomError(g,c,d);if(isFailedStatusCode(v?.status))throw new R(v,v.message);return v}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,credentials:u,context:d,cacheTTL:f}){let p;if(p=typeof l?.envelope==`string`?l.envelope:typeof l?.envelope==`object`?Z.build(l.envelope):await buildEnvelope(o,l),A.validate(p,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let m,h={"Content-Type":`application/xml`,...r};l?.soapAction&&(h.SOAPAction=l.soapAction);try{m=await e?.request({method:n,url:t,headers:h,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:p,requestConfig:l,context:d,cacheTTL:f})}catch(e){if(s(e?.response))throw e;m=e.response}let g=ct.parse(m.data),_=g.Envelope||g,v=_.Body||_,y=v.Fault;if(y)throw new R({...m,status:500,data:y,message:y.faultstring??y.faultcode??`SOAP Fault`},y.faultstring??`SOAP Fault occurred`);m.data=v;let b=translateCustomError(m,c,u);if(isFailedStatusCode(b?.status))throw new R(b,b.message);return b}};const Z=new pe(X),ct=new me({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if(d(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Z.build(t.envelope);if(A.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Z.build(n);if(A.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await _(e.namespaceIdentifier),namespace:await _(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(s(e)||s(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if(s(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if(s(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};const arrayFormatToPairs=(e,t,n)=>n===`brackets`?t.map(t=>[`${e}[]`,t]):n===`comma`?[[e,t.join(`,`)]]:n===`stringify`?[[e,JSON.stringify(t)]]:t.map(t=>[e,t]),toStringArray=e=>Array.isArray(e)?e:[e],isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),flattenQueryParams=e=>{if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))r!=null&&(isHttpQueryParamValue(r)?t.push(...arrayFormatToPairs(n,toStringArray(r.value),r.arrayFormat)):t.push(...arrayFormatToPairs(n,toStringArray(r),void 0)));return t},hmac=(e,t)=>w(`sha256`,e).update(t).digest(),hash=e=>C(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),Q=e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),lt=e((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),d=u.slice(0,8),f=new URL(e.url),p=f.pathname.split(`/`).map(e=>{try{return Q(decodeURIComponent(e))}catch{return Q(e)}}).join(`/`)||`/`,m=[];for(let[e,t]of f.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=lt(e,n);return i===0?lt(t,r):i});let h=m.map(([e,t])=>`${Q(e)}=${Q(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=C(`sha256`).update(g).digest(),v=_.toString(`hex`),y={host:f.host,"x-amz-content-sha256":v,"x-amz-date":u};a&&(y[`x-amz-security-token`]=a);for(let[t,n]of Object.entries(e.headers??{})){let e=t.toLowerCase();e!==`authorization`&&e!==`x-amz-date`&&e!==`x-amz-content-sha256`&&e!==`x-amz-security-token`&&(y[e]=n)}let b=Object.keys(y).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),x=g.length>0&&!b,S;x&&(S=_.toString(`base64`),y[`x-amz-checksum-sha256`]=S);let T=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),ee=T.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),E=T.join(`;`),te=[e.method.toUpperCase(),p,h,ee,E,v].join(`
|
|
206
|
-
`),
|
|
207
|
-
`),
|
|
208
|
-
`),_=w(c,r).update(g).digest(`hex`);return{[l]:`${u} ${_}`,"X-Timestamp":d}},
|
|
209
|
-
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${v}`).toString(`base64`)}`,Date:m}:{[i??`X-Signature`]:`${a??`hmac-${d}`} ${v}`,"X-Timestamp":m}}const
|
|
205
|
+
`};let Y=null,X=null;const initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i,getCacheClient:a=buildRedisClientInstance}=e;d(n)&&(H.getInstance().setLogger(n),J.getInstance().setLogger(n));try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],o=await acquireSharedCacheClient(a,t,n);if(s(o))throw Error(`Failed to build the shared transport Redis client`);let[c,l]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,cacheClient:o,scripts:Xe,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,cacheClient:o,scripts:Ze,logger:n})]),u=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,cacheClient:o,scripts:we,logger:n,additionalArgs:e}),d=[{name:`ConcurrencyManager`,ready:u.isReady()},{name:`QueueManager`,ready:c.isReady()},{name:`RateLimitManager`,ready:l.isReady()}],f=d.filter(e=>!e.ready);if(f.length>0){let e=f.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:d.map(e=>e.name)}}),{concurrencyManager:u,queueManager:c,rateLimitManager:l}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),closeAndResetManagers(n),await releaseSharedCacheClient(n),e}},acquireSharedCacheClient=async(e,t,n)=>{if(d(Y))return Y;X??=e(t,n,`TransportSystem`);try{return Y=await X??null,Y}finally{X=null}},releaseSharedCacheClient=async e=>{let t=Y;if(Y=null,X=null,!s(t))try{await t.close?.()}catch(t){e?.error({category:`TransportInitialization`,message:`Error closing the shared transport Redis client`,code:`TRANSPORT_CLIENT_CLOSE_ERROR`,error:t})}},closeAndResetManagers=e=>{let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);for(let[i,a]of[[`ConcurrencyManager`,t],[`QueueManager`,n],[`RateLimitManager`,r]])try{a?.close()}catch(t){e?.error({category:`TransportInitialization`,message:`Error closing ${i}`,code:`TRANSPORT_MANAGER_CLOSE_ERROR`,error:t})}SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager)},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`}),closeAndResetManagers(e),releaseSharedCacheClient(e),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},Qe=new Set([`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/x-icon`,`image/vnd.microsoft.icon`]),startsWith=(e,t,n=0)=>t.every((t,r)=>e[n+r]===t),isRasterImage=e=>startsWith(e,[137,80,78,71,13,10,26,10])||startsWith(e,[255,216,255])||startsWith(e,[71,73,70,56])||startsWith(e,[82,73,70,70])&&startsWith(e,[87,69,66,80],8)||startsWith(e,[0,0,1,0]),getSite=e=>de(e,{allowPrivateDomains:!0}),isSameSite=(e,t)=>{let n=getSite(t.hostname);return n?getSite(e.hostname)===n:e.origin===t.origin},getMediaType=e=>(e.headers.get(`content-type`)??``).split(`;`)[0].trim().toLowerCase(),fetchOnSite=async(e,t,n=3)=>{if(e.protocol!==`https:`||e.href.length>2048||e.username||e.password||!isSameSite(e,t.server))return;let r=await t.fetchFn(e,{redirect:`manual`,signal:t.signal}),i=r.headers.get(`location`);if(r.status>=300&&r.status<400&&i&&n>0)return await r.body?.cancel(),fetchOnSite(new URL(i,e),t,n-1);if(!r.ok){await r.body?.cancel();return}return{response:r,url:e}},readBytes=async(e,t)=>{let n=e.body?.getReader(),r=[],i=0;try{for(;n&&i<t;){let{done:e,value:t}=await n.read();if(e)break;r.push(t),i+=t.length}}finally{await n?.cancel()}return Buffer.concat(r).subarray(0,t)},verifyIcon=async(e,t)=>{let n=await fetchOnSite(e,t);if(!n)return;if(!Qe.has(getMediaType(n.response))){await n.response.body?.cancel();return}let r=await readBytes(n.response,262145);return r.length<=262144&&isRasterImage(r)?n.url.toString():void 0},readAttributes=e=>new Map(Array.from(e.matchAll(/([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g),([,e,...t])=>[e.toLowerCase(),(t.find(e=>e!==void 0)??``).replaceAll(`&`,`&`)])),findDeclaredIcons=(e,t,n)=>{let r=e.search(/<\/head\b|<body\b/i),i=r===-1?e:e.slice(0,r);return Array.from(i.matchAll(/<link\b[^<>]*>/gi),([e])=>{let r=readAttributes(e),i=(r.get(`rel`)??``).toLowerCase().split(/\s+/),a=i.some(e=>e.startsWith(`apple-touch-icon`)),o=r.get(`href`)?.trim(),s=o?URL.parse(o,t.href):null;return!(i.includes(`icon`)||a)||r.get(`type`)?.toLowerCase()===`image/svg+xml`||r.get(`media`)?.toLowerCase().includes(`dark`)||s?.protocol!==`https:`||!isSameSite(s,n)||s.pathname.toLowerCase().endsWith(`.svg`)?[]:[{url:s,size:(r.get(`sizes`)??``).split(/\s+/).reduce((e,t)=>Math.max(e,Number.parseInt(t,10)||0),0)||(a?180:0)}]}).flat().sort((e,t)=>t.size-e.size).map(({url:e})=>e)},readHomePage=async(e,t)=>{let n=await fetchOnSite(e,t);return!n||getMediaType(n.response)!==`text/html`?(await n?.response.body?.cancel(),{icons:[],url:n?.url??e}):{icons:findDeclaredIcons((await readBytes(n.response,1048576)).toString(`utf8`),n.url,t.server),url:n.url}},findMcpIcon=async(e,t,n=fetch)=>{let r=new AbortController,i=setTimeout(()=>r.abort(),5e3);try{let i=new URL(e),a=getSite(i.hostname);if(i.protocol!==`https:`||!a)return;let o={server:i,fetchFn:n,signal:r.signal},tryIcon=e=>e?verifyIcon(e,o).catch(()=>void 0):void 0,s=await tryIcon(t?URL.parse(t):void 0);if(s)return s;let c=new URL(`https://${a}/`),l=await readHomePage(c,o).catch(()=>({icons:[],url:c})),u=[...l.icons.slice(0,3),new URL(`/favicon.ico`,l.url)];for(let e of u){let t=await tryIcon(e);if(t)return t}return}catch{return}finally{clearTimeout(i)}},abortReason=e=>e.reason??new DOMException(`The operation was aborted`,`AbortError`),abortableDelay=(e,t)=>t?.aborted?Promise.reject(abortReason(t)):new Promise((n,r)=>{let i=setTimeout(()=>{t?.removeEventListener(`abort`,onAbort),n()},e),onAbort=()=>{clearTimeout(i),r(abortReason(t))};t?.addEventListener(`abort`,onAbort,{once:!0})}),$e=e((e,t)=>fetch(e,t),`defaultBaseFetch`),createRetryingFetch=(e=$e,{maxRetries:t=5,delay:r=abortableDelay}={})=>{let fetchWithRetry=async(i,a,o)=>{let s=await e(i,a);if(s.status!==429||o>=t)return s;let c=s.headers.get(`retry-after`),l=o+1,u=c?getRetryAfterWaitTime(c)*U:n(l);return await s.body?.cancel().catch(()=>void 0),await r(u,a?.signal),fetchWithRetry(i,a,l)};return(e,t)=>fetchWithRetry(e,t,0)},defaultBaseFetch=(e,t)=>fetch(e,t),createThrottledFetch=(e=defaultBaseFetch,{requestConfig:t,context:n,getManagers:r=getTransportManagers,delay:i=abortableDelay}={})=>async(a,o)=>{let c=r(),l=n?.provider,u=n?.accountSecureId;if(s(c)||s(l)||s(u))return e(a,o);let{rateLimitManager:f,concurrencyManager:p}=c,m=t?.rateLimits??je,h=t?.concurrency??Ce,g=`${u}-${l}`,_=a.toString(),v=f.getDynamicMaxWaitTime(m,h,_),y=Date.now()+v*U,remainingBudgetMs=()=>Math.max(y-Date.now(),0),registerRequest=()=>p.registerRequest(g,h,fe(),_,remainingBudgetMs(),o?.signal??void 0),acquireSlot=async()=>{let e=await f.getWaitTime(g,m,_)??0;return e<=0||remainingBudgetMs()<=0?registerRequest():(await i(Math.min(Math.max(e,50),remainingBudgetMs()),o?.signal),acquireSlot())},b=await acquireSlot();try{return await e(a,o)}finally{let{requestId:e,targetConcurrencyKey:t,acquired:n}=b??{};n!==!1&&d(e)&&d(t)&&await p.releaseRequest(e,t).catch(()=>void 0)}},et={name:`stackone-connect`,version:`1.0.0`},tt={mode:`auto`},nt={createClient:(e,t)=>new ie(e,t),createTransport:(e,t)=>new oe(e,t)};var McpClient=class{constructor(e,t=nt){this.config=e,this.sdk=t}async callTool({name:e,arguments:t}){let{content:n,structuredContent:r,isError:i}=await(await this.getConnectedClient()).callTool({name:e,arguments:t??{}},this.buildRequestOptions());return{content:n??[],structuredContent:r,isError:i===!0}}async listTools(e){let t=await(await this.getConnectedClient()).listTools(e?.cursor?{cursor:e.cursor}:void 0,this.buildRequestOptions());return{tools:t.tools,nextCursor:t.nextCursor}}async getServerInfo(){let e=await this.getConnectedClient(),t=e.getServerVersion();return{name:t?.name,title:t?.title,version:t?.version,description:t?.description,websiteUrl:t?.websiteUrl,instructions:e.getInstructions(),iconUrl:this.resolveIconUrl(t?.icons)}}resolveIconUrl(e){let t=(e??[]).flatMap(e=>{let t=this.toServerIconUrl(e.src);return t?[{theme:e.theme,url:t}]:[]});return(t.find(e=>e.theme!==`dark`)??t[0])?.url}toServerIconUrl(e){if(e.trim())try{let t=new URL(this.config.serverUrl);t.search=``,t.hash=``;let n=new URL(e,t);return n.username=``,n.password=``,n.protocol===`https:`&&isSameSite(n,t)?n.toString():void 0}catch{return}}async close(){let e=this.connectedClient;this.connectedClient=void 0,e&&await(await e.catch(()=>void 0))?.close()}getConnectedClient(){return this.connectedClient??=this.connect(),this.connectedClient.catch(e=>{throw this.connectedClient=void 0,e})}async connect(){let{serverUrl:e,headers:t,clientInfo:n,requestConfig:r,context:i}=this.config,a=this.sdk.createClient(n??et,{versionNegotiation:tt}),o=this.sdk.createTransport(new URL(e),{requestInit:t?{headers:t}:void 0,fetch:createRetryingFetch(createThrottledFetch(void 0,{requestConfig:r,context:i}))});return await a.connect(o,this.buildRequestOptions()),a}buildRequestOptions(){return this.config.timeout?{timeout:this.config.timeout}:void 0}};const fetchAuthorizationChallenge=async e=>{let t=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:`ping`})});if(await t.body?.cancel().catch(()=>void 0),t.status!==401)return;let{resourceMetadataUrl:n,scope:r}=ue(t);return{resourceMetadataUrl:n?.toString(),scope:r}},rt={createClient:e=>new McpClient({serverUrl:e}),fetchAuthorizationChallenge,discoverResourceMetadata:(e,t)=>le(e,t?{resourceMetadataUrl:t}:void 0),discoverAuthorizationServer:e=>ce(e)},isAuthorizationFailure=e=>e instanceof se||e instanceof ae&&e.status===401,buildOAuthProbe=async(e,t,n)=>{let r=e?.authorization_servers,i=r?.[0]?await n.discoverAuthorizationServer(r[0]).catch(()=>void 0):void 0,a=e?.resource_name||e?.resource_documentation?{name:e.resource_name,documentationUrl:e.resource_documentation}:void 0;return{oauth:{scopes:e?.scopes_supported??t?.scope?.split(` `)??i?.scopes_supported,authorizationServers:r,dynamicRegistration:d(i)?d(i.registration_endpoint):void 0,resourceMetadataUrl:t?.resourceMetadataUrl,tokenEndpoint:i?.token_endpoint,refreshTokenGrant:d(i)?i.grant_types_supported?.includes(`refresh_token`)??!1:void 0},...a?{resource:a}:{}}},probeProtectedServer=async(e,t)=>{let n=await t.fetchAuthorizationChallenge(e).catch(()=>void 0),r=await t.discoverResourceMetadata(e,n?.resourceMetadataUrl).catch(()=>void 0);return!r&&!n?.resourceMetadataUrl?{requiresAuthorization:!0}:{requiresAuthorization:!0,...await buildOAuthProbe(r,n,t)}},probeOpenServer=async(e,t,n)=>{let r=await t.getServerInfo().catch(()=>void 0),i=await n.discoverResourceMetadata(e).catch(()=>void 0);return i?{requiresAuthorization:!0,...await buildOAuthProbe(i,void 0,n),server:r}:{requiresAuthorization:!1,server:r}},probeMcpServer=async(e,t=rt)=>{let n=t.createClient(e);try{return await n.listTools(),await probeOpenServer(e,n,t)}catch(n){if(!isAuthorizationFailure(n))throw n;return probeProtectedServer(e,t)}finally{await n.close().catch(()=>void 0)}},it=e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),Z=e(e=>Array.isArray(e)?e:[e],`toStringArray`),isNullish=e=>e==null,toQueryValue=e=>Array.isArray(e)?e.filter(e=>!isNullish(e)).map(String):String(e),hasValue=e=>e.in===`body`||!isNullish(e.value),mergeQueryValues=(e,t,n)=>{let r=Z(t);if(it(e))return{value:[...Z(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...Z(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.filter(hasValue).reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.inline)e.body=t.value;else if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),at=[`query`,`body`,`headers`],ot=[`repeat`,`brackets`,`comma`,`stringify`],st={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},ct=new pe(st),getContentType=e=>{let t=Object.entries(e).find(([e])=>e.toLowerCase()===`content-type`)?.[1];return typeof t==`string`?t.toLowerCase():``},isXmlContentTypeValue=e=>e.includes(`application/xml`)||e.includes(`text/xml`)||/application\/\S+\+xml/.test(e),isXmlContentType=e=>isXmlContentTypeValue(getContentType(e)),serializeBodyToXml=e=>{try{return ct.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?A.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>d(e)&&e>=200&&e<=299,isFailedStatusCode=e=>d(e)&&e>=400&&e<=599,isInfoStatusCode=e=>d(e)&&e>=100&&e<=199,lt=[`arraybuffer`,`blob`,`document`,`text`];let ut;const getXmlParser=()=>(ut??=new me({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),ut);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,httpsAgent:u,credentials:d,responseType:f,context:p,cacheTTL:m,timeoutMs:h}){let g,_=o;if(isXmlContentType(r))if(typeof o==`string`)_=o;else if(Array.isArray(o))throw Error(`Cannot serialize an array body to XML: XML requires a single root element. Wrap the array in an object with a root key.`);else o!=null&&(_=serializeBodyToXml(o));try{g=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:_,requestConfig:l,httpsAgent:u,responseType:f,context:p,cacheTTL:m,timeoutMs:h})}catch(e){if(s(e?.response))throw e;g=e.response}if(typeof g.data==`string`&&/\S/.test(g.data)&&g.headers&&isXmlContentType(g.headers)&&(!f||!lt.includes(f))){let e=j.validate(g.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);g={...g,data:getXmlParser().parse(g.data)}}let v=translateCustomError(g,c,d);if(isFailedStatusCode(v?.status))throw new z(v,v.message);return v}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,credentials:u,context:d,cacheTTL:f}){let p;if(p=typeof l?.envelope==`string`?l.envelope:typeof l?.envelope==`object`?Q.build(l.envelope):await buildEnvelope(o,l),j.validate(p,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let m,h={"Content-Type":`application/xml`,...r};l?.soapAction&&(h.SOAPAction=l.soapAction);try{m=await e?.request({method:n,url:t,headers:h,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:p,requestConfig:l,context:d,cacheTTL:f})}catch(e){if(s(e?.response))throw e;m=e.response}let g=dt.parse(m.data),_=g.Envelope||g,v=_.Body||_,y=v.Fault;if(y)throw new z({...m,status:500,data:y,message:y.faultstring??y.faultcode??`SOAP Fault`},y.faultstring??`SOAP Fault occurred`);m.data=v;let b=translateCustomError(m,c,u);if(isFailedStatusCode(b?.status))throw new z(b,b.message);return b}};const Q=new pe(st),dt=new me({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if(d(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Q.build(t.envelope);if(j.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Q.build(n);if(j.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await _(e.namespaceIdentifier),namespace:await _(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(s(e)||s(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if(s(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if(s(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};const arrayFormatToPairs=(e,t,n)=>n===`brackets`?t.map(t=>[`${e}[]`,t]):n===`comma`?[[e,t.join(`,`)]]:n===`stringify`?[[e,JSON.stringify(t)]]:t.map(t=>[e,t]),toStringArray=e=>Array.isArray(e)?e:[e],isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),flattenQueryParams=e=>{if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))r!=null&&(isHttpQueryParamValue(r)?t.push(...arrayFormatToPairs(n,toStringArray(r.value),r.arrayFormat)):t.push(...arrayFormatToPairs(n,toStringArray(r),void 0)));return t},hmac=(e,t)=>w(`sha256`,e).update(t).digest(),hash=e=>C(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),$=e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),ft=e((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),d=u.slice(0,8),f=new URL(e.url),p=f.pathname.split(`/`).map(e=>{try{return $(decodeURIComponent(e))}catch{return $(e)}}).join(`/`)||`/`,m=[];for(let[e,t]of f.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=ft(e,n);return i===0?ft(t,r):i});let h=m.map(([e,t])=>`${$(e)}=${$(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=C(`sha256`).update(g).digest(),v=_.toString(`hex`),y={host:f.host,"x-amz-content-sha256":v,"x-amz-date":u};a&&(y[`x-amz-security-token`]=a);for(let[t,n]of Object.entries(e.headers??{})){let e=t.toLowerCase();e!==`authorization`&&e!==`x-amz-date`&&e!==`x-amz-content-sha256`&&e!==`x-amz-security-token`&&(y[e]=n)}let b=Object.keys(y).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),x=g.length>0&&!b,S;x&&(S=_.toString(`base64`),y[`x-amz-checksum-sha256`]=S);let T=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),ee=T.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),E=T.join(`;`),D=[e.method.toUpperCase(),p,h,ee,E,v].join(`
|
|
206
|
+
`),O=`${d}/${l}/${s}/aws4_request`,te=[`AWS4-HMAC-SHA256`,u,O,hash(D)].join(`
|
|
207
|
+
`),k={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${O}, SignedHeaders=${E}, Signature=${w(`sha256`,getSigningKey(i,d,l,s)).update(te).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":v};return a&&(k[`x-amz-security-token`]=a),S!==void 0&&(k[`x-amz-checksum-sha256`]=S),k},pt=[`sha256`,`sha512`],isValidAlgorithm=e=>pt.includes(e),hashPayload=e=>C(`sha256`).update(e).digest(`hex`),byteCompare=(e,t)=>e<t?-1:+(e>t),rfc3986Encode=e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),hmacSigningStrategy=(e,t,n)=>{if(n.strategy!==`hmac`)throw Error(`hmacSigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let r=t.secretKey;if(!r)throw Error(`HMAC signing requires secretKey in credentials`);let i=n;if(requiresExtendedSigning(i))return signWithExtendedOptions(e,r,i);let{algorithm:a,headerName:o,prefix:s}=i;if(a!==void 0&&!isValidAlgorithm(a))throw Error(`Unsupported HMAC algorithm "${a}". Use "sha256" or "sha512".`);let c=a??`sha256`,l=o??`X-Signature`,u=s??`hmac-${c}`,d=new Date().toISOString(),f=new URL(e.url),p=[];for(let[e,t]of f.searchParams.entries())p.push([e,t]);p.push(...flattenQueryParams(e.query)),p.sort(([e,t],[n,r])=>{let i=byteCompare(e,n);return i===0?byteCompare(t,r):i});let m=p.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),h=hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})),g=[d,e.method.toUpperCase(),f.pathname,m,h].join(`
|
|
208
|
+
`),_=w(c,r).update(g).digest(`hex`);return{[l]:`${u} ${_}`,"X-Timestamp":d}},mt=[`sha1`,`sha256`,`sha512`],formatRfc2822Date=e=>e.toUTCString().replace(`GMT`,`-0000`),extractBodyParams=e=>{let t=[];for(let[n,r]of Object.entries(e)){if(r==null)continue;let e=Array.isArray(r)?r:[r];for(let r of e)t.push([n,String(r)])}return t};function requiresExtendedSigning(e){let{algorithm:t,dateFormat:n,includeHost:r,includeBodyHash:i,outputFormat:a,username:o}=e;return!!(n===`rfc2822`||r===!0||i===!1||a===`basic`||o||t===`sha1`)}function signWithExtendedOptions(e,t,n){let{algorithm:r,headerName:i,prefix:a,dateFormat:o=`iso8601`,includeHost:s=!1,includeBodyHash:c=!0,outputFormat:l=`header`,username:u}=n;if(r&&!mt.includes(r))throw Error(`Unsupported HMAC algorithm "${r}". Use "sha1", "sha256", or "sha512".`);if(l===`basic`&&!u)throw Error(`HMAC signing with outputFormat "basic" requires username`);if(u&&/[:\r\n]/.test(u))throw Error(`HMAC signing username cannot contain ":", "\\r", or "\\n"`);let d=r??`sha256`,f=new URL(e.url),p=new Date,m=o===`rfc2822`?formatRfc2822Date(p):p.toISOString(),h=[...f.searchParams.entries(),...flattenQueryParams(e.query)];!c&&e.body&&typeof e.body==`object`&&!Array.isArray(e.body)&&(e.headers?.[`content-type`]??e.headers?.[`Content-Type`]??``).toLowerCase().includes(`application/x-www-form-urlencoded`)&&h.push(...extractBodyParams(e.body)),h.sort(([e,t],[n,r])=>byteCompare(e,n)||byteCompare(t,r));let g=h.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),_=[m,e.method.toUpperCase()];s&&_.push(f.hostname.toLowerCase()),_.push(f.pathname,g),c&&_.push(hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})));let v=w(d,t).update(_.join(`
|
|
209
|
+
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${v}`).toString(`base64`)}`,Date:m}:{[i??`X-Signature`]:`${a??`hmac-${d}`} ${v}`,"X-Timestamp":m}}const ht={},registerSigningStrategy=(e,t)=>{ht[e]=t},getSigningStrategy=e=>ht[e];registerSigningStrategy(`aws4`,aws4SigningStrategy),registerSigningStrategy(`hmac`,hmacSigningStrategy);export{Te as CUSTOM_ERROR_CONFIG_SCHEMA,ConcurrencyManager,EventClient,HttpClient,HttpClientManager,R as HttpErrorMessages,Ye as HttpMethods,z as HttpResponseError,HttpTransportFactory,H as InstanceManager,LockManager,McpClient,MemoryStore,J as PersistentInstanceManager,ot as QueryArrayFormats,QueueManager,RateLimitManager,ve as RedisClient,RequestAbortedError,RequestClientFactory,at as RequestParameterLocations,ScriptManager,SubscriptionManager,TransportManagersUnavailableError,buildHttpClientInstance,buildHttpsAgent,convertError,createAuthorizationHeaders,findMcpIcon,getCancelledCallCount,getRetryAfterWaitTime,getSigningStrategy,getTransportInstance,getTransportManagers,initializeTransportSystem,isFailedStatusCode,isInfoStatusCode,isRequestAbortedError,isSuccessStatusCode,isTransportSystemReady,parseRequestParameters,probeMcpServer,registerSigningStrategy,serializeHttpResponseError,shutdownTransportSystem,superNormalizeHeaders,translateCustomError};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stackone/transport",
|
|
3
|
-
"version": "2.40.
|
|
3
|
+
"version": "2.40.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"main": "dist/index.cjs",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
"prebuild": "pnpm clean",
|
|
44
44
|
"build": "tsdown --env.NODE_ENV=production --minify",
|
|
45
45
|
"prebuild:dev": "pnpm clean",
|
|
46
|
-
"build:dev": "tsdown --format esm --format cjs --
|
|
46
|
+
"build:dev": "tsdown --format esm --format cjs --env.NODE_ENV=development",
|
|
47
47
|
"code:format": "biome format ./src ./*.mjs",
|
|
48
48
|
"code:format:fix": "biome format --write ./src ./*.mjs",
|
|
49
49
|
"code:lint": "biome lint --error-on-warnings ./src ./*.mjs",
|