@stackone/transport 2.45.1 → 2.45.2
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 +2 -2
- package/dist/index.d.cts +7 -1
- package/dist/index.d.mts +7 -1
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,o)=>(o=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let o=require("@stackone/utils"),s=require("node:util"),c=require("node:zlib"),l=require("redis");l=__toESM(l);let u=require("@stackone/expressions"),d=require("node:http");d=__toESM(d);let f=require("node:https");f=__toESM(f);let p=require("node:net"),m=require("node:tls");m=__toESM(m);let h=require("axios");h=__toESM(h);let g=require("crypto"),_=require("node:timers"),v=require("mathjs"),y=require("jsonpath-plus"),b=require("@stackone/redaction"),x=require("node:crypto"),S=require("qs");S=__toESM(S);let C=require("node:stream"),w=require("@modelcontextprotocol/client"),T=require("tldts"),E=require("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=/* @__PURE__ */ 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 D=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??/* @__PURE__ */ new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??/* @__PURE__ */ new Map,this.ttlMap=/* @__PURE__ */ new Map,this.slidingExpiration=e?.slidingExpiration??!1,this.hashStore=/* @__PURE__ */ new Map,this.hashExpiryMap=/* @__PURE__ */ new Map,this.groupMap=/* @__PURE__ */ new Map,this.groupExpiryMap=/* @__PURE__ */ 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 getGroupSize(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.getLiveGroup(e)?.size??0}async listGroupKeys(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.groupMap.keys()).filter(t=>t.startsWith(e)&&(this.getLiveGroup(t)?.size??0)>0)}async deleteDataKeyFromGroup(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let n=this.getLiveGroup(e);if((0,o.isMissing)(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(0,o.notMissing)(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(),(0,o.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*D,s=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{((0,o.notMissing)(this.typeGuard)&&this.typeGuard(t)||(0,o.isMissing)(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,s),this.slidingExpiration&&this.ttlMap.set(e,a)}),(0,o.notMissing)(r)&&r.length>0){let t=(0,o.notMissing)(i)&&Number.isFinite(i)&&i>0?i*D:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,/* @__PURE__ */ new Set),this.groupMap.get(n)?.add(e),(0,o.notMissing)(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((0,o.notMissing)(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((0,o.notMissing)(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((0,o.notMissing)(e?.dataStoreSize)&&(0,o.notMissing)(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(0,o.notMissing)(this.evictionInterval)&&(0,o.notMissing)(this.dataStore)&&(0,o.notMissing)(this.expiryMap)&&(0,o.notMissing)(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*D;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(0,o.notMissing)(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)??/* @__PURE__ */ 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*D),!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(0,o.isMissing)(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((0,o.isMissing)(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)=>{(0,o.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,o.notMissing)(t?.reject)&&t.reject(/* @__PURE__ */ 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(0,o.notMissing)(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);(0,o.isMissing)(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(0,o.isObject)(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:((0,o.isMissing)(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,(0,o.isMissing)(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay()),this.retryTimeout.unref()),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=/* @__PURE__ */ new Map;#r=/* @__PURE__ */ 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 O=1e4,k=6e4,A=`\0gz:`,j=67108864,ee=/* @__PURE__ */ new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof l.ConnectionTimeoutError||e instanceof l.SocketClosedUnexpectedlyError)return!0;let t=e.code;return t!==void 0&&ee.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 l.ConnectionTimeoutError&&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 te=(0,s.promisify)(c.gzip),ne=(0,s.promisify)(c.gunzip),encodeForStorage=async(e,t)=>{let n=e.startsWith(A);return!t&&!n?e:Buffer.byteLength(e)>67108864?n?null:e:`${A}${(await te(e)).toString(`base64`)}`},buildRedisClientInstance=async(e,t,n)=>{try{return await re.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 re=class RedisClient{#e;#t;static async build({getRedisClient:e=l.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:s,connectTimeout:c=O,initialConnectTimeout:u=15e3,pingInterval:d},f,p){let m=new RedisClient,h=p??`RedisClient`;m.#t=f;try{m.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:!0,keepAliveInitialDelay:i,connectTimeout:c,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:s,RESP:2,commandOptions:{timeout:0},disableOfflineQueue:!0,...(0,o.notMissing)(d)?{pingInterval:d}:{}});let l=new RedisConnectionHealth(c),f=getDefaultRedisListeners(h,m.#t,l);return addRedisEventHandlers(m.#e,f),l.recordAttemptStart(),await connectWithinBudget(m.#e,u,h,m.#t)?m:(m.#t?.error({message:`Redis client did not connect within its ${u}ms budget, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:h}),await teardownUnusableClient(m.#e),null)}catch(e){let t=e;return m.#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(0,o.isString)(t)?e:t}async#i(e){if(!e.startsWith(`\0gz:`))return this.#r(e);try{let t=await ne(Buffer.from(e.slice(4),`base64`),{maxOutputLength:j});return this.#r(t.toString())}catch(e){return this.#t?.error({message:`Error decompressing data`,error:e,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getData(e){if(!this.#o())return null;try{let t=await this.#e.get(e);return(0,o.notMissing)(t)?await this.#i(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.#o())return e.map(()=>null);try{let t=await this.#e.mGet(e);return await Promise.all(t.map(e=>(0,o.notMissing)(e)?this.#i(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.#o())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 getGroupSize(e){if(!this.#o())return null;try{return await this.#e.sCard(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting group size`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async listGroupKeys(e){if(!this.#o())return null;try{let t=/* @__PURE__ */ new Set;for await(let n of this.#e.scanIterator({MATCH:`${escapeGlobPattern(e)}*`,COUNT:1e3,TYPE:`set`}))for(let e of n)t.add(e);return Array.from(t)}catch(e){let t=e;return this.#t?.error({message:`Error listing group keys`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i,compress:a}){if(!this.#o())return!1;try{let s=(0,o.isString)(t)?t:JSON.stringify(t),c=await encodeForStorage(s,a===!0);if(c===null)return this.#t?.error({message:`Refusing to store a value over ${j} bytes that starts with the compression prefix`,code:`RedisClientWriteError`,category:RedisClient.name}),!1;if(await this.#e.set(e,c,{EX:n}),(0,o.notMissing)(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),(0,o.notMissing)(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.#o())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===1}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.#o())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.#o())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.#o())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#a(e,t,n){if(!this.#o())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=(await this.#e.multi().addCommand([e,t]).addCommand([`expire`,t,n.toString()]).exec())?.[0];return typeof r==`number`?r: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.#a(`incr`,e,t)}async decrement(e,t){return this.#a(`decr`,e,t)}async subscribe(e,t){if(!this.#o())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.#o())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.#o())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.#o()?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})}}#o(){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=await this.#e.sScan(e,n||`0`,{COUNT:t}),i=[];for(let e of r.members){let t=await this.getData(e);(0,o.notMissing)(t)&&i.push(t)}return{items:i,cursor:r.cursor===`0`?void 0:r.cursor}}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.#o())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),(0,o.notMissing)(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.#o())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.#o())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,(0,o.isString)(t)?t:JSON.stringify(t)]);return await this.#e.multi().addCommand([`hset`,e,...t]).addCommand([`expire`,e,n.toString()]).exec(),!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.#o())return null;try{let n=await this.#e.hGet(e,t);return n!==``&&(0,o.isMissing)(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.#o())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.#o())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())},escapeGlobPattern=e=>e.replace(/[\\*?[\]]/g,`\\$&`),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(O))=>{let r=new LogThrottle(k);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),s=n.assess(a),c={consecutiveFailures:s.consecutiveFailures,unhealthyForMs:s.unhealthyForMs,attemptElapsedMs:s.attemptElapsedMs,isFreezeArtifact:s.isFreezeArtifact};if(s.severity===`transient`){t?.debug({message:s.isFreezeArtifact?`Redis connect timeout reported after ${s.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}:${s.severity}:${a.name}`);if((0,o.isMissing)(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};s.severity===`sustained`?t?.error(u):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(k)}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 s=(0,o.isMissing)(t),c=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||s,this.scripts=n,this.scriptMap=r??/* @__PURE__ */ new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),s&&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?.();(0,o.notMissing)(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((0,o.notMissing)(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!((0,o.isMissing)(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((0,o.notMissing)(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(o.notMissing),i=/* @__PURE__ */ new Map;if(r.length>0&&(0,o.notMissing)(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if((0,o.notMissing)(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);(0,o.notMissing)(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,t,n){if(!this.isRedisReady()){let r=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return(0,o.notMissing)(r)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n,suppressedSinceLastLog:r.suppressed}}),null}let r=this.scriptMap?.get(e);if((0,o.isMissing)(r))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:r,keys:t,args:n})??null}catch(i){if(i instanceof Error&&i.message.includes(`NOSCRIPT`)){let i=Date.now()-this.lastReloadTime;if(i<1500){let t=1500-i;this.logger?.info({message:`Script ${e} not found, reload occurred ${i}ms ago. Waiting ${t}ms before reloading`,category:this.name}),await(0,o.delay)(t)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),(0,o.isMissing)(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${i.message}`,category:this.name,context:{keys:t,args:n},error:i,code:`ScriptManagerExecutionError`}),i}}isRedisReady(){let e=this.cacheClient?.getClient?.();if((0,o.notMissing)(this.cacheClient)&&(0,o.isMissing)(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()&&(0,o.notMissing)(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)}}),(0,o.notMissing)(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=(0,o.getContentHash)(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(0,o.notMissing)(this.subscriptionClient)&&(0,o.notMissing)(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const M=15e3,ie=15e3,N=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if((0,o.isMissing)(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:ie,truncateThreshold:N,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ie,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((0,o.notMissing)(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return(0,o.isMissing)(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(0,o.notMissing)(this.subscriptionManager)&&(0,o.notMissing)(this.cacheClient)&&(0,o.notMissing)(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__:`,ae=[`${P}set`,`${P}expire`,`${P}expired`],oe={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,se={tryConcurrency:`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,__name=(e,n)=>t(e,`name`,{value:n,configurable:!0}),n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},__toESM=(n,r,o)=>(o=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));let o=require("@stackone/utils"),s=require("node:util"),c=require("node:zlib"),l=require("redis");l=__toESM(l);let u=require("@stackone/expressions"),d=require("node:http");d=__toESM(d);let f=require("node:https");f=__toESM(f);let p=require("node:net"),m=require("node:tls");m=__toESM(m);let h=require("axios");h=__toESM(h);let g=require("crypto"),_=require("node:timers"),v=require("mathjs"),y=require("jsonpath-plus"),b=require("@stackone/redaction"),x=require("node:crypto"),S=require("qs");S=__toESM(S);let C=require("node:stream"),w=require("@modelcontextprotocol/client"),T=require("tldts"),E=require("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=/* @__PURE__ */ 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 D=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??/* @__PURE__ */ new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??/* @__PURE__ */ new Map,this.ttlMap=/* @__PURE__ */ new Map,this.slidingExpiration=e?.slidingExpiration??!1,this.hashStore=/* @__PURE__ */ new Map,this.hashExpiryMap=/* @__PURE__ */ new Map,this.groupMap=/* @__PURE__ */ new Map,this.groupExpiryMap=/* @__PURE__ */ 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 getGroupSize(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.getLiveGroup(e)?.size??0}async listGroupKeys(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.groupMap.keys()).filter(t=>t.startsWith(e)&&(this.getLiveGroup(t)?.size??0)>0)}async deleteDataKeyFromGroup(e,t){this.isReady()||this.initialize(),this.updateLastAccessedAt();let n=this.getLiveGroup(e);if((0,o.isMissing)(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(0,o.notMissing)(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(),(0,o.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let a=n*D,s=Date.now()+a;if(await this.lockManager.withLock(e,async()=>{((0,o.notMissing)(this.typeGuard)&&this.typeGuard(t)||(0,o.isMissing)(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,s),this.slidingExpiration&&this.ttlMap.set(e,a)}),(0,o.notMissing)(r)&&r.length>0){let t=(0,o.notMissing)(i)&&Number.isFinite(i)&&i>0?i*D:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,/* @__PURE__ */ new Set),this.groupMap.get(n)?.add(e),(0,o.notMissing)(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((0,o.notMissing)(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((0,o.notMissing)(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((0,o.notMissing)(e?.dataStoreSize)&&(0,o.notMissing)(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(0,o.notMissing)(this.evictionInterval)&&(0,o.notMissing)(this.dataStore)&&(0,o.notMissing)(this.expiryMap)&&(0,o.notMissing)(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*D;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(0,o.notMissing)(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)??/* @__PURE__ */ 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*D),!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(0,o.isMissing)(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((0,o.isMissing)(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)=>{(0,o.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,o.notMissing)(t?.reject)&&t.reject(/* @__PURE__ */ 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(0,o.notMissing)(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);(0,o.isMissing)(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(0,o.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingletonResetError=class extends Error{constructor(e,t){super(`${e} was reset while initializing`),this.name=`AsyncSingletonResetError`,this.cause=t?.cause}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[],this.generation=0,this.attempts=0}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:((0,o.isMissing)(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.attempts+=1,this.initPromise=this.init(this.generation,this.attempts,e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,t,n,...r){let i=await(async()=>this.initInstance(n,...r))().catch(t=>this.failInit(e,t));if(e!==this.generation)throw t===this.attempts&&this.disposeStaleInstance(i),new AsyncSingletonResetError(this.name);return this.instance=i,this.status=`ready`,i}failInit(e,t){throw e===this.generation?(this.status=`failed`,this.initPromise=null,(0,o.isMissing)(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay()),this.retryTimeout.unref()),t):new AsyncSingletonResetError(this.name,{cause:t})}disposeStaleInstance(e){}reset(){this.generation+=1,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=/* @__PURE__ */ new Map;#r=/* @__PURE__ */ 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 O=1e4,k=6e4,A=`\0gz:`,j=67108864,ee=/* @__PURE__ */ new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof l.ConnectionTimeoutError||e instanceof l.SocketClosedUnexpectedlyError)return!0;let t=e.code;return t!==void 0&&ee.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 l.ConnectionTimeoutError&&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`}};const waitFor=e=>{let t={};return{done:new Promise(n=>{t.id=setTimeout(n,e),t.id.unref?.()}),cancel:()=>clearTimeout(t.id)}},settlesWithin=async({outcome:e,timeoutMs:t,now:n})=>{let r={settled:!1},i=e.then(()=>{r.settled=!0},()=>{r.settled=!0}),waitOneWindow=async()=>{let e=n(),a=waitFor(t);return await Promise.race([i,a.done]),a.cancel(),r.settled?!0:n()-e>t*2&&waitOneWindow()};return waitOneWindow()},startConnectionHeartbeat=({client:e,intervalMs:t,timeoutMs:n,onUnresponsive:r,now:i=Date.now})=>{let a={stopped:!1,endHandshakeWatch:()=>void 0},reportUnlessStopped=()=>{a.stopped||r()},beat=async()=>{let t=!e.isReady||await settlesWithin({outcome:e.sendCommand([`PING`]),timeoutMs:n,now:i});a.stopped||(t||r(),schedule())},schedule=()=>{let e=waitFor(t);a.next=e,e.done.then(beat)},watchHandshake=()=>{a.endHandshakeWatch();let e=new Promise(e=>{a.endHandshakeWatch=e});settlesWithin({outcome:e,timeoutMs:n,now:i}).then(e=>{e||reportUnlessStopped()})},endHandshakeWatch=()=>a.endHandshakeWatch();return e.on(`connect`,watchHandshake),e.on(`ready`,endHandshakeWatch),e.on(`error`,endHandshakeWatch),e.on(`end`,endHandshakeWatch),schedule(),{stop:()=>{a.stopped=!0,a.next?.cancel(),e.off(`connect`,watchHandshake),e.off(`ready`,endHandshakeWatch),e.off(`error`,endHandshakeWatch),e.off(`end`,endHandshakeWatch),a.endHandshakeWatch()}}};function isTlsOptions(e){return typeof e==`object`&&!!e}const te=(0,s.promisify)(c.gzip),ne=(0,s.promisify)(c.gunzip),encodeForStorage=async(e,t)=>{let n=e.startsWith(A);return!t&&!n?e:Buffer.byteLength(e)>67108864?n?null:e:`${A}${(await te(e)).toString(`base64`)}`},buildRedisClientInstance=async(e,t,n)=>{try{return await re.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 re=class RedisClient{#e;#t;#n;#r=!1;#i={inProgress:!1,consecutive:0,lastConnect:Promise.resolve()};static async build({getRedisClient:e=l.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:s,connectTimeout:c=O,initialConnectTimeout:u=15e3,pingInterval:d,pingTimeout:f},p,m){let h=new RedisClient,g=m??`RedisClient`;h.#t=p;let _=a&&isTimerDelay(d)&&isTimerDelay(f)?{intervalMs:d,timeoutMs:f}:void 0;(0,o.notMissing)(f)&&(0,o.isMissing)(_)&&p?.warning({message:`pingTimeout is ignored: it needs reconnect and a pingInterval, both whole milliseconds from 1 to 2147483647`,code:`RedisClientError`,category:g});try{h.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:!0,keepAliveInitialDelay:i,connectTimeout:c,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:s,RESP:2,commandOptions:{timeout:0},disableOfflineQueue:!0,...isTimerDelay(d)&&(0,o.isMissing)(_)?{pingInterval:d}:{}});let l=new RedisConnectionHealth(c),f=getDefaultRedisListeners(g,h.#t,l);return addRedisEventHandlers(h.#e,f),l.recordAttemptStart(),await connectWithinBudget(h.#e,u,g,h.#t)?((0,o.notMissing)(_)&&h.#a({..._,category:g}),h):(h.#t?.error({message:`Redis client did not connect within its ${u}ms budget, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:g}),await teardownUnusableClient(h.#e),null)}catch(e){let t=e;return h.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:g}),null}}#a({intervalMs:e,timeoutMs:t,category:n}){let r=this.#e;this.#n=startConnectionHeartbeat({client:r,intervalMs:e,timeoutMs:t,onUnresponsive:()=>{this.#o({timeoutMs:t,category:n})}})}async#o({timeoutMs:e,category:t}){let n=this.#i;if(!n.inProgress){n.inProgress=!0,this.#t?.warning({message:`Redis did not answer within ${e}ms, replacing the connection`,code:`RedisClientConnectionUnresponsive`,category:t});try{let e=this.#e;if(e.destroy(),await n.lastConnect,await new Promise(e=>setTimeout(e,computeReconnectDelay(n.consecutive)).unref()),n.consecutive+=1,this.#r)return;n.lastConnect=e.connect().then(()=>{n.consecutive=0},e=>this.#s(e,t))}catch(e){this.#s(e,t)}finally{n.inProgress=!1}}}#s(e,t){this.#t?.error({message:`Redis client could not reconnect after replacing an unresponsive connection`,error:e,code:`RedisClientError`,category:t})}#c(e){try{return JSON.parse(e)}catch{return e}}#l(e){let t=this.#c(e);return(0,o.isString)(t)?e:t}async#u(e){if(!e.startsWith(`\0gz:`))return this.#l(e);try{let t=await ne(Buffer.from(e.slice(4),`base64`),{maxOutputLength:j});return this.#l(t.toString())}catch(e){return this.#t?.error({message:`Error decompressing data`,error:e,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getData(e){if(!this.#f())return null;try{let t=await this.#e.get(e);return(0,o.notMissing)(t)?await this.#u(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.#f())return e.map(()=>null);try{let t=await this.#e.mGet(e);return await Promise.all(t.map(e=>(0,o.notMissing)(e)?this.#u(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.#f())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 getGroupSize(e){if(!this.#f())return null;try{return await this.#e.sCard(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting group size`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async listGroupKeys(e){if(!this.#f())return null;try{let t=/* @__PURE__ */ new Set;for await(let n of this.#e.scanIterator({MATCH:`${escapeGlobPattern(e)}*`,COUNT:1e3,TYPE:`set`}))for(let e of n)t.add(e);return Array.from(t)}catch(e){let t=e;return this.#t?.error({message:`Error listing group keys`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i,compress:a}){if(!this.#f())return!1;try{let s=(0,o.isString)(t)?t:JSON.stringify(t),c=await encodeForStorage(s,a===!0);if(c===null)return this.#t?.error({message:`Refusing to store a value over ${j} bytes that starts with the compression prefix`,code:`RedisClientWriteError`,category:RedisClient.name}),!1;if(await this.#e.set(e,c,{EX:n}),(0,o.notMissing)(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),(0,o.notMissing)(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.#f())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===1}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.#f())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.#f())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.#f())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#d(e,t,n){if(!this.#f())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=(await this.#e.multi().addCommand([e,t]).addCommand([`expire`,t,n.toString()]).exec())?.[0];return typeof r==`number`?r: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.#d(`incr`,e,t)}async decrement(e,t){return this.#d(`decr`,e,t)}async subscribe(e,t){if(!this.#f())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.#f())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.#f())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.#f()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){this.#r=!0,this.#n?.stop();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})}}#f(){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=await this.#e.sScan(e,n||`0`,{COUNT:t}),i=[];for(let e of r.members){let t=await this.getData(e);(0,o.notMissing)(t)&&i.push(t)}return{items:i,cursor:r.cursor===`0`?void 0:r.cursor}}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.#f())return!1;let n=await this.#e.del(e);return n===0&&this.#t?.debug({message:`No keys deleted for ${e}`,category:RedisClient.name}),(0,o.notMissing)(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.#f())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.#f())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,(0,o.isString)(t)?t:JSON.stringify(t)]);return await this.#e.multi().addCommand([`hset`,e,...t]).addCommand([`expire`,e,n.toString()]).exec(),!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.#f())return null;try{let n=await this.#e.hGet(e,t);return n!==``&&(0,o.isMissing)(n)?null:this.#l(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.#f())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.#l(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.#f())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 isTimerDelay=e=>Number.isInteger(e)&&e>0&&e<=2147483647,computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},escapeGlobPattern=e=>e.replace(/[\\*?[\]]/g,`\\$&`),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(O))=>{let r=new LogThrottle(k);return[{eventName:`error`,listener:i=>{let a=i instanceof Error?i:Error(String(i)),s=n.assess(a),c={consecutiveFailures:s.consecutiveFailures,unhealthyForMs:s.unhealthyForMs,attemptElapsedMs:s.attemptElapsedMs,isFreezeArtifact:s.isFreezeArtifact};if(s.severity===`transient`){t?.debug({message:s.isFreezeArtifact?`Redis connect timeout reported after ${s.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}:${s.severity}:${a.name}`);if((0,o.isMissing)(l))return;let u={message:`Redis client error ${a.message}`,error:a,code:`RedisClientError`,category:e,context:{...c,suppressedSinceLastLog:l.suppressed}};s.severity===`sustained`?t?.error(u):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(k)}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 s=(0,o.isMissing)(t),c=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(c))throw Error(`Failed to build Redis client`);this.redisClientConfig=e,this.logger=i,this.cacheClient=c,this.ownsCacheClient=this.ownsCacheClient||s,this.scripts=n,this.scriptMap=r??/* @__PURE__ */ new Map,this.additionalArgs=a??[];try{await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[])}catch(e){throw this.releaseAdditionalResources(),s&&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`})}})()}disposeStaleInstance(){this.releaseAdditionalResources(),this.closeCacheClient()}releaseAdditionalResources(){}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,o.notMissing)(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((0,o.notMissing)(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!((0,o.isMissing)(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((0,o.notMissing)(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(o.notMissing),i=/* @__PURE__ */ new Map;if(r.length>0&&(0,o.notMissing)(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if((0,o.notMissing)(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);(0,o.notMissing)(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,t,n){if(!this.isRedisReady()){let r=this.unavailableLogThrottle.consume(`${this.name}:${e}`);return(0,o.notMissing)(r)&&this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n,suppressedSinceLastLog:r.suppressed}}),null}let r=this.scriptMap?.get(e);if((0,o.isMissing)(r))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:r,keys:t,args:n})??null}catch(i){if(i instanceof Error&&i.message.includes(`NOSCRIPT`)){let i=Date.now()-this.lastReloadTime;if(i<1500){let t=1500-i;this.logger?.info({message:`Script ${e} not found, reload occurred ${i}ms ago. Waiting ${t}ms before reloading`,category:this.name}),await(0,o.delay)(t)}if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),(0,o.isMissing)(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${i.message}`,category:this.name,context:{keys:t,args:n},error:i,code:`ScriptManagerExecutionError`}),i}}isRedisReady(){let e=this.cacheClient?.getClient?.();if((0,o.notMissing)(this.cacheClient)&&(0,o.isMissing)(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()&&(0,o.notMissing)(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)}}),(0,o.notMissing)(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=(0,o.getContentHash)(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(0,o.notMissing)(this.subscriptionClient)&&(0,o.notMissing)(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionClient?.close?.(),this.subscriptionMap=null,this.subscriptionClient=null}};const M=15e3,ie=15e3,N=1e4;var QueueManager=class extends ScriptManager{constructor(...e){super(...e),this.subscriptionManager=null,this.eventClient=null,this.name=`QueueManager`}async additionalInitialization(){if((0,o.isMissing)(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:ie,truncateThreshold:N,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ie,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((0,o.notMissing)(n)&&n.aborted)return!0;let r=this.eventClient?.waitForEvent(e,t);return(0,o.isMissing)(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(0,o.notMissing)(this.subscriptionManager)&&(0,o.notMissing)(this.cacheClient)&&(0,o.notMissing)(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__:`,ae=[`${P}set`,`${P}expire`,`${P}expired`],oe={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,se={tryConcurrency:`
|
|
2
2
|
local requestId = KEYS[1]
|
|
3
3
|
local targetKey = KEYS[2]
|
|
4
4
|
local queueKey = KEYS[3]
|
|
@@ -216,7 +216,7 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
216
216
|
-- open with a warning, so returning nil here would report the ordinary un-throttled path as
|
|
217
217
|
-- an outage. nil is reserved for the client genuinely being unavailable.
|
|
218
218
|
return 0
|
|
219
|
-
`};let Y=null,X=null;const initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i,getCacheClient:a=buildRedisClientInstance}=e;(0,o.notMissing)(n)&&(V.getInstance().setLogger(n),J.getInstance().setLogger(n));try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],s=await acquireSharedCacheClient(a,t,n);if((0,o.isMissing)(s))throw Error(`Failed to build the shared transport Redis client`);let[c,l]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,cacheClient:s,scripts:Be,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,cacheClient:s,scripts:Ve,logger:n})]),u=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,cacheClient:s,scripts:se,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((0,o.notMissing)(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,!(0,o.isMissing)(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},He=/* @__PURE__ */ 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=>(0,T.getDomain)(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();else 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(!He.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);if(!n||getMediaType(n.response)!==`text/html`)return await n?.response.body?.cancel(),{icons:[],url:n?.url??e};let r=(await readBytes(n.response,1048576)).toString(`utf8`);return{icons:findDeclaredIcons(r,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})}),Ue=/* @__PURE__ */ __name((e,t)=>fetch(e,t),`defaultBaseFetch`),createRetryingFetch=(e=Ue,{maxRetries:t=5,delay:n=abortableDelay}={})=>{let fetchWithRetry=async(r,i,a)=>{let s=await e(r,i);if(s.status!==429||a>=t)return s;let c=s.headers.get(`retry-after`),l=a+1,u=c?getRetryAfterWaitTime(c)*U:(0,o.exponentialBackoffInMS)(l);return await s.body?.cancel().catch(()=>void 0),await n(u,i?.signal),fetchWithRetry(r,i,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,s)=>{let c=r(),l=n?.provider,u=n?.accountSecureId;if((0,o.isMissing)(c)||(0,o.isMissing)(l)||(0,o.isMissing)(u))return e(a,s);let{rateLimitManager:d,concurrencyManager:f}=c,p=t?.rateLimits??xe,m=t?.concurrency??oe,h=`${u}-${l}`,g=a.toString(),_=d.getDynamicMaxWaitTime(p,m,g),v=Date.now()+_*U,remainingBudgetMs=()=>Math.max(v-Date.now(),0),registerRequest=()=>f.registerRequest(h,m,(0,x.randomUUID)(),g,remainingBudgetMs(),s?.signal??void 0),acquireSlot=async()=>{let e=await d.getWaitTime(h,p,g)??0;return e<=0||remainingBudgetMs()<=0?registerRequest():(await i(Math.min(Math.max(e,50),remainingBudgetMs()),s?.signal),acquireSlot())},y=await acquireSlot();try{return await e(a,s)}finally{let{requestId:e,targetConcurrencyKey:t,acquired:n}=y??{};n!==!1&&(0,o.notMissing)(e)&&(0,o.notMissing)(t)&&await f.releaseRequest(e,t).catch(()=>void 0)}},We={name:`stackone-connect`,version:`1.0.0`},Ge={mode:`auto`},Ke={createClient:(e,t)=>new w.Client(e,t),createTransport:(e,t)=>new w.StreamableHTTPClientTransport(e,t)},qe=/^[\t\x20-\x7e\x80-\xff]*$/,isHttpWhitespace=e=>e===9||e===10||e===13||e===32,trimHttpWhitespace=e=>{let t=0,n=e.length;for(;t<n&&isHttpWhitespace(e.charCodeAt(t));)t++;for(;n>t&&isHttpWhitespace(e.charCodeAt(n-1));)n--;return e.slice(t,n)},toRedactedServerUrl=e=>{try{return new URL(e).origin}catch{return``}},toSendableHeaders=(e,t)=>{if(!t)return;let n=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,String(t)])),r=Object.entries(n).filter(([,e])=>!qe.test(trimHttpWhitespace(e))).map(([e])=>e);if(r.length===0)return n;let i=`The MCP header(s) ${r.join(`, `)} hold characters that cannot be sent`;throw new R({status:400,data:{message:i},headers:{},requestUrl:toRedactedServerUrl(e),message:i},i)};var McpClient=class{constructor(e,t=Ke){this.config=e,this.sdk=t,e.egressProxyUrl&&parseEgressProxyUrl(e.egressProxyUrl)}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,egressProxyUrl:a}=this.config,o=toSendableHeaders(e,t),s=this.sdk.createClient(n??We,{versionNegotiation:Ge}),c=this.sdk.createTransport(new URL(e),{requestInit:o?{headers:o}:void 0,fetch:createRetryingFetch(createThrottledFetch(a?createEgressProxyFetch(a):void 0,{requestConfig:r,context:i}))});return await s.connect(c,this.buildRequestOptions()),s}buildRequestOptions(){return this.config.timeout?{timeout:this.config.timeout}:void 0}};const Je={discoverServerInfo:(e,t)=>(0,w.discoverOAuthServerInfo)(e,t),discoverResourceMetadata:(e,t)=>(0,w.discoverOAuthProtectedResourceMetadata)(e,void 0,t),discoverAuthorizationServerMetadata:(e,t)=>(0,w.discoverAuthorizationServerMetadata)(e,t)},isSameSiteIssuer=(e,t)=>{if(!(0,o.isString)(e)||!(0,o.isString)(t))return!1;try{let n=new URL(e),r=new URL(t);return n.protocol===`https:`&&r.protocol===`https:`&&r.port===n.port&&r.hostname.endsWith(`.${n.hostname}`)}catch{return!1}},isSameSiteMetadataMismatch=e=>e instanceof w.IssuerMismatchError&&e.kind===`metadata`&&isSameSiteIssuer(e.expected,e.received),discoverSameSiteAuthorizationServerMetadata=async(e,t={},n=Je)=>{let{fetchFn:r,onSameSiteIssuerFallback:i}=t;try{return await n.discoverAuthorizationServerMetadata(e,{fetchFn:r})}catch(e){if(!isSameSiteMetadataMismatch(e))throw e;i?.({expectedIssuer:e.expected,receivedIssuer:e.received});let t=await n.discoverAuthorizationServerMetadata(e.received,{fetchFn:r});if((0,o.isMissing)(t))throw e;return t}},discoverMcpOAuthServerInfo=async(e,t={},n=Je)=>{let{fetchFn:r,onSameSiteIssuerFallback:i}=t;try{return await n.discoverServerInfo(e,{fetchFn:r})}catch(t){if(!isSameSiteMetadataMismatch(t))throw t;i?.({expectedIssuer:t.expected,receivedIssuer:t.received});let[a,s]=await Promise.all([n.discoverResourceMetadata(e,r).catch(()=>void 0),n.discoverAuthorizationServerMetadata(t.received,{fetchFn:r})]);if((0,o.isMissing)(s))throw t;return{authorizationServerUrl:t.received,authorizationServerMetadata:s,resourceMetadata:a}}},Ye=3e4,fetchAuthorizationChallenge=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(new DOMException(`No authorization challenge within ${Ye}ms`,`TimeoutError`)),Ye);try{let n=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`}),signal:t.signal});if(await n.body?.cancel().catch(()=>void 0),n.status===429||n.status>=500)throw Error(`Authorization challenge request failed with status ${n.status}`);if(n.status!==401)return;let{resourceMetadataUrl:r,scope:i}=(0,w.extractWWWAuthenticateParams)(n);return{resourceMetadataUrl:r?.toString(),scope:i}}finally{clearTimeout(n)}},Xe={createClient:e=>new McpClient({serverUrl:e}),fetchAuthorizationChallenge,discoverResourceMetadata:(e,t)=>(0,w.discoverOAuthProtectedResourceMetadata)(e,t?{resourceMetadataUrl:t}:void 0),discoverAuthorizationServer:e=>discoverSameSiteAuthorizationServerMetadata(e)},mcpResourceIndicator=(e,t)=>{let n=new URL(e),r=`${n.origin}${n.pathname}`;if(!t||!URL.canParse(t)||!(0,w.checkResourceAllowed)({requestedResource:r,configuredResource:t}))return r;let i=new URL(t);return`${i.origin}${i.pathname}`},isAuthorizationFailure=e=>e instanceof w.UnauthorizedError||e instanceof w.SdkHttpError&&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:(0,o.notMissing)(i)?(0,o.notMissing)(i.registration_endpoint):void 0,clientIdMetadataDocument:(0,o.notMissing)(i)?i.client_id_metadata_document_supported===!0:void 0,resourceMetadataUrl:t?.resourceMetadataUrl,advertisedResource:e?.resource,tokenEndpoint:i?.token_endpoint,refreshTokenGrant:(0,o.notMissing)(i)?i.grant_types_supported?.includes(`refresh_token`)??!1:void 0,tokenEndpointAuthMethods:i?.token_endpoint_auth_methods_supported},...a?{resource:a}:{}}},probeProtectedServer=async(e,t)=>{let{challenge:n,challengeFailure:r}=await t.fetchAuthorizationChallenge(e).then(e=>({challenge:e,challengeFailure:void 0}),e=>({challenge:void 0,challengeFailure:{error:e}})),i=await t.discoverResourceMetadata(e,n?.resourceMetadataUrl).catch(()=>void 0);if(!i&&!n?.resourceMetadataUrl){if(r)throw r.error;return{requiresAuthorization:!0}}return{requiresAuthorization:!0,...await buildOAuthProbe(i,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=Xe)=>{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)}},Ze=/* @__PURE__ */ __name(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),Z=/* @__PURE__ */ __name(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(Ze(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)?e.body=Array.isArray(e.body)?e.body.concat(t.value):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:{}}),Qe=[`query`,`body`,`headers`],$e=[`repeat`,`brackets`,`comma`,`stringify`],et={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},tt=new E.XMLBuilder(et),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 tt.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`)?S.default.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>(0,o.notMissing)(e)&&e>=200&&e<=299,isFailedStatusCode=e=>(0,o.notMissing)(e)&&e>=400&&e<=599,isInfoStatusCode=e=>(0,o.notMissing)(e)&&e>=100&&e<=199,getProviderResponse=e=>{let{response:t,getStatus:n}=e??{};return(0,o.isObject)(t)&&typeof t.status==`number`&&typeof n!=`function`?t:void 0},nt=[`arraybuffer`,`blob`,`document`,`text`];let rt;const getXmlParser=()=>(rt??=new E.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),rt);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:s,requestConfig:c,httpsAgent:l,credentials:u,responseType:d,context:f,cacheTTL:p,timeoutMs:m}){let h,g=o;if(isXmlContentType(r)){if(typeof o==`string`)g=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&&(g=serializeBodyToXml(o))}try{h=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:g,requestConfig:c,httpsAgent:l,responseType:d,context:f,cacheTTL:p,timeoutMs:m})}catch(e){let t=getProviderResponse(e);if(!t)throw e;h=t}if(typeof h.data==`string`&&/\S/.test(h.data)&&h.headers&&isXmlContentType(h.headers)&&(!d||!nt.includes(d))){let e=E.XMLValidator.validate(h.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);h={...h,data:getXmlParser().parse(h.data)}}let _=translateCustomError(h,s,u);if(isFailedStatusCode(_?.status))throw new R(_,_.message);return _}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:s,requestConfig:c,credentials:l,context:u,cacheTTL:d}){let f;if(f=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Q.build(c.envelope):await buildEnvelope(o,c),E.XMLValidator.validate(f,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let p,m={"Content-Type":`application/xml`,...r};c?.soapAction&&(m.SOAPAction=c.soapAction);try{p=await e?.request({method:n,url:t,headers:m,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:f,requestConfig:c,context:u,cacheTTL:d})}catch(e){let t=getProviderResponse(e);if(!t)throw e;p=t}let h=it.parse(p.data),g=h.Envelope||h,_=g.Body||g,v=_.Fault;if(v)throw new R({...p,status:500,data:v,message:v.faultstring??v.faultcode??`SOAP Fault`},v.faultstring??`SOAP Fault occurred`);p.data=_;let y=translateCustomError(p,s,l);if(isFailedStatusCode(y?.status))throw new R(y,y.message);return y}};const Q=new E.XMLBuilder(et),it=new E.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if((0,o.notMissing)(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Q.build(t.envelope);if(E.XMLValidator.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Q.build(n);if(E.XMLValidator.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(0,u.evaluate)(e.namespaceIdentifier),namespace:await(0,u.evaluate)(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if((0,o.isMissing)(e)||(0,o.isMissing)(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((0,o.isMissing)(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((0,o.isMissing)(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)=>(0,g.createHmac)(`sha256`,e).update(t).digest(),hash=e=>(0,g.createHash)(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>{let i=hmac(`AWS4${e}`,t),a=hmac(i,n),o=hmac(a,r);return hmac(o,`aws4_request`)},$=/* @__PURE__ */ __name(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),at=/* @__PURE__ */ __name((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=(/* @__PURE__ */ 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=at(e,n);return i===0?at(t,r):i});let h=m.map(([e,t])=>`${$(e)}=${$(t)}`).join(`&`),_=serializeRequestBodyForSigning(e.body,e.headers??{}),v=(0,g.createHash)(`sha256`).update(_).digest(),y=v.toString(`hex`),b={host:f.host,"x-amz-content-sha256":y,"x-amz-date":u};a&&(b[`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`&&(b[e]=n)}let x=Object.keys(b).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),S=_.length>0&&!x,C;S&&(C=v.toString(`base64`),b[`x-amz-checksum-sha256`]=C);let w=Object.keys(b).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),T=w.map(e=>`${e}:${canonicalHeaderValue(b[e])}\n`).join(``),E=w.join(`;`),D=[e.method.toUpperCase(),p,h,T,E,y].join(`
|
|
219
|
+
`};let Y=null,X=null;const initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i,getCacheClient:a=buildRedisClientInstance}=e;(0,o.notMissing)(n)&&(V.getInstance().setLogger(n),J.getInstance().setLogger(n));try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],s=await acquireSharedCacheClient(a,t,n);if((0,o.isMissing)(s))throw Error(`Failed to build the shared transport Redis client`);let[c,l]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,cacheClient:s,scripts:Be,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,cacheClient:s,scripts:Ve,logger:n})]),u=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,cacheClient:s,scripts:se,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){if(e instanceof AsyncSingletonResetError)throw 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((0,o.notMissing)(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,!(0,o.isMissing)(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},He=/* @__PURE__ */ 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=>(0,T.getDomain)(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();else 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(!He.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);if(!n||getMediaType(n.response)!==`text/html`)return await n?.response.body?.cancel(),{icons:[],url:n?.url??e};let r=(await readBytes(n.response,1048576)).toString(`utf8`);return{icons:findDeclaredIcons(r,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})}),Ue=/* @__PURE__ */ __name((e,t)=>fetch(e,t),`defaultBaseFetch`),createRetryingFetch=(e=Ue,{maxRetries:t=5,delay:n=abortableDelay}={})=>{let fetchWithRetry=async(r,i,a)=>{let s=await e(r,i);if(s.status!==429||a>=t)return s;let c=s.headers.get(`retry-after`),l=a+1,u=c?getRetryAfterWaitTime(c)*U:(0,o.exponentialBackoffInMS)(l);return await s.body?.cancel().catch(()=>void 0),await n(u,i?.signal),fetchWithRetry(r,i,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,s)=>{let c=r(),l=n?.provider,u=n?.accountSecureId;if((0,o.isMissing)(c)||(0,o.isMissing)(l)||(0,o.isMissing)(u))return e(a,s);let{rateLimitManager:d,concurrencyManager:f}=c,p=t?.rateLimits??xe,m=t?.concurrency??oe,h=`${u}-${l}`,g=a.toString(),_=d.getDynamicMaxWaitTime(p,m,g),v=Date.now()+_*U,remainingBudgetMs=()=>Math.max(v-Date.now(),0),registerRequest=()=>f.registerRequest(h,m,(0,x.randomUUID)(),g,remainingBudgetMs(),s?.signal??void 0),acquireSlot=async()=>{let e=await d.getWaitTime(h,p,g)??0;return e<=0||remainingBudgetMs()<=0?registerRequest():(await i(Math.min(Math.max(e,50),remainingBudgetMs()),s?.signal),acquireSlot())},y=await acquireSlot();try{return await e(a,s)}finally{let{requestId:e,targetConcurrencyKey:t,acquired:n}=y??{};n!==!1&&(0,o.notMissing)(e)&&(0,o.notMissing)(t)&&await f.releaseRequest(e,t).catch(()=>void 0)}},We={name:`stackone-connect`,version:`1.0.0`},Ge={mode:`auto`},Ke={createClient:(e,t)=>new w.Client(e,t),createTransport:(e,t)=>new w.StreamableHTTPClientTransport(e,t)},qe=/^[\t\x20-\x7e\x80-\xff]*$/,isHttpWhitespace=e=>e===9||e===10||e===13||e===32,trimHttpWhitespace=e=>{let t=0,n=e.length;for(;t<n&&isHttpWhitespace(e.charCodeAt(t));)t++;for(;n>t&&isHttpWhitespace(e.charCodeAt(n-1));)n--;return e.slice(t,n)},toRedactedServerUrl=e=>{try{return new URL(e).origin}catch{return``}},toSendableHeaders=(e,t)=>{if(!t)return;let n=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,String(t)])),r=Object.entries(n).filter(([,e])=>!qe.test(trimHttpWhitespace(e))).map(([e])=>e);if(r.length===0)return n;let i=`The MCP header(s) ${r.join(`, `)} hold characters that cannot be sent`;throw new R({status:400,data:{message:i},headers:{},requestUrl:toRedactedServerUrl(e),message:i},i)};var McpClient=class{constructor(e,t=Ke){this.config=e,this.sdk=t,e.egressProxyUrl&&parseEgressProxyUrl(e.egressProxyUrl)}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,egressProxyUrl:a}=this.config,o=toSendableHeaders(e,t),s=this.sdk.createClient(n??We,{versionNegotiation:Ge}),c=this.sdk.createTransport(new URL(e),{requestInit:o?{headers:o}:void 0,fetch:createRetryingFetch(createThrottledFetch(a?createEgressProxyFetch(a):void 0,{requestConfig:r,context:i}))});return await s.connect(c,this.buildRequestOptions()),s}buildRequestOptions(){return this.config.timeout?{timeout:this.config.timeout}:void 0}};const Je={discoverServerInfo:(e,t)=>(0,w.discoverOAuthServerInfo)(e,t),discoverResourceMetadata:(e,t)=>(0,w.discoverOAuthProtectedResourceMetadata)(e,void 0,t),discoverAuthorizationServerMetadata:(e,t)=>(0,w.discoverAuthorizationServerMetadata)(e,t)},isSameSiteIssuer=(e,t)=>{if(!(0,o.isString)(e)||!(0,o.isString)(t))return!1;try{let n=new URL(e),r=new URL(t);return n.protocol===`https:`&&r.protocol===`https:`&&r.port===n.port&&r.hostname.endsWith(`.${n.hostname}`)}catch{return!1}},isSameSiteMetadataMismatch=e=>e instanceof w.IssuerMismatchError&&e.kind===`metadata`&&isSameSiteIssuer(e.expected,e.received),discoverSameSiteAuthorizationServerMetadata=async(e,t={},n=Je)=>{let{fetchFn:r,onSameSiteIssuerFallback:i}=t;try{return await n.discoverAuthorizationServerMetadata(e,{fetchFn:r})}catch(e){if(!isSameSiteMetadataMismatch(e))throw e;i?.({expectedIssuer:e.expected,receivedIssuer:e.received});let t=await n.discoverAuthorizationServerMetadata(e.received,{fetchFn:r});if((0,o.isMissing)(t))throw e;return t}},discoverMcpOAuthServerInfo=async(e,t={},n=Je)=>{let{fetchFn:r,onSameSiteIssuerFallback:i}=t;try{return await n.discoverServerInfo(e,{fetchFn:r})}catch(t){if(!isSameSiteMetadataMismatch(t))throw t;i?.({expectedIssuer:t.expected,receivedIssuer:t.received});let[a,s]=await Promise.all([n.discoverResourceMetadata(e,r).catch(()=>void 0),n.discoverAuthorizationServerMetadata(t.received,{fetchFn:r})]);if((0,o.isMissing)(s))throw t;return{authorizationServerUrl:t.received,authorizationServerMetadata:s,resourceMetadata:a}}},Ye=3e4,fetchAuthorizationChallenge=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(new DOMException(`No authorization challenge within ${Ye}ms`,`TimeoutError`)),Ye);try{let n=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`}),signal:t.signal});if(await n.body?.cancel().catch(()=>void 0),n.status===429||n.status>=500)throw Error(`Authorization challenge request failed with status ${n.status}`);if(n.status!==401)return;let{resourceMetadataUrl:r,scope:i}=(0,w.extractWWWAuthenticateParams)(n);return{resourceMetadataUrl:r?.toString(),scope:i}}finally{clearTimeout(n)}},Xe={createClient:e=>new McpClient({serverUrl:e}),fetchAuthorizationChallenge,discoverResourceMetadata:(e,t)=>(0,w.discoverOAuthProtectedResourceMetadata)(e,t?{resourceMetadataUrl:t}:void 0),discoverAuthorizationServer:e=>discoverSameSiteAuthorizationServerMetadata(e)},mcpResourceIndicator=(e,t)=>{let n=new URL(e),r=`${n.origin}${n.pathname}`;if(!t||!URL.canParse(t)||!(0,w.checkResourceAllowed)({requestedResource:r,configuredResource:t}))return r;let i=new URL(t);return`${i.origin}${i.pathname}`},isAuthorizationFailure=e=>e instanceof w.UnauthorizedError||e instanceof w.SdkHttpError&&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:(0,o.notMissing)(i)?(0,o.notMissing)(i.registration_endpoint):void 0,clientIdMetadataDocument:(0,o.notMissing)(i)?i.client_id_metadata_document_supported===!0:void 0,resourceMetadataUrl:t?.resourceMetadataUrl,advertisedResource:e?.resource,tokenEndpoint:i?.token_endpoint,refreshTokenGrant:(0,o.notMissing)(i)?i.grant_types_supported?.includes(`refresh_token`)??!1:void 0,tokenEndpointAuthMethods:i?.token_endpoint_auth_methods_supported},...a?{resource:a}:{}}},probeProtectedServer=async(e,t)=>{let{challenge:n,challengeFailure:r}=await t.fetchAuthorizationChallenge(e).then(e=>({challenge:e,challengeFailure:void 0}),e=>({challenge:void 0,challengeFailure:{error:e}})),i=await t.discoverResourceMetadata(e,n?.resourceMetadataUrl).catch(()=>void 0);if(!i&&!n?.resourceMetadataUrl){if(r)throw r.error;return{requiresAuthorization:!0}}return{requiresAuthorization:!0,...await buildOAuthProbe(i,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=Xe)=>{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)}},Ze=/* @__PURE__ */ __name(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),Z=/* @__PURE__ */ __name(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(Ze(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)?e.body=Array.isArray(e.body)?e.body.concat(t.value):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:{}}),Qe=[`query`,`body`,`headers`],$e=[`repeat`,`brackets`,`comma`,`stringify`],et={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},tt=new E.XMLBuilder(et),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 tt.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`)?S.default.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>(0,o.notMissing)(e)&&e>=200&&e<=299,isFailedStatusCode=e=>(0,o.notMissing)(e)&&e>=400&&e<=599,isInfoStatusCode=e=>(0,o.notMissing)(e)&&e>=100&&e<=199,getProviderResponse=e=>{let{response:t,getStatus:n}=e??{};return(0,o.isObject)(t)&&typeof t.status==`number`&&typeof n!=`function`?t:void 0},nt=[`arraybuffer`,`blob`,`document`,`text`];let rt;const getXmlParser=()=>(rt??=new E.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),rt);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:s,requestConfig:c,httpsAgent:l,credentials:u,responseType:d,context:f,cacheTTL:p,timeoutMs:m}){let h,g=o;if(isXmlContentType(r)){if(typeof o==`string`)g=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&&(g=serializeBodyToXml(o))}try{h=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:g,requestConfig:c,httpsAgent:l,responseType:d,context:f,cacheTTL:p,timeoutMs:m})}catch(e){let t=getProviderResponse(e);if(!t)throw e;h=t}if(typeof h.data==`string`&&/\S/.test(h.data)&&h.headers&&isXmlContentType(h.headers)&&(!d||!nt.includes(d))){let e=E.XMLValidator.validate(h.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);h={...h,data:getXmlParser().parse(h.data)}}let _=translateCustomError(h,s,u);if(isFailedStatusCode(_?.status))throw new R(_,_.message);return _}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:s,requestConfig:c,credentials:l,context:u,cacheTTL:d}){let f;if(f=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Q.build(c.envelope):await buildEnvelope(o,c),E.XMLValidator.validate(f,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let p,m={"Content-Type":`application/xml`,...r};c?.soapAction&&(m.SOAPAction=c.soapAction);try{p=await e?.request({method:n,url:t,headers:m,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:f,requestConfig:c,context:u,cacheTTL:d})}catch(e){let t=getProviderResponse(e);if(!t)throw e;p=t}let h=it.parse(p.data),g=h.Envelope||h,_=g.Body||g,v=_.Fault;if(v)throw new R({...p,status:500,data:v,message:v.faultstring??v.faultcode??`SOAP Fault`},v.faultstring??`SOAP Fault occurred`);p.data=_;let y=translateCustomError(p,s,l);if(isFailedStatusCode(y?.status))throw new R(y,y.message);return y}};const Q=new E.XMLBuilder(et),it=new E.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if((0,o.notMissing)(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Q.build(t.envelope);if(E.XMLValidator.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Q.build(n);if(E.XMLValidator.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(0,u.evaluate)(e.namespaceIdentifier),namespace:await(0,u.evaluate)(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if((0,o.isMissing)(e)||(0,o.isMissing)(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((0,o.isMissing)(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((0,o.isMissing)(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)=>(0,g.createHmac)(`sha256`,e).update(t).digest(),hash=e=>(0,g.createHash)(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>{let i=hmac(`AWS4${e}`,t),a=hmac(i,n),o=hmac(a,r);return hmac(o,`aws4_request`)},$=/* @__PURE__ */ __name(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),at=/* @__PURE__ */ __name((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=(/* @__PURE__ */ 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=at(e,n);return i===0?at(t,r):i});let h=m.map(([e,t])=>`${$(e)}=${$(t)}`).join(`&`),_=serializeRequestBodyForSigning(e.body,e.headers??{}),v=(0,g.createHash)(`sha256`).update(_).digest(),y=v.toString(`hex`),b={host:f.host,"x-amz-content-sha256":y,"x-amz-date":u};a&&(b[`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`&&(b[e]=n)}let x=Object.keys(b).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),S=_.length>0&&!x,C;S&&(C=v.toString(`base64`),b[`x-amz-checksum-sha256`]=C);let w=Object.keys(b).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),T=w.map(e=>`${e}:${canonicalHeaderValue(b[e])}\n`).join(``),E=w.join(`;`),D=[e.method.toUpperCase(),p,h,T,E,y].join(`
|
|
220
220
|
`),O=`${d}/${l}/${s}/aws4_request`,k=[`AWS4-HMAC-SHA256`,u,O,hash(D)].join(`
|
|
221
221
|
`),A=getSigningKey(i,d,l,s),j={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${O}, SignedHeaders=${E}, Signature=${(0,g.createHmac)(`sha256`,A).update(k).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":y};return a&&(j[`x-amz-security-token`]=a),C!==void 0&&(j[`x-amz-checksum-sha256`]=C),j},ot=[`sha256`,`sha512`],isValidAlgorithm=e=>ot.includes(e),hashPayload=e=>(0,g.createHash)(`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=(/* @__PURE__ */ 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=serializeRequestBodyForSigning(e.body,e.headers??{}),_=hashPayload(h),v=[d,e.method.toUpperCase(),f.pathname,m,_].join(`
|
|
222
222
|
`),y=(0,g.createHmac)(c,r).update(v).digest(`hex`);return{[l]:`${u} ${y}`,"X-Timestamp":d}},st=[`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&&!st.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=/* @__PURE__ */ 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 _=h.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),v=[m,e.method.toUpperCase()];s&&v.push(f.hostname.toLowerCase()),v.push(f.pathname,_),c&&v.push(hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})));let y=(0,g.createHmac)(d,t).update(v.join(`
|
package/dist/index.d.cts
CHANGED
|
@@ -15,6 +15,8 @@ declare abstract class AsyncSingleton<T, O> {
|
|
|
15
15
|
private status;
|
|
16
16
|
private initOptions;
|
|
17
17
|
private initArgs;
|
|
18
|
+
private generation;
|
|
19
|
+
private attempts;
|
|
18
20
|
protected abstract initInstance(options: O | null, ...args: unknown[]): Promise<T>;
|
|
19
21
|
protected abstract name: string;
|
|
20
22
|
protected getRetryDelay(): number;
|
|
@@ -24,6 +26,8 @@ declare abstract class AsyncSingleton<T, O> {
|
|
|
24
26
|
isReady(): boolean;
|
|
25
27
|
hasInitFailed(): boolean;
|
|
26
28
|
private init;
|
|
29
|
+
private failInit;
|
|
30
|
+
protected disposeStaleInstance(_instance: T): void;
|
|
27
31
|
reset(): void;
|
|
28
32
|
}
|
|
29
33
|
interface ICacheClient<ClientType = unknown> {
|
|
@@ -88,12 +92,13 @@ interface RedisClientConfig {
|
|
|
88
92
|
connectTimeout?: number;
|
|
89
93
|
initialConnectTimeout?: number;
|
|
90
94
|
pingInterval?: number;
|
|
95
|
+
pingTimeout?: number;
|
|
91
96
|
}
|
|
92
97
|
type RedisClientBuilder = (config: RedisClientConfig, logger?: ILogger, invoker?: string) => Promise<ICacheClient<RedisClientType> | undefined>;
|
|
93
98
|
declare const buildRedisClientInstance: (config: RedisClientConfig, logger?: ILogger, invoker?: string) => Promise<ICacheClient<RedisClientType> | undefined>;
|
|
94
99
|
export declare class RedisClient implements ICacheClient<RedisClientType> {
|
|
95
100
|
#private;
|
|
96
|
-
static build({ getRedisClient, host, port, tls, keepAlive, reconnect, database, connectTimeout, initialConnectTimeout, pingInterval }: RedisClientConfig, logger?: ILogger, invoker?: string): Promise<ICacheClient<RedisClientType> | null>;
|
|
101
|
+
static build({ getRedisClient, host, port, tls, keepAlive, reconnect, database, connectTimeout, initialConnectTimeout, pingInterval, pingTimeout }: RedisClientConfig, logger?: ILogger, invoker?: string): Promise<ICacheClient<RedisClientType> | null>;
|
|
97
102
|
getData<T>(key: string): Promise<T | null>;
|
|
98
103
|
getDataBatch<T>(keys: string[]): Promise<(T | null)[]>;
|
|
99
104
|
getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
|
|
@@ -175,6 +180,7 @@ export declare abstract class ScriptManager<T extends string, S extends ScriptMa
|
|
|
175
180
|
protected unavailableLogThrottle: LogThrottle;
|
|
176
181
|
protected initInstance({ redisClientConfig, cacheClient, scripts, scriptMap, logger, additionalArgs }: ScriptManagerOptions<T>): Promise<S>;
|
|
177
182
|
protected closeCacheClient(): void;
|
|
183
|
+
protected disposeStaleInstance(): void;
|
|
178
184
|
protected abstract additionalInitialization(...args: unknown[]): Promise<void>;
|
|
179
185
|
protected releaseAdditionalResources(): void;
|
|
180
186
|
protected setupReconnectHandler(): void;
|
package/dist/index.d.mts
CHANGED
|
@@ -15,6 +15,8 @@ declare abstract class AsyncSingleton<T, O> {
|
|
|
15
15
|
private status;
|
|
16
16
|
private initOptions;
|
|
17
17
|
private initArgs;
|
|
18
|
+
private generation;
|
|
19
|
+
private attempts;
|
|
18
20
|
protected abstract initInstance(options: O | null, ...args: unknown[]): Promise<T>;
|
|
19
21
|
protected abstract name: string;
|
|
20
22
|
protected getRetryDelay(): number;
|
|
@@ -24,6 +26,8 @@ declare abstract class AsyncSingleton<T, O> {
|
|
|
24
26
|
isReady(): boolean;
|
|
25
27
|
hasInitFailed(): boolean;
|
|
26
28
|
private init;
|
|
29
|
+
private failInit;
|
|
30
|
+
protected disposeStaleInstance(_instance: T): void;
|
|
27
31
|
reset(): void;
|
|
28
32
|
}
|
|
29
33
|
interface ICacheClient<ClientType = unknown> {
|
|
@@ -88,12 +92,13 @@ interface RedisClientConfig {
|
|
|
88
92
|
connectTimeout?: number;
|
|
89
93
|
initialConnectTimeout?: number;
|
|
90
94
|
pingInterval?: number;
|
|
95
|
+
pingTimeout?: number;
|
|
91
96
|
}
|
|
92
97
|
type RedisClientBuilder = (config: RedisClientConfig, logger?: ILogger, invoker?: string) => Promise<ICacheClient<RedisClientType> | undefined>;
|
|
93
98
|
declare const buildRedisClientInstance: (config: RedisClientConfig, logger?: ILogger, invoker?: string) => Promise<ICacheClient<RedisClientType> | undefined>;
|
|
94
99
|
export declare class RedisClient implements ICacheClient<RedisClientType> {
|
|
95
100
|
#private;
|
|
96
|
-
static build({ getRedisClient, host, port, tls, keepAlive, reconnect, database, connectTimeout, initialConnectTimeout, pingInterval }: RedisClientConfig, logger?: ILogger, invoker?: string): Promise<ICacheClient<RedisClientType> | null>;
|
|
101
|
+
static build({ getRedisClient, host, port, tls, keepAlive, reconnect, database, connectTimeout, initialConnectTimeout, pingInterval, pingTimeout }: RedisClientConfig, logger?: ILogger, invoker?: string): Promise<ICacheClient<RedisClientType> | null>;
|
|
97
102
|
getData<T>(key: string): Promise<T | null>;
|
|
98
103
|
getDataBatch<T>(keys: string[]): Promise<(T | null)[]>;
|
|
99
104
|
getDataKeysFromGroup(groupKey: string): Promise<string[] | null>;
|
|
@@ -175,6 +180,7 @@ export declare abstract class ScriptManager<T extends string, S extends ScriptMa
|
|
|
175
180
|
protected unavailableLogThrottle: LogThrottle;
|
|
176
181
|
protected initInstance({ redisClientConfig, cacheClient, scripts, scriptMap, logger, additionalArgs }: ScriptManagerOptions<T>): Promise<S>;
|
|
177
182
|
protected closeCacheClient(): void;
|
|
183
|
+
protected disposeStaleInstance(): void;
|
|
178
184
|
protected abstract additionalInitialization(...args: unknown[]): Promise<void>;
|
|
179
185
|
protected releaseAdditionalResources(): void;
|
|
180
186
|
protected setupReconnectHandler(): void;
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-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{promisify as m}from"node:util";import{gunzip as h,gzip as g}from"node:zlib";import*as _ from"redis";import{ConnectionTimeoutError as v,SocketClosedUnexpectedlyError as y}from"redis";import{evaluate as b,safeEvaluate as x}from"@stackone/expressions";import S from"node:http";import C from"node:https";import{isIP as w}from"node:net";import T from"node:tls";import E,{AxiosError as D,isAxiosError as O}from"axios";import{createHash as k,createHmac as A,randomUUID as ee}from"crypto";import{clearTimeout as j}from"node:timers";import{hasNumericValue as te,isString as ne}from"mathjs";import{JSONPath as re}from"jsonpath-plus";import{redactFields as ie,redactUrl as M}from"@stackone/redaction";import{createHash as ae,randomUUID as oe}from"node:crypto";import N from"qs";import{Readable as se}from"node:stream";import{Client as ce,IssuerMismatchError as le,SdkHttpError as ue,StreamableHTTPClientTransport as de,UnauthorizedError as fe,checkResourceAllowed as pe,discoverAuthorizationServerMetadata as me,discoverOAuthProtectedResourceMetadata as he,discoverOAuthServerInfo as ge,extractWWWAuthenticateParams as _e}from"@modelcontextprotocol/client";import{getDomain as ve}from"tldts";import{XMLBuilder as ye,XMLParser as be,XMLValidator as P}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=/* @__PURE__ */ 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 F=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??/* @__PURE__ */ new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??/* @__PURE__ */ new Map,this.ttlMap=/* @__PURE__ */ new Map,this.slidingExpiration=e?.slidingExpiration??!1,this.hashStore=/* @__PURE__ */ new Map,this.hashExpiryMap=/* @__PURE__ */ new Map,this.groupMap=/* @__PURE__ */ new Map,this.groupExpiryMap=/* @__PURE__ */ 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 getGroupSize(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.getLiveGroup(e)?.size??0}async listGroupKeys(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.groupMap.keys()).filter(t=>t.startsWith(e)&&(this.getLiveGroup(t)?.size??0)>0)}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*F,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*F:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,/* @__PURE__ */ 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*F;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)??/* @__PURE__ */ 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*F),!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(/* @__PURE__ */ 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()),this.retryTimeout.unref()),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=/* @__PURE__ */ new Map;#r=/* @__PURE__ */ 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 xe=1e4,Se=6e4,Ce=`\0gz:`,we=67108864,Te=/* @__PURE__ */ new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof v||e instanceof y)return!0;let t=e.code;return t!==void 0&&Te.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 v&&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 Ee=m(g),De=m(h),encodeForStorage=async(e,t)=>{let n=e.startsWith(Ce);return!t&&!n?e:Buffer.byteLength(e)>67108864?n?null:e:`${Ce}${(await Ee(e)).toString(`base64`)}`},buildRedisClientInstance=async(e,t,n)=>{try{return await Oe.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 Oe=class RedisClient{#e;#t;static async build({getRedisClient:e=_.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o,connectTimeout:s=xe,initialConnectTimeout:c=15e3,pingInterval:l},u,f){let p=new RedisClient,m=f??`RedisClient`;p.#t=u;try{p.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:!0,keepAliveInitialDelay:i,connectTimeout:s,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,RESP:2,commandOptions:{timeout:0},disableOfflineQueue:!0,...d(l)?{pingInterval:l}:{}});let u=new RedisConnectionHealth(s),f=getDefaultRedisListeners(m,p.#t,u);return addRedisEventHandlers(p.#e,f),u.recordAttemptStart(),await connectWithinBudget(p.#e,c,m,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:m}),await teardownUnusableClient(p.#e),null)}catch(e){let t=e;return p.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:m}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}#r(e){let t=this.#n(e);return u(t)?e:t}async#i(e){if(!e.startsWith(`\0gz:`))return this.#r(e);try{let t=await De(Buffer.from(e.slice(4),`base64`),{maxOutputLength:we});return this.#r(t.toString())}catch(e){return this.#t?.error({message:`Error decompressing data`,error:e,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getData(e){if(!this.#o())return null;try{let t=await this.#e.get(e);return d(t)?await this.#i(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.#o())return e.map(()=>null);try{let t=await this.#e.mGet(e);return await Promise.all(t.map(e=>d(e)?this.#i(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.#o())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 getGroupSize(e){if(!this.#o())return null;try{return await this.#e.sCard(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting group size`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async listGroupKeys(e){if(!this.#o())return null;try{let t=/* @__PURE__ */ new Set;for await(let n of this.#e.scanIterator({MATCH:`${escapeGlobPattern(e)}*`,COUNT:1e3,TYPE:`set`}))for(let e of n)t.add(e);return Array.from(t)}catch(e){let t=e;return this.#t?.error({message:`Error listing group keys`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i,compress:a}){if(!this.#o())return!1;try{let o=u(t)?t:JSON.stringify(t),s=await encodeForStorage(o,a===!0);if(s===null)return this.#t?.error({message:`Refusing to store a value over ${we} bytes that starts with the compression prefix`,code:`RedisClientWriteError`,category:RedisClient.name}),!1;if(await this.#e.set(e,s,{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.#o())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===1}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.#o())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.#o())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.#o())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#a(e,t,n){if(!this.#o())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=(await this.#e.multi().addCommand([e,t]).addCommand([`expire`,t,n.toString()]).exec())?.[0];return typeof r==`number`?r: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.#a(`incr`,e,t)}async decrement(e,t){return this.#a(`decr`,e,t)}async subscribe(e,t){if(!this.#o())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.#o())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.#o())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.#o()?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})}}#o(){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=await this.#e.sScan(e,n||`0`,{COUNT:t}),i=[];for(let e of r.members){let t=await this.getData(e);d(t)&&i.push(t)}return{items:i,cursor:r.cursor===`0`?void 0:r.cursor}}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.#o())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.#o())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.#o())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.multi().addCommand([`hset`,e,...t]).addCommand([`expire`,e,n.toString()]).exec(),!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.#o())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.#o())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.#o())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())},escapeGlobPattern=e=>e.replace(/[\\*?[\]]/g,`\\$&`),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(xe))=>{let r=new LogThrottle(Se);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}};o.severity===`sustained`?t?.error(u):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(Se)}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??/* @__PURE__ */ 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=/* @__PURE__ */ 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 I=15e3,ke=15e3,L=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:L,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:ke,truncateThreshold:L,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ke,truncateThreshold:L,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=I,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 R=`__keyevent@0__:`,Ae=[`${R}set`,`${R}expire`,`${R}expired`],je={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,Me={tryConcurrency:`
|
|
1
|
+
import{t as e}from"./rolldown-runtime-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{promisify as m}from"node:util";import{gunzip as h,gzip as g}from"node:zlib";import*as _ from"redis";import{ConnectionTimeoutError as v,SocketClosedUnexpectedlyError as y}from"redis";import{evaluate as b,safeEvaluate as x}from"@stackone/expressions";import S from"node:http";import C from"node:https";import{isIP as w}from"node:net";import T from"node:tls";import E,{AxiosError as D,isAxiosError as O}from"axios";import{createHash as k,createHmac as A,randomUUID as ee}from"crypto";import{clearTimeout as j}from"node:timers";import{hasNumericValue as te,isString as ne}from"mathjs";import{JSONPath as re}from"jsonpath-plus";import{redactFields as ie,redactUrl as M}from"@stackone/redaction";import{createHash as ae,randomUUID as oe}from"node:crypto";import N from"qs";import{Readable as se}from"node:stream";import{Client as ce,IssuerMismatchError as le,SdkHttpError as ue,StreamableHTTPClientTransport as de,UnauthorizedError as fe,checkResourceAllowed as pe,discoverAuthorizationServerMetadata as me,discoverOAuthProtectedResourceMetadata as he,discoverOAuthServerInfo as ge,extractWWWAuthenticateParams as _e}from"@modelcontextprotocol/client";import{getDomain as ve}from"tldts";import{XMLBuilder as ye,XMLParser as be,XMLValidator as P}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=/* @__PURE__ */ 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 F=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??/* @__PURE__ */ new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??/* @__PURE__ */ new Map,this.ttlMap=/* @__PURE__ */ new Map,this.slidingExpiration=e?.slidingExpiration??!1,this.hashStore=/* @__PURE__ */ new Map,this.hashExpiryMap=/* @__PURE__ */ new Map,this.groupMap=/* @__PURE__ */ new Map,this.groupExpiryMap=/* @__PURE__ */ 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 getGroupSize(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.getLiveGroup(e)?.size??0}async listGroupKeys(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),Array.from(this.groupMap.keys()).filter(t=>t.startsWith(e)&&(this.getLiveGroup(t)?.size??0)>0)}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*F,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*F:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,/* @__PURE__ */ 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*F;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)??/* @__PURE__ */ 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*F),!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(/* @__PURE__ */ 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}},AsyncSingletonResetError=class extends Error{constructor(e,t){super(`${e} was reset while initializing`),this.name=`AsyncSingletonResetError`,this.cause=t?.cause}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[],this.generation=0,this.attempts=0}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.attempts+=1,this.initPromise=this.init(this.generation,this.attempts,e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,t,n,...r){let i=await(async()=>this.initInstance(n,...r))().catch(t=>this.failInit(e,t));if(e!==this.generation)throw t===this.attempts&&this.disposeStaleInstance(i),new AsyncSingletonResetError(this.name);return this.instance=i,this.status=`ready`,i}failInit(e,t){throw e===this.generation?(this.status=`failed`,this.initPromise=null,s(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay()),this.retryTimeout.unref()),t):new AsyncSingletonResetError(this.name,{cause:t})}disposeStaleInstance(e){}reset(){this.generation+=1,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=/* @__PURE__ */ new Map;#r=/* @__PURE__ */ 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 xe=1e4,Se=6e4,Ce=`\0gz:`,we=67108864,Te=/* @__PURE__ */ new Set([`ECONNRESET`,`ECONNREFUSED`,`EPIPE`,`ETIMEDOUT`,`EHOSTUNREACH`,`ENETUNREACH`,`ENETRESET`,`EAI_AGAIN`]),isTransientError=e=>{if(e instanceof v||e instanceof y)return!0;let t=e.code;return t!==void 0&&Te.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 v&&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`}};const waitFor=e=>{let t={};return{done:new Promise(n=>{t.id=setTimeout(n,e),t.id.unref?.()}),cancel:()=>clearTimeout(t.id)}},settlesWithin=async({outcome:e,timeoutMs:t,now:n})=>{let r={settled:!1},i=e.then(()=>{r.settled=!0},()=>{r.settled=!0}),waitOneWindow=async()=>{let e=n(),a=waitFor(t);return await Promise.race([i,a.done]),a.cancel(),r.settled?!0:n()-e>t*2&&waitOneWindow()};return waitOneWindow()},startConnectionHeartbeat=({client:e,intervalMs:t,timeoutMs:n,onUnresponsive:r,now:i=Date.now})=>{let a={stopped:!1,endHandshakeWatch:()=>void 0},reportUnlessStopped=()=>{a.stopped||r()},beat=async()=>{let t=!e.isReady||await settlesWithin({outcome:e.sendCommand([`PING`]),timeoutMs:n,now:i});a.stopped||(t||r(),schedule())},schedule=()=>{let e=waitFor(t);a.next=e,e.done.then(beat)},watchHandshake=()=>{a.endHandshakeWatch();let e=new Promise(e=>{a.endHandshakeWatch=e});settlesWithin({outcome:e,timeoutMs:n,now:i}).then(e=>{e||reportUnlessStopped()})},endHandshakeWatch=()=>a.endHandshakeWatch();return e.on(`connect`,watchHandshake),e.on(`ready`,endHandshakeWatch),e.on(`error`,endHandshakeWatch),e.on(`end`,endHandshakeWatch),schedule(),{stop:()=>{a.stopped=!0,a.next?.cancel(),e.off(`connect`,watchHandshake),e.off(`ready`,endHandshakeWatch),e.off(`error`,endHandshakeWatch),e.off(`end`,endHandshakeWatch),a.endHandshakeWatch()}}};function isTlsOptions(e){return typeof e==`object`&&!!e}const Ee=m(g),De=m(h),encodeForStorage=async(e,t)=>{let n=e.startsWith(Ce);return!t&&!n?e:Buffer.byteLength(e)>67108864?n?null:e:`${Ce}${(await Ee(e)).toString(`base64`)}`},buildRedisClientInstance=async(e,t,n)=>{try{return await Oe.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 Oe=class RedisClient{#e;#t;#n;#r=!1;#i={inProgress:!1,consecutive:0,lastConnect:Promise.resolve()};static async build({getRedisClient:e=_.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o,connectTimeout:c=xe,initialConnectTimeout:l=15e3,pingInterval:u,pingTimeout:f},p,m){let h=new RedisClient,g=m??`RedisClient`;h.#t=p;let v=a&&isTimerDelay(u)&&isTimerDelay(f)?{intervalMs:u,timeoutMs:f}:void 0;d(f)&&s(v)&&p?.warning({message:`pingTimeout is ignored: it needs reconnect and a pingInterval, both whole milliseconds from 1 to 2147483647`,code:`RedisClientError`,category:g});try{h.#e=e({socket:{reconnectStrategy:a?computeReconnectDelay:!1,host:t,port:n,keepAlive:!0,keepAliveInitialDelay:i,connectTimeout:c,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,RESP:2,commandOptions:{timeout:0},disableOfflineQueue:!0,...isTimerDelay(u)&&s(v)?{pingInterval:u}:{}});let f=new RedisConnectionHealth(c),p=getDefaultRedisListeners(g,h.#t,f);return addRedisEventHandlers(h.#e,p),f.recordAttemptStart(),await connectWithinBudget(h.#e,l,g,h.#t)?(d(v)&&h.#a({...v,category:g}),h):(h.#t?.error({message:`Redis client did not connect within its ${l}ms budget, giving up so the caller can degrade`,code:`RedisClientConnectTimeout`,category:g}),await teardownUnusableClient(h.#e),null)}catch(e){let t=e;return h.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:g}),null}}#a({intervalMs:e,timeoutMs:t,category:n}){let r=this.#e;this.#n=startConnectionHeartbeat({client:r,intervalMs:e,timeoutMs:t,onUnresponsive:()=>{this.#o({timeoutMs:t,category:n})}})}async#o({timeoutMs:e,category:t}){let n=this.#i;if(!n.inProgress){n.inProgress=!0,this.#t?.warning({message:`Redis did not answer within ${e}ms, replacing the connection`,code:`RedisClientConnectionUnresponsive`,category:t});try{let e=this.#e;if(e.destroy(),await n.lastConnect,await new Promise(e=>setTimeout(e,computeReconnectDelay(n.consecutive)).unref()),n.consecutive+=1,this.#r)return;n.lastConnect=e.connect().then(()=>{n.consecutive=0},e=>this.#s(e,t))}catch(e){this.#s(e,t)}finally{n.inProgress=!1}}}#s(e,t){this.#t?.error({message:`Redis client could not reconnect after replacing an unresponsive connection`,error:e,code:`RedisClientError`,category:t})}#c(e){try{return JSON.parse(e)}catch{return e}}#l(e){let t=this.#c(e);return u(t)?e:t}async#u(e){if(!e.startsWith(`\0gz:`))return this.#l(e);try{let t=await De(Buffer.from(e.slice(4),`base64`),{maxOutputLength:we});return this.#l(t.toString())}catch(e){return this.#t?.error({message:`Error decompressing data`,error:e,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getData(e){if(!this.#f())return null;try{let t=await this.#e.get(e);return d(t)?await this.#u(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.#f())return e.map(()=>null);try{let t=await this.#e.mGet(e);return await Promise.all(t.map(e=>d(e)?this.#u(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.#f())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 getGroupSize(e){if(!this.#f())return null;try{return await this.#e.sCard(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting group size`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async listGroupKeys(e){if(!this.#f())return null;try{let t=/* @__PURE__ */ new Set;for await(let n of this.#e.scanIterator({MATCH:`${escapeGlobPattern(e)}*`,COUNT:1e3,TYPE:`set`}))for(let e of n)t.add(e);return Array.from(t)}catch(e){let t=e;return this.#t?.error({message:`Error listing group keys`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i,compress:a}){if(!this.#f())return!1;try{let o=u(t)?t:JSON.stringify(t),s=await encodeForStorage(o,a===!0);if(s===null)return this.#t?.error({message:`Refusing to store a value over ${we} bytes that starts with the compression prefix`,code:`RedisClientWriteError`,category:RedisClient.name}),!1;if(await this.#e.set(e,s,{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.#f())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===1}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.#f())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.#f())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.#f())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#d(e,t,n){if(!this.#f())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=(await this.#e.multi().addCommand([e,t]).addCommand([`expire`,t,n.toString()]).exec())?.[0];return typeof r==`number`?r: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.#d(`incr`,e,t)}async decrement(e,t){return this.#d(`decr`,e,t)}async subscribe(e,t){if(!this.#f())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.#f())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.#f())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.#f()?this.#e:null}isAvailable(){return this.#e.isReady&&this.#e.isOpen}async close(){this.#r=!0,this.#n?.stop();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})}}#f(){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=await this.#e.sScan(e,n||`0`,{COUNT:t}),i=[];for(let e of r.members){let t=await this.getData(e);d(t)&&i.push(t)}return{items:i,cursor:r.cursor===`0`?void 0:r.cursor}}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.#f())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.#f())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.#f())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.multi().addCommand([`hset`,e,...t]).addCommand([`expire`,e,n.toString()]).exec(),!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.#f())return null;try{let n=await this.#e.hGet(e,t);return n!==``&&s(n)?null:this.#l(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.#f())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.#l(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.#f())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 isTimerDelay=e=>Number.isInteger(e)&&e>0&&e<=2147483647,computeReconnectDelay=e=>{let t=Math.min(100*2**e,5e3);return Math.round(t-t*.5*Math.random())},escapeGlobPattern=e=>e.replace(/[\\*?[\]]/g,`\\$&`),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(xe))=>{let r=new LogThrottle(Se);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}};o.severity===`sustained`?t?.error(u):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(Se)}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??/* @__PURE__ */ 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`})}})()}disposeStaleInstance(){this.releaseAdditionalResources(),this.closeCacheClient()}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=/* @__PURE__ */ 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 I=15e3,ke=15e3,L=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:L,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:ke,truncateThreshold:L,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ke,truncateThreshold:L,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=I,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 R=`__keyevent@0__:`,Ae=[`${R}set`,`${R}expire`,`${R}expired`],je={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,Me={tryConcurrency:`
|
|
2
2
|
local requestId = KEYS[1]
|
|
3
3
|
local targetKey = KEYS[2]
|
|
4
4
|
local queueKey = KEYS[3]
|
|
@@ -216,7 +216,7 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
216
216
|
-- open with a warning, so returning nil here would report the ordinary un-throttled path as
|
|
217
217
|
-- an outage. nil is reserved for the client genuinely being unavailable.
|
|
218
218
|
return 0
|
|
219
|
-
`};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:ht,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,cacheClient:o,scripts:gt,logger:n})]),u=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,cacheClient:o,scripts:Me,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},_t=/* @__PURE__ */ 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=>ve(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();else 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(!_t.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);if(!n||getMediaType(n.response)!==`text/html`)return await n?.response.body?.cancel(),{icons:[],url:n?.url??e};let r=(await readBytes(n.response,1048576)).toString(`utf8`);return{icons:findDeclaredIcons(r,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})}),vt=/* @__PURE__ */ e((e,t)=>fetch(e,t),`defaultBaseFetch`),createRetryingFetch=(e=vt,{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??Xe,h=t?.concurrency??je,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,oe(),_,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)}},yt={name:`stackone-connect`,version:`1.0.0`},bt={mode:`auto`},xt={createClient:(e,t)=>new ce(e,t),createTransport:(e,t)=>new de(e,t)},St=/^[\t\x20-\x7e\x80-\xff]*$/,isHttpWhitespace=e=>e===9||e===10||e===13||e===32,trimHttpWhitespace=e=>{let t=0,n=e.length;for(;t<n&&isHttpWhitespace(e.charCodeAt(t));)t++;for(;n>t&&isHttpWhitespace(e.charCodeAt(n-1));)n--;return e.slice(t,n)},toRedactedServerUrl=e=>{try{return new URL(e).origin}catch{return``}},toSendableHeaders=(e,t)=>{if(!t)return;let n=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,String(t)])),r=Object.entries(n).filter(([,e])=>!St.test(trimHttpWhitespace(e))).map(([e])=>e);if(r.length===0)return n;let i=`The MCP header(s) ${r.join(`, `)} hold characters that cannot be sent`;throw new B({status:400,data:{message:i},headers:{},requestUrl:toRedactedServerUrl(e),message:i},i)};var McpClient=class{constructor(e,t=xt){this.config=e,this.sdk=t,e.egressProxyUrl&&parseEgressProxyUrl(e.egressProxyUrl)}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,egressProxyUrl:a}=this.config,o=toSendableHeaders(e,t),s=this.sdk.createClient(n??yt,{versionNegotiation:bt}),c=this.sdk.createTransport(new URL(e),{requestInit:o?{headers:o}:void 0,fetch:createRetryingFetch(createThrottledFetch(a?createEgressProxyFetch(a):void 0,{requestConfig:r,context:i}))});return await s.connect(c,this.buildRequestOptions()),s}buildRequestOptions(){return this.config.timeout?{timeout:this.config.timeout}:void 0}};const Ct={discoverServerInfo:(e,t)=>ge(e,t),discoverResourceMetadata:(e,t)=>he(e,void 0,t),discoverAuthorizationServerMetadata:(e,t)=>me(e,t)},isSameSiteIssuer=(e,t)=>{if(!u(e)||!u(t))return!1;try{let n=new URL(e),r=new URL(t);return n.protocol===`https:`&&r.protocol===`https:`&&r.port===n.port&&r.hostname.endsWith(`.${n.hostname}`)}catch{return!1}},isSameSiteMetadataMismatch=e=>e instanceof le&&e.kind===`metadata`&&isSameSiteIssuer(e.expected,e.received),discoverSameSiteAuthorizationServerMetadata=async(e,t={},n=Ct)=>{let{fetchFn:r,onSameSiteIssuerFallback:i}=t;try{return await n.discoverAuthorizationServerMetadata(e,{fetchFn:r})}catch(e){if(!isSameSiteMetadataMismatch(e))throw e;i?.({expectedIssuer:e.expected,receivedIssuer:e.received});let t=await n.discoverAuthorizationServerMetadata(e.received,{fetchFn:r});if(s(t))throw e;return t}},discoverMcpOAuthServerInfo=async(e,t={},n=Ct)=>{let{fetchFn:r,onSameSiteIssuerFallback:i}=t;try{return await n.discoverServerInfo(e,{fetchFn:r})}catch(t){if(!isSameSiteMetadataMismatch(t))throw t;i?.({expectedIssuer:t.expected,receivedIssuer:t.received});let[a,o]=await Promise.all([n.discoverResourceMetadata(e,r).catch(()=>void 0),n.discoverAuthorizationServerMetadata(t.received,{fetchFn:r})]);if(s(o))throw t;return{authorizationServerUrl:t.received,authorizationServerMetadata:o,resourceMetadata:a}}},wt=3e4,fetchAuthorizationChallenge=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(new DOMException(`No authorization challenge within ${wt}ms`,`TimeoutError`)),wt);try{let n=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`}),signal:t.signal});if(await n.body?.cancel().catch(()=>void 0),n.status===429||n.status>=500)throw Error(`Authorization challenge request failed with status ${n.status}`);if(n.status!==401)return;let{resourceMetadataUrl:r,scope:i}=_e(n);return{resourceMetadataUrl:r?.toString(),scope:i}}finally{clearTimeout(n)}},Tt={createClient:e=>new McpClient({serverUrl:e}),fetchAuthorizationChallenge,discoverResourceMetadata:(e,t)=>he(e,t?{resourceMetadataUrl:t}:void 0),discoverAuthorizationServer:e=>discoverSameSiteAuthorizationServerMetadata(e)},mcpResourceIndicator=(e,t)=>{let n=new URL(e),r=`${n.origin}${n.pathname}`;if(!t||!URL.canParse(t)||!pe({requestedResource:r,configuredResource:t}))return r;let i=new URL(t);return`${i.origin}${i.pathname}`},isAuthorizationFailure=e=>e instanceof fe||e instanceof ue&&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,clientIdMetadataDocument:d(i)?i.client_id_metadata_document_supported===!0:void 0,resourceMetadataUrl:t?.resourceMetadataUrl,advertisedResource:e?.resource,tokenEndpoint:i?.token_endpoint,refreshTokenGrant:d(i)?i.grant_types_supported?.includes(`refresh_token`)??!1:void 0,tokenEndpointAuthMethods:i?.token_endpoint_auth_methods_supported},...a?{resource:a}:{}}},probeProtectedServer=async(e,t)=>{let{challenge:n,challengeFailure:r}=await t.fetchAuthorizationChallenge(e).then(e=>({challenge:e,challengeFailure:void 0}),e=>({challenge:void 0,challengeFailure:{error:e}})),i=await t.discoverResourceMetadata(e,n?.resourceMetadataUrl).catch(()=>void 0);if(!i&&!n?.resourceMetadataUrl){if(r)throw r.error;return{requiresAuthorization:!0}}return{requiresAuthorization:!0,...await buildOAuthProbe(i,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)}},Et=/* @__PURE__ */ e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),Z=/* @__PURE__ */ 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(Et(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)?e.body=Array.isArray(e.body)?e.body.concat(t.value):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:{}}),Dt=[`query`,`body`,`headers`],Ot=[`repeat`,`brackets`,`comma`,`stringify`],kt={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},At=new ye(kt),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`)?N.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,getProviderResponse=e=>{let{response:t,getStatus:n}=e??{};return l(t)&&typeof t.status==`number`&&typeof n!=`function`?t:void 0},jt=[`arraybuffer`,`blob`,`document`,`text`];let Mt;const getXmlParser=()=>(Mt??=new be({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),Mt);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:s,requestConfig:c,httpsAgent:l,credentials:u,responseType:d,context:f,cacheTTL:p,timeoutMs:m}){let h,g=o;if(isXmlContentType(r)){if(typeof o==`string`)g=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&&(g=serializeBodyToXml(o))}try{h=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:g,requestConfig:c,httpsAgent:l,responseType:d,context:f,cacheTTL:p,timeoutMs:m})}catch(e){let t=getProviderResponse(e);if(!t)throw e;h=t}if(typeof h.data==`string`&&/\S/.test(h.data)&&h.headers&&isXmlContentType(h.headers)&&(!d||!jt.includes(d))){let e=P.validate(h.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);h={...h,data:getXmlParser().parse(h.data)}}let _=translateCustomError(h,s,u);if(isFailedStatusCode(_?.status))throw new B(_,_.message);return _}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:s,requestConfig:c,credentials:l,context:u,cacheTTL:d}){let f;if(f=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Q.build(c.envelope):await buildEnvelope(o,c),P.validate(f,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let p,m={"Content-Type":`application/xml`,...r};c?.soapAction&&(m.SOAPAction=c.soapAction);try{p=await e?.request({method:n,url:t,headers:m,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:f,requestConfig:c,context:u,cacheTTL:d})}catch(e){let t=getProviderResponse(e);if(!t)throw e;p=t}let h=Nt.parse(p.data),g=h.Envelope||h,_=g.Body||g,v=_.Fault;if(v)throw new B({...p,status:500,data:v,message:v.faultstring??v.faultcode??`SOAP Fault`},v.faultstring??`SOAP Fault occurred`);p.data=_;let y=translateCustomError(p,s,l);if(isFailedStatusCode(y?.status))throw new B(y,y.message);return y}};const Q=new ye(kt),Nt=new be({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(P.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Q.build(n);if(P.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 b(e.namespaceIdentifier),namespace:await b(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)=>A(`sha256`,e).update(t).digest(),hash=e=>k(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>{let i=hmac(`AWS4${e}`,t),a=hmac(i,n),o=hmac(a,r);return hmac(o,`aws4_request`)},$=/* @__PURE__ */ e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),Pt=/* @__PURE__ */ 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=(/* @__PURE__ */ 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=Pt(e,n);return i===0?Pt(t,r):i});let h=m.map(([e,t])=>`${$(e)}=${$(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=k(`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 C=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),w=C.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),T=C.join(`;`),E=[e.method.toUpperCase(),p,h,w,T,v].join(`
|
|
219
|
+
`};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:ht,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,cacheClient:o,scripts:gt,logger:n})]),u=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,cacheClient:o,scripts:Me,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){if(e instanceof AsyncSingletonResetError)throw 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},_t=/* @__PURE__ */ 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=>ve(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();else 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(!_t.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);if(!n||getMediaType(n.response)!==`text/html`)return await n?.response.body?.cancel(),{icons:[],url:n?.url??e};let r=(await readBytes(n.response,1048576)).toString(`utf8`);return{icons:findDeclaredIcons(r,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})}),vt=/* @__PURE__ */ e((e,t)=>fetch(e,t),`defaultBaseFetch`),createRetryingFetch=(e=vt,{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??Xe,h=t?.concurrency??je,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,oe(),_,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)}},yt={name:`stackone-connect`,version:`1.0.0`},bt={mode:`auto`},xt={createClient:(e,t)=>new ce(e,t),createTransport:(e,t)=>new de(e,t)},St=/^[\t\x20-\x7e\x80-\xff]*$/,isHttpWhitespace=e=>e===9||e===10||e===13||e===32,trimHttpWhitespace=e=>{let t=0,n=e.length;for(;t<n&&isHttpWhitespace(e.charCodeAt(t));)t++;for(;n>t&&isHttpWhitespace(e.charCodeAt(n-1));)n--;return e.slice(t,n)},toRedactedServerUrl=e=>{try{return new URL(e).origin}catch{return``}},toSendableHeaders=(e,t)=>{if(!t)return;let n=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,String(t)])),r=Object.entries(n).filter(([,e])=>!St.test(trimHttpWhitespace(e))).map(([e])=>e);if(r.length===0)return n;let i=`The MCP header(s) ${r.join(`, `)} hold characters that cannot be sent`;throw new B({status:400,data:{message:i},headers:{},requestUrl:toRedactedServerUrl(e),message:i},i)};var McpClient=class{constructor(e,t=xt){this.config=e,this.sdk=t,e.egressProxyUrl&&parseEgressProxyUrl(e.egressProxyUrl)}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,egressProxyUrl:a}=this.config,o=toSendableHeaders(e,t),s=this.sdk.createClient(n??yt,{versionNegotiation:bt}),c=this.sdk.createTransport(new URL(e),{requestInit:o?{headers:o}:void 0,fetch:createRetryingFetch(createThrottledFetch(a?createEgressProxyFetch(a):void 0,{requestConfig:r,context:i}))});return await s.connect(c,this.buildRequestOptions()),s}buildRequestOptions(){return this.config.timeout?{timeout:this.config.timeout}:void 0}};const Ct={discoverServerInfo:(e,t)=>ge(e,t),discoverResourceMetadata:(e,t)=>he(e,void 0,t),discoverAuthorizationServerMetadata:(e,t)=>me(e,t)},isSameSiteIssuer=(e,t)=>{if(!u(e)||!u(t))return!1;try{let n=new URL(e),r=new URL(t);return n.protocol===`https:`&&r.protocol===`https:`&&r.port===n.port&&r.hostname.endsWith(`.${n.hostname}`)}catch{return!1}},isSameSiteMetadataMismatch=e=>e instanceof le&&e.kind===`metadata`&&isSameSiteIssuer(e.expected,e.received),discoverSameSiteAuthorizationServerMetadata=async(e,t={},n=Ct)=>{let{fetchFn:r,onSameSiteIssuerFallback:i}=t;try{return await n.discoverAuthorizationServerMetadata(e,{fetchFn:r})}catch(e){if(!isSameSiteMetadataMismatch(e))throw e;i?.({expectedIssuer:e.expected,receivedIssuer:e.received});let t=await n.discoverAuthorizationServerMetadata(e.received,{fetchFn:r});if(s(t))throw e;return t}},discoverMcpOAuthServerInfo=async(e,t={},n=Ct)=>{let{fetchFn:r,onSameSiteIssuerFallback:i}=t;try{return await n.discoverServerInfo(e,{fetchFn:r})}catch(t){if(!isSameSiteMetadataMismatch(t))throw t;i?.({expectedIssuer:t.expected,receivedIssuer:t.received});let[a,o]=await Promise.all([n.discoverResourceMetadata(e,r).catch(()=>void 0),n.discoverAuthorizationServerMetadata(t.received,{fetchFn:r})]);if(s(o))throw t;return{authorizationServerUrl:t.received,authorizationServerMetadata:o,resourceMetadata:a}}},wt=3e4,fetchAuthorizationChallenge=async e=>{let t=new AbortController,n=setTimeout(()=>t.abort(new DOMException(`No authorization challenge within ${wt}ms`,`TimeoutError`)),wt);try{let n=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`}),signal:t.signal});if(await n.body?.cancel().catch(()=>void 0),n.status===429||n.status>=500)throw Error(`Authorization challenge request failed with status ${n.status}`);if(n.status!==401)return;let{resourceMetadataUrl:r,scope:i}=_e(n);return{resourceMetadataUrl:r?.toString(),scope:i}}finally{clearTimeout(n)}},Tt={createClient:e=>new McpClient({serverUrl:e}),fetchAuthorizationChallenge,discoverResourceMetadata:(e,t)=>he(e,t?{resourceMetadataUrl:t}:void 0),discoverAuthorizationServer:e=>discoverSameSiteAuthorizationServerMetadata(e)},mcpResourceIndicator=(e,t)=>{let n=new URL(e),r=`${n.origin}${n.pathname}`;if(!t||!URL.canParse(t)||!pe({requestedResource:r,configuredResource:t}))return r;let i=new URL(t);return`${i.origin}${i.pathname}`},isAuthorizationFailure=e=>e instanceof fe||e instanceof ue&&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,clientIdMetadataDocument:d(i)?i.client_id_metadata_document_supported===!0:void 0,resourceMetadataUrl:t?.resourceMetadataUrl,advertisedResource:e?.resource,tokenEndpoint:i?.token_endpoint,refreshTokenGrant:d(i)?i.grant_types_supported?.includes(`refresh_token`)??!1:void 0,tokenEndpointAuthMethods:i?.token_endpoint_auth_methods_supported},...a?{resource:a}:{}}},probeProtectedServer=async(e,t)=>{let{challenge:n,challengeFailure:r}=await t.fetchAuthorizationChallenge(e).then(e=>({challenge:e,challengeFailure:void 0}),e=>({challenge:void 0,challengeFailure:{error:e}})),i=await t.discoverResourceMetadata(e,n?.resourceMetadataUrl).catch(()=>void 0);if(!i&&!n?.resourceMetadataUrl){if(r)throw r.error;return{requiresAuthorization:!0}}return{requiresAuthorization:!0,...await buildOAuthProbe(i,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)}},Et=/* @__PURE__ */ e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),Z=/* @__PURE__ */ 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(Et(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)?e.body=Array.isArray(e.body)?e.body.concat(t.value):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:{}}),Dt=[`query`,`body`,`headers`],Ot=[`repeat`,`brackets`,`comma`,`stringify`],kt={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},At=new ye(kt),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`)?N.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,getProviderResponse=e=>{let{response:t,getStatus:n}=e??{};return l(t)&&typeof t.status==`number`&&typeof n!=`function`?t:void 0},jt=[`arraybuffer`,`blob`,`document`,`text`];let Mt;const getXmlParser=()=>(Mt??=new be({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),Mt);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:s,requestConfig:c,httpsAgent:l,credentials:u,responseType:d,context:f,cacheTTL:p,timeoutMs:m}){let h,g=o;if(isXmlContentType(r)){if(typeof o==`string`)g=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&&(g=serializeBodyToXml(o))}try{h=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:g,requestConfig:c,httpsAgent:l,responseType:d,context:f,cacheTTL:p,timeoutMs:m})}catch(e){let t=getProviderResponse(e);if(!t)throw e;h=t}if(typeof h.data==`string`&&/\S/.test(h.data)&&h.headers&&isXmlContentType(h.headers)&&(!d||!jt.includes(d))){let e=P.validate(h.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);h={...h,data:getXmlParser().parse(h.data)}}let _=translateCustomError(h,s,u);if(isFailedStatusCode(_?.status))throw new B(_,_.message);return _}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:s,requestConfig:c,credentials:l,context:u,cacheTTL:d}){let f;if(f=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Q.build(c.envelope):await buildEnvelope(o,c),P.validate(f,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let p,m={"Content-Type":`application/xml`,...r};c?.soapAction&&(m.SOAPAction=c.soapAction);try{p=await e?.request({method:n,url:t,headers:m,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:f,requestConfig:c,context:u,cacheTTL:d})}catch(e){let t=getProviderResponse(e);if(!t)throw e;p=t}let h=Nt.parse(p.data),g=h.Envelope||h,_=g.Body||g,v=_.Fault;if(v)throw new B({...p,status:500,data:v,message:v.faultstring??v.faultcode??`SOAP Fault`},v.faultstring??`SOAP Fault occurred`);p.data=_;let y=translateCustomError(p,s,l);if(isFailedStatusCode(y?.status))throw new B(y,y.message);return y}};const Q=new ye(kt),Nt=new be({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(P.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Q.build(n);if(P.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 b(e.namespaceIdentifier),namespace:await b(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)=>A(`sha256`,e).update(t).digest(),hash=e=>k(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>{let i=hmac(`AWS4${e}`,t),a=hmac(i,n),o=hmac(a,r);return hmac(o,`aws4_request`)},$=/* @__PURE__ */ e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),Pt=/* @__PURE__ */ 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=(/* @__PURE__ */ 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=Pt(e,n);return i===0?Pt(t,r):i});let h=m.map(([e,t])=>`${$(e)}=${$(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=k(`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 C=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),w=C.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),T=C.join(`;`),E=[e.method.toUpperCase(),p,h,w,T,v].join(`
|
|
220
220
|
`),D=`${d}/${l}/${s}/aws4_request`,O=[`AWS4-HMAC-SHA256`,u,D,hash(E)].join(`
|
|
221
221
|
`),ee=getSigningKey(i,d,l,s),j={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${D}, SignedHeaders=${T}, Signature=${A(`sha256`,ee).update(O).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":v};return a&&(j[`x-amz-security-token`]=a),S!==void 0&&(j[`x-amz-checksum-sha256`]=S),j},Ft=[`sha256`,`sha512`],isValidAlgorithm=e=>Ft.includes(e),hashPayload=e=>k(`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=(/* @__PURE__ */ 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=serializeRequestBodyForSigning(e.body,e.headers??{}),g=hashPayload(h),_=[d,e.method.toUpperCase(),f.pathname,m,g].join(`
|
|
222
222
|
`),v=A(c,r).update(_).digest(`hex`);return{[l]:`${u} ${v}`,"X-Timestamp":d}},It=[`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&&!It.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=/* @__PURE__ */ 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=A(d,t).update(_.join(`
|