@stackone/transport 2.28.1 → 2.28.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 +19 -10
- package/dist/index.d.cts +10 -2
- package/dist/index.d.mts +10 -2
- package/dist/index.mjs +18 -9
- 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,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@stackone/utils"),s=require("redis");s=__toESM(s);let c=require("@stackone/expressions"),l=require("axios");l=__toESM(l);let u=require("node:https");u=__toESM(u);let d=require("crypto"),f=require("node:timers"),p=require("mathjs"),m=require("jsonpath-plus"),h=require("@stackone/redaction"),g=require("qs");g=__toESM(g);let _=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=new Map}async withLock(e,t){await this.lock(e);try{return 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 v=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return(0,o.notMissing)(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}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*v,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)}),(0,o.notMissing)(r)&&r.length>0){let t=(0,o.notMissing)(i)&&Number.isFinite(i)&&i>0?i*v:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,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){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}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.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}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*v;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}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.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.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 defaultExecutorMethodDispose(e,t){(0,o.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,o.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,o.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}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())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await y.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 y=class RedisClient{#e;#t;static async build({getRedisClient:e=s.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},c,l){let u=new RedisClient;u.#t=c;try{u.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,keepAlive:i,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(l??`RedisClient`,u.#t);return addRedisEventHandlers(u.#e,s),await u.#e.connect(),u}catch(e){let t=e;return u.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:l??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return(0,o.isString)(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataKeysFromGroup(e){if(!this.#i())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#i())return!1;try{let a=(0,o.isString)(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{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.#i())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#i())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.#i())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.#i())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#r(e,t,n){if(!this.#i())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#r(`incr`,e,t)}async decrement(e,t){return this.#r(`decr`,e,t)}async subscribe(e,t){if(!this.#i())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.#i())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.#i())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.#i()?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})}}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);(0,o.notMissing)(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#i())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}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:`RedisClientError`,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}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=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(s))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,o.notMissing)(e)&&(e.on(`ready`,async()=>{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=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())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n}}),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 b=15e3,x=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:x,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:b,truncateThreshold:x,truncationPercentage:1},{instantiator:this.name,evictionFrequency:b,truncateThreshold:x,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1;return(!i||!o)&&await this.eventClient?.waitForEvent(a,15e3),await this.eventClient?.deleteEvent(a),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 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}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const S=`__keyevent@0__:`,C=`${S}set`,w=`${S}expire`,T=`${S}expired`,E=`${S}srem`,D=[C,w,T],O={mainMaxConcurrency:30},k={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,a)=>(a=n==null?{}:e(i(n)),__copyProps(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let o=require("@stackone/utils"),s=require("redis");s=__toESM(s);let c=require("@stackone/expressions"),l=require("axios");l=__toESM(l);let u=require("node:https");u=__toESM(u);let d=require("crypto"),f=require("node:timers"),p=require("mathjs"),m=require("jsonpath-plus"),h=require("@stackone/redaction"),g=require("qs");g=__toESM(g);let _=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=new Map}async withLock(e,t){await this.lock(e);try{return 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 v=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return(0,o.notMissing)(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}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*v,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)}),(0,o.notMissing)(r)&&r.length>0){let t=(0,o.notMissing)(i)&&Number.isFinite(i)&&i>0?i*v:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,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){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}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.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}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*v;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}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.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.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 defaultExecutorMethodDispose(e,t){(0,o.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,o.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,o.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}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())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await y.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 y=class RedisClient{#e;#t;static async build({getRedisClient:e=s.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},c,l){let u=new RedisClient;u.#t=c;try{u.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,keepAlive:i,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(l??`RedisClient`,u.#t);return addRedisEventHandlers(u.#e,s),await u.#e.connect(),u}catch(e){let t=e;return u.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:l??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return(0,o.isString)(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataKeysFromGroup(e){if(!this.#i())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#i())return!1;try{let a=(0,o.isString)(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{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.#i())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#i())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.#i())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.#i())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#r(e,t,n){if(!this.#i())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#r(`incr`,e,t)}async decrement(e,t){return this.#r(`decr`,e,t)}async subscribe(e,t){if(!this.#i())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.#i())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.#i())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.#i()?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})}}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);(0,o.notMissing)(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#i())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}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:`RedisClientError`,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}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=t??await buildRedisClientInstance(e,i,this.name);if((0,o.isMissing)(s))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=s,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();(0,o.notMissing)(e)&&(e.on(`ready`,async()=>{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=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())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:t,args:n}}),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 b=15e3,x=15e3,S=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:S,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:x,truncateThreshold:S,truncationPercentage:1},{instantiator:this.name,evictionFrequency:x,truncateThreshold:S,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=b,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}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const C=`__keyevent@0__:`,w=`${C}set`,T=`${C}expire`,E=`${C}expired`,D=`${C}srem`,O=[w,T,E],k={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,A={tryConcurrency:`
|
|
2
2
|
local requestId = KEYS[1]
|
|
3
3
|
local targetKey = KEYS[2]
|
|
4
4
|
local queueKey = KEYS[3]
|
|
@@ -94,7 +94,7 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
94
94
|
|
|
95
95
|
redis.call('publish', nextItemKey, nextItem)
|
|
96
96
|
end
|
|
97
|
-
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??o.generateRequestId,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if((0,o.isMissing)(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return(0,o.isMissing)(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(C)&&n.includes(w)&&n.includes(T)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(D.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return await this.subscriptionManager?.subscribe(T,async(n,r)=>{if(r===T&&n.includes(t)&&n.includes(e))try{await this.releaseRequest(e,t)}catch(n){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:{requestId:e,targetConcurrencyKey:t},error:n,code:`ConcurrencyManagerReleaseRequestFailed`})}})??!1}async subscribeToSetRemoval(e,t){return await this.subscriptionManager?.subscribe(E,async(n,r)=>{if(r===E&&n.includes(e))try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}})??!1}async registerRequest(e,t,n,r){let i=`concurrency:${e}`,a=`queue:${e}`,s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(r??``):r?.includes(e.urlPattern))?.subPoolKey,c=(0,o.notMissing)(s)?`${i}-${s}`:i,{mainMaxConcurrency:l,subPools:u}=t,d=[{key:i,maxConcurrency:l},...u?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${i}-${t}`,maxConcurrency:n}})??[]],f=d.map(e=>e.key),p=d.map(e=>e.maxConcurrency),[m,h]=await Promise.all([this.subscribeToLeaseExpiry(n,c),this.subscribeToSetRemoval(c,a)]),g={requestId:n,targetConcurrencyKey:c,leaseSubscription:m,setRemovalSubscription:h,queueKey:a},_=await this.executeScript(`tryConcurrency`,[n,c,a,...f],[`60`,l.toString(),`90`,...p.map(String)]);if((0,o.notMissing)(_)&&_[0])return{...g,joinCondition:`optimistic`,failureReason:_[1]};let v=0,y=[];for(;v<5;){let e=v>1,t=await this.queueManager?.joinAndWaitTurn(a,n,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[n,c,a,...f],[`60`,l.toString(),`90`,...p.map(String)]),!1),r=(0,o.notMissing)(t)?t[0]:!1,i=(0,o.notMissing)(t)?t[1]:``;if((0,o.notMissing)(i)&&i!==``&&y.push(i),v++,r)return v>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${v} attempts.`,context:{...g,registerAttempts:v,joinCondition:`attempts`,failureMessages:y}}),{...g,joinCondition:`attempts`};await(0,o.delay)((0,o.exponentialBackoffInMS)(v,100))}return this.logger?.error({category:this.name,message:`Failed to register request after ${v} attempts.`,context:{...g,registerAttempts:v,joinCondition:`failed`,failureMessages:y},code:`ConcurrencyManagerRegistrationFailed`}),{...g,joinCondition:`failed`}}async releaseRequest(e,t){return(0,o.isString)(t)&&(0,o.isString)(e)?!!await this.executeScript(`removeFromSet`,[t],[e]):!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.hasValidRedisConfig=!1}};const A={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if((0,o.isMissing)(t)||t?.length===0||(0,o.isMissing)(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=(0,c.safeEvaluate)(r,n?{...e,credentials:n}:e)===!0;if((0,o.isMissing)(r)||i){let n=t?.message,r;return r=(0,o.isMissing)(n)?A[t.targetStatus]??`Unknown error`:String((0,c.safeEvaluate)(n,e)??A[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},j=(0,o.zStrictObject)({receivedStatus:o.z.number(),targetStatus:o.z.number(),message:o.z.string().optional(),condition:o.z.string().optional()});var M=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new u.default.Agent(n),d=l.default.create({...t,httpsAgent:c});if(d.close=()=>{c.destroy()},e){let t={axiosInstance:d,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(d,e,t)}return d}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return(0,o.notMissing)(e)&&(0,o.isFunction)(e)&&typeof e(t)==`function`?e(t):e??null}},N=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return(0,o.isMissing)(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>(0,o.notMissing)(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:(0,o.notMissing)(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return(0,o.notMissing)(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const P=N.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},F={mainRatelimit:25},createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&(0,f.clearTimeout)(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},I=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:I,...a,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(t),hasConfig:(0,o.notMissing)(a)},code:`InterceptorContextNotPresent`});else if((0,o.isMissing)(i)||(0,o.isMissing)(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:I,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:(0,o.notMissing)(i),concurrencyManagerInitialized:(0,o.notMissing)(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let o=(0,d.randomUUID)(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??F,u=n?.concurrency??O,f=await i.getDynamicMaxWaitTime(l,u,a.url),register=async()=>r.registerRequest(`${c}-${s}`,u,o,a.url),p,m=0;for(;m<=f;){let n=Math.floor(Date.now()/1e3),r=await i.getWaitTime(`${c}-${s}`,l,a.url)??0,o=Math.max(r-n,0);if(r===0){p=await register();break}if(await abortableDelay(o*1e3,a),m+=o,m>=f){p=await register(),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:I,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:f},code:`InterceptorMaxWaitTimeExceeded`});break}}return{...a,requestMetadata:p}}return a};return checkConcurrencyInterceptor},L=1e3,R=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*L:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&(0,o.isFutureUnixTimestamp)(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*L},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=(0,p.hasNumericValue)(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o.isMissing)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return(0,o.isFutureUnixTimestamp)(e)||(0,o.isNumber)(e)?evaluateRetryAfterNumber(Number(e),r,t,n):(0,p.isString)(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/L);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(R.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/L);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let retryErrorInterceptor=async i=>{let{response:a,config:s}=i;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,a));let{status:c,retryAfter:l}=convertError(a,r,n,t);if(c===429&&(0,o.notMissing)(s)){let n=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...r??{},retryAfterHeader:l,retryAfterAsNumber:n}}),Promise.reject(i);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?n*L:(0,o.exponentialBackoffInMS)(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...r??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,a),e?.request(u)}return Promise.reject(i)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:c}=e??{},{retryafter:l}=superNormalizeHeaders(s??{});if((0,o.isMissing)(i)||(0,o.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,o.isMissing)(e),providerIsMissing:(0,o.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:l??`undefined`}}),{status:a,retryAfter:l};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,o.notMissing)(u)&&(0,o.notMissing)(c))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=testMessage((0,o.isObject)(c)?(0,m.JSONPath)({path:f,json:c})[0]:c,r);if(t===a&&p){let e=convertRetryAfter(d??extractRetryAfter(s,i),u);return{status:429,retryAfter:l??e}}}return{status:a,retryAfter:l}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>(0,o.notMissing)(t)&&(0,o.notMissing)(e)?(0,m.JSONPath)({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>(0,o.notMissing)(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/L;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},z=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let rateLimitErrorInterceptor=async a=>{let{response:s,config:c}=a,l=c?.signal;if((0,o.isMissing)(r)||(0,o.isMissing)(c))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:`InterceptorContextNotPresent`}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p}=c?.requestMetadata??{};if(!((0,o.notMissing)(u)&&(0,o.notMissing)(d)&&await i.releaseRequest(u,d))&&(0,o.notMissing)(c?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:z,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:`RateLimiterReleaseRequestFailed`}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:m,retryAfter:h}=convertError(s,r,n,t);if(m===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(h);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:h,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=h?n*L:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:h,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},B=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0}});else if((0,o.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,o.notMissing)(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:B,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u}=i?.requestMetadata??{};if(await n.releaseRequest(s,c)||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:B,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),V=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],H=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],U=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],W=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,o.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:s,subPools:c}=t,l=[{key:r,rateLimit:s},...c?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=l.map(e=>e.key),d=l.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...u],[s.toString(),...d.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,o.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,o.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||s===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=l?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(c.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...U),m.push(...W)}let h=generateRequestKey(n);if((0,o.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,o.notMissing)(a)}}),a;let g=await P.get(h);if((0,o.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},v=HttpTransportFactory.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await P.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(a)},error:t,code:`HttpTransportInstanceCreateError`}),(0,o.notMissing)(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:V,responseConfigs:H},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=(0,h.redactFields)(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?(0,o.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:s,context:c,traceId:l,payload:u,httpsAgent:d,httpAgent:f,requestConfig:p,httpsAgentConfig:m}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let h=this.#v(t,r),g=this.#l(e),_=this.#h(u,e),v=await this.#s({url:h,payload:_,method:n,cacheTTL:s,context:c});if(v)return{...v,responseTime:new Date};let y=N.getInstance(),b=((0,o.notMissing)(l)?await y.get(l):null)?.signal,x=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:c,requestConfig:p,httpsAgentConfig:m})).request({headers:g,url:h,method:n,maxRedirects:i,responseType:a,data:_,httpsAgent:d,httpAgent:f,signal:b}),S={data:x.data,status:x.status,body:_,method:n,headers:this.#u(x.headers),requestHeaders:buildSafeRequestHeaders(g),requestUrl:h,responseType:x?.config?.responseType,responseTime:new Date};return await this.#c({url:h,payload:_,method:n,cacheTTL:s,context:c,response:S}),S}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:d,httpsAgentConfig:f}){try{let p=this.#v(t,r),m=this.#l(e),h=this.#h(c,e),g=N.getInstance(),_=((0,o.notMissing)(s)?await g.get(s):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:d,httpsAgentConfig:f})).request({headers:m,url:p,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:l,httpAgent:u,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?g.default.stringify(e):e}#g(e){if((0,l.isAxiosError)(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t){if((0,o.isMissing)(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={},s={};for(let[e,o]of Object.entries(t))if(this.#_(o)){let t=o.arrayFormat,c=o.value;t===`repeat`?r[e]=Array.isArray(c)?c:[c]:t===`brackets`?i[e]=Array.isArray(c)?c:[c]:t===`comma`?a[e]=Array.isArray(c)?c:[c]:t===`stringify`?s[e]=JSON.stringify(Array.isArray(c)?c:[c]):n[e]=c}else n[e]=o;let c=[];Object.keys(n).length>0&&c.push(g.default.stringify(n)),Object.keys(r).length>0&&c.push(g.default.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&c.push(g.default.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&c.push(g.default.stringify(a,{arrayFormat:`comma`})),Object.keys(s).length>0&&c.push(g.default.stringify(s));let l=c.join(`&`);return(0,o.notMissing)(l)?`${e}?${l}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const G=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
97
|
+
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==E)return;let n=this.leaseRegistry.get(e);if(!(0,o.isMissing)(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==D)return;let n=this.setRemovalRegistry.get(e);if(!(0,o.isMissing)(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??o.generateRequestId,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if((0,o.isMissing)(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return(0,o.isMissing)(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(w)&&n.includes(T)&&n.includes(E)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(O.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(E,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(D,this.setRemovalDispatcher)??!1}async registerRequest(e,t,n,r,i=b*5,a){let s=`concurrency:${e}`,c=`queue:${e}`,l=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(r??``):r?.includes(e.urlPattern))?.subPoolKey,u=(0,o.notMissing)(l)?`${s}-${l}`:s,{mainMaxConcurrency:d,subPools:f}=t,p=[{key:s,maxConcurrency:d},...f?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${s}-${t}`,maxConcurrency:n}})??[]],m=p.map(e=>e.key),h=p.map(e=>e.maxConcurrency),[g,_]=await Promise.all([this.subscribeToLeaseExpiry(n,u),this.subscribeToSetRemoval(u,c)]),v={requestId:n,targetConcurrencyKey:u,leaseSubscription:g,setRemovalSubscription:_,queueKey:c,acquired:!1},y=!1,x=!1;try{let e=await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]);if((0,o.notMissing)(e)&&e[0])return y=!0,{...v,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let t=0,r=i,s=[],isAborted=()=>a?.aborted===!0;for(;r>0&&t<5&&!isAborted();){let e=t>1,i=Math.min(b,r);x=!0;let l=await this.queueManager?.joinAndWaitTurn(c,n,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]),!1,i,a);r-=i;let f=(0,o.notMissing)(l)?l[0]:!1,p=(0,o.notMissing)(l)?l[1]:``;if((0,o.notMissing)(p)&&p!==``&&s.push(p),t++,f)return y=!0,t>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${t} attempts.`,context:{...v,registerAttempts:t,joinCondition:`attempts`,failureMessages:s}}),{...v,joinCondition:`attempts`,acquired:!0};let g=(0,o.exponentialBackoffInMS)(t,100);if(r-=g,r<=0||isAborted())break;await(0,o.delay)(g)}return this.logger?.error({category:this.name,message:`Failed to register request after ${t} attempts.`,context:{...v,registerAttempts:t,joinCondition:`failed`,failureMessages:s},code:`ConcurrencyManagerRegistrationFailed`}),{...v,joinCondition:`failed`}}finally{if(!y&&(this.leaseRegistry.delete(buildLeaseKey(u,n)),x))try{await this.queueManager?.remove(c,n)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...v,queueKey:c},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if((0,o.isString)(t)&&(0,o.isString)(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const j={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if((0,o.isMissing)(t)||t?.length===0||(0,o.isMissing)(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=(0,c.safeEvaluate)(r,n?{...e,credentials:n}:e)===!0;if((0,o.isMissing)(r)||i){let n=t?.message,r;return r=(0,o.isMissing)(n)?j[t.targetStatus]??`Unknown error`:String((0,c.safeEvaluate)(n,e)??j[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},ee=(0,o.zStrictObject)({receivedStatus:o.z.number(),targetStatus:o.z.number(),message:o.z.string().optional(),condition:o.z.string().optional()});var M=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new u.default.Agent(n),d=l.default.create({...t,httpsAgent:c});if(d.close=()=>{c.destroy()},e){let t={axiosInstance:d,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(d,e,t)}return d}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return(0,o.notMissing)(e)&&(0,o.isFunction)(e)&&typeof e(t)==`function`?e(t):e??null}},N=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return(0,o.isMissing)(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>(0,o.notMissing)(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:(0,o.notMissing)(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return(0,o.notMissing)(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const P=N.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},F={mainRatelimit:25},createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&(0,f.clearTimeout)(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},I=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:I,...a,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(t),hasConfig:(0,o.notMissing)(a)},code:`InterceptorContextNotPresent`});else if((0,o.isMissing)(i)||(0,o.isMissing)(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:I,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:(0,o.notMissing)(i),concurrencyManagerInitialized:(0,o.notMissing)(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let o=(0,d.randomUUID)(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??F,u=n?.concurrency??k,f=await i.getDynamicMaxWaitTime(l,u,a.url),register=async e=>r.registerRequest(`${c}-${s}`,u,o,a.url,Math.max((f-e)*1e3,0),a.signal),p,m=0;for(;m<=f;){let n=await i.getWaitTime(`${c}-${s}`,l,a.url)??0;if(n<=0){p=await register(m);break}let r=Math.min(Math.max(n,1),f-m);if(await abortableDelay(r*1e3,a),m+=r,m>=f){p=await register(m),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:I,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:f},code:`InterceptorMaxWaitTimeExceeded`});break}}return{...a,requestMetadata:p}}return a};return checkConcurrencyInterceptor},L=1e3,R=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*L:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&(0,o.isFutureUnixTimestamp)(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*L},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=(0,p.hasNumericValue)(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o.isMissing)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return(0,o.isFutureUnixTimestamp)(e)||(0,o.isNumber)(e)?evaluateRetryAfterNumber(Number(e),r,t,n):(0,p.isString)(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/L);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(R.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/L);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let retryErrorInterceptor=async i=>{let{response:a,config:s}=i;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,a));let{status:c,retryAfter:l}=convertError(a,r,n,t);if(c===429&&(0,o.notMissing)(s)){let n=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...r??{},retryAfterHeader:l,retryAfterAsNumber:n}}),Promise.reject(i);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?n*L:(0,o.exponentialBackoffInMS)(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...r??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,a),e?.request(u)}return Promise.reject(i)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:c}=e??{},{retryafter:l}=superNormalizeHeaders(s??{});if((0,o.isMissing)(i)||(0,o.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,o.isMissing)(e),providerIsMissing:(0,o.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:l??`undefined`}}),{status:a,retryAfter:l};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,o.notMissing)(u)&&(0,o.notMissing)(c))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=testMessage((0,o.isObject)(c)?(0,m.JSONPath)({path:f,json:c})[0]:c,r);if(t===a&&p){let e=convertRetryAfter(d??extractRetryAfter(s,i),u);return{status:429,retryAfter:l??e}}}return{status:a,retryAfter:l}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>(0,o.notMissing)(t)&&(0,o.notMissing)(e)?(0,m.JSONPath)({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>(0,o.notMissing)(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/L;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},z=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let rateLimitErrorInterceptor=async a=>{let{response:s,config:c}=a,l=c?.signal;if((0,o.isMissing)(r)||(0,o.isMissing)(c))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:`InterceptorContextNotPresent`}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p,acquired:m}=c?.requestMetadata??{},h=m!==!1&&(0,o.notMissing)(u)&&(0,o.notMissing)(d);if(!(h&&await i.releaseRequest(u,d))&&h&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:z,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:`RateLimiterReleaseRequestFailed`}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:g,retryAfter:_}=convertError(s,r,n,t);if(g===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(_);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=_?n*L:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},B=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0}});else if((0,o.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,o.notMissing)(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:B,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u,acquired:d}=i?.requestMetadata??{},f=d!==!1&&(0,o.notMissing)(s)&&(0,o.notMissing)(c);if(!(f&&await n.releaseRequest(s,c))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:B,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),V=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],H=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],U=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],W=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,o.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:s,subPools:c}=t,l=[{key:r,rateLimit:s},...c?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=l.map(e=>e.key),d=l.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...u],[s.toString(),...d.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,o.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,o.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||s===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=l?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(c.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...U),m.push(...W)}let h=generateRequestKey(n);if((0,o.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,o.notMissing)(a)}}),a;let g=await P.get(h);if((0,o.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},v=HttpTransportFactory.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await P.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(a)},error:t,code:`HttpTransportInstanceCreateError`}),(0,o.notMissing)(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:V,responseConfigs:H},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=(0,h.redactFields)(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?(0,o.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:s,context:c,traceId:l,payload:u,httpsAgent:d,httpAgent:f,requestConfig:p,httpsAgentConfig:m}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let h=this.#v(t,r),g=this.#l(e),_=this.#h(u,e),v=await this.#s({url:h,payload:_,method:n,cacheTTL:s,context:c});if(v)return{...v,responseTime:new Date};let y=N.getInstance(),b=((0,o.notMissing)(l)?await y.get(l):null)?.signal,x=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:c,requestConfig:p,httpsAgentConfig:m})).request({headers:g,url:h,method:n,maxRedirects:i,responseType:a,data:_,httpsAgent:d,httpAgent:f,signal:b}),S={data:x.data,status:x.status,body:_,method:n,headers:this.#u(x.headers),requestHeaders:buildSafeRequestHeaders(g),requestUrl:h,responseType:x?.config?.responseType,responseTime:new Date};return await this.#c({url:h,payload:_,method:n,cacheTTL:s,context:c,response:S}),S}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:d,httpsAgentConfig:f}){try{let p=this.#v(t,r),m=this.#l(e),h=this.#h(c,e),g=N.getInstance(),_=((0,o.notMissing)(s)?await g.get(s):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:d,httpsAgentConfig:f})).request({headers:m,url:p,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:l,httpAgent:u,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?g.default.stringify(e):e}#g(e){if((0,l.isAxiosError)(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t){if((0,o.isMissing)(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={},s={};for(let[e,o]of Object.entries(t))if(this.#_(o)){let t=o.arrayFormat,c=o.value;t===`repeat`?r[e]=Array.isArray(c)?c:[c]:t===`brackets`?i[e]=Array.isArray(c)?c:[c]:t===`comma`?a[e]=Array.isArray(c)?c:[c]:t===`stringify`?s[e]=JSON.stringify(Array.isArray(c)?c:[c]):n[e]=c}else n[e]=o;let c=[];Object.keys(n).length>0&&c.push(g.default.stringify(n)),Object.keys(r).length>0&&c.push(g.default.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&c.push(g.default.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&c.push(g.default.stringify(a,{arrayFormat:`comma`})),Object.keys(s).length>0&&c.push(g.default.stringify(s));let l=c.join(`&`);return(0,o.notMissing)(l)?`${e}?${l}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const G=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
98
98
|
`).replace(/\r\n/g,`
|
|
99
99
|
`).replace(/\r/g,`
|
|
100
100
|
`).trim();t=t.replace(/(-----BEGIN [A-Z0-9 ]+-----) +/g,`$1
|
|
@@ -102,28 +102,36 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
102
102
|
$1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+-----)/);if(n){let[,e,r,i]=n;if(!r.includes(`
|
|
103
103
|
`)&&r.includes(` `)){let n=r.replace(/ /g,``);t=`${e}\n${n.match(/.{1,64}/g)?.join(`
|
|
104
104
|
`)??n}\n${i}`}}return t},decodeCertOrKey=e=>{if(!e||e.length===0)return e;let t=normalizePem(e);if(isPemFormat(t))return t;try{let e=Buffer.from(t,`base64`).toString(`utf-8`);return isPemFormat(e)?normalizePem(e):t}catch{return t}},buildHttpsAgent=e=>{if(!e)return;let{certs:t,keys:n}=e;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(e=>typeof e==`string`&&e.trim().length>0),i=n.filter(e=>typeof e==`string`&&e.trim().length>0);if(r.length===0||i.length===0)return;let a=r.map(decodeCertOrKey),o=i.map(decodeCertOrKey);return new u.default.Agent({cert:a,key:o})},K={rPush:`
|
|
105
|
+
-- Drop any stale copy first so a retrying request holds at most one queue slot.
|
|
106
|
+
redis.call('LREM', KEYS[1], 0, ARGV[1])
|
|
107
|
+
|
|
105
108
|
local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
|
|
106
109
|
|
|
107
110
|
redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
|
108
111
|
|
|
109
112
|
return queueLength
|
|
110
113
|
`,lPush:`
|
|
114
|
+
-- Drop any stale copy first so a retrying request holds at most one queue slot.
|
|
115
|
+
redis.call('LREM', KEYS[1], 0, ARGV[1])
|
|
116
|
+
|
|
111
117
|
local queueLength = redis.call('LPUSH', KEYS[1], ARGV[1])
|
|
112
118
|
|
|
113
119
|
redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
|
114
120
|
|
|
115
121
|
return queueLength
|
|
122
|
+
`,remove:`
|
|
123
|
+
-- Remove every copy so terminal requests can never remain at the queue head.
|
|
124
|
+
return redis.call('LREM', KEYS[1], 0, ARGV[1])
|
|
116
125
|
`,lPop:`
|
|
117
126
|
local queueKey = KEYS[1]
|
|
118
127
|
|
|
119
128
|
return redis.call("lpop", queueKey)
|
|
120
|
-
`,llen:`return redis.call("llen", KEYS[1])`},
|
|
129
|
+
`,llen:`return redis.call("llen", KEYS[1])`},te={incr:`
|
|
121
130
|
local targetKey = KEYS[1]
|
|
122
131
|
local totalLimit = tonumber(ARGV[1])
|
|
123
132
|
|
|
124
133
|
local shouldWait = false
|
|
125
134
|
local totalCount = 0
|
|
126
|
-
local now = redis.call('TIME')[1]
|
|
127
135
|
|
|
128
136
|
-- Check each key from KEYS[2] onward
|
|
129
137
|
for i = 2, #KEYS do
|
|
@@ -144,9 +152,10 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
144
152
|
shouldWait = true
|
|
145
153
|
end
|
|
146
154
|
|
|
147
|
-
-- If
|
|
155
|
+
-- If rate limited, return a relative wait in seconds for the caller to sleep. Relative,
|
|
156
|
+
-- not an absolute epoch, so the caller never diffs a Redis timestamp against its own clock.
|
|
148
157
|
if shouldWait then
|
|
149
|
-
return
|
|
158
|
+
return 1
|
|
150
159
|
end
|
|
151
160
|
|
|
152
161
|
-- No limits exceeded, increment the target key and set expiration for 1 second
|
|
@@ -159,8 +168,8 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
159
168
|
end
|
|
160
169
|
|
|
161
170
|
return nil
|
|
162
|
-
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],[a,o]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:K,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:ee,logger:n})]),s=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:k,logger:n,additionalArgs:e}),c=[{name:`ConcurrencyManager`,ready:s.isReady()},{name:`QueueManager`,ready:a.isReady()},{name:`RateLimitManager`,ready:o.isReady()}],l=c.filter(e=>!e.ready);if(l.length>0){let e=l.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:c.map(e=>e.name)}}),{concurrencyManager:s,queueManager:a,rateLimitManager:o}}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`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),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},te=__name(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),q=__name(e=>Array.isArray(e)?e:[e],`toStringArray`),toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=q(t);if(te(e))return{value:[...q(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...q(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.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.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),ne=[`query`,`body`,`headers`],re=[`repeat`,`brackets`,`comma`,`stringify`],J={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},ie=new _.XMLBuilder(J),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 ie.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`)?g.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;let Y;const getXmlParser=()=>(Y??=new _.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),Y);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c,httpsAgent:l,credentials:u}){let d,f=a;if(isXmlContentType(r))if(typeof a==`string`)f=a;else if(Array.isArray(a))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 a!=null&&(f=serializeBodyToXml(a));try{d=await e?.request({method:n,url:t,headers:r,queryParams:i,maxRedirects:0,payload:f,requestConfig:c,httpsAgent:l})}catch(e){if((0,o.isMissing)(e?.response))throw e;d=e.response}if(typeof d.data==`string`&&d.data.length>0&&d.headers&&isXmlContentType(d.headers)){let e=_.XMLValidator.validate(d.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);d={...d,data:getXmlParser().parse(d.data)}}let p=translateCustomError(d,s,u);if(isFailedStatusCode(p?.status))throw new M(p,p.message);return p}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c,credentials:l}){let u;if(u=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?X.build(c.envelope):await buildEnvelope(a,c),_.XMLValidator.validate(u,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let d,f={"Content-Type":`application/xml`,...r};c?.soapAction&&(f.SOAPAction=c.soapAction);try{d=await e?.request({method:n,url:t,headers:f,queryParams:i,maxRedirects:0,payload:u,requestConfig:c})}catch(e){if((0,o.isMissing)(e?.response))throw e;d=e.response}let p=ae.parse(d.data),m=p.Envelope||p,h=m.Body||m,g=h.Fault;if(g)throw new M({...d,status:500,data:g,message:g.faultstring??g.faultcode??`SOAP Fault`},g.faultstring??`SOAP Fault occurred`);d.data=h;let v=translateCustomError(d,s,l);if(isFailedStatusCode(v?.status))throw new M(v,v.message);return v}};const X=new _.XMLBuilder(J),ae=new _.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:X.build(t.envelope);if(_.XMLValidator.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=X.build(n);if(_.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,c.evaluate)(e.namespaceIdentifier),namespace:await(0,c.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,d.createHmac)(`sha256`,e).update(t).digest(),hash=e=>(0,d.createHash)(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),Z=__name(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),Q=__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=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),f=u.slice(0,8),p=new URL(e.url),m=p.pathname.split(`/`).map(e=>{try{return Z(decodeURIComponent(e))}catch{return Z(e)}}).join(`/`)||`/`,h=[];for(let[e,t]of p.searchParams.entries())h.push([e,t]);h.push(...flattenQueryParams(e.query)),h.sort(([e,t],[n,r])=>{let i=Q(e,n);return i===0?Q(t,r):i});let g=h.map(([e,t])=>`${Z(e)}=${Z(t)}`).join(`&`),_=serializeRequestBodyForSigning(e.body,e.headers??{}),v=(0,d.createHash)(`sha256`).update(_).digest(),y=v.toString(`hex`),b={host:p.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(),m,g,T,E,y].join(`
|
|
171
|
+
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],[a,o]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:K,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:te,logger:n})]),s=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:A,logger:n,additionalArgs:e}),c=[{name:`ConcurrencyManager`,ready:s.isReady()},{name:`QueueManager`,ready:a.isReady()},{name:`RateLimitManager`,ready:o.isReady()}],l=c.filter(e=>!e.ready);if(l.length>0){let e=l.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:c.map(e=>e.name)}}),{concurrencyManager:s,queueManager:a,rateLimitManager:o}}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`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),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},ne=__name(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),q=__name(e=>Array.isArray(e)?e:[e],`toStringArray`),toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=q(t);if(ne(e))return{value:[...q(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...q(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.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.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),re=[`query`,`body`,`headers`],ie=[`repeat`,`brackets`,`comma`,`stringify`],J={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},ae=new _.XMLBuilder(J),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 ae.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`)?g.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;let Y;const getXmlParser=()=>(Y??=new _.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),Y);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c,httpsAgent:l,credentials:u}){let d,f=a;if(isXmlContentType(r))if(typeof a==`string`)f=a;else if(Array.isArray(a))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 a!=null&&(f=serializeBodyToXml(a));try{d=await e?.request({method:n,url:t,headers:r,queryParams:i,maxRedirects:0,payload:f,requestConfig:c,httpsAgent:l})}catch(e){if((0,o.isMissing)(e?.response))throw e;d=e.response}if(typeof d.data==`string`&&d.data.length>0&&d.headers&&isXmlContentType(d.headers)){let e=_.XMLValidator.validate(d.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);d={...d,data:getXmlParser().parse(d.data)}}let p=translateCustomError(d,s,u);if(isFailedStatusCode(p?.status))throw new M(p,p.message);return p}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c,credentials:l}){let u;if(u=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?X.build(c.envelope):await buildEnvelope(a,c),_.XMLValidator.validate(u,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let d,f={"Content-Type":`application/xml`,...r};c?.soapAction&&(f.SOAPAction=c.soapAction);try{d=await e?.request({method:n,url:t,headers:f,queryParams:i,maxRedirects:0,payload:u,requestConfig:c})}catch(e){if((0,o.isMissing)(e?.response))throw e;d=e.response}let p=oe.parse(d.data),m=p.Envelope||p,h=m.Body||m,g=h.Fault;if(g)throw new M({...d,status:500,data:g,message:g.faultstring??g.faultcode??`SOAP Fault`},g.faultstring??`SOAP Fault occurred`);d.data=h;let v=translateCustomError(d,s,l);if(isFailedStatusCode(v?.status))throw new M(v,v.message);return v}};const X=new _.XMLBuilder(J),oe=new _.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:X.build(t.envelope);if(_.XMLValidator.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=X.build(n);if(_.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,c.evaluate)(e.namespaceIdentifier),namespace:await(0,c.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,d.createHmac)(`sha256`,e).update(t).digest(),hash=e=>(0,d.createHash)(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),Z=__name(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),Q=__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=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),f=u.slice(0,8),p=new URL(e.url),m=p.pathname.split(`/`).map(e=>{try{return Z(decodeURIComponent(e))}catch{return Z(e)}}).join(`/`)||`/`,h=[];for(let[e,t]of p.searchParams.entries())h.push([e,t]);h.push(...flattenQueryParams(e.query)),h.sort(([e,t],[n,r])=>{let i=Q(e,n);return i===0?Q(t,r):i});let g=h.map(([e,t])=>`${Z(e)}=${Z(t)}`).join(`&`),_=serializeRequestBodyForSigning(e.body,e.headers??{}),v=(0,d.createHash)(`sha256`).update(_).digest(),y=v.toString(`hex`),b={host:p.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(),m,g,T,E,y].join(`
|
|
163
172
|
`),O=`${f}/${l}/${s}/aws4_request`,k=[`AWS4-HMAC-SHA256`,u,O,hash(D)].join(`
|
|
164
|
-
`),A={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${O}, SignedHeaders=${E}, Signature=${(0,d.createHmac)(`sha256`,getSigningKey(i,f,l,s)).update(k).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":y};return a&&(A[`x-amz-security-token`]=a),C!==void 0&&(A[`x-amz-checksum-sha256`]=C),A},
|
|
165
|
-
`),v=(0,d.createHmac)(c,r).update(_).digest(`hex`);return{[l]:`${u} ${v}`,"X-Timestamp":f}},
|
|
166
|
-
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${y}`).toString(`base64`)}`,Date:h}:{[i??`X-Signature`]:`${a??`hmac-${f}`} ${y}`,"X-Timestamp":h}}const $={},registerSigningStrategy=(e,t)=>{$[e]=t},getSigningStrategy=e=>$[e];registerSigningStrategy(`aws4`,aws4SigningStrategy),registerSigningStrategy(`hmac`,hmacSigningStrategy),exports.CUSTOM_ERROR_CONFIG_SCHEMA=
|
|
173
|
+
`),A={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${O}, SignedHeaders=${E}, Signature=${(0,d.createHmac)(`sha256`,getSigningKey(i,f,l,s)).update(k).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":y};return a&&(A[`x-amz-security-token`]=a),C!==void 0&&(A[`x-amz-checksum-sha256`]=C),A},se=[`sha256`,`sha512`],isValidAlgorithm=e=>se.includes(e),hashPayload=e=>(0,d.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}`,f=new Date().toISOString(),p=new URL(e.url),m=[];for(let[e,t]of p.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=byteCompare(e,n);return i===0?byteCompare(t,r):i});let h=m.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),g=hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})),_=[f,e.method.toUpperCase(),p.pathname,h,g].join(`
|
|
174
|
+
`),v=(0,d.createHmac)(c,r).update(_).digest(`hex`);return{[l]:`${u} ${v}`,"X-Timestamp":f}},ce=[`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&&!ce.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 f=r??`sha256`,p=new URL(e.url),m=new Date,h=o===`rfc2822`?formatRfc2822Date(m):m.toISOString(),g=[...p.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`)&&g.push(...extractBodyParams(e.body)),g.sort(([e,t],[n,r])=>byteCompare(e,n)||byteCompare(t,r));let _=g.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),v=[h,e.method.toUpperCase()];s&&v.push(p.hostname.toLowerCase()),v.push(p.pathname,_),c&&v.push(hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})));let y=(0,d.createHmac)(f,t).update(v.join(`
|
|
175
|
+
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${y}`).toString(`base64`)}`,Date:h}:{[i??`X-Signature`]:`${a??`hmac-${f}`} ${y}`,"X-Timestamp":h}}const $={},registerSigningStrategy=(e,t)=>{$[e]=t},getSigningStrategy=e=>$[e];registerSigningStrategy(`aws4`,aws4SigningStrategy),registerSigningStrategy(`hmac`,hmacSigningStrategy),exports.CUSTOM_ERROR_CONFIG_SCHEMA=ee,exports.ConcurrencyManager=ConcurrencyManager,exports.EventClient=EventClient,exports.HttpClient=HttpClient,exports.HttpClientManager=HttpClientManager,exports.HttpErrorMessages=j,exports.HttpMethods=G,exports.HttpResponseError=M,exports.HttpTransportFactory=HttpTransportFactory,exports.InstanceManager=N,exports.LockManager=LockManager,exports.MemoryStore=MemoryStore,exports.QueryArrayFormats=ie,exports.QueueManager=QueueManager,exports.RateLimitManager=RateLimitManager,exports.RedisClient=y,exports.RequestClientFactory=RequestClientFactory,exports.RequestParameterLocations=re,exports.ScriptManager=ScriptManager,exports.SubscriptionManager=SubscriptionManager,exports.buildHttpClientInstance=buildHttpClientInstance,exports.buildHttpsAgent=buildHttpsAgent,exports.convertError=convertError,exports.createAuthorizationHeaders=createAuthorizationHeaders,exports.getRetryAfterWaitTime=getRetryAfterWaitTime,exports.getSigningStrategy=getSigningStrategy,exports.getTransportInstance=getTransportInstance,exports.getTransportManagers=getTransportManagers,exports.initializeTransportSystem=initializeTransportSystem,exports.isFailedStatusCode=isFailedStatusCode,exports.isInfoStatusCode=isInfoStatusCode,exports.isSuccessStatusCode=isSuccessStatusCode,exports.isTransportSystemReady=isTransportSystemReady,exports.parseRequestParameters=parseRequestParameters,exports.registerSigningStrategy=registerSigningStrategy,exports.serializeHttpResponseError=serializeHttpResponseError,exports.shutdownTransportSystem=shutdownTransportSystem,exports.superNormalizeHeaders=superNormalizeHeaders,exports.translateCustomError=translateCustomError;
|
package/dist/index.d.cts
CHANGED
|
@@ -217,6 +217,7 @@ type RequestMetadata = {
|
|
|
217
217
|
leaseSubscription: boolean;
|
|
218
218
|
setRemovalSubscription: boolean;
|
|
219
219
|
queueKey: string;
|
|
220
|
+
acquired: boolean;
|
|
220
221
|
joinCondition?: 'optimistic' | 'attempts' | 'failed';
|
|
221
222
|
failureReason?: string;
|
|
222
223
|
};
|
|
@@ -234,6 +235,10 @@ declare class ConcurrencyManager extends ScriptManager<ConcurrencyMethods, Concu
|
|
|
234
235
|
private subscriptionManager;
|
|
235
236
|
private queueManager;
|
|
236
237
|
private generateUUID;
|
|
238
|
+
private readonly leaseRegistry;
|
|
239
|
+
private readonly setRemovalRegistry;
|
|
240
|
+
private readonly leaseExpiryDispatcher;
|
|
241
|
+
private readonly setRemovalDispatcher;
|
|
237
242
|
name: string;
|
|
238
243
|
protected additionalInitialization(generateUUID?: () => string, initOptions?: ConcurrencyManagerInitOptions): Promise<void>;
|
|
239
244
|
private addTestSubscription;
|
|
@@ -241,7 +246,7 @@ declare class ConcurrencyManager extends ScriptManager<ConcurrencyMethods, Concu
|
|
|
241
246
|
isRedisConfigured(): boolean;
|
|
242
247
|
private subscribeToLeaseExpiry;
|
|
243
248
|
private subscribeToSetRemoval;
|
|
244
|
-
registerRequest(requestKey: string, config: ConcurrencyConfig, requestId: string, requestUrl: string | undefined): Promise<RequestMetadata>;
|
|
249
|
+
registerRequest(requestKey: string, config: ConcurrencyConfig, requestId: string, requestUrl: string | undefined, maxWaitMs?: number, signal?: AbortSignal): Promise<RequestMetadata>;
|
|
245
250
|
releaseRequest(requestId: string, targetConcurrencyKey: string): Promise<boolean>;
|
|
246
251
|
isReady(): boolean;
|
|
247
252
|
close(): void;
|
|
@@ -865,6 +870,7 @@ declare class HttpTransportFactory {
|
|
|
865
870
|
declare enum QueueMethods {
|
|
866
871
|
rPush = "rPush",
|
|
867
872
|
lPush = "lPush",
|
|
873
|
+
remove = "remove",
|
|
868
874
|
lPop = "lPop",
|
|
869
875
|
llen = "llen"
|
|
870
876
|
}
|
|
@@ -878,7 +884,9 @@ declare class QueueManager extends ScriptManager<QueueMethods, QueueManager> {
|
|
|
878
884
|
private eventClient;
|
|
879
885
|
name: string;
|
|
880
886
|
protected additionalInitialization(): Promise<void>;
|
|
881
|
-
joinAndWaitTurn<T>(queueName: string, value: string, hasPriority: boolean, onTurn: OnTurnFunction<T>, coldStartEnabled?: boolean): Promise<T | null>;
|
|
887
|
+
joinAndWaitTurn<T>(queueName: string, value: string, hasPriority: boolean, onTurn: OnTurnFunction<T>, coldStartEnabled?: boolean, maxWaitMs?: number, signal?: AbortSignal): Promise<T | null>;
|
|
888
|
+
private waitForTurnOrAbort;
|
|
889
|
+
remove(queueName: string, value: string): Promise<boolean>;
|
|
882
890
|
pop<T>(queueName: string): Promise<T | null>;
|
|
883
891
|
length(queueName: string): Promise<number | null>;
|
|
884
892
|
isReady(): boolean;
|
package/dist/index.d.mts
CHANGED
|
@@ -216,6 +216,7 @@ type RequestMetadata = {
|
|
|
216
216
|
leaseSubscription: boolean;
|
|
217
217
|
setRemovalSubscription: boolean;
|
|
218
218
|
queueKey: string;
|
|
219
|
+
acquired: boolean;
|
|
219
220
|
joinCondition?: 'optimistic' | 'attempts' | 'failed';
|
|
220
221
|
failureReason?: string;
|
|
221
222
|
};
|
|
@@ -233,6 +234,10 @@ declare class ConcurrencyManager extends ScriptManager<ConcurrencyMethods, Concu
|
|
|
233
234
|
private subscriptionManager;
|
|
234
235
|
private queueManager;
|
|
235
236
|
private generateUUID;
|
|
237
|
+
private readonly leaseRegistry;
|
|
238
|
+
private readonly setRemovalRegistry;
|
|
239
|
+
private readonly leaseExpiryDispatcher;
|
|
240
|
+
private readonly setRemovalDispatcher;
|
|
236
241
|
name: string;
|
|
237
242
|
protected additionalInitialization(generateUUID?: () => string, initOptions?: ConcurrencyManagerInitOptions): Promise<void>;
|
|
238
243
|
private addTestSubscription;
|
|
@@ -240,7 +245,7 @@ declare class ConcurrencyManager extends ScriptManager<ConcurrencyMethods, Concu
|
|
|
240
245
|
isRedisConfigured(): boolean;
|
|
241
246
|
private subscribeToLeaseExpiry;
|
|
242
247
|
private subscribeToSetRemoval;
|
|
243
|
-
registerRequest(requestKey: string, config: ConcurrencyConfig, requestId: string, requestUrl: string | undefined): Promise<RequestMetadata>;
|
|
248
|
+
registerRequest(requestKey: string, config: ConcurrencyConfig, requestId: string, requestUrl: string | undefined, maxWaitMs?: number, signal?: AbortSignal): Promise<RequestMetadata>;
|
|
244
249
|
releaseRequest(requestId: string, targetConcurrencyKey: string): Promise<boolean>;
|
|
245
250
|
isReady(): boolean;
|
|
246
251
|
close(): void;
|
|
@@ -864,6 +869,7 @@ declare class HttpTransportFactory {
|
|
|
864
869
|
declare enum QueueMethods {
|
|
865
870
|
rPush = "rPush",
|
|
866
871
|
lPush = "lPush",
|
|
872
|
+
remove = "remove",
|
|
867
873
|
lPop = "lPop",
|
|
868
874
|
llen = "llen"
|
|
869
875
|
}
|
|
@@ -877,7 +883,9 @@ declare class QueueManager extends ScriptManager<QueueMethods, QueueManager> {
|
|
|
877
883
|
private eventClient;
|
|
878
884
|
name: string;
|
|
879
885
|
protected additionalInitialization(): Promise<void>;
|
|
880
|
-
joinAndWaitTurn<T>(queueName: string, value: string, hasPriority: boolean, onTurn: OnTurnFunction<T>, coldStartEnabled?: boolean): Promise<T | null>;
|
|
886
|
+
joinAndWaitTurn<T>(queueName: string, value: string, hasPriority: boolean, onTurn: OnTurnFunction<T>, coldStartEnabled?: boolean, maxWaitMs?: number, signal?: AbortSignal): Promise<T | null>;
|
|
887
|
+
private waitForTurnOrAbort;
|
|
888
|
+
remove(queueName: string, value: string): Promise<boolean>;
|
|
881
889
|
pop<T>(queueName: string): Promise<T | null>;
|
|
882
890
|
length(queueName: string): Promise<number | null>;
|
|
883
891
|
isReady(): boolean;
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInMS as n,generateRequestId as r,getContentHash as i,isFunction as a,isFutureUnixTimestamp as o,isMissing as s,isNumber as c,isObject as l,isString as u,notMissing as d,z as f,zStrictObject as p}from"@stackone/utils";import*as m from"redis";import{evaluate as h,safeEvaluate as g}from"@stackone/expressions";import _,{isAxiosError as v}from"axios";import y from"node:https";import{createHash as b,createHmac as x,randomUUID as S}from"crypto";import{clearTimeout as C}from"node:timers";import{hasNumericValue as w,isString as T}from"mathjs";import{JSONPath as E}from"jsonpath-plus";import{redactFields as D,redactUrl as O}from"@stackone/redaction";import k from"qs";import{XMLBuilder as A,XMLParser as j,XMLValidator as M}from"fast-xml-parser";const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return 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 N=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}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*N,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)}),d(r)&&r.length>0){let t=d(i)&&Number.isFinite(i)&&i>0?i*N:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),d(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}if(d(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}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*N;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}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.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.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 defaultExecutorMethodDispose(e,t){d(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):d(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(s(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,s(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await P.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 P=class RedisClient{#e;#t;static async build({getRedisClient:e=m.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},s,c){let l=new RedisClient;l.#t=s;try{l.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,keepAlive:i,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(c??`RedisClient`,l.#t);return addRedisEventHandlers(l.#e,s),await l.#e.connect(),l}catch(e){let t=e;return l.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:c??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return u(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataKeysFromGroup(e){if(!this.#i())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#i())return!1;try{let a=u(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),d(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),d(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#i())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#i())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.#i())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.#i())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#r(e,t,n){if(!this.#i())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#r(`incr`,e,t)}async decrement(e,t){return this.#r(`decr`,e,t)}async subscribe(e,t){if(!this.#i())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.#i())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.#i())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.#i()?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})}}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);d(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#i())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}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:`RedisClientError`,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}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=t??await buildRedisClientInstance(e,i,this.name);if(s(o))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(d(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(s(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if(d(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(d),i=new Map;if(r.length>0&&d(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(d(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);d(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,n,r){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r}}),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 ee=15e3,F=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:F,truncationPercentage:1}),await this.subscriptionManager?.initialize(),this.eventClient=new EventClient({instantiator:this.name,timeoutResolveValue:!1},{instantiator:this.name,evictionFrequency:ee,truncateThreshold:F,truncationPercentage:1},{instantiator:this.name,evictionFrequency:ee,truncateThreshold:F,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0){try{let a=`${e}:${t}`;await this.subscriptionManager?.subscribe(a,async(n,r)=>{if(r.includes(a)&&r.includes(t)){let t=`${e}:${n}`;return this.eventClient?.resolveEvent(t,!0)}});let o=await this.executeScript(n?`lPush`:`rPush`,[e],[t,`60000`])===1;return(!i||!o)&&await this.eventClient?.waitForEvent(a,15e3),await this.eventClient?.deleteEvent(a),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 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}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const I=`__keyevent@0__:`,L=`${I}set`,R=`${I}expire`,z=`${I}expired`,B=`${I}srem`,te=[L,R,z],ne={mainMaxConcurrency:30},re={tryConcurrency:`
|
|
1
|
+
import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInMS as n,generateRequestId as r,getContentHash as i,isFunction as a,isFutureUnixTimestamp as o,isMissing as s,isNumber as c,isObject as l,isString as u,notMissing as d,z as f,zStrictObject as p}from"@stackone/utils";import*as m from"redis";import{evaluate as h,safeEvaluate as g}from"@stackone/expressions";import _,{isAxiosError as v}from"axios";import y from"node:https";import{createHash as b,createHmac as x,randomUUID as S}from"crypto";import{clearTimeout as C}from"node:timers";import{hasNumericValue as w,isString as T}from"mathjs";import{JSONPath as E}from"jsonpath-plus";import{redactFields as D,redactUrl as O}from"@stackone/redaction";import k from"qs";import{XMLBuilder as A,XMLParser as j,XMLValidator as M}from"fast-xml-parser";const createAuthorizationHeaders=e=>{switch(e.type){case`none`:return{};case`basic`:return createBasicAuthorizationHeader(e);case`bearer`:return createBearerAuthorizationHeader(e);case`oauth2`:return createBearerAuthorizationHeader(e);default:throw Error(`Invalid authentication type`)}},createBasicAuthorizationHeader=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n;return{authorization:`Basic ${Buffer.from(`${e}:${t}`).toString(r)}`}},createBearerAuthorizationHeader=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var LockManager=class{constructor(){this.locks=new Map}async withLock(e,t){await this.lock(e);try{return 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 N=1e3;var MemoryStore=class{constructor(e={}){this.lastAccessedAt=Date.now(),this.config=e,this.initialize(e)}initialize(e=this.config){this.instantiator=e?.instantiator??`Unknown`,this.logger=e?.logger,this.dataStore=e?.dataStore??new Map,this.lockManager=e?.lockManager??new LockManager,this.expiryMap=e?.expiryMap??new Map,this.groupMap=new Map,this.groupExpiryMap=new Map,this.evictionFrequency=e?.evictionFrequency??6e4,this.staleDataThreshold=e?.staleDataThreshold??6e5,this.truncateThreshold=e?.truncateThreshold??100,this.truncationPercentage=e?.truncationPercentage??10,this.typeGuard=e?.typeGuard,this.dispose=e?.dispose,this.startEvictionTask()}async getData(e){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>this.dataStore.get(e)??null)}async getDataKeysFromGroup(e){this.isReady()||this.initialize(),this.updateLastAccessedAt();let t=this.groupExpiryMap.get(e);return d(t)&&t<=Date.now()?(this.groupMap.delete(e),this.groupExpiryMap.delete(e),[]):Array.from(this.groupMap.get(e)??[])}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*N,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)}),d(r)&&r.length>0){let t=d(i)&&Number.isFinite(i)&&i>0?i*N:void 0;for(let n of r)this.groupMap.has(n)||this.groupMap.set(n,new Set),this.groupMap.get(n)?.add(e),d(t)&&this.groupExpiryMap.set(n,Date.now()+t)}return!0}typeGuardBypass(e){return this.logger?.debug({category:`MemoryStore`,message:`${this.instantiator} MemoryStore setting data without type guard - you should probably configure one`}),!0}async delete(e,t){return this.isReady()||this.initialize(),this.updateLastAccessedAt(),this.lockManager.withLock(e,async()=>{if(this.dispose){let t=this.dataStore.get(e);await this.dispose(e,t)}if(d(t)&&t.length>0)for(let n of t)this.groupMap.get(n)?.delete(e);return this.expiryMap.delete(e),this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=[],i=0;return this.dataStore.forEach((e,a)=>{let o=Date.now(),s=this.expiryMap.get(a)??0,c=this.truncateThreshold*this.truncationPercentage/100;(s<=o||t&&i>=0&&i<=c)&&(r.push(a),n.push(this.lockManager.withLock(a,async()=>(this.dispose&&await this.dispose(a,e),this.expiryMap.delete(a),this.dataStore.delete(a))))),i++}),await Promise.all(n),this.removeKeysFromGroups(r),{dataStoreSize:e,prunedDataStoreSize:this.dataStore.size}}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*N;return await this.lockManager.withLock(e,async()=>{this.expiryMap.set(e,Date.now()+n)}),!0}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.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.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 defaultExecutorMethodDispose(e,t){d(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):d(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return l(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},AsyncSingleton=class{constructor(){this.instance=null,this.initPromise=null,this.retryTimeout=null,this.status=`uninitialized`,this.initOptions=null,this.initArgs=[]}getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(s(this.initPromise)&&(this.initOptions=e??null,this.initArgs=t,this.initPromise=this.init(e??null,...t)),this.initPromise)}getInstanceIfReady(){return this.instance}isReady(){return this.status===`ready`}hasInitFailed(){return this.status===`failed`}async init(e,...t){try{let n=await this.initInstance(e,...t);return this.instance=n,this.status=`ready`,n}catch(e){throw this.status=`failed`,this.initPromise=null,s(this.retryTimeout)&&(this.retryTimeout=setTimeout(()=>{this.retryTimeout=null,this.getInstance(this.initOptions,...this.initArgs).catch(()=>{})},this.getRetryDelay())),e}}reset(){this.instance=null,this.initPromise=null,this.initOptions=null,this.status=`uninitialized`,this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}};function isTlsOptions(e){return typeof e==`object`&&!!e}const buildRedisClientInstance=async(e,t,n)=>{try{return await P.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 P=class RedisClient{#e;#t;static async build({getRedisClient:e=m.createClient,host:t,port:n,tls:r,keepAlive:i=3e4,reconnect:a=!0,database:o},s,c){let l=new RedisClient;l.#t=s;try{l.#e=e({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:t,port:n,keepAlive:i,...r===!0?{tls:!0}:isTlsOptions(r)?{tls:!0,...r}:{}},database:o,disableOfflineQueue:!0});let s=getDefaultRedisListeners(c??`RedisClient`,l.#t);return addRedisEventHandlers(l.#e,s),await l.#e.connect(),l}catch(e){let t=e;return l.#t?.error({message:`Error building Cache Manager.`,error:t,code:`RedisClientError`,category:c??`RedisClient`}),null}}#n(e){try{return JSON.parse(e)}catch{return e}}async getData(e){if(!this.#i())return null;try{let t=await this.#e.get(e);if(!t)return null;let n=this.#n(t);return u(n)?t:n}catch(e){let t=e;return this.#t?.error({message:`Error getting data`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async getDataKeysFromGroup(e){if(!this.#i())return null;try{return await this.#e.sMembers(e)}catch(e){let t=e;return this.#t?.error({message:`Error getting data from group`,error:t,code:`RedisClientReadError`,category:RedisClient.name}),null}}async setData({key:e,value:t,cacheTTL:n,groupKeys:r,groupKeyTTL:i}){if(!this.#i())return!1;try{let a=u(t)?t:JSON.stringify(t);if(await this.#e.set(e,a,{EX:n}),d(r)&&r.length>0)for(let t of r)await this.#e.sAdd(t,[e]),d(i)&&Number.isFinite(i)&&i>0&&await this.#e.expire(t,i);return!0}catch(e){let t=e;return this.#t?.error({message:`Error setting data`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async setTTL(e,t){if(!this.#i())return!1;if(!Number.isFinite(t)||t<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),!1;try{let n=await this.#e.expire(e,t);return n||this.#t?.debug({message:`No keys updated for ${e}`,category:RedisClient.name}),n}catch(e){let t=e;return this.#t?.error({message:`Error resetting data TTL`,error:t,code:`RedisClientWriteError`,category:RedisClient.name}),!1}}async executeScript({sha1:e,keys:t,args:n}){if(!this.#i())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.#i())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.#i())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#r(e,t,n){if(!this.#i())return null;if(!Number.isFinite(n)||n<=0)return this.#t?.error({message:`Invalid cacheTTL parameter`,category:RedisClient.name,code:`RedisClientInvalidTTL`}),null;try{let r=[{args:[e,t]},{args:[`expire`,t,n.toString()]}],i=(await this.#e.multiExecutor(r))?.[0];return typeof i==`number`?i:null}catch(t){let n=t;return this.#t?.error({message:`Error executing ${e} operation`,error:n,code:`RedisClientCommandError`,category:RedisClient.name}),null}}async increment(e,t){return this.#r(`incr`,e,t)}async decrement(e,t){return this.#r(`decr`,e,t)}async subscribe(e,t){if(!this.#i())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.#i())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.#i())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.#i()?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})}}#i(){let e=this.isAvailable();return e||this.#t?.error({message:`Redis Client is not ready.`,category:RedisClient.name,code:`RedisClientRedisNotReady`}),e}async listData({partialKey:e,limit:t,cursor:n}){try{let r=n?parseInt(n,10):0,i=await this.#e.sScan(e,r,{COUNT:t}),a=[];for(let e of i.members){let t=await this.getData(e);d(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(e){let t=e;return this.#t?.error({message:`Error listing data`,error:t,code:`RedisClientListError`,category:RedisClient.name}),{items:null}}}async deleteData(e,t){try{if(!this.#i())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}}};const addRedisEventHandlers=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},getDefaultRedisListeners=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:`RedisClientError`,category:e})}},{eventName:`ready`,listener:()=>{t?.info({message:`Redis client ready`,category:e})}},{eventName:`connect`,listener:()=>{t?.info({message:`Redis client connected`,category:e})}},{eventName:`reconnecting`,listener:()=>{t?.info({message:`Redis client reconnecting`,category:e})}},{eventName:`end`,listener:()=>{t?.info({message:`Redis client disconnected`,category:e})}}];var ScriptManager=class extends AsyncSingleton{constructor(...e){super(...e),this.isInitialConnection=!0,this.reloadInProgress=null,this.lastReloadTime=0}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=t??await buildRedisClientInstance(e,i,this.name);if(s(o))throw Error(`Failed to build Redis client`);return this.redisClientConfig=e,this.logger=i,this.cacheClient=o,this.scripts=n,this.scriptMap=r??new Map,this.additionalArgs=a??[],await this.loadScripts(n,r),this.setupReconnectHandler(),await this.additionalInitialization(...a??[]),this}setupReconnectHandler(){let e=this.cacheClient?.getClient?.();d(e)&&(e.on(`ready`,async()=>{this.isInitialConnection?this.isInitialConnection=!1:(this.logger?.info({message:`Redis reconnected - reloading scripts`,category:this.name}),await this.reloadScripts())}),e.on(`end`,()=>{this.logger?.info({message:`Redis connection closed`,category:this.name})}))}async reloadScripts(){if(d(this.reloadInProgress))return this.logger?.info({message:`Script reload already in progress, waiting for completion`,category:this.name}),this.reloadInProgress;if(!(s(this.scripts)||Object.keys(this.scripts).length===0)){this.reloadInProgress=this.performReload();try{await this.reloadInProgress}finally{this.reloadInProgress=null}}}async performReload(){this.logger?.info({message:`Reloading ${Object.keys(this.scripts).length} scripts after Redis reconnection`,category:this.name}),this.scriptMap.clear(),await this.loadScripts(this.scripts),this.lastReloadTime=Date.now()}async loadScripts(e,t){if(d(t))for(let[e,n]of t)this.scriptMap.set(e,n);let n=Object.entries(e),r=n.map(([e])=>this.scriptMap.get(e)).filter(d),i=new Map;if(r.length>0&&d(this.cacheClient?.scriptExists)){let e=await this.cacheClient.scriptExists(r);if(d(e)){r.forEach((t,n)=>{i.set(t,e[n]??!1)});let t=e.filter(Boolean).length;t>0&&this.logger?.info({message:`${t}/${r.length} scripts already exist in Redis; skipping load for existing scripts`,category:this.name})}}for(let[e,t]of n){let n=this.scriptMap.get(e);if(n&&i.get(n))continue;let r=await this.cacheClient?.loadScript?.(t);d(r)?this.scriptMap?.set(e,r):this.logger?.error({message:`Error loading script ${e}`,category:this.name,code:`ScriptManagerLoadingError`})}}async executeScript(e,n,r){if(!this.isRedisReady())return this.logger?.warning({message:`Redis not ready, cannot execute script ${e}`,category:this.name,context:{keys:n,args:r}}),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 F=15e3,I=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:I,truncateThreshold:L,truncationPercentage:1},{instantiator:this.name,evictionFrequency:I,truncateThreshold:L,truncationPercentage:1}),this.logger?.info({category:this.name,message:`QueueManager initialized.`})}async joinAndWaitTurn(e,t,n,r,i=!0,a=F,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}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const R=`__keyevent@0__:`,z=`${R}set`,ee=`${R}expire`,B=`${R}expired`,V=`${R}srem`,te=[z,ee,B],ne={mainMaxConcurrency:30},buildLeaseKey=(e,t)=>`lease:${e}:${t}`,re={tryConcurrency:`
|
|
2
2
|
local requestId = KEYS[1]
|
|
3
3
|
local targetKey = KEYS[2]
|
|
4
4
|
local queueKey = KEYS[3]
|
|
@@ -94,7 +94,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInM
|
|
|
94
94
|
|
|
95
95
|
redis.call('publish', nextItemKey, nextItem)
|
|
96
96
|
end
|
|
97
|
-
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??r,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(s(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return s(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(L)&&n.includes(R)&&n.includes(z)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(te.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return await this.subscriptionManager?.subscribe(z,async(n,r)=>{if(r===z&&n.includes(t)&&n.includes(e))try{await this.releaseRequest(e,t)}catch(n){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:{requestId:e,targetConcurrencyKey:t},error:n,code:`ConcurrencyManagerReleaseRequestFailed`})}})??!1}async subscribeToSetRemoval(e,t){return await this.subscriptionManager?.subscribe(B,async(n,r)=>{if(r===B&&n.includes(e))try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}})??!1}async registerRequest(e,r,i,a){let o=`concurrency:${e}`,s=`queue:${e}`,c=r.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,l=d(c)?`${o}-${c}`:o,{mainMaxConcurrency:u,subPools:f}=r,p=[{key:o,maxConcurrency:u},...f?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${o}-${t}`,maxConcurrency:n}})??[]],m=p.map(e=>e.key),h=p.map(e=>e.maxConcurrency),[g,_]=await Promise.all([this.subscribeToLeaseExpiry(i,l),this.subscribeToSetRemoval(l,s)]),v={requestId:i,targetConcurrencyKey:l,leaseSubscription:g,setRemovalSubscription:_,queueKey:s},y=await this.executeScript(`tryConcurrency`,[i,l,s,...m],[`60`,u.toString(),`90`,...h.map(String)]);if(d(y)&&y[0])return{...v,joinCondition:`optimistic`,failureReason:y[1]};let b=0,x=[];for(;b<5;){let e=b>1,r=await this.queueManager?.joinAndWaitTurn(s,i,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[i,l,s,...m],[`60`,u.toString(),`90`,...h.map(String)]),!1),a=d(r)?r[0]:!1,o=d(r)?r[1]:``;if(d(o)&&o!==``&&x.push(o),b++,a)return b>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${b} attempts.`,context:{...v,registerAttempts:b,joinCondition:`attempts`,failureMessages:x}}),{...v,joinCondition:`attempts`};await t(n(b,100))}return this.logger?.error({category:this.name,message:`Failed to register request after ${b} attempts.`,context:{...v,registerAttempts:b,joinCondition:`failed`,failureMessages:x},code:`ConcurrencyManagerRegistrationFailed`}),{...v,joinCondition:`failed`}}async releaseRequest(e,t){return u(t)&&u(e)?!!await this.executeScript(`removeFromSet`,[t],[e]):!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.hasValidRedisConfig=!1}};const V={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if(s(t)||t?.length===0||s(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=g(r,n?{...e,credentials:n}:e)===!0;if(s(r)||i){let n=t?.message,r;return r=s(n)?V[t.targetStatus]??`Unknown error`:String(g(n,e)??V[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},ie=p({receivedStatus:f.number(),targetStatus:f.number(),message:f.string().optional(),condition:f.string().optional()});var H=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new y.Agent(n),l=_.create({...t,httpsAgent:c});if(l.close=()=>{c.destroy()},e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return d(e)&&a(e)&&typeof e(t)==`function`?e(t):e??null}},U=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return s(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>d(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:d(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return d(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const W=U.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},ae={mainRatelimit:25},createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&C(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},G=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if(s(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:G,...a,httpsAgent:void 0,headers:void 0,hasContext:d(t),hasConfig:d(a)},code:`InterceptorContextNotPresent`});else if(s(i)||s(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:G,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:d(i),concurrencyManagerInitialized:d(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if(d(t.provider)&&d(t.accountSecureId)){let o=S(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??ae,u=n?.concurrency??ne,d=await i.getDynamicMaxWaitTime(l,u,a.url),register=async()=>r.registerRequest(`${c}-${s}`,u,o,a.url),f,p=0;for(;p<=d;){let n=Math.floor(Date.now()/1e3),r=await i.getWaitTime(`${c}-${s}`,l,a.url)??0,o=Math.max(r-n,0);if(r===0){f=await register();break}if(await abortableDelay(o*1e3,a),p+=o,p>=d){f=await register(),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:G,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:d},code:`InterceptorMaxWaitTimeExceeded`});break}}return{...a,requestMetadata:f}}return a};return checkConcurrencyInterceptor},K=1e3,oe=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*K:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&o(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*K},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=w(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:c}=e??{};return[t,n,r,o].some(s)?null:[t,n,r,i,a,o,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return o(e)||c(e)?evaluateRetryAfterNumber(Number(e),r,t,n):T(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/K);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(oe.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/K);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i})=>{let retryErrorInterceptor=async a=>{let{response:o,config:s}=a;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,i,r,t);if(c===429&&d(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*K:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),e?.request(u)}return Promise.reject(a)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:c}=e??{},{retryafter:u}=superNormalizeHeaders(o??{});if(s(i)||s(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:s(e),providerIsMissing:s(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:u??`undefined`}}),{status:a,retryAfter:u};let f=n?.rateLimits?.mappedRateLimitErrors;if(d(f)&&d(c))for(let e of f){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:s,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=testMessage(l(c)?E({path:f,json:c})[0]:c,r);if(t===a&&p){let e=convertRetryAfter(d??extractRetryAfter(o,i),s);return{status:429,retryAfter:u??e}}}return{status:a,retryAfter:u}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>d(t)&&d(e)?E({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>d(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/K;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},q=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i,concurrencyManager:a})=>{let rateLimitErrorInterceptor=async o=>{let{response:c,config:l}=o,u=l?.signal;if(s(i)||s(l))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:q,...l,httpsAgent:void 0,headers:void 0,hasContext:d(i),hasConfig:d(l)},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(a))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:q,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(a)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(o);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h}=l?.requestMetadata??{};if(!(d(f)&&d(p)&&await a.releaseRequest(f,p))&&d(l?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:q,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:`RateLimiterReleaseRequestFailed`}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,l,`ERR_CANCELED`,c));let{status:g,retryAfter:_}=convertError(c,i,r,t);if(g===429&&d(l)){let r=getRetryAfterWaitTime(_);if(l._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:r}}),Promise.reject(o);let a=l?._retryCount??0,s={...l,_retryCount:a+1},u=_?r*K:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,l,c),e?.request(s)}return Promise.reject(o)};return rateLimitErrorInterceptor},J=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if(s(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:J,...i,httpsAgent:void 0,headers:void 0}});else if(s(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:J,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if(d(t.provider)&&d(t.accountSecureId)){let t=r?.headers;if(d(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:J,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l}=i?.requestMetadata??{};if(await n.releaseRequest(o,s)||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:J,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),se=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ce=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],le=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],ue=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=d(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),u=c.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(s(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(d(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),s(n?.service)||s(n?.organizationId)||o===`test`||s(t)||s(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=l?.isReady(),p=u?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...le),h.push(...ue)}let g=generateRequestKey(n);if(s(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:d(a)}}),a;let _=await W.get(g);if(d(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await W.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(a)},error:t,code:`HttpTransportInstanceCreateError`}),d(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:se,responseConfigs:ce},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>_.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=D(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?i(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:o,context:c,traceId:l,payload:u,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:h}){try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let g=this.#v(t,r),_=this.#l(e),v=this.#h(u,e),y=await this.#s({url:g,payload:v,method:n,cacheTTL:o,context:c});if(y)return{...y,responseTime:new Date};let b=U.getInstance(),x=(d(l)?await b.get(l):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:c,requestConfig:m,httpsAgentConfig:h})).request({headers:_,url:g,method:n,maxRedirects:i,responseType:a,data:v,httpsAgent:f,httpAgent:p,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#u(S.headers),requestHeaders:buildSafeRequestHeaders(_),requestUrl:g,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:g,payload:v,method:n,cacheTTL:o,context:c,response:C}),C}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw d(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:o,payload:s,httpsAgent:c,httpAgent:l,requestConfig:u,httpsAgentConfig:f}){try{let p=this.#v(t,r),m=this.#l(e),h=this.#h(s,e),g=U.getInstance(),_=(d(o)?await g.get(o):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:u,httpsAgentConfig:f})).request({headers:m,url:p,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:c,httpAgent:l,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw d(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?k.stringify(e):e}#g(e){if(v(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t){if(s(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={},o={};for(let[e,s]of Object.entries(t))if(this.#_(s)){let t=s.arrayFormat,c=s.value;t===`repeat`?r[e]=Array.isArray(c)?c:[c]:t===`brackets`?i[e]=Array.isArray(c)?c:[c]:t===`comma`?a[e]=Array.isArray(c)?c:[c]:t===`stringify`?o[e]=JSON.stringify(Array.isArray(c)?c:[c]):n[e]=c}else n[e]=s;let c=[];Object.keys(n).length>0&&c.push(k.stringify(n)),Object.keys(r).length>0&&c.push(k.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&c.push(k.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&c.push(k.stringify(a,{arrayFormat:`comma`})),Object.keys(o).length>0&&c.push(k.stringify(o));let l=c.join(`&`);return d(l)?`${e}?${l}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const de=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
97
|
+
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==B)return;let n=this.leaseRegistry.get(e);if(!s(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==V)return;let n=this.setRemovalRegistry.get(e);if(!s(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??r,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(s(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return s(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(z)&&n.includes(ee)&&n.includes(B)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(te.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(B,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(V,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=F*5,s){let c=`concurrency:${e}`,l=`queue:${e}`,u=r.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,f=d(u)?`${c}-${u}`:c,{mainMaxConcurrency:p,subPools:m}=r,h=[{key:c,maxConcurrency:p},...m?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${c}-${t}`,maxConcurrency:n}})??[]],g=h.map(e=>e.key),_=h.map(e=>e.maxConcurrency),[v,y]=await Promise.all([this.subscribeToLeaseExpiry(i,f),this.subscribeToSetRemoval(f,l)]),b={requestId:i,targetConcurrencyKey:f,leaseSubscription:v,setRemovalSubscription:y,queueKey:l,acquired:!1},x=!1,S=!1;try{let e=await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]);if(d(e)&&e[0])return x=!0,{...b,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let r=0,a=o,c=[],isAborted=()=>s?.aborted===!0;for(;a>0&&r<5&&!isAborted();){let e=r>1,o=Math.min(F,a);S=!0;let u=await this.queueManager?.joinAndWaitTurn(l,i,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]),!1,o,s);a-=o;let m=d(u)?u[0]:!1,h=d(u)?u[1]:``;if(d(h)&&h!==``&&c.push(h),r++,m)return x=!0,r>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${r} attempts.`,context:{...b,registerAttempts:r,joinCondition:`attempts`,failureMessages:c}}),{...b,joinCondition:`attempts`,acquired:!0};let v=n(r,100);if(a-=v,a<=0||isAborted())break;await t(v)}return this.logger?.error({category:this.name,message:`Failed to register request after ${r} attempts.`,context:{...b,registerAttempts:r,joinCondition:`failed`,failureMessages:c},code:`ConcurrencyManagerRegistrationFailed`}),{...b,joinCondition:`failed`}}finally{if(!x&&(this.leaseRegistry.delete(buildLeaseKey(f,i)),S))try{await this.queueManager?.remove(l,i)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...b,queueKey:l},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if(u(t)&&u(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const H={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if(s(t)||t?.length===0||s(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=g(r,n?{...e,credentials:n}:e)===!0;if(s(r)||i){let n=t?.message,r;return r=s(n)?H[t.targetStatus]??`Unknown error`:String(g(n,e)??H[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},ie=p({receivedStatus:f.number(),targetStatus:f.number(),message:f.string().optional(),condition:f.string().optional()});var U=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new y.Agent(n),l=_.create({...t,httpsAgent:c});if(l.close=()=>{c.destroy()},e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return d(e)&&a(e)&&typeof e(t)==`function`?e(t):e??null}},W=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return s(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>d(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:d(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return d(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const G=W.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},ae={mainRatelimit:25},createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&C(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},K=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if(s(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:K,...a,httpsAgent:void 0,headers:void 0,hasContext:d(t),hasConfig:d(a)},code:`InterceptorContextNotPresent`});else if(s(i)||s(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:K,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:d(i),concurrencyManagerInitialized:d(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if(d(t.provider)&&d(t.accountSecureId)){let o=S(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??ae,u=n?.concurrency??ne,d=await i.getDynamicMaxWaitTime(l,u,a.url),register=async e=>r.registerRequest(`${c}-${s}`,u,o,a.url,Math.max((d-e)*1e3,0),a.signal),f,p=0;for(;p<=d;){let n=await i.getWaitTime(`${c}-${s}`,l,a.url)??0;if(n<=0){f=await register(p);break}let r=Math.min(Math.max(n,1),d-p);if(await abortableDelay(r*1e3,a),p+=r,p>=d){f=await register(p),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:K,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:d},code:`InterceptorMaxWaitTimeExceeded`});break}}return{...a,requestMetadata:f}}return a};return checkConcurrencyInterceptor},q=1e3,oe=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*q:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&o(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*q},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=w(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:c}=e??{};return[t,n,r,o].some(s)?null:[t,n,r,i,a,o,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return o(e)||c(e)?evaluateRetryAfterNumber(Number(e),r,t,n):T(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/q);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(oe.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/q);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i})=>{let retryErrorInterceptor=async a=>{let{response:o,config:s}=a;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,i,r,t);if(c===429&&d(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*q:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),e?.request(u)}return Promise.reject(a)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:c}=e??{},{retryafter:u}=superNormalizeHeaders(o??{});if(s(i)||s(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:s(e),providerIsMissing:s(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:u??`undefined`}}),{status:a,retryAfter:u};let f=n?.rateLimits?.mappedRateLimitErrors;if(d(f)&&d(c))for(let e of f){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:s,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=testMessage(l(c)?E({path:f,json:c})[0]:c,r);if(t===a&&p){let e=convertRetryAfter(d??extractRetryAfter(o,i),s);return{status:429,retryAfter:u??e}}}return{status:a,retryAfter:u}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>d(t)&&d(e)?E({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>d(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/q;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},J=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i,concurrencyManager:a})=>{let rateLimitErrorInterceptor=async o=>{let{response:c,config:l}=o,u=l?.signal;if(s(i)||s(l))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:J,...l,httpsAgent:void 0,headers:void 0,hasContext:d(i),hasConfig:d(l)},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(a))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:J,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(a)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(o);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h,acquired:g}=l?.requestMetadata??{},_=g!==!1&&d(f)&&d(p);if(!(_&&await a.releaseRequest(f,p))&&_&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:J,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:`RateLimiterReleaseRequestFailed`}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,l,`ERR_CANCELED`,c));let{status:v,retryAfter:y}=convertError(c,i,r,t);if(v===429&&d(l)){let r=getRetryAfterWaitTime(y);if(l._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:y,retryAfterAsNumber:r}}),Promise.reject(o);let a=l?._retryCount??0,s={...l,_retryCount:a+1},u=y?r*q:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:y,calculatedRetryAfter:u}}),await abortableDelay(u,l,c),e?.request(s)}return Promise.reject(o)};return rateLimitErrorInterceptor},Y=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if(s(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:Y,...i,httpsAgent:void 0,headers:void 0}});else if(s(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:Y,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if(d(t.provider)&&d(t.accountSecureId)){let t=r?.headers;if(d(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:Y,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l,acquired:u}=i?.requestMetadata??{},f=u!==!1&&d(o)&&d(s);if(!(f&&await n.releaseRequest(o,s))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:Y,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),se=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ce=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],le=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],ue=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=d(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),u=c.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(s(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(d(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),s(n?.service)||s(n?.organizationId)||o===`test`||s(t)||s(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=l?.isReady(),p=u?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...le),h.push(...ue)}let g=generateRequestKey(n);if(s(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:d(a)}}),a;let _=await G.get(g);if(d(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await G.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(a)},error:t,code:`HttpTransportInstanceCreateError`}),d(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:se,responseConfigs:ce},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>_.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=D(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?i(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:o,context:c,traceId:l,payload:u,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:h}){try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let g=this.#v(t,r),_=this.#l(e),v=this.#h(u,e),y=await this.#s({url:g,payload:v,method:n,cacheTTL:o,context:c});if(y)return{...y,responseTime:new Date};let b=W.getInstance(),x=(d(l)?await b.get(l):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:c,requestConfig:m,httpsAgentConfig:h})).request({headers:_,url:g,method:n,maxRedirects:i,responseType:a,data:v,httpsAgent:f,httpAgent:p,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#u(S.headers),requestHeaders:buildSafeRequestHeaders(_),requestUrl:g,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:g,payload:v,method:n,cacheTTL:o,context:c,response:C}),C}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw d(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:o,payload:s,httpsAgent:c,httpAgent:l,requestConfig:u,httpsAgentConfig:f}){try{let p=this.#v(t,r),m=this.#l(e),h=this.#h(s,e),g=W.getInstance(),_=(d(o)?await g.get(o):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:u,httpsAgentConfig:f})).request({headers:m,url:p,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:c,httpAgent:l,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw d(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?k.stringify(e):e}#g(e){if(v(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t){if(s(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={},o={};for(let[e,s]of Object.entries(t))if(this.#_(s)){let t=s.arrayFormat,c=s.value;t===`repeat`?r[e]=Array.isArray(c)?c:[c]:t===`brackets`?i[e]=Array.isArray(c)?c:[c]:t===`comma`?a[e]=Array.isArray(c)?c:[c]:t===`stringify`?o[e]=JSON.stringify(Array.isArray(c)?c:[c]):n[e]=c}else n[e]=s;let c=[];Object.keys(n).length>0&&c.push(k.stringify(n)),Object.keys(r).length>0&&c.push(k.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&c.push(k.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&c.push(k.stringify(a,{arrayFormat:`comma`})),Object.keys(o).length>0&&c.push(k.stringify(o));let l=c.join(`&`);return d(l)?`${e}?${l}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const de=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
98
98
|
`).replace(/\r\n/g,`
|
|
99
99
|
`).replace(/\r/g,`
|
|
100
100
|
`).trim();t=t.replace(/(-----BEGIN [A-Z0-9 ]+-----) +/g,`$1
|
|
@@ -102,17 +102,26 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInM
|
|
|
102
102
|
$1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+-----)/);if(n){let[,e,r,i]=n;if(!r.includes(`
|
|
103
103
|
`)&&r.includes(` `)){let n=r.replace(/ /g,``);t=`${e}\n${n.match(/.{1,64}/g)?.join(`
|
|
104
104
|
`)??n}\n${i}`}}return t},decodeCertOrKey=e=>{if(!e||e.length===0)return e;let t=normalizePem(e);if(isPemFormat(t))return t;try{let e=Buffer.from(t,`base64`).toString(`utf-8`);return isPemFormat(e)?normalizePem(e):t}catch{return t}},buildHttpsAgent=e=>{if(!e)return;let{certs:t,keys:n}=e;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(e=>typeof e==`string`&&e.trim().length>0),i=n.filter(e=>typeof e==`string`&&e.trim().length>0);if(r.length===0||i.length===0)return;let a=r.map(decodeCertOrKey),o=i.map(decodeCertOrKey);return new y.Agent({cert:a,key:o})},fe={rPush:`
|
|
105
|
+
-- Drop any stale copy first so a retrying request holds at most one queue slot.
|
|
106
|
+
redis.call('LREM', KEYS[1], 0, ARGV[1])
|
|
107
|
+
|
|
105
108
|
local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
|
|
106
109
|
|
|
107
110
|
redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
|
108
111
|
|
|
109
112
|
return queueLength
|
|
110
113
|
`,lPush:`
|
|
114
|
+
-- Drop any stale copy first so a retrying request holds at most one queue slot.
|
|
115
|
+
redis.call('LREM', KEYS[1], 0, ARGV[1])
|
|
116
|
+
|
|
111
117
|
local queueLength = redis.call('LPUSH', KEYS[1], ARGV[1])
|
|
112
118
|
|
|
113
119
|
redis.call('PEXPIRE', KEYS[1], ARGV[2])
|
|
114
120
|
|
|
115
121
|
return queueLength
|
|
122
|
+
`,remove:`
|
|
123
|
+
-- Remove every copy so terminal requests can never remain at the queue head.
|
|
124
|
+
return redis.call('LREM', KEYS[1], 0, ARGV[1])
|
|
116
125
|
`,lPop:`
|
|
117
126
|
local queueKey = KEYS[1]
|
|
118
127
|
|
|
@@ -123,7 +132,6 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
123
132
|
|
|
124
133
|
local shouldWait = false
|
|
125
134
|
local totalCount = 0
|
|
126
|
-
local now = redis.call('TIME')[1]
|
|
127
135
|
|
|
128
136
|
-- Check each key from KEYS[2] onward
|
|
129
137
|
for i = 2, #KEYS do
|
|
@@ -144,9 +152,10 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
144
152
|
shouldWait = true
|
|
145
153
|
end
|
|
146
154
|
|
|
147
|
-
-- If
|
|
155
|
+
-- If rate limited, return a relative wait in seconds for the caller to sleep. Relative,
|
|
156
|
+
-- not an absolute epoch, so the caller never diffs a Redis timestamp against its own clock.
|
|
148
157
|
if shouldWait then
|
|
149
|
-
return
|
|
158
|
+
return 1
|
|
150
159
|
end
|
|
151
160
|
|
|
152
161
|
-- No limits exceeded, increment the target key and set expiration for 1 second
|
|
@@ -159,8 +168,8 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
159
168
|
end
|
|
160
169
|
|
|
161
170
|
return nil
|
|
162
|
-
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],[a,o]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:fe,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:pe,logger:n})]),s=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:re,logger:n,additionalArgs:e}),c=[{name:`ConcurrencyManager`,ready:s.isReady()},{name:`QueueManager`,ready:a.isReady()},{name:`RateLimitManager`,ready:o.isReady()}],l=c.filter(e=>!e.ready);if(l.length>0){let e=l.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:c.map(e=>e.name)}}),{concurrencyManager:s,queueManager:a,rateLimitManager:o}}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`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),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},me=e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),Y=e(e=>Array.isArray(e)?e:[e],`toStringArray`),toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=Y(t);if(me(e))return{value:[...Y(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...Y(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.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.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),he=[`query`,`body`,`headers`],ge=[`repeat`,`brackets`,`comma`,`stringify`],X={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},_e=new A(X),getContentType=e=>{let t=Object.entries(e).find(([e])=>e.toLowerCase()===`content-type`)?.[1];return typeof t==`string`?t.toLowerCase():``},isXmlContentTypeValue=e=>e.includes(`application/xml`)||e.includes(`text/xml`)||/application\/\S+\+xml/.test(e),isXmlContentType=e=>isXmlContentTypeValue(getContentType(e)),serializeBodyToXml=e=>{try{return _e.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?k.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>d(e)&&e>=200&&e<=299,isFailedStatusCode=e=>d(e)&&e>=400&&e<=599,isInfoStatusCode=e=>d(e)&&e>=100&&e<=199;let Z;const getXmlParser=()=>(Z??=new j({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),Z);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:c,httpsAgent:l,credentials:u}){let d,f=a;if(isXmlContentType(r))if(typeof a==`string`)f=a;else if(Array.isArray(a))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 a!=null&&(f=serializeBodyToXml(a));try{d=await e?.request({method:n,url:t,headers:r,queryParams:i,maxRedirects:0,payload:f,requestConfig:c,httpsAgent:l})}catch(e){if(s(e?.response))throw e;d=e.response}if(typeof d.data==`string`&&d.data.length>0&&d.headers&&isXmlContentType(d.headers)){let e=M.validate(d.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);d={...d,data:getXmlParser().parse(d.data)}}let p=translateCustomError(d,o,u);if(isFailedStatusCode(p?.status))throw new H(p,p.message);return p}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:c,credentials:l}){let u;if(u=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Q.build(c.envelope):await buildEnvelope(a,c),M.validate(u,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let d,f={"Content-Type":`application/xml`,...r};c?.soapAction&&(f.SOAPAction=c.soapAction);try{d=await e?.request({method:n,url:t,headers:f,queryParams:i,maxRedirects:0,payload:u,requestConfig:c})}catch(e){if(s(e?.response))throw e;d=e.response}let p=ve.parse(d.data),m=p.Envelope||p,h=m.Body||m,g=h.Fault;if(g)throw new H({...d,status:500,data:g,message:g.faultstring??g.faultcode??`SOAP Fault`},g.faultstring??`SOAP Fault occurred`);d.data=h;let _=translateCustomError(d,o,l);if(isFailedStatusCode(_?.status))throw new H(_,_.message);return _}};const Q=new A(X),ve=new j({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(M.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Q.build(n);if(M.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 h(e.namespaceIdentifier),namespace:await h(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)=>x(`sha256`,e).update(t).digest(),hash=e=>b(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),$=e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),ye=e((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),d=u.slice(0,8),f=new URL(e.url),p=f.pathname.split(`/`).map(e=>{try{return $(decodeURIComponent(e))}catch{return $(e)}}).join(`/`)||`/`,m=[];for(let[e,t]of f.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=ye(e,n);return i===0?ye(t,r):i});let h=m.map(([e,t])=>`${$(e)}=${$(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=b(`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 S=Object.keys(y).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),C=g.length>0&&!S,w;C&&(w=_.toString(`base64`),y[`x-amz-checksum-sha256`]=w);let T=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),E=T.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),D=T.join(`;`),O=[e.method.toUpperCase(),p,h,E,D,v].join(`
|
|
171
|
+
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],[a,o]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:fe,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:pe,logger:n})]),s=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:re,logger:n,additionalArgs:e}),c=[{name:`ConcurrencyManager`,ready:s.isReady()},{name:`QueueManager`,ready:a.isReady()},{name:`RateLimitManager`,ready:o.isReady()}],l=c.filter(e=>!e.ready);if(l.length>0){let e=l.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:c.map(e=>e.name)}}),{concurrencyManager:s,queueManager:a,rateLimitManager:o}}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`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),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},me=e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),X=e(e=>Array.isArray(e)?e:[e],`toStringArray`),toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=X(t);if(me(e))return{value:[...X(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...X(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.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.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),he=[`query`,`body`,`headers`],ge=[`repeat`,`brackets`,`comma`,`stringify`],Z={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},_e=new A(Z),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 _e.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?k.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>d(e)&&e>=200&&e<=299,isFailedStatusCode=e=>d(e)&&e>=400&&e<=599,isInfoStatusCode=e=>d(e)&&e>=100&&e<=199;let ve;const getXmlParser=()=>(ve??=new j({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),ve);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:c,httpsAgent:l,credentials:u}){let d,f=a;if(isXmlContentType(r))if(typeof a==`string`)f=a;else if(Array.isArray(a))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 a!=null&&(f=serializeBodyToXml(a));try{d=await e?.request({method:n,url:t,headers:r,queryParams:i,maxRedirects:0,payload:f,requestConfig:c,httpsAgent:l})}catch(e){if(s(e?.response))throw e;d=e.response}if(typeof d.data==`string`&&d.data.length>0&&d.headers&&isXmlContentType(d.headers)){let e=M.validate(d.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);d={...d,data:getXmlParser().parse(d.data)}}let p=translateCustomError(d,o,u);if(isFailedStatusCode(p?.status))throw new U(p,p.message);return p}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:c,credentials:l}){let u;if(u=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Q.build(c.envelope):await buildEnvelope(a,c),M.validate(u,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let d,f={"Content-Type":`application/xml`,...r};c?.soapAction&&(f.SOAPAction=c.soapAction);try{d=await e?.request({method:n,url:t,headers:f,queryParams:i,maxRedirects:0,payload:u,requestConfig:c})}catch(e){if(s(e?.response))throw e;d=e.response}let p=ye.parse(d.data),m=p.Envelope||p,h=m.Body||m,g=h.Fault;if(g)throw new U({...d,status:500,data:g,message:g.faultstring??g.faultcode??`SOAP Fault`},g.faultstring??`SOAP Fault occurred`);d.data=h;let _=translateCustomError(d,o,l);if(isFailedStatusCode(_?.status))throw new U(_,_.message);return _}};const Q=new A(Z),ye=new j({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(M.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Q.build(n);if(M.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 h(e.namespaceIdentifier),namespace:await h(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)=>x(`sha256`,e).update(t).digest(),hash=e=>b(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),$=e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),be=e((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),d=u.slice(0,8),f=new URL(e.url),p=f.pathname.split(`/`).map(e=>{try{return $(decodeURIComponent(e))}catch{return $(e)}}).join(`/`)||`/`,m=[];for(let[e,t]of f.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=be(e,n);return i===0?be(t,r):i});let h=m.map(([e,t])=>`${$(e)}=${$(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=b(`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 S=Object.keys(y).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),C=g.length>0&&!S,w;C&&(w=_.toString(`base64`),y[`x-amz-checksum-sha256`]=w);let T=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),E=T.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),D=T.join(`;`),O=[e.method.toUpperCase(),p,h,E,D,v].join(`
|
|
163
172
|
`),k=`${d}/${l}/${s}/aws4_request`,A=[`AWS4-HMAC-SHA256`,u,k,hash(O)].join(`
|
|
164
|
-
`),j={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${k}, SignedHeaders=${D}, Signature=${x(`sha256`,getSigningKey(i,d,l,s)).update(A).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":v};return a&&(j[`x-amz-security-token`]=a),w!==void 0&&(j[`x-amz-checksum-sha256`]=w),j},
|
|
165
|
-
`),_=x(c,r).update(g).digest(`hex`);return{[l]:`${u} ${_}`,"X-Timestamp":d}},
|
|
166
|
-
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${v}`).toString(`base64`)}`,Date:m}:{[i??`X-Signature`]:`${a??`hmac-${d}`} ${v}`,"X-Timestamp":m}}const
|
|
173
|
+
`),j={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${k}, SignedHeaders=${D}, Signature=${x(`sha256`,getSigningKey(i,d,l,s)).update(A).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":v};return a&&(j[`x-amz-security-token`]=a),w!==void 0&&(j[`x-amz-checksum-sha256`]=w),j},xe=[`sha256`,`sha512`],isValidAlgorithm=e=>xe.includes(e),hashPayload=e=>b(`sha256`).update(e).digest(`hex`),byteCompare=(e,t)=>e<t?-1:+(e>t),rfc3986Encode=e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),hmacSigningStrategy=(e,t,n)=>{if(n.strategy!==`hmac`)throw Error(`hmacSigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let r=t.secretKey;if(!r)throw Error(`HMAC signing requires secretKey in credentials`);let i=n;if(requiresExtendedSigning(i))return signWithExtendedOptions(e,r,i);let{algorithm:a,headerName:o,prefix:s}=i;if(a!==void 0&&!isValidAlgorithm(a))throw Error(`Unsupported HMAC algorithm "${a}". Use "sha256" or "sha512".`);let c=a??`sha256`,l=o??`X-Signature`,u=s??`hmac-${c}`,d=new Date().toISOString(),f=new URL(e.url),p=[];for(let[e,t]of f.searchParams.entries())p.push([e,t]);p.push(...flattenQueryParams(e.query)),p.sort(([e,t],[n,r])=>{let i=byteCompare(e,n);return i===0?byteCompare(t,r):i});let m=p.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),h=hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})),g=[d,e.method.toUpperCase(),f.pathname,m,h].join(`
|
|
174
|
+
`),_=x(c,r).update(g).digest(`hex`);return{[l]:`${u} ${_}`,"X-Timestamp":d}},Se=[`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&&!Se.includes(r))throw Error(`Unsupported HMAC algorithm "${r}". Use "sha1", "sha256", or "sha512".`);if(l===`basic`&&!u)throw Error(`HMAC signing with outputFormat "basic" requires username`);if(u&&/[:\r\n]/.test(u))throw Error(`HMAC signing username cannot contain ":", "\\r", or "\\n"`);let d=r??`sha256`,f=new URL(e.url),p=new Date,m=o===`rfc2822`?formatRfc2822Date(p):p.toISOString(),h=[...f.searchParams.entries(),...flattenQueryParams(e.query)];!c&&e.body&&typeof e.body==`object`&&!Array.isArray(e.body)&&(e.headers?.[`content-type`]??e.headers?.[`Content-Type`]??``).toLowerCase().includes(`application/x-www-form-urlencoded`)&&h.push(...extractBodyParams(e.body)),h.sort(([e,t],[n,r])=>byteCompare(e,n)||byteCompare(t,r));let g=h.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),_=[m,e.method.toUpperCase()];s&&_.push(f.hostname.toLowerCase()),_.push(f.pathname,g),c&&_.push(hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})));let v=x(d,t).update(_.join(`
|
|
175
|
+
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${v}`).toString(`base64`)}`,Date:m}:{[i??`X-Signature`]:`${a??`hmac-${d}`} ${v}`,"X-Timestamp":m}}const Ce={},registerSigningStrategy=(e,t)=>{Ce[e]=t},getSigningStrategy=e=>Ce[e];registerSigningStrategy(`aws4`,aws4SigningStrategy),registerSigningStrategy(`hmac`,hmacSigningStrategy);export{ie as CUSTOM_ERROR_CONFIG_SCHEMA,ConcurrencyManager,EventClient,HttpClient,HttpClientManager,H as HttpErrorMessages,de as HttpMethods,U as HttpResponseError,HttpTransportFactory,W as InstanceManager,LockManager,MemoryStore,ge as QueryArrayFormats,QueueManager,RateLimitManager,P as RedisClient,RequestClientFactory,he as RequestParameterLocations,ScriptManager,SubscriptionManager,buildHttpClientInstance,buildHttpsAgent,convertError,createAuthorizationHeaders,getRetryAfterWaitTime,getSigningStrategy,getTransportInstance,getTransportManagers,initializeTransportSystem,isFailedStatusCode,isInfoStatusCode,isSuccessStatusCode,isTransportSystemReady,parseRequestParameters,registerSigningStrategy,serializeHttpResponseError,shutdownTransportSystem,superNormalizeHeaders,translateCustomError};
|