@stackone/transport 2.2.1 → 2.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(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},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const l=c(require(`@stackone/utils`)),u=c(require(`redis`)),d=c(require(`axios`)),f=c(require(`node:https`)),p=c(require(`crypto`)),m=c(require(`node:timers`)),h=c(require(`jsonpath`)),g=c(require(`@stackone/redaction`)),_=c(require(`qs`)),v=c(require(`@stackone/expressions`)),y=e=>{switch(e.type){case`none`:return{};case`basic`:return b(e);case`bearer`:return x(e);case`oauth2`:return x(e);default:throw Error(`Invalid authentication type`)}},b=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},x=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var S=class{locks;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);if(r&&i){i.push({lock:n,unlock:t});let e=i.length-2;await i[e].lock}else 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 ee=1e3,C=100,te=60,w=6e4,T=te,ne=w,re=w*10,ie=C,E=10;let D=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var ae=class{config;instantiator;dataStore;lockManager;expiryMap;evictionFrequency;staleDataThreshold;truncateThreshold;truncationPercentage;logger;typeGuard;dispose;evictionInterval;lastAccessedAt=Date.now();constructor(e={}){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 S,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??ne,this.staleDataThreshold=e?.staleDataThreshold??re,this.truncateThreshold=e?.truncateThreshold??ie,this.truncationPercentage=e?.truncationPercentage??E,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 setData({key:e,value:t,cacheTTL:n=T}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),(0,l.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*ee,i=Date.now()+r;return await this.lockManager.withLock(e,async()=>{((0,l.notMissing)(this.typeGuard)&&this.typeGuard(t)||(0,l.isMissing)(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,i)}),!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){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)}return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/C;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n);let i=this.dataStore.size;return{dataStoreSize:e,prunedDataStoreSize:i}}startEvictionTask(){if((0,l.notMissing)(this.evictionInterval))return;let e=async()=>{let t;try{let n=this.lastAccessedAt+this.staleDataThreshold,r=Date.now();if(n<r){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),this.close();return}t=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(e,this.evictionFrequency)}catch(t){t instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:t,code:D.MemoryStorePruneError}),this.evictionInterval=setTimeout(e,this.evictionFrequency)}finally{if((0,l.notMissing)(t?.dataStoreSize)&&(0,l.notMissing)(t?.prunedDataStoreSize)){let{dataStoreSize:e,prunedDataStoreSize:n}=t,r=e-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(e,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&(clearTimeout(this.evictionInterval),this.evictionInterval=void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return(0,l.notMissing)(this.evictionInterval)&&(0,l.notMissing)(this.dataStore)&&(0,l.notMissing)(this.expiryMap)&&(0,l.notMissing)(this.lockManager)}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()),i=r.filter(t=>t.includes(e)),a=[],o=t?parseInt(t,10):0;for(let e=o;e<n+o;e++){let t=i[e];if(!t)break;let r=await this.getData(t);if(r&&a.push(r),a.length>=n)break}return{items:a,cursor:a.length<n?void 0:(o+n).toString()}}};const oe=1e3,se=6e4;let ce=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var le=class{executorMethodStore=null;promiseStore=null;logger;eventClientConfig=null;executorMethodStoreConfig=null;pendingPromiseStoreConfig=null;constructor(e,t,n){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 ae(i),this.promiseStore=new ae(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/oe;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,l.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,l.isMissing)(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??se),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:ce.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){(0,l.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,l.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,l.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},ue=class{instance=null;initPromise=null;retryTimeout=null;status=`uninitialized`;initOptions=null;initArgs=[];getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:((0,l.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,l.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}};let O=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const de=async(e,t,n)=>{try{let r=await fe.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:O.RedisClientError,category:n??`buildRedisClientInstance`});return}};var fe=class e{#redisClient;#logger;static async build({getRedisClient:t=u.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s,c){let l=new e;l.#logger=s;try{l.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let e=me(c??`RedisClient`,l.#logger);return pe(l.#redisClient,e),await l.#redisClient.connect(),l}catch(e){let t=e;return l.#logger?.error({message:`Error building Cache Manager.`,error:t,code:O.RedisClientError,category:c??`RedisClient`}),null}}#parseData(e){try{return JSON.parse(e)}catch{return e}}async getData(t){if(!this.#isRedisClientAvailable())return null;try{let e=await this.#redisClient.get(t);if(!e)return null;let n=this.#parseData(e);return(0,l.isString)(n)?e:n}catch(t){let n=t;return this.#logger?.error({message:`Error getting data`,error:n,code:O.RedisClientReadError,category:e.name}),null}}async setData({key:t,value:n,cacheTTL:r,groupKey:i}){if(!this.#isRedisClientAvailable())return!1;try{let e=(0,l.isString)(n)?n:JSON.stringify(n);return await this.#redisClient.set(t,e,{EX:r}),(0,l.notMissing)(i)&&await this.#redisClient.sAdd(i,[t]),!0}catch(t){let n=t;return this.#logger?.error({message:`Error setting data`,error:n,code:O.RedisClientWriteError,category:e.name}),!1}}async executeScript({sha1:t,keys:n,args:r}){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.evalSha(t,{keys:n,arguments:r})}catch(t){let n=t;return this.#logger?.error({message:`Error executing script`,error:n,code:O.RedisClientScriptExecuteError,category:e.name}),null}}async loadScript(t){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.scriptLoad(t)}catch(t){let n=t;return this.#logger?.error({message:`Error loading script`,error:n,code:O.RedisClientScriptLoadError,category:e.name}),null}}async#executeCounterCommand(t,n,r){if(!this.#isRedisClientAvailable())return null;if(!Number.isFinite(r)||r<=0)return this.#logger?.error({message:`Invalid cacheTTL parameter`,category:e.name,code:O.RedisClientInvalidTTL}),null;try{let e=[{args:[t,n]},{args:[`expire`,n,r.toString()]}],i=await this.#redisClient.multiExecutor(e),a=i?.[0];return typeof a==`number`?a:null}catch(n){let r=n;return this.#logger?.error({message:`Error executing ${t} operation`,error:r,code:O.RedisClientCommandError,category:e.name}),null}}async increment(e,t){return this.#executeCounterCommand(`incr`,e,t)}async decrement(e,t){return this.#executeCounterCommand(`decr`,e,t)}async subscribe(t,n){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pSubscribe(t,n),!0}catch(n){let r=n;return this.#logger?.error({message:`Error subscribing to ${t}`,error:r,code:O.RedisClientSubscribeError,category:e.name}),!1}}async unsubscribe(t){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pUnsubscribe(t),!0}catch(n){let r=n;return this.#logger?.error({message:`Error unsubscribing from ${t}`,error:r,code:O.RedisClientUnsubscribeError,category:e.name}),!1}}async publish(t,n){if(!this.#isRedisClientAvailable())return null;try{let r=await this.#redisClient.publish(t,n);return r===0&&this.#logger?.debug({message:`No subscribers found for channel ${t}`,category:e.name}),r}catch(n){let r=n;return this.#logger?.error({message:`Error publishing to ${t}`,error:r,code:O.RedisClientPublishError,category:e.name}),null}}getClient(){return this.#isRedisClientAvailable()?this.#redisClient:null}#isRedisClientAvailable(){let t=this.#redisClient.isReady&&this.#redisClient.isOpen;return t||this.#logger?.error({message:`Redis Client is not ready.`,category:e.name,code:O.RedisClientRedisNotReady}),t}async listData({partialKey:t,limit:n,cursor:r}){try{let e=r?parseInt(r,10):0,i=await this.#redisClient.sScan(t,e,{COUNT:n}),a=[];for(let e of i.members){let t=await this.getData(e);(0,l.notMissing)(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(t){let n=t;return this.#logger?.error({message:`Error listing data`,error:n,code:O.RedisClientListError,category:e.name}),{items:null}}}async deleteData(t){try{if(!this.#isRedisClientAvailable())return!1;let n=await this.#redisClient.del(t);return n===0&&this.#logger?.debug({message:`No keys deleted for ${t}`,category:e.name}),n>0}catch(t){let n=t;return this.#logger?.error({message:`Error deleting data`,error:n,code:O.RedisClientDeleteError,category:e.name}),!1}}};const pe=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},me=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:O.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})}}];let he=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var ge=class extends ue{redisClientConfig;scripts;scriptMap;cacheClient;logger;additionalArgs;isInitialConnection=!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 de(e,i,this.name);if((0,l.isMissing)(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?.();(0,l.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(){(0,l.isMissing)(this.scripts)||Object.keys(this.scripts).length===0||(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))}async loadScripts(e,t){if((0,l.notMissing)(t))for(let[e,n]of t)this.scriptMap.set(e,n);for(let[t,n]of Object.entries(e)){let e=await this.cacheClient?.loadScript?.(n);(0,l.notMissing)(e)?this.scriptMap?.set(t,e):this.logger?.error({message:`Error loading script ${t}`,category:this.name,code:he.ScriptManagerLoadingError})}}async executeScript(e,t,n){try{if(!this.isRedisReady())throw Error(`Redis client is not ready`);let r=this.scriptMap?.get(e);if((0,l.isMissing)(r))throw 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`)){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,l.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}}catch(r){throw r instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${r.message}`,category:this.name,context:{keys:t,args:n},error:r,code:he.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&(0,l.notMissing)(this.cacheClient)}},_e=class{options={getCacheClient:de};subscriptionMap=null;subscriptionClient=null;logger;name=`SubscriptionManager`;constructor(e){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 ae({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,l.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,l.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,l.notMissing)(this.subscriptionClient)&&(0,l.notMissing)(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const ve=6e4,ye=15e3,be=!1,xe=6e4,Se=15e3,Ce=1e4,we=1;let Te=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),k=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var A=class extends ge{subscriptionManager=null;eventClient=null;name=`QueueManager`;async additionalInitialization(){if((0,l.isMissing)(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new _e({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:xe,truncateThreshold:Ce,truncationPercentage:we}),await this.subscriptionManager?.initialize(),this.eventClient=new le({instantiator:this.name,timeoutResolveValue:be},{instantiator:this.name,evictionFrequency:Se,truncateThreshold:Ce,truncationPercentage:we},{instantiator:this.name,evictionFrequency:Se,truncateThreshold:Ce,truncationPercentage:we}),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?k.lPush:k.rPush,[e],[t,ve.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,ye),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:Te.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(k.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Te.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(k.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Te.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return(0,l.notMissing)(this.subscriptionManager)&&(0,l.notMissing)(this.cacheClient)&&(0,l.notMissing)(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const Ee=5,De=12e4,Oe=1e4,ke=1,Ae=60,je=90,Me=`__keyevent@0__:`,Ne=`${Me}set`,Pe=`${Me}expire`,Fe=`${Me}expired`,Ie=`${Me}srem`,Le=`config_check_test_key`,Re=[Ne,Pe,Fe],ze=1,Be=15e3,Ve={mainMaxConcurrency:30};let He=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),Ue=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const We={[Ue.tryConcurrency]:`
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(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},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const l=c(require(`@stackone/utils`)),u=c(require(`redis`)),d=c(require(`axios`)),f=c(require(`node:https`)),p=c(require(`crypto`)),m=c(require(`node:timers`)),h=c(require(`jsonpath`)),g=c(require(`@stackone/redaction`)),_=c(require(`qs`)),v=c(require(`@stackone/expressions`)),y=e=>{switch(e.type){case`none`:return{};case`basic`:return b(e);case`bearer`:return x(e);case`oauth2`:return x(e);default:throw Error(`Invalid authentication type`)}},b=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},x=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var S=class{locks;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);if(r&&i){i.push({lock:n,unlock:t});let e=i.length-2;await i[e].lock}else 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 ee=1e3,C=100,te=60,w=6e4,T=te,ne=w,re=w*10,ie=C,E=10;let D=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var ae=class{config;instantiator;dataStore;lockManager;expiryMap;evictionFrequency;staleDataThreshold;truncateThreshold;truncationPercentage;logger;typeGuard;dispose;evictionInterval;lastAccessedAt=Date.now();constructor(e={}){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 S,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??ne,this.staleDataThreshold=e?.staleDataThreshold??re,this.truncateThreshold=e?.truncateThreshold??ie,this.truncationPercentage=e?.truncationPercentage??E,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 setData({key:e,value:t,cacheTTL:n=T}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),(0,l.notMissing)(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*ee,i=Date.now()+r;return await this.lockManager.withLock(e,async()=>{((0,l.notMissing)(this.typeGuard)&&this.typeGuard(t)||(0,l.isMissing)(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,i)}),!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){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)}return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/C;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n);let i=this.dataStore.size;return{dataStoreSize:e,prunedDataStoreSize:i}}startEvictionTask(){if((0,l.notMissing)(this.evictionInterval))return;let e=async()=>{let t;try{let n=this.lastAccessedAt+this.staleDataThreshold,r=Date.now();if(n<r){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),this.close();return}t=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(e,this.evictionFrequency)}catch(t){t instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:t,code:D.MemoryStorePruneError}),this.evictionInterval=setTimeout(e,this.evictionFrequency)}finally{if((0,l.notMissing)(t?.dataStoreSize)&&(0,l.notMissing)(t?.prunedDataStoreSize)){let{dataStoreSize:e,prunedDataStoreSize:n}=t,r=e-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(e,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&(clearTimeout(this.evictionInterval),this.evictionInterval=void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return(0,l.notMissing)(this.evictionInterval)&&(0,l.notMissing)(this.dataStore)&&(0,l.notMissing)(this.expiryMap)&&(0,l.notMissing)(this.lockManager)}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()),i=r.filter(t=>t.includes(e)),a=[],o=t?parseInt(t,10):0;for(let e=o;e<n+o;e++){let t=i[e];if(!t)break;let r=await this.getData(t);if(r&&a.push(r),a.length>=n)break}return{items:a,cursor:a.length<n?void 0:(o+n).toString()}}};const oe=1e3,se=6e4;let ce=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var le=class{executorMethodStore=null;promiseStore=null;logger;eventClientConfig=null;executorMethodStoreConfig=null;pendingPromiseStoreConfig=null;constructor(e,t,n){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 ae(i),this.promiseStore=new ae(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/oe;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,l.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,l.isMissing)(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??se),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:ce.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){(0,l.notMissing)(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):(0,l.notMissing)(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return(0,l.isObject)(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},ue=class{instance=null;initPromise=null;retryTimeout=null;status=`uninitialized`;initOptions=null;initArgs=[];getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:((0,l.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,l.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}};let O=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const de=async(e,t,n)=>{try{let r=await fe.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:O.RedisClientError,category:n??`buildRedisClientInstance`});return}};var fe=class e{#redisClient;#logger;static async build({getRedisClient:t=u.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s,c){let l=new e;l.#logger=s;try{l.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let e=me(c??`RedisClient`,l.#logger);return pe(l.#redisClient,e),await l.#redisClient.connect(),l}catch(e){let t=e;return l.#logger?.error({message:`Error building Cache Manager.`,error:t,code:O.RedisClientError,category:c??`RedisClient`}),null}}#parseData(e){try{return JSON.parse(e)}catch{return e}}async getData(t){if(!this.#isRedisClientAvailable())return null;try{let e=await this.#redisClient.get(t);if(!e)return null;let n=this.#parseData(e);return(0,l.isString)(n)?e:n}catch(t){let n=t;return this.#logger?.error({message:`Error getting data`,error:n,code:O.RedisClientReadError,category:e.name}),null}}async setData({key:t,value:n,cacheTTL:r,groupKey:i}){if(!this.#isRedisClientAvailable())return!1;try{let e=(0,l.isString)(n)?n:JSON.stringify(n);return await this.#redisClient.set(t,e,{EX:r}),(0,l.notMissing)(i)&&await this.#redisClient.sAdd(i,[t]),!0}catch(t){let n=t;return this.#logger?.error({message:`Error setting data`,error:n,code:O.RedisClientWriteError,category:e.name}),!1}}async executeScript({sha1:t,keys:n,args:r}){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.evalSha(t,{keys:n,arguments:r})}catch(t){let n=t;return this.#logger?.error({message:`Error executing script`,error:n,code:O.RedisClientScriptExecuteError,category:e.name}),null}}async loadScript(t){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.scriptLoad(t)}catch(t){let n=t;return this.#logger?.error({message:`Error loading script`,error:n,code:O.RedisClientScriptLoadError,category:e.name}),null}}async#executeCounterCommand(t,n,r){if(!this.#isRedisClientAvailable())return null;if(!Number.isFinite(r)||r<=0)return this.#logger?.error({message:`Invalid cacheTTL parameter`,category:e.name,code:O.RedisClientInvalidTTL}),null;try{let e=[{args:[t,n]},{args:[`expire`,n,r.toString()]}],i=await this.#redisClient.multiExecutor(e),a=i?.[0];return typeof a==`number`?a:null}catch(n){let r=n;return this.#logger?.error({message:`Error executing ${t} operation`,error:r,code:O.RedisClientCommandError,category:e.name}),null}}async increment(e,t){return this.#executeCounterCommand(`incr`,e,t)}async decrement(e,t){return this.#executeCounterCommand(`decr`,e,t)}async subscribe(t,n){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pSubscribe(t,n),!0}catch(n){let r=n;return this.#logger?.error({message:`Error subscribing to ${t}`,error:r,code:O.RedisClientSubscribeError,category:e.name}),!1}}async unsubscribe(t){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pUnsubscribe(t),!0}catch(n){let r=n;return this.#logger?.error({message:`Error unsubscribing from ${t}`,error:r,code:O.RedisClientUnsubscribeError,category:e.name}),!1}}async publish(t,n){if(!this.#isRedisClientAvailable())return null;try{let r=await this.#redisClient.publish(t,n);return r===0&&this.#logger?.debug({message:`No subscribers found for channel ${t}`,category:e.name}),r}catch(n){let r=n;return this.#logger?.error({message:`Error publishing to ${t}`,error:r,code:O.RedisClientPublishError,category:e.name}),null}}getClient(){return this.#isRedisClientAvailable()?this.#redisClient:null}#isRedisClientAvailable(){let t=this.#redisClient.isReady&&this.#redisClient.isOpen;return t||this.#logger?.error({message:`Redis Client is not ready.`,category:e.name,code:O.RedisClientRedisNotReady}),t}async listData({partialKey:t,limit:n,cursor:r}){try{let e=r?parseInt(r,10):0,i=await this.#redisClient.sScan(t,e,{COUNT:n}),a=[];for(let e of i.members){let t=await this.getData(e);(0,l.notMissing)(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(t){let n=t;return this.#logger?.error({message:`Error listing data`,error:n,code:O.RedisClientListError,category:e.name}),{items:null}}}async deleteData(t){try{if(!this.#isRedisClientAvailable())return!1;let n=await this.#redisClient.del(t);return n===0&&this.#logger?.debug({message:`No keys deleted for ${t}`,category:e.name}),n>0}catch(t){let n=t;return this.#logger?.error({message:`Error deleting data`,error:n,code:O.RedisClientDeleteError,category:e.name}),!1}}};const pe=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},me=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:O.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})}}];let he=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var ge=class extends ue{redisClientConfig;scripts;scriptMap;cacheClient;logger;additionalArgs;isInitialConnection=!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 de(e,i,this.name);if((0,l.isMissing)(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?.();(0,l.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(){(0,l.isMissing)(this.scripts)||Object.keys(this.scripts).length===0||(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))}async loadScripts(e,t){if((0,l.notMissing)(t))for(let[e,n]of t)this.scriptMap.set(e,n);for(let[t,n]of Object.entries(e)){let e=await this.cacheClient?.loadScript?.(n);(0,l.notMissing)(e)?this.scriptMap?.set(t,e):this.logger?.error({message:`Error loading script ${t}`,category:this.name,code:he.ScriptManagerLoadingError})}}async executeScript(e,t,n){try{if(!this.isRedisReady())throw Error(`Redis client is not ready`);let r=this.scriptMap?.get(e);if((0,l.isMissing)(r))throw 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`)){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,l.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}}catch(r){throw r instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${r.message}`,category:this.name,context:{keys:t,args:n},error:r,code:he.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&(0,l.notMissing)(this.cacheClient)}},_e=class{options={getCacheClient:de};subscriptionMap=null;subscriptionClient=null;logger;name=`SubscriptionManager`;constructor(e){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 ae({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,l.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,l.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,l.notMissing)(this.subscriptionClient)&&(0,l.notMissing)(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const ve=6e4,ye=15e3,be=!1,xe=6e4,Se=15e3,Ce=1e4,we=1;let Te=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),k=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var A=class extends ge{subscriptionManager=null;eventClient=null;name=`QueueManager`;async additionalInitialization(){if((0,l.isMissing)(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new _e({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:xe,truncateThreshold:Ce,truncationPercentage:we}),await this.subscriptionManager?.initialize(),this.eventClient=new le({instantiator:this.name,timeoutResolveValue:be},{instantiator:this.name,evictionFrequency:Se,truncateThreshold:Ce,truncationPercentage:we},{instantiator:this.name,evictionFrequency:Se,truncateThreshold:Ce,truncationPercentage:we}),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?k.lPush:k.rPush,[e],[t,ve.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,ye),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:Te.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(k.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Te.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(k.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Te.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return(0,l.notMissing)(this.subscriptionManager)&&(0,l.notMissing)(this.cacheClient)&&(0,l.notMissing)(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const Ee=5,De=12e4,Oe=1e4,ke=1,Ae=60,je=90,Me=`__keyevent@0__:`,Ne=`${Me}set`,Pe=`${Me}expire`,Fe=`${Me}expired`,Ie=`${Me}srem`,Le=`config_check_test_key`,Re=[Ne,Pe,Fe],ze=1,Be=2e4,Ve={mainMaxConcurrency:30};let He=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),Ue=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const We={[Ue.tryConcurrency]:`
2
2
  local requestId = KEYS[1]
3
3
  local targetKey = KEYS[2]
4
4
  local queueKey = KEYS[3]
@@ -192,4 +192,4 @@ var Or=9e15,kr=1e9,Ar=`0123456789abcdef`,jr=`2.302585092994045684017991454684364
192
192
  `);let t=new xs(`!xml`),n=t,r=``,i=``;for(let a=0;a<e.length;a++){let o=e[a];if(o===`<`)if(e[a+1]===`/`){let t=Zs(e,`>`,a,`Closing Tag is not closed.`),o=e.substring(a+2,t).trim();if(this.options.removeNSPrefix){let e=o.indexOf(`:`);e!==-1&&(o=o.substr(e+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),n&&(r=this.saveTextToParentTag(r,n,i));let s=i.substring(i.lastIndexOf(`.`)+1);if(o&&this.options.unpairedTags.indexOf(o)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${o}>`);let c=0;s&&this.options.unpairedTags.indexOf(s)!==-1?(c=i.lastIndexOf(`.`,i.lastIndexOf(`.`)-1),this.tagsNodeStack.pop()):c=i.lastIndexOf(`.`),i=i.substring(0,c),n=this.tagsNodeStack.pop(),r=``,a=t}else if(e[a+1]===`?`){let t=Qs(e,a,!1,`?>`);if(!t)throw Error(`Pi Tag is not closed.`);if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&t.tagName===`?xml`||this.options.ignorePiTags)){let e=new xs(t.tagName);e.add(this.options.textNodeName,``),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[`:@`]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(n,e,i,a)}a=t.closeIndex+1}else if(e.substr(a+1,3)===`!--`){let t=Zs(e,`-->`,a+4,`Comment is not closed.`);if(this.options.commentPropName){let o=e.substring(a+4,t-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}a=t}else if(e.substr(a+1,2)===`!D`){let t=Ss(e,a);this.docTypeEntities=t.entities,a=t.i}else if(e.substr(a+1,2)===`![`){let t=Zs(e,`]]>`,a,`CDATA is not closed.`)-2,o=e.substring(a+9,t);r=this.saveTextToParentTag(r,n,i);let s=this.parseTextData(o,n.tagname,i,!0,!1,!0,!0);s??=``,this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):n.add(this.options.textNodeName,s),a=t+2}else{let o=Qs(e,a,this.options.removeNSPrefix),s=o.tagName,c=o.rawTagName,l=o.tagExp,u=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(s=this.options.transformTagName(s)),n&&r&&n.tagname!==`!xml`&&(r=this.saveTextToParentTag(r,n,i,!1));let f=n;f&&this.options.unpairedTags.indexOf(f.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf(`.`))),s!==t.tagname&&(i+=i?`.`+s:s);let p=a;if(this.isItStopNode(this.options.stopNodes,i,s)){let t=``;if(l.length>0&&l.lastIndexOf(`/`)===l.length-1)s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),a=o.closeIndex;else if(this.options.unpairedTags.indexOf(s)!==-1)a=o.closeIndex;else{let n=this.readStopNodeData(e,c,d+1);if(!n)throw Error(`Unexpected end of ${c}`);a=n.i,t=n.tagContent}let r=new xs(s);s!==l&&u&&(r[`:@`]=this.buildAttributesMap(l,i,s)),t&&=this.parseTextData(t,s,i,!0,u,!0,!0),i=i.substr(0,i.lastIndexOf(`.`)),r.add(this.options.textNodeName,t),this.addChild(n,r,i,p)}else{if(l.length>0&&l.lastIndexOf(`/`)===l.length-1){s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),this.options.transformTagName&&(s=this.options.transformTagName(s));let e=new xs(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`))}else{let e=new xs(s);this.tagsNodeStack.push(n),s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),n=e}r=``,a=d}}else r+=e[a]}return t.child};function Ks(e,t,n,r){this.options.captureMetaData||(r=void 0);let i=this.options.updateTag(t.tagname,n,t[`:@`]);i===!1||(typeof i==`string`&&(t.tagname=i),e.addChild(t,r))}const qs=function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){let n=this.docTypeEntities[t];e=e.replace(n.regx,n.val)}for(let t in this.lastEntities){let n=this.lastEntities[t];e=e.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){let n=this.htmlEntities[t];e=e.replace(n.regex,n.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function Js(e,t,n,r){return e&&(r===void 0&&(r=t.child.length===0),e=this.parseTextData(e,t.tagname,n,!1,t[`:@`]?Object.keys(t[`:@`]).length!==0:!1,r),e!==void 0&&e!==``&&t.add(this.options.textNodeName,e),e=``),e}function Ys(e,t,n){let r=`*.`+n;for(let n in e){let i=e[n];if(r===i||t===i)return!0}return!1}function Xs(e,t,n=`>`){let r,i=``;for(let a=t;a<e.length;a++){let t=e[a];if(r)t===r&&(r=``);else if(t===`"`||t===`'`)r=t;else if(t===n[0])if(n[1]){if(e[a+1]===n[1])return{data:i,index:a}}else return{data:i,index:a};else t===` `&&(t=` `);i+=t}}function Zs(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function Qs(e,t,n,r=`>`){let i=Xs(e,t+1,r);if(!i)return;let a=i.data,o=i.index,s=a.search(/\s/),c=a,l=!0;s!==-1&&(c=a.substring(0,s),a=a.substring(s+1).trimStart());let u=c;if(n){let e=c.indexOf(`:`);e!==-1&&(c=c.substr(e+1),l=c!==i.data.substr(e+1))}return{tagName:c,tagExp:a,closeIndex:o,attrExpPresent:l,rawTagName:u}}function $s(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=Zs(e,`>`,n,`${t} is not closed`),o=e.substring(n+2,a).trim();if(o===t&&(i--,i===0))return{tagContent:e.substring(r,n),i:a};n=a}else if(e[n+1]===`?`){let t=Zs(e,`?>`,n+1,`StopNode is not closed.`);n=t}else if(e.substr(n+1,3)===`!--`){let t=Zs(e,`-->`,n+3,`StopNode is not closed.`);n=t}else if(e.substr(n+1,2)===`![`){let t=Zs(e,`]]>`,n,`StopNode is not closed.`)-2;n=t}else{let r=Qs(e,n,`>`);if(r){let e=r&&r.tagName;e===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex}}}function ec(e,t,n){if(t&&typeof e==`string`){let t=e.trim();return t===`true`?!0:t===`false`?!1:Ns(e,n)}else if(es(e))return e;else return``}const tc=xs.getMetaDataSymbol();function nc(e,t){return rc(e,t)}function rc(e,t,n){let r,i={};for(let a=0;a<e.length;a++){let o=e[a],s=ic(o),c=``;if(c=n===void 0?s:n+`.`+s,s===t.textNodeName)r===void 0?r=o[s]:r+=``+o[s];else if(s===void 0)continue;else if(o[s]){let e=rc(o[s],t,c),n=oc(e,t);o[tc]!==void 0&&(e[tc]=o[tc]),o[`:@`]?ac(e,o[`:@`],c,t):Object.keys(e).length===1&&e[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?e=e[t.textNodeName]:Object.keys(e).length===0&&(t.alwaysCreateTextNode?e[t.textNodeName]=``:e=``),i[s]!==void 0&&i.hasOwnProperty(s)?(Array.isArray(i[s])||(i[s]=[i[s]]),i[s].push(e)):t.isArray(s,c,n)?i[s]=[e]:i[s]=e}}return typeof r==`string`?r.length>0&&(i[t.textNodeName]=r):r!==void 0&&(i[t.textNodeName]=r),i}function ic(e){let t=Object.keys(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==`:@`)return n}}function ac(e,t,n,r){if(t){let i=Object.keys(t),a=i.length;for(let o=0;o<a;o++){let a=i[o];r.isArray(a,n+`.`+a,!0,!0)?e[a]=[t[a]]:e[a]=t[a]}}}function oc(e,t){let{textNodeName:n}=t,r=Object.keys(e).length;return!!(r===0||r===1&&(e[n]||typeof e[n]==`boolean`||e[n]===0))}var sc=class{constructor(e){this.externalEntities={},this.options=ys(e)}parse(e,t){if(typeof e!=`string`)if(e.toString)e=e.toString();else throw Error(`XML data is accepted in String or Bytes[] form.`);if(t){t===!0&&(t={});let n=ns(e,t);if(n!==!0)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}let n=new zs(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(e);return this.options.preserveOrder||r===void 0?r:nc(r,this.options)}addEntity(e,t){if(t.indexOf(`&`)!==-1)throw Error(`Entity value can't have '&'`);if(e.indexOf(`&`)!==-1||e.indexOf(`;`)!==-1)throw Error(`An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'`);if(t===`&`)throw Error(`An entity with value '&' is not permitted`);this.externalEntities[e]=t}static getMetaDataSymbol(){return xs.getMetaDataSymbol()}};const cc=`
193
193
  `;function lc(e,t){let n=``;return t.format&&t.indentBy.length>0&&(n=cc),uc(e,t,``,n)}function uc(e,t,n,r){let i=``,a=!1;for(let o=0;o<e.length;o++){let s=e[o],c=dc(s);if(c===void 0)continue;let l=``;if(l=n.length===0?c:`${n}.${c}`,c===t.textNodeName){let e=s[c];pc(l,t)||(e=t.tagValueProcessor(c,e),e=mc(e,t)),a&&(i+=r),i+=e,a=!1;continue}else if(c===t.cdataPropName){a&&(i+=r),i+=`<![CDATA[${s[c][0][t.textNodeName]}]]>`,a=!1;continue}else if(c===t.commentPropName){i+=r+`<!--${s[c][0][t.textNodeName]}-->`,a=!0;continue}else if(c[0]===`?`){let e=fc(s[`:@`],t),n=c===`?xml`?``:r,o=s[c][0][t.textNodeName];o=o.length===0?``:` `+o,i+=n+`<${c}${o}${e}?>`,a=!0;continue}let u=r;u!==``&&(u+=t.indentBy);let d=fc(s[`:@`],t),f=r+`<${c}${d}`,p=uc(s[c],t,l,u);t.unpairedTags.indexOf(c)===-1?(!p||p.length===0)&&t.suppressEmptyNode?i+=f+`/>`:p&&p.endsWith(`>`)?i+=f+`>${p}${r}</${c}>`:(i+=f+`>`,p&&r!==``&&(p.includes(`/>`)||p.includes(`</`))?i+=r+t.indentBy+p+r:i+=p,i+=`</${c}>`):t.suppressUnpairedNode?i+=f+`>`:i+=f+`/>`,a=!0}return i}function dc(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];if(e.hasOwnProperty(r)&&r!==`:@`)return r}}function fc(e,t){let n=``;if(e&&!t.ignoreAttributes)for(let r in e){if(!e.hasOwnProperty(r))continue;let i=t.attributeValueProcessor(r,e[r]);i=mc(i,t),i===!0&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function pc(e,t){e=e.substr(0,e.length-t.textNodeName.length-1);let n=e.substr(e.lastIndexOf(`.`)+1);for(let r in t.stopNodes)if(t.stopNodes[r]===e||t.stopNodes[r]===`*.`+n)return!0;return!1}function mc(e,t){if(e&&e.length>0&&t.processEntities)for(let n=0;n<t.entities.length;n++){let r=t.entities[n];e=e.replace(r.regex,r.val)}return e}const hc={attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:` `,suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:RegExp(`&`,`g`),val:`&amp;`},{regex:RegExp(`>`,`g`),val:`&gt;`},{regex:RegExp(`<`,`g`),val:`&lt;`},{regex:RegExp(`'`,`g`),val:`&apos;`},{regex:RegExp(`"`,`g`),val:`&quot;`}],processEntities:!0,stopNodes:[],oneListGroup:!1};function gc(e){this.options=Object.assign({},hc,e),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Rs(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=yc),this.processTextOrObjNode=_c,this.options.format?(this.indentate=vc,this.tagEndChar=`>
194
194
  `,this.newLine=`
195
- `):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}gc.prototype.build=function(e){return this.options.preserveOrder?lc(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},gc.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n)}return{attrStr:r,val:i}},gc.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`};function _c(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}gc.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),(n||n===``)&&e.indexOf(`<`)===-1?this.indentate(r)+`<`+t+n+a+`>`+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i}},gc.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},gc.prototype.buildTextValNode=function(e,t,n,r){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},gc.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function vc(e){return this.options.indentBy.repeat(e)}function yc(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}const bc={validate:ns},xc=`@_`;var Sc=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:s}){let c;if(c=typeof s?.envelope==`string`?s.envelope:typeof s?.envelope==`object`?Cc.build(s.envelope):await Tc(a,s),bc.validate(c,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let u,d={...r,"Content-Type":`text/xml`};s?.soapAction&&(d.SOAPAction=s.soapAction);try{u=await e?.request({method:n,url:t,headers:d,queryParams:i,maxRedirects:0,payload:c,requestConfig:s})}catch(e){if((0,l.isMissing)(e?.response))throw e;u=e.response}let f=wc.parse(u.data),p=f.Envelope||f,m=p.Body||p,h=m.Fault;if(h)throw new Je({...u,status:500,data:h,message:h.faultstring??h.faultcode??`SOAP Fault`},h.faultstring??`SOAP Fault occurred`);u.data=m;let g=Uo(u,o);if(Go(g?.status))throw new Je(g,g.message);return g}};const Cc=new gc({attributeNamePrefix:xc,ignoreAttributes:!1,suppressBooleanAttributes:!1}),wc=new sc({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),Tc=async(e,t)=>{if((0,l.notMissing)(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Cc.build(t.envelope),n=bc.validate(e,{allowBooleanAttributes:!0});if(n!==!0)throw Error(`Invalid XML envelope`);return e}let n=await Ec(t,e),r=Cc.build(n),i=bc.validate(r,{allowBooleanAttributes:!0});if(i!==!0)throw Error(`Invalid XML envelope`);return r},Ec=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await(0,v.evaluate)(e.namespaceIdentifier),namespace:await(0,v.evaluate)(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if((0,l.isMissing)(e)||(0,l.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 Dc(t,e??{}),"soapenv:Body":await kc(t,e?.operation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},Dc=async(e,t)=>[await Oc(e,t)],Oc=async(e,t)=>{if((0,l.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`}}},kc=async(e,t,n)=>{if((0,l.isMissing)(t))throw Error(`Missing soapOperation in config`);return[Ac({[t]:e},n)]},Ac=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>Ac(e,t));let n={};for(let r in e){let i=jc(r,t);n[i]=Ac(e[r],t)}return n},jc=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(xc)?`${xc}${t}:${e.slice(2)}`:`${t}:${e}`};var Mc=class{static build(e=`rest`){if(e===`rest`)return new qo;if(e===`soap`)return new Sc;throw Error(`Unknown request client type: ${e}`)}};exports.CUSTOM_ERROR_CONFIG_SCHEMA=Ke,exports.ConcurrencyManager=Ge,exports.EventClient=le,exports.HttpClient=jo,exports.HttpClientManager=No,exports.HttpErrorMessages=qe,exports.HttpMethods=Po,exports.HttpResponseError=Je,exports.HttpTransportFactory=Qe,exports.InstanceManager=et,exports.LockManager=S,exports.MemoryStore=ae,exports.QueueManager=A,exports.RateLimitManager=To,exports.RedisClient=fe,exports.RequestClientFactory=Mc,exports.RequestParameterLocations=Ho,exports.ScriptManager=ge,exports.SubscriptionManager=_e,exports.buildHttpClientInstance=Mo,exports.createAuthorizationHeaders=y,exports.getTransportInstance=Do,exports.getTransportManagers=Bo,exports.initializeTransportSystem=Lo,exports.isFailedStatusCode=Go,exports.isInfoStatusCode=Ko,exports.isSuccessStatusCode=Wo,exports.isTransportSystemReady=zo,exports.parseRequestParameters=Vo,exports.serializeHttpResponseError=Ze,exports.shutdownTransportSystem=Ro;
195
+ `):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}gc.prototype.build=function(e){return this.options.preserveOrder?lc(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},gc.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n)}return{attrStr:r,val:i}},gc.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`};function _c(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}gc.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),(n||n===``)&&e.indexOf(`<`)===-1?this.indentate(r)+`<`+t+n+a+`>`+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i}},gc.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},gc.prototype.buildTextValNode=function(e,t,n,r){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},gc.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function vc(e){return this.options.indentBy.repeat(e)}function yc(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}const bc={validate:ns},xc=`@_`;var Sc=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:s}){let c;if(c=typeof s?.envelope==`string`?s.envelope:typeof s?.envelope==`object`?Cc.build(s.envelope):await Tc(a,s),bc.validate(c,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let u,d={...r,"Content-Type":`text/xml`};s?.soapAction&&(d.SOAPAction=s.soapAction);try{u=await e?.request({method:n,url:t,headers:d,queryParams:i,maxRedirects:0,payload:c,requestConfig:s})}catch(e){if((0,l.isMissing)(e?.response))throw e;u=e.response}let f=wc.parse(u.data),p=f.Envelope||f,m=p.Body||p,h=m.Fault;if(h)throw new Je({...u,status:500,data:h,message:h.faultstring??h.faultcode??`SOAP Fault`},h.faultstring??`SOAP Fault occurred`);u.data=m;let g=Uo(u,o);if(Go(g?.status))throw new Je(g,g.message);return g}};const Cc=new gc({attributeNamePrefix:xc,ignoreAttributes:!1,suppressBooleanAttributes:!1}),wc=new sc({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),Tc=async(e,t)=>{if((0,l.notMissing)(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Cc.build(t.envelope),n=bc.validate(e,{allowBooleanAttributes:!0});if(n!==!0)throw Error(`Invalid XML envelope`);return e}let n=await Ec(t,e),r=Cc.build(n),i=bc.validate(r,{allowBooleanAttributes:!0});if(i!==!0)throw Error(`Invalid XML envelope`);return r},Ec=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await(0,v.evaluate)(e.namespaceIdentifier),namespace:await(0,v.evaluate)(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if((0,l.isMissing)(e)||(0,l.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 Dc(t,e??{}),"soapenv:Body":await kc(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},Dc=async(e,t)=>[await Oc(e,t)],Oc=async(e,t)=>{if((0,l.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`}}},kc=async(e,t,n)=>{if((0,l.isMissing)(t))throw Error(`Missing soapOperation in config`);let r=Ac({[t]:e}),i=Array.isArray(r)?r:[r];return i.map(e=>jc(e,n))},Ac=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),n=e.filter(e=>!e.startsWith(xc));if(n.length===1){let e=n[0],r=t[e];if(typeof r==`object`&&r&&!Array.isArray(r)){let t=Object.keys(r),n=t.filter(e=>e.startsWith(xc)),i=t.filter(e=>!e.startsWith(xc)),a=n.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let t=r[a],i=n.filter(e=>e!==a),o=t.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[e]:o}}}}}}return e.map(e=>Ac(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=Ac(r)}return t},jc=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>jc(e,t));let n={};for(let r in e){let i=Mc(r,t);n[i]=jc(e[r],t)}return n},Mc=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(xc)?`${xc}${t}:${e.slice(2)}`:`${t}:${e}`};var Nc=class{static build(e=`rest`){if(e===`rest`)return new qo;if(e===`soap`)return new Sc;throw Error(`Unknown request client type: ${e}`)}};exports.CUSTOM_ERROR_CONFIG_SCHEMA=Ke,exports.ConcurrencyManager=Ge,exports.EventClient=le,exports.HttpClient=jo,exports.HttpClientManager=No,exports.HttpErrorMessages=qe,exports.HttpMethods=Po,exports.HttpResponseError=Je,exports.HttpTransportFactory=Qe,exports.InstanceManager=et,exports.LockManager=S,exports.MemoryStore=ae,exports.QueueManager=A,exports.RateLimitManager=To,exports.RedisClient=fe,exports.RequestClientFactory=Nc,exports.RequestParameterLocations=Ho,exports.ScriptManager=ge,exports.SubscriptionManager=_e,exports.buildHttpClientInstance=Mo,exports.createAuthorizationHeaders=y,exports.getTransportInstance=Do,exports.getTransportManagers=Bo,exports.initializeTransportSystem=Lo,exports.isFailedStatusCode=Go,exports.isInfoStatusCode=Ko,exports.isSuccessStatusCode=Wo,exports.isTransportSystemReady=zo,exports.parseRequestParameters=Vo,exports.serializeHttpResponseError=Ze,exports.shutdownTransportSystem=Ro;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{delay as e,exponentialBackoffInMS as t,generateRequestId as n,getContentHash as r,isFunction as i,isFutureUnixTimestamp as a,isMissing as o,isNumber as s,isObject as c,isString as l,notMissing as u,z as d,zStrictObject as f}from"@stackone/utils";import*as p from"redis";import m,{isAxiosError as h}from"axios";import g from"node:https";import{randomUUID as _}from"crypto";import{clearTimeout as v}from"node:timers";import y from"jsonpath";import{redactUrl as b}from"@stackone/redaction";import x from"qs";import{evaluate as S,safeEvaluate as ee}from"@stackone/expressions";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,te=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,D=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),O=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=E(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ne.call(e,s)&&s!==n&&w(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=T(t,s))||r.enumerable});return e},k=(e,t,n)=>(n=e==null?{}:C(te(e)),O(t||!e||!e.__esModule?w(n,`default`,{value:e,enumerable:!0}):n,e));const re=e=>{switch(e.type){case`none`:return{};case`basic`:return ie(e);case`bearer`:return ae(e);case`oauth2`:return ae(e);default:throw Error(`Invalid authentication type`)}},ie=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},ae=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var oe=class{locks;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);if(r&&i){i.push({lock:n,unlock:t});let e=i.length-2;await i[e].lock}else 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 se=1e3,ce=100,le=60,ue=6e4,de=le,fe=ue,pe=ue*10,me=ce,he=10;let ge=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var _e=class{config;instantiator;dataStore;lockManager;expiryMap;evictionFrequency;staleDataThreshold;truncateThreshold;truncationPercentage;logger;typeGuard;dispose;evictionInterval;lastAccessedAt=Date.now();constructor(e={}){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 oe,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??fe,this.staleDataThreshold=e?.staleDataThreshold??pe,this.truncateThreshold=e?.truncateThreshold??me,this.truncationPercentage=e?.truncationPercentage??he,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 setData({key:e,value:t,cacheTTL:n=de}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),u(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*se,i=Date.now()+r;return await this.lockManager.withLock(e,async()=>{(u(this.typeGuard)&&this.typeGuard(t)||o(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,i)}),!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){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)}return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/ce;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n);let i=this.dataStore.size;return{dataStoreSize:e,prunedDataStoreSize:i}}startEvictionTask(){if(u(this.evictionInterval))return;let e=async()=>{let t;try{let n=this.lastAccessedAt+this.staleDataThreshold,r=Date.now();if(n<r){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),this.close();return}t=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(e,this.evictionFrequency)}catch(t){t instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:t,code:ge.MemoryStorePruneError}),this.evictionInterval=setTimeout(e,this.evictionFrequency)}finally{if(u(t?.dataStoreSize)&&u(t?.prunedDataStoreSize)){let{dataStoreSize:e,prunedDataStoreSize:n}=t,r=e-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(e,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&(clearTimeout(this.evictionInterval),this.evictionInterval=void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return u(this.evictionInterval)&&u(this.dataStore)&&u(this.expiryMap)&&u(this.lockManager)}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()),i=r.filter(t=>t.includes(e)),a=[],o=t?parseInt(t,10):0;for(let e=o;e<n+o;e++){let t=i[e];if(!t)break;let r=await this.getData(t);if(r&&a.push(r),a.length>=n)break}return{items:a,cursor:a.length<n?void 0:(o+n).toString()}}};const ve=1e3,ye=6e4;let be=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var xe=class{executorMethodStore=null;promiseStore=null;logger;eventClientConfig=null;executorMethodStoreConfig=null;pendingPromiseStoreConfig=null;constructor(e,t,n){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 _e(i),this.promiseStore=new _e(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/ve;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 u(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);o(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??ye),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:be.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){u(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):u(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return c(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},Se=class{instance=null;initPromise=null;retryTimeout=null;status=`uninitialized`;initOptions=null;initArgs=[];getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(o(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,o(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}};let A=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const Ce=async(e,t,n)=>{try{let r=await we.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:A.RedisClientError,category:n??`buildRedisClientInstance`});return}};var we=class e{#redisClient;#logger;static async build({getRedisClient:t=p.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s,c){let l=new e;l.#logger=s;try{l.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let e=Ee(c??`RedisClient`,l.#logger);return Te(l.#redisClient,e),await l.#redisClient.connect(),l}catch(e){let t=e;return l.#logger?.error({message:`Error building Cache Manager.`,error:t,code:A.RedisClientError,category:c??`RedisClient`}),null}}#parseData(e){try{return JSON.parse(e)}catch{return e}}async getData(t){if(!this.#isRedisClientAvailable())return null;try{let e=await this.#redisClient.get(t);if(!e)return null;let n=this.#parseData(e);return l(n)?e:n}catch(t){let n=t;return this.#logger?.error({message:`Error getting data`,error:n,code:A.RedisClientReadError,category:e.name}),null}}async setData({key:t,value:n,cacheTTL:r,groupKey:i}){if(!this.#isRedisClientAvailable())return!1;try{let e=l(n)?n:JSON.stringify(n);return await this.#redisClient.set(t,e,{EX:r}),u(i)&&await this.#redisClient.sAdd(i,[t]),!0}catch(t){let n=t;return this.#logger?.error({message:`Error setting data`,error:n,code:A.RedisClientWriteError,category:e.name}),!1}}async executeScript({sha1:t,keys:n,args:r}){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.evalSha(t,{keys:n,arguments:r})}catch(t){let n=t;return this.#logger?.error({message:`Error executing script`,error:n,code:A.RedisClientScriptExecuteError,category:e.name}),null}}async loadScript(t){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.scriptLoad(t)}catch(t){let n=t;return this.#logger?.error({message:`Error loading script`,error:n,code:A.RedisClientScriptLoadError,category:e.name}),null}}async#executeCounterCommand(t,n,r){if(!this.#isRedisClientAvailable())return null;if(!Number.isFinite(r)||r<=0)return this.#logger?.error({message:`Invalid cacheTTL parameter`,category:e.name,code:A.RedisClientInvalidTTL}),null;try{let e=[{args:[t,n]},{args:[`expire`,n,r.toString()]}],i=await this.#redisClient.multiExecutor(e),a=i?.[0];return typeof a==`number`?a:null}catch(n){let r=n;return this.#logger?.error({message:`Error executing ${t} operation`,error:r,code:A.RedisClientCommandError,category:e.name}),null}}async increment(e,t){return this.#executeCounterCommand(`incr`,e,t)}async decrement(e,t){return this.#executeCounterCommand(`decr`,e,t)}async subscribe(t,n){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pSubscribe(t,n),!0}catch(n){let r=n;return this.#logger?.error({message:`Error subscribing to ${t}`,error:r,code:A.RedisClientSubscribeError,category:e.name}),!1}}async unsubscribe(t){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pUnsubscribe(t),!0}catch(n){let r=n;return this.#logger?.error({message:`Error unsubscribing from ${t}`,error:r,code:A.RedisClientUnsubscribeError,category:e.name}),!1}}async publish(t,n){if(!this.#isRedisClientAvailable())return null;try{let r=await this.#redisClient.publish(t,n);return r===0&&this.#logger?.debug({message:`No subscribers found for channel ${t}`,category:e.name}),r}catch(n){let r=n;return this.#logger?.error({message:`Error publishing to ${t}`,error:r,code:A.RedisClientPublishError,category:e.name}),null}}getClient(){return this.#isRedisClientAvailable()?this.#redisClient:null}#isRedisClientAvailable(){let t=this.#redisClient.isReady&&this.#redisClient.isOpen;return t||this.#logger?.error({message:`Redis Client is not ready.`,category:e.name,code:A.RedisClientRedisNotReady}),t}async listData({partialKey:t,limit:n,cursor:r}){try{let e=r?parseInt(r,10):0,i=await this.#redisClient.sScan(t,e,{COUNT:n}),a=[];for(let e of i.members){let t=await this.getData(e);u(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(t){let n=t;return this.#logger?.error({message:`Error listing data`,error:n,code:A.RedisClientListError,category:e.name}),{items:null}}}async deleteData(t){try{if(!this.#isRedisClientAvailable())return!1;let n=await this.#redisClient.del(t);return n===0&&this.#logger?.debug({message:`No keys deleted for ${t}`,category:e.name}),n>0}catch(t){let n=t;return this.#logger?.error({message:`Error deleting data`,error:n,code:A.RedisClientDeleteError,category:e.name}),!1}}};const Te=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},Ee=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:A.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})}}];let De=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var Oe=class extends Se{redisClientConfig;scripts;scriptMap;cacheClient;logger;additionalArgs;isInitialConnection=!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 Ce(e,i,this.name);if(o(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?.();u(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(){o(this.scripts)||Object.keys(this.scripts).length===0||(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))}async loadScripts(e,t){if(u(t))for(let[e,n]of t)this.scriptMap.set(e,n);for(let[t,n]of Object.entries(e)){let e=await this.cacheClient?.loadScript?.(n);u(e)?this.scriptMap?.set(t,e):this.logger?.error({message:`Error loading script ${t}`,category:this.name,code:De.ScriptManagerLoadingError})}}async executeScript(e,t,n){try{if(!this.isRedisReady())throw Error(`Redis client is not ready`);let r=this.scriptMap?.get(e);if(o(r))throw 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`)){if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),o(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i}}catch(r){throw r instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${r.message}`,category:this.name,context:{keys:t,args:n},error:r,code:De.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&u(this.cacheClient)}},ke=class{options={getCacheClient:Ce};subscriptionMap=null;subscriptionClient=null;logger;name=`SubscriptionManager`;constructor(e){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 _e({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)}}),u(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),i=r(t.toString());return await this.subscriptionMap?.setData({key:e,value:i}),n===i?!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 u(this.subscriptionClient)&&u(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const Ae=6e4,je=15e3,Me=!1,Ne=6e4,Pe=15e3,Fe=1e4,Ie=1;let Le=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),Re=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var ze=class extends Oe{subscriptionManager=null;eventClient=null;name=`QueueManager`;async additionalInitialization(){if(o(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new ke({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:Ne,truncateThreshold:Fe,truncationPercentage:Ie}),await this.subscriptionManager?.initialize(),this.eventClient=new xe({instantiator:this.name,timeoutResolveValue:Me},{instantiator:this.name,evictionFrequency:Pe,truncateThreshold:Fe,truncationPercentage:Ie},{instantiator:this.name,evictionFrequency:Pe,truncateThreshold:Fe,truncationPercentage:Ie}),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?Re.lPush:Re.rPush,[e],[t,Ae.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,je),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:Le.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(Re.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Le.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(Re.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Le.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return u(this.subscriptionManager)&&u(this.cacheClient)&&u(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const Be=5,Ve=12e4,He=1e4,Ue=1,We=60,Ge=90,Ke=`__keyevent@0__:`,qe=`${Ke}set`,Je=`${Ke}expire`,Ye=`${Ke}expired`,Xe=`${Ke}srem`,Ze=`config_check_test_key`,Qe=[qe,Je,Ye],$e=1,et=15e3,tt={mainMaxConcurrency:30};let nt=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),rt=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const it={[rt.tryConcurrency]:`
1
+ import{delay as e,exponentialBackoffInMS as t,generateRequestId as n,getContentHash as r,isFunction as i,isFutureUnixTimestamp as a,isMissing as o,isNumber as s,isObject as c,isString as l,notMissing as u,z as d,zStrictObject as f}from"@stackone/utils";import*as p from"redis";import m,{isAxiosError as h}from"axios";import g from"node:https";import{randomUUID as _}from"crypto";import{clearTimeout as v}from"node:timers";import y from"jsonpath";import{redactUrl as b}from"@stackone/redaction";import x from"qs";import{evaluate as S,safeEvaluate as ee}from"@stackone/expressions";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,te=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,D=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),O=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=E(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ne.call(e,s)&&s!==n&&w(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=T(t,s))||r.enumerable});return e},k=(e,t,n)=>(n=e==null?{}:C(te(e)),O(t||!e||!e.__esModule?w(n,`default`,{value:e,enumerable:!0}):n,e));const re=e=>{switch(e.type){case`none`:return{};case`basic`:return ie(e);case`bearer`:return ae(e);case`oauth2`:return ae(e);default:throw Error(`Invalid authentication type`)}},ie=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},ae=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var oe=class{locks;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);if(r&&i){i.push({lock:n,unlock:t});let e=i.length-2;await i[e].lock}else 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 se=1e3,ce=100,le=60,ue=6e4,de=le,fe=ue,pe=ue*10,me=ce,he=10;let ge=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var _e=class{config;instantiator;dataStore;lockManager;expiryMap;evictionFrequency;staleDataThreshold;truncateThreshold;truncationPercentage;logger;typeGuard;dispose;evictionInterval;lastAccessedAt=Date.now();constructor(e={}){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 oe,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??fe,this.staleDataThreshold=e?.staleDataThreshold??pe,this.truncateThreshold=e?.truncateThreshold??me,this.truncationPercentage=e?.truncationPercentage??he,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 setData({key:e,value:t,cacheTTL:n=de}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),u(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*se,i=Date.now()+r;return await this.lockManager.withLock(e,async()=>{(u(this.typeGuard)&&this.typeGuard(t)||o(this.typeGuard)&&this.typeGuardBypass(t))&&this.dataStore.set(e,t),this.expiryMap.set(e,i)}),!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){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)}return this.dataStore.delete(e)})}async pruneExpiredKeys(){let e=this.dataStore.size,t=e>=this.truncateThreshold;if(e<=0)return;let n=[],r=0;this.dataStore.forEach(async(e,i)=>{let a=Date.now(),o=this.expiryMap.get(i)??0,s=this.truncateThreshold*this.truncationPercentage/ce;(o<=a||t&&r>=0&&r<=s)&&n.push(this.lockManager.withLock(i,async()=>(this.dispose&&await this.dispose(i,e),this.dataStore.delete(i)))),r++}),await Promise.all(n);let i=this.dataStore.size;return{dataStoreSize:e,prunedDataStoreSize:i}}startEvictionTask(){if(u(this.evictionInterval))return;let e=async()=>{let t;try{let n=this.lastAccessedAt+this.staleDataThreshold,r=Date.now();if(n<r){this.logger?.warning({message:`Closing the ${this.instantiator}'s MemoryStore instance - received no requests for a while.`,category:`MemoryStore`}),this.close();return}t=await this.pruneExpiredKeys(),this.evictionInterval=setTimeout(e,this.evictionFrequency)}catch(t){t instanceof Error&&this.logger?.error({message:`Error during pruning expired keys:`,category:`MemoryStore`,error:t,code:ge.MemoryStorePruneError}),this.evictionInterval=setTimeout(e,this.evictionFrequency)}finally{if(u(t?.dataStoreSize)&&u(t?.prunedDataStoreSize)){let{dataStoreSize:e,prunedDataStoreSize:n}=t,r=e-n;this.logger?.debug({message:`Pruned ${r} expired keys, ${n} remain, scheduling next prune.`,category:`MemoryStore`,context:{instantiator:this.instantiator}})}}};this.evictionInterval=setTimeout(e,this.evictionFrequency)}stopEvictionTask(){this.evictionInterval&&(clearTimeout(this.evictionInterval),this.evictionInterval=void 0)}updateLastAccessedAt(){this.lastAccessedAt=Date.now()}isReady(){return u(this.evictionInterval)&&u(this.dataStore)&&u(this.expiryMap)&&u(this.lockManager)}close(){this.stopEvictionTask(),this.dataStore.clear(),this.expiryMap.clear(),this.lockManager.close()}async listData({partialKey:e,cursor:t,limit:n}){let r=Array.from(this.dataStore.keys()),i=r.filter(t=>t.includes(e)),a=[],o=t?parseInt(t,10):0;for(let e=o;e<n+o;e++){let t=i[e];if(!t)break;let r=await this.getData(t);if(r&&a.push(r),a.length>=n)break}return{items:a,cursor:a.length<n?void 0:(o+n).toString()}}};const ve=1e3,ye=6e4;let be=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var xe=class{executorMethodStore=null;promiseStore=null;logger;eventClientConfig=null;executorMethodStoreConfig=null;pendingPromiseStoreConfig=null;constructor(e,t,n){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 _e(i),this.promiseStore=new _e(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/ve;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 u(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);o(n)&&(await this.setPendingEvent(e,this.eventClientConfig?.defaultTimeoutMS??ye),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:be.EventClientResolveError})}}async defaultExecutorMethodDispose(e,t){u(t?.resolve)?t.resolve(this.eventClientConfig?.timeoutResolveValue):u(t?.reject)&&t.reject(Error(`Event key: ${e} was not resolved or the event was disposed`))}defaultExecutorMethodTypeGuard(e){return c(e)&&e.hasOwnProperty(`resolve`)&&e.hasOwnProperty(`reject`)}async defaultPendingPromiseDispose(e,t){t instanceof Promise&&t?.finally(()=>{})}defaultPendingPromiseTypeGuard(e){return e instanceof Promise}},Se=class{instance=null;initPromise=null;retryTimeout=null;status=`uninitialized`;initOptions=null;initArgs=[];getRetryDelay(){return 5e3}getSingleton(e){throw Error(`getSingleton method not implemented`)}async getInstance(e,...t){return this.instance?this.instance:(o(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,o(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}};let A=function(e){return e.RedisClientError=`RedisClientError`,e.RedisClientCommandError=`RedisClientCommandError`,e.RedisClientDeleteError=`RedisClientDeleteError`,e.RedisClientInvalidTTL=`RedisClientInvalidTTL`,e.RedisClientListError=`RedisClientListError`,e.RedisClientNotInitialized=`RedisClientNotInitialized`,e.RedisClientPublishError=`RedisClientPublishError`,e.RedisClientReadError=`RedisClientReadError`,e.RedisClientRedisNotReady=`RedisClientRedisNotReady`,e.RedisClientScriptError=`RedisClientScriptError`,e.RedisClientScriptExecuteError=`RedisClientScriptExecuteError`,e.RedisClientScriptLoadError=`RedisClientScriptLoadError`,e.RedisClientSubscribeError=`RedisClientSubscribeError`,e.RedisClientUnsubscribeError=`RedisClientUnsubscribeError`,e.RedisClientWriteError=`RedisClientWriteError`,e}({});const Ce=async(e,t,n)=>{try{let r=await we.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:A.RedisClientError,category:n??`buildRedisClientInstance`});return}};var we=class e{#redisClient;#logger;static async build({getRedisClient:t=p.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s,c){let l=new e;l.#logger=s;try{l.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let e=Ee(c??`RedisClient`,l.#logger);return Te(l.#redisClient,e),await l.#redisClient.connect(),l}catch(e){let t=e;return l.#logger?.error({message:`Error building Cache Manager.`,error:t,code:A.RedisClientError,category:c??`RedisClient`}),null}}#parseData(e){try{return JSON.parse(e)}catch{return e}}async getData(t){if(!this.#isRedisClientAvailable())return null;try{let e=await this.#redisClient.get(t);if(!e)return null;let n=this.#parseData(e);return l(n)?e:n}catch(t){let n=t;return this.#logger?.error({message:`Error getting data`,error:n,code:A.RedisClientReadError,category:e.name}),null}}async setData({key:t,value:n,cacheTTL:r,groupKey:i}){if(!this.#isRedisClientAvailable())return!1;try{let e=l(n)?n:JSON.stringify(n);return await this.#redisClient.set(t,e,{EX:r}),u(i)&&await this.#redisClient.sAdd(i,[t]),!0}catch(t){let n=t;return this.#logger?.error({message:`Error setting data`,error:n,code:A.RedisClientWriteError,category:e.name}),!1}}async executeScript({sha1:t,keys:n,args:r}){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.evalSha(t,{keys:n,arguments:r})}catch(t){let n=t;return this.#logger?.error({message:`Error executing script`,error:n,code:A.RedisClientScriptExecuteError,category:e.name}),null}}async loadScript(t){if(!this.#isRedisClientAvailable())return null;try{return await this.#redisClient.scriptLoad(t)}catch(t){let n=t;return this.#logger?.error({message:`Error loading script`,error:n,code:A.RedisClientScriptLoadError,category:e.name}),null}}async#executeCounterCommand(t,n,r){if(!this.#isRedisClientAvailable())return null;if(!Number.isFinite(r)||r<=0)return this.#logger?.error({message:`Invalid cacheTTL parameter`,category:e.name,code:A.RedisClientInvalidTTL}),null;try{let e=[{args:[t,n]},{args:[`expire`,n,r.toString()]}],i=await this.#redisClient.multiExecutor(e),a=i?.[0];return typeof a==`number`?a:null}catch(n){let r=n;return this.#logger?.error({message:`Error executing ${t} operation`,error:r,code:A.RedisClientCommandError,category:e.name}),null}}async increment(e,t){return this.#executeCounterCommand(`incr`,e,t)}async decrement(e,t){return this.#executeCounterCommand(`decr`,e,t)}async subscribe(t,n){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pSubscribe(t,n),!0}catch(n){let r=n;return this.#logger?.error({message:`Error subscribing to ${t}`,error:r,code:A.RedisClientSubscribeError,category:e.name}),!1}}async unsubscribe(t){if(!this.#isRedisClientAvailable())return!1;try{return await this.#redisClient.pUnsubscribe(t),!0}catch(n){let r=n;return this.#logger?.error({message:`Error unsubscribing from ${t}`,error:r,code:A.RedisClientUnsubscribeError,category:e.name}),!1}}async publish(t,n){if(!this.#isRedisClientAvailable())return null;try{let r=await this.#redisClient.publish(t,n);return r===0&&this.#logger?.debug({message:`No subscribers found for channel ${t}`,category:e.name}),r}catch(n){let r=n;return this.#logger?.error({message:`Error publishing to ${t}`,error:r,code:A.RedisClientPublishError,category:e.name}),null}}getClient(){return this.#isRedisClientAvailable()?this.#redisClient:null}#isRedisClientAvailable(){let t=this.#redisClient.isReady&&this.#redisClient.isOpen;return t||this.#logger?.error({message:`Redis Client is not ready.`,category:e.name,code:A.RedisClientRedisNotReady}),t}async listData({partialKey:t,limit:n,cursor:r}){try{let e=r?parseInt(r,10):0,i=await this.#redisClient.sScan(t,e,{COUNT:n}),a=[];for(let e of i.members){let t=await this.getData(e);u(t)&&a.push(t)}return{items:a,cursor:i.cursor>0?i.cursor.toString():void 0}}catch(t){let n=t;return this.#logger?.error({message:`Error listing data`,error:n,code:A.RedisClientListError,category:e.name}),{items:null}}}async deleteData(t){try{if(!this.#isRedisClientAvailable())return!1;let n=await this.#redisClient.del(t);return n===0&&this.#logger?.debug({message:`No keys deleted for ${t}`,category:e.name}),n>0}catch(t){let n=t;return this.#logger?.error({message:`Error deleting data`,error:n,code:A.RedisClientDeleteError,category:e.name}),!1}}};const Te=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},Ee=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:A.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})}}];let De=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var Oe=class extends Se{redisClientConfig;scripts;scriptMap;cacheClient;logger;additionalArgs;isInitialConnection=!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 Ce(e,i,this.name);if(o(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?.();u(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(){o(this.scripts)||Object.keys(this.scripts).length===0||(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))}async loadScripts(e,t){if(u(t))for(let[e,n]of t)this.scriptMap.set(e,n);for(let[t,n]of Object.entries(e)){let e=await this.cacheClient?.loadScript?.(n);u(e)?this.scriptMap?.set(t,e):this.logger?.error({message:`Error loading script ${t}`,category:this.name,code:De.ScriptManagerLoadingError})}}async executeScript(e,t,n){try{if(!this.isRedisReady())throw Error(`Redis client is not ready`);let r=this.scriptMap?.get(e);if(o(r))throw 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`)){if(this.logger?.info({message:`Script ${e} not found in Redis, reloading scripts`,category:this.name}),await this.reloadScripts(),r=this.scriptMap?.get(e),o(r))throw Error(`Script for ${e} could not be reloaded`);return await this.cacheClient?.executeScript?.({sha1:r,keys:t,args:n})??null}throw i}}catch(r){throw r instanceof Error&&this.logger?.error({message:`Error executing script ${e}: ${r.message}`,category:this.name,context:{keys:t,args:n},error:r,code:De.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&u(this.cacheClient)}},ke=class{options={getCacheClient:Ce};subscriptionMap=null;subscriptionClient=null;logger;name=`SubscriptionManager`;constructor(e){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 _e({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)}}),u(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),i=r(t.toString());return await this.subscriptionMap?.setData({key:e,value:i}),n===i?!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 u(this.subscriptionClient)&&u(this.subscriptionMap)}close(){this.subscriptionMap?.close(),this.subscriptionMap=null,this.subscriptionClient=null}};const Ae=6e4,je=15e3,Me=!1,Ne=6e4,Pe=15e3,Fe=1e4,Ie=1;let Le=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),Re=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var ze=class extends Oe{subscriptionManager=null;eventClient=null;name=`QueueManager`;async additionalInitialization(){if(o(this.redisClientConfig))throw Error(`Redis client configuration is required to initialize QueueManager.`);this.subscriptionManager=new ke({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:Ne,truncateThreshold:Fe,truncationPercentage:Ie}),await this.subscriptionManager?.initialize(),this.eventClient=new xe({instantiator:this.name,timeoutResolveValue:Me},{instantiator:this.name,evictionFrequency:Pe,truncateThreshold:Fe,truncationPercentage:Ie},{instantiator:this.name,evictionFrequency:Pe,truncateThreshold:Fe,truncationPercentage:Ie}),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?Re.lPush:Re.rPush,[e],[t,Ae.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,je),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:Le.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(Re.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Le.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(Re.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Le.QueueManagerLengthError,context:{queueName:e}}),t}}isReady(){return u(this.subscriptionManager)&&u(this.cacheClient)&&u(this.scriptMap)&&this.scriptMap.size>0}close(){this.subscriptionManager?.close(),this.scriptMap?.clear()}};const Be=5,Ve=12e4,He=1e4,Ue=1,We=60,Ge=90,Ke=`__keyevent@0__:`,qe=`${Ke}set`,Je=`${Ke}expire`,Ye=`${Ke}expired`,Xe=`${Ke}srem`,Ze=`config_check_test_key`,Qe=[qe,Je,Ye],$e=1,et=2e4,tt={mainMaxConcurrency:30};let nt=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),rt=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const it={[rt.tryConcurrency]:`
2
2
  local requestId = KEYS[1]
3
3
  local targetKey = KEYS[2]
4
4
  local queueKey = KEYS[3]
@@ -192,4 +192,4 @@ var Vr=9e15,Hr=1e9,Ur=`0123456789abcdef`,Wr=`2.302585092994045684017991454684364
192
192
  `);let t=new Ns(`!xml`),n=t,r=``,i=``;for(let a=0;a<e.length;a++){let o=e[a];if(o===`<`)if(e[a+1]===`/`){let t=lc(e,`>`,a,`Closing Tag is not closed.`),o=e.substring(a+2,t).trim();if(this.options.removeNSPrefix){let e=o.indexOf(`:`);e!==-1&&(o=o.substr(e+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),n&&(r=this.saveTextToParentTag(r,n,i));let s=i.substring(i.lastIndexOf(`.`)+1);if(o&&this.options.unpairedTags.indexOf(o)!==-1)throw Error(`Unpaired tag can not be used as closing tag: </${o}>`);let c=0;s&&this.options.unpairedTags.indexOf(s)!==-1?(c=i.lastIndexOf(`.`,i.lastIndexOf(`.`)-1),this.tagsNodeStack.pop()):c=i.lastIndexOf(`.`),i=i.substring(0,c),n=this.tagsNodeStack.pop(),r=``,a=t}else if(e[a+1]===`?`){let t=uc(e,a,!1,`?>`);if(!t)throw Error(`Pi Tag is not closed.`);if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&t.tagName===`?xml`||this.options.ignorePiTags)){let e=new Ns(t.tagName);e.add(this.options.textNodeName,``),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[`:@`]=this.buildAttributesMap(t.tagExp,i,t.tagName)),this.addChild(n,e,i,a)}a=t.closeIndex+1}else if(e.substr(a+1,3)===`!--`){let t=lc(e,`-->`,a+4,`Comment is not closed.`);if(this.options.commentPropName){let o=e.substring(a+4,t-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}a=t}else if(e.substr(a+1,2)===`!D`){let t=Ps(e,a);this.docTypeEntities=t.entities,a=t.i}else if(e.substr(a+1,2)===`![`){let t=lc(e,`]]>`,a,`CDATA is not closed.`)-2,o=e.substring(a+9,t);r=this.saveTextToParentTag(r,n,i);let s=this.parseTextData(o,n.tagname,i,!0,!1,!0,!0);s??=``,this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):n.add(this.options.textNodeName,s),a=t+2}else{let o=uc(e,a,this.options.removeNSPrefix),s=o.tagName,c=o.rawTagName,l=o.tagExp,u=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(s=this.options.transformTagName(s)),n&&r&&n.tagname!==`!xml`&&(r=this.saveTextToParentTag(r,n,i,!1));let f=n;f&&this.options.unpairedTags.indexOf(f.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf(`.`))),s!==t.tagname&&(i+=i?`.`+s:s);let p=a;if(this.isItStopNode(this.options.stopNodes,i,s)){let t=``;if(l.length>0&&l.lastIndexOf(`/`)===l.length-1)s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),a=o.closeIndex;else if(this.options.unpairedTags.indexOf(s)!==-1)a=o.closeIndex;else{let n=this.readStopNodeData(e,c,d+1);if(!n)throw Error(`Unexpected end of ${c}`);a=n.i,t=n.tagContent}let r=new Ns(s);s!==l&&u&&(r[`:@`]=this.buildAttributesMap(l,i,s)),t&&=this.parseTextData(t,s,i,!0,u,!0,!0),i=i.substr(0,i.lastIndexOf(`.`)),r.add(this.options.textNodeName,t),this.addChild(n,r,i,p)}else{if(l.length>0&&l.lastIndexOf(`/`)===l.length-1){s[s.length-1]===`/`?(s=s.substr(0,s.length-1),i=i.substr(0,i.length-1),l=s):l=l.substr(0,l.length-1),this.options.transformTagName&&(s=this.options.transformTagName(s));let e=new Ns(s);s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),i=i.substr(0,i.lastIndexOf(`.`))}else{let e=new Ns(s);this.tagsNodeStack.push(n),s!==l&&u&&(e[`:@`]=this.buildAttributesMap(l,i,s)),this.addChild(n,e,i,p),n=e}r=``,a=d}}else r+=e[a]}return t.child};function ic(e,t,n,r){this.options.captureMetaData||(r=void 0);let i=this.options.updateTag(t.tagname,n,t[`:@`]);i===!1||(typeof i==`string`&&(t.tagname=i),e.addChild(t,r))}const ac=function(e){if(this.options.processEntities){for(let t in this.docTypeEntities){let n=this.docTypeEntities[t];e=e.replace(n.regx,n.val)}for(let t in this.lastEntities){let n=this.lastEntities[t];e=e.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let t in this.htmlEntities){let n=this.htmlEntities[t];e=e.replace(n.regex,n.val)}e=e.replace(this.ampEntity.regex,this.ampEntity.val)}return e};function oc(e,t,n,r){return e&&(r===void 0&&(r=t.child.length===0),e=this.parseTextData(e,t.tagname,n,!1,t[`:@`]?Object.keys(t[`:@`]).length!==0:!1,r),e!==void 0&&e!==``&&t.add(this.options.textNodeName,e),e=``),e}function sc(e,t,n){let r=`*.`+n;for(let n in e){let i=e[n];if(r===i||t===i)return!0}return!1}function cc(e,t,n=`>`){let r,i=``;for(let a=t;a<e.length;a++){let t=e[a];if(r)t===r&&(r=``);else if(t===`"`||t===`'`)r=t;else if(t===n[0])if(n[1]){if(e[a+1]===n[1])return{data:i,index:a}}else return{data:i,index:a};else t===` `&&(t=` `);i+=t}}function lc(e,t,n,r){let i=e.indexOf(t,n);if(i===-1)throw Error(r);return i+t.length-1}function uc(e,t,n,r=`>`){let i=cc(e,t+1,r);if(!i)return;let a=i.data,o=i.index,s=a.search(/\s/),c=a,l=!0;s!==-1&&(c=a.substring(0,s),a=a.substring(s+1).trimStart());let u=c;if(n){let e=c.indexOf(`:`);e!==-1&&(c=c.substr(e+1),l=c!==i.data.substr(e+1))}return{tagName:c,tagExp:a,closeIndex:o,attrExpPresent:l,rawTagName:u}}function dc(e,t,n){let r=n,i=1;for(;n<e.length;n++)if(e[n]===`<`)if(e[n+1]===`/`){let a=lc(e,`>`,n,`${t} is not closed`),o=e.substring(n+2,a).trim();if(o===t&&(i--,i===0))return{tagContent:e.substring(r,n),i:a};n=a}else if(e[n+1]===`?`){let t=lc(e,`?>`,n+1,`StopNode is not closed.`);n=t}else if(e.substr(n+1,3)===`!--`){let t=lc(e,`-->`,n+3,`StopNode is not closed.`);n=t}else if(e.substr(n+1,2)===`![`){let t=lc(e,`]]>`,n,`StopNode is not closed.`)-2;n=t}else{let r=uc(e,n,`>`);if(r){let e=r&&r.tagName;e===t&&r.tagExp[r.tagExp.length-1]!==`/`&&i++,n=r.closeIndex}}}function fc(e,t,n){if(t&&typeof e==`string`){let t=e.trim();return t===`true`?!0:t===`false`?!1:Gs(e,n)}else if(ms(e))return e;else return``}const pc=Ns.getMetaDataSymbol();function mc(e,t){return hc(e,t)}function hc(e,t,n){let r,i={};for(let a=0;a<e.length;a++){let o=e[a],s=gc(o),c=``;if(c=n===void 0?s:n+`.`+s,s===t.textNodeName)r===void 0?r=o[s]:r+=``+o[s];else if(s===void 0)continue;else if(o[s]){let e=hc(o[s],t,c),n=vc(e,t);o[pc]!==void 0&&(e[pc]=o[pc]),o[`:@`]?_c(e,o[`:@`],c,t):Object.keys(e).length===1&&e[t.textNodeName]!==void 0&&!t.alwaysCreateTextNode?e=e[t.textNodeName]:Object.keys(e).length===0&&(t.alwaysCreateTextNode?e[t.textNodeName]=``:e=``),i[s]!==void 0&&i.hasOwnProperty(s)?(Array.isArray(i[s])||(i[s]=[i[s]]),i[s].push(e)):t.isArray(s,c,n)?i[s]=[e]:i[s]=e}}return typeof r==`string`?r.length>0&&(i[t.textNodeName]=r):r!==void 0&&(i[t.textNodeName]=r),i}function gc(e){let t=Object.keys(e);for(let e=0;e<t.length;e++){let n=t[e];if(n!==`:@`)return n}}function _c(e,t,n,r){if(t){let i=Object.keys(t),a=i.length;for(let o=0;o<a;o++){let a=i[o];r.isArray(a,n+`.`+a,!0,!0)?e[a]=[t[a]]:e[a]=t[a]}}}function vc(e,t){let{textNodeName:n}=t,r=Object.keys(e).length;return!!(r===0||r===1&&(e[n]||typeof e[n]==`boolean`||e[n]===0))}var yc=class{constructor(e){this.externalEntities={},this.options=js(e)}parse(e,t){if(typeof e!=`string`)if(e.toString)e=e.toString();else throw Error(`XML data is accepted in String or Bytes[] form.`);if(t){t===!0&&(t={});let n=gs(e,t);if(n!==!0)throw Error(`${n.err.msg}:${n.err.line}:${n.err.col}`)}let n=new Zs(this.options);n.addExternalEntities(this.externalEntities);let r=n.parseXml(e);return this.options.preserveOrder||r===void 0?r:mc(r,this.options)}addEntity(e,t){if(t.indexOf(`&`)!==-1)throw Error(`Entity value can't have '&'`);if(e.indexOf(`&`)!==-1||e.indexOf(`;`)!==-1)throw Error(`An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'`);if(t===`&`)throw Error(`An entity with value '&' is not permitted`);this.externalEntities[e]=t}static getMetaDataSymbol(){return Ns.getMetaDataSymbol()}};const bc=`
193
193
  `;function xc(e,t){let n=``;return t.format&&t.indentBy.length>0&&(n=bc),Sc(e,t,``,n)}function Sc(e,t,n,r){let i=``,a=!1;for(let o=0;o<e.length;o++){let s=e[o],c=Cc(s);if(c===void 0)continue;let l=``;if(l=n.length===0?c:`${n}.${c}`,c===t.textNodeName){let e=s[c];Tc(l,t)||(e=t.tagValueProcessor(c,e),e=Ec(e,t)),a&&(i+=r),i+=e,a=!1;continue}else if(c===t.cdataPropName){a&&(i+=r),i+=`<![CDATA[${s[c][0][t.textNodeName]}]]>`,a=!1;continue}else if(c===t.commentPropName){i+=r+`<!--${s[c][0][t.textNodeName]}-->`,a=!0;continue}else if(c[0]===`?`){let e=wc(s[`:@`],t),n=c===`?xml`?``:r,o=s[c][0][t.textNodeName];o=o.length===0?``:` `+o,i+=n+`<${c}${o}${e}?>`,a=!0;continue}let u=r;u!==``&&(u+=t.indentBy);let d=wc(s[`:@`],t),f=r+`<${c}${d}`,p=Sc(s[c],t,l,u);t.unpairedTags.indexOf(c)===-1?(!p||p.length===0)&&t.suppressEmptyNode?i+=f+`/>`:p&&p.endsWith(`>`)?i+=f+`>${p}${r}</${c}>`:(i+=f+`>`,p&&r!==``&&(p.includes(`/>`)||p.includes(`</`))?i+=r+t.indentBy+p+r:i+=p,i+=`</${c}>`):t.suppressUnpairedNode?i+=f+`>`:i+=f+`/>`,a=!0}return i}function Cc(e){let t=Object.keys(e);for(let n=0;n<t.length;n++){let r=t[n];if(e.hasOwnProperty(r)&&r!==`:@`)return r}}function wc(e,t){let n=``;if(e&&!t.ignoreAttributes)for(let r in e){if(!e.hasOwnProperty(r))continue;let i=t.attributeValueProcessor(r,e[r]);i=Ec(i,t),i===!0&&t.suppressBooleanAttributes?n+=` ${r.substr(t.attributeNamePrefix.length)}`:n+=` ${r.substr(t.attributeNamePrefix.length)}="${i}"`}return n}function Tc(e,t){e=e.substr(0,e.length-t.textNodeName.length-1);let n=e.substr(e.lastIndexOf(`.`)+1);for(let r in t.stopNodes)if(t.stopNodes[r]===e||t.stopNodes[r]===`*.`+n)return!0;return!1}function Ec(e,t){if(e&&e.length>0&&t.processEntities)for(let n=0;n<t.entities.length;n++){let r=t.entities[n];e=e.replace(r.regex,r.val)}return e}const Dc={attributeNamePrefix:`@_`,attributesGroupName:!1,textNodeName:`#text`,ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:` `,suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:RegExp(`&`,`g`),val:`&amp;`},{regex:RegExp(`>`,`g`),val:`&gt;`},{regex:RegExp(`<`,`g`),val:`&lt;`},{regex:RegExp(`'`,`g`),val:`&apos;`},{regex:RegExp(`"`,`g`),val:`&quot;`}],processEntities:!0,stopNodes:[],oneListGroup:!1};function Oc(e){this.options=Object.assign({},Dc,e),this.options.ignoreAttributes===!0||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Xs(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=jc),this.processTextOrObjNode=kc,this.options.format?(this.indentate=Ac,this.tagEndChar=`>
194
194
  `,this.newLine=`
195
- `):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}Oc.prototype.build=function(e){return this.options.preserveOrder?xc(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},Oc.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n)}return{attrStr:r,val:i}},Oc.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`};function kc(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}Oc.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),(n||n===``)&&e.indexOf(`<`)===-1?this.indentate(r)+`<`+t+n+a+`>`+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i}},Oc.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},Oc.prototype.buildTextValNode=function(e,t,n,r){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},Oc.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function Ac(e){return this.options.indentBy.repeat(e)}function jc(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}const Mc={validate:gs},Nc=`@_`;var Pc=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c}){let l;if(l=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Fc.build(c.envelope):await Lc(a,c),Mc.validate(l,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let u,d={...r,"Content-Type":`text/xml`};c?.soapAction&&(d.SOAPAction=c.soapAction);try{u=await e?.request({method:n,url:t,headers:d,queryParams:i,maxRedirects:0,payload:l,requestConfig:c})}catch(e){if(o(e?.response))throw e;u=e.response}let f=Ic.parse(u.data),p=f.Envelope||f,m=p.Body||p,h=m.Fault;if(h)throw new ct({...u,status:500,data:h,message:h.faultstring??h.faultcode??`SOAP Fault`},h.faultstring??`SOAP Fault occurred`);u.data=m;let g=ns(u,s);if(os(g?.status))throw new ct(g,g.message);return g}};const Fc=new Oc({attributeNamePrefix:Nc,ignoreAttributes:!1,suppressBooleanAttributes:!1}),Ic=new yc({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),Lc=async(e,t)=>{if(u(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Fc.build(t.envelope),n=Mc.validate(e,{allowBooleanAttributes:!0});if(n!==!0)throw Error(`Invalid XML envelope`);return e}let n=await Rc(t,e),r=Fc.build(n),i=Mc.validate(r,{allowBooleanAttributes:!0});if(i!==!0)throw Error(`Invalid XML envelope`);return r},Rc=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await S(e.namespaceIdentifier),namespace:await S(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(o(e)||o(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 zc(t,e??{}),"soapenv:Body":await Vc(t,e?.operation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},zc=async(e,t)=>[await Bc(e,t)],Bc=async(e,t)=>{if(o(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`}}},Vc=async(e,t,n)=>{if(o(t))throw Error(`Missing soapOperation in config`);return[Hc({[t]:e},n)]},Hc=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>Hc(e,t));let n={};for(let r in e){let i=Uc(r,t);n[i]=Hc(e[r],t)}return n},Uc=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(Nc)?`${Nc}${t}:${e.slice(2)}`:`${t}:${e}`};var Wc=class{static build(e=`rest`){if(e===`rest`)return new cs;if(e===`soap`)return new Pc;throw Error(`Unknown request client type: ${e}`)}};export{ot as CUSTOM_ERROR_CONFIG_SCHEMA,at as ConcurrencyManager,xe as EventClient,Wo as HttpClient,Ko as HttpClientManager,st as HttpErrorMessages,qo as HttpMethods,ct as HttpResponseError,ft as HttpTransportFactory,mt as InstanceManager,oe as LockManager,_e as MemoryStore,ze as QueueManager,Ro as RateLimitManager,we as RedisClient,Wc as RequestClientFactory,ts as RequestParameterLocations,Oe as ScriptManager,ke as SubscriptionManager,Go as buildHttpClientInstance,re as createAuthorizationHeaders,Bo as getTransportInstance,$o as getTransportManagers,Xo as initializeTransportSystem,os as isFailedStatusCode,ss as isInfoStatusCode,rs as isSuccessStatusCode,Qo as isTransportSystemReady,es as parseRequestParameters,dt as serializeHttpResponseError,Zo as shutdownTransportSystem};
195
+ `):(this.indentate=function(){return``},this.tagEndChar=`>`,this.newLine=``)}Oc.prototype.build=function(e){return this.options.preserveOrder?xc(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},Oc.prototype.j2x=function(e,t,n){let r=``,i=``,a=n.join(`.`);for(let o in e){if(!Object.prototype.hasOwnProperty.call(e,o))continue;if(e[o]===void 0)this.isAttribute(o)&&(i+=``);else if(e[o]===null)this.isAttribute(o)||o===this.options.cdataPropName?i+=``:o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(e[o]instanceof Date)i+=this.buildTextValNode(e[o],o,``,t);else if(typeof e[o]!=`object`){let n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,a))r+=this.buildAttrPairStr(n,``+e[o]);else if(!n)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,``+e[o]);i+=this.replaceEntitiesValue(t)}else i+=this.buildTextValNode(e[o],o,``,t)}else if(Array.isArray(e[o])){let r=e[o].length,a=``,s=``;for(let c=0;c<r;c++){let r=e[o][c];if(r!==void 0)if(r===null)o[0]===`?`?i+=this.indentate(t)+`<`+o+`?`+this.tagEndChar:i+=this.indentate(t)+`<`+o+`/`+this.tagEndChar;else if(typeof r==`object`)if(this.options.oneListGroup){let e=this.j2x(r,t+1,n.concat(o));a+=e.val,this.options.attributesGroupName&&r.hasOwnProperty(this.options.attributesGroupName)&&(s+=e.attrStr)}else a+=this.processTextOrObjNode(r,o,t,n);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,r);e=this.replaceEntitiesValue(e),a+=e}else a+=this.buildTextValNode(r,o,``,t)}this.options.oneListGroup&&(a=this.buildObjectNode(a,o,s,t)),i+=a}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){let t=Object.keys(e[o]),n=t.length;for(let i=0;i<n;i++)r+=this.buildAttrPairStr(t[i],``+e[o][t[i]])}else i+=this.processTextOrObjNode(e[o],o,t,n)}return{attrStr:r,val:i}},Oc.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,``+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&t===`true`?` `+e:` `+e+`="`+t+`"`};function kc(e,t,n,r){let i=this.j2x(e,n+1,r.concat(t));return e[this.options.textNodeName]!==void 0&&Object.keys(e).length===1?this.buildTextValNode(e[this.options.textNodeName],t,i.attrStr,n):this.buildObjectNode(i.val,t,i.attrStr,n)}Oc.prototype.buildObjectNode=function(e,t,n,r){if(e===``)return t[0]===`?`?this.indentate(r)+`<`+t+n+`?`+this.tagEndChar:this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar;{let i=`</`+t+this.tagEndChar,a=``;return t[0]===`?`&&(a=`?`,i=``),(n||n===``)&&e.indexOf(`<`)===-1?this.indentate(r)+`<`+t+n+a+`>`+e+i:this.options.commentPropName!==!1&&t===this.options.commentPropName&&a.length===0?this.indentate(r)+`<!--${e}-->`+this.newLine:this.indentate(r)+`<`+t+n+a+this.tagEndChar+e+this.indentate(r)+i}},Oc.prototype.closeTag=function(e){let t=``;return this.options.unpairedTags.indexOf(e)===-1?t=this.options.suppressEmptyNode?`/`:`></${e}`:this.options.suppressUnpairedNode||(t=`/`),t},Oc.prototype.buildTextValNode=function(e,t,n,r){if(this.options.cdataPropName!==!1&&t===this.options.cdataPropName)return this.indentate(r)+`<![CDATA[${e}]]>`+this.newLine;if(this.options.commentPropName!==!1&&t===this.options.commentPropName)return this.indentate(r)+`<!--${e}-->`+this.newLine;if(t[0]===`?`)return this.indentate(r)+`<`+t+n+`?`+this.tagEndChar;{let i=this.options.tagValueProcessor(t,e);return i=this.replaceEntitiesValue(i),i===``?this.indentate(r)+`<`+t+n+this.closeTag(t)+this.tagEndChar:this.indentate(r)+`<`+t+n+`>`+i+`</`+t+this.tagEndChar}},Oc.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){let n=this.options.entities[t];e=e.replace(n.regex,n.val)}return e};function Ac(e){return this.options.indentBy.repeat(e)}function jc(e){return e.startsWith(this.options.attributeNamePrefix)&&e!==this.options.textNodeName?e.substr(this.attrPrefixLen):!1}const Mc={validate:gs},Nc=`@_`;var Pc=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c}){let l;if(l=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Fc.build(c.envelope):await Lc(a,c),Mc.validate(l,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let u,d={...r,"Content-Type":`text/xml`};c?.soapAction&&(d.SOAPAction=c.soapAction);try{u=await e?.request({method:n,url:t,headers:d,queryParams:i,maxRedirects:0,payload:l,requestConfig:c})}catch(e){if(o(e?.response))throw e;u=e.response}let f=Ic.parse(u.data),p=f.Envelope||f,m=p.Body||p,h=m.Fault;if(h)throw new ct({...u,status:500,data:h,message:h.faultstring??h.faultcode??`SOAP Fault`},h.faultstring??`SOAP Fault occurred`);u.data=m;let g=ns(u,s);if(os(g?.status))throw new ct(g,g.message);return g}};const Fc=new Oc({attributeNamePrefix:Nc,ignoreAttributes:!1,suppressBooleanAttributes:!1}),Ic=new yc({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),Lc=async(e,t)=>{if(u(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Fc.build(t.envelope),n=Mc.validate(e,{allowBooleanAttributes:!0});if(n!==!0)throw Error(`Invalid XML envelope`);return e}let n=await Rc(t,e),r=Fc.build(n),i=Mc.validate(r,{allowBooleanAttributes:!0});if(i!==!0)throw Error(`Invalid XML envelope`);return r},Rc=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await S(e.namespaceIdentifier),namespace:await S(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(o(e)||o(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 zc(t,e??{}),"soapenv:Body":await Vc(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},zc=async(e,t)=>[await Bc(e,t)],Bc=async(e,t)=>{if(o(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`}}},Vc=async(e,t,n)=>{if(o(t))throw Error(`Missing soapOperation in config`);let r=Hc({[t]:e}),i=Array.isArray(r)?r:[r];return i.map(e=>Uc(e,n))},Hc=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),n=e.filter(e=>!e.startsWith(Nc));if(n.length===1){let e=n[0],r=t[e];if(typeof r==`object`&&r&&!Array.isArray(r)){let t=Object.keys(r),n=t.filter(e=>e.startsWith(Nc)),i=t.filter(e=>!e.startsWith(Nc)),a=n.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let t=r[a],i=n.filter(e=>e!==a),o=t.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[e]:o}}}}}}return e.map(e=>Hc(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=Hc(r)}return t},Uc=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>Uc(e,t));let n={};for(let r in e){let i=Wc(r,t);n[i]=Uc(e[r],t)}return n},Wc=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(Nc)?`${Nc}${t}:${e.slice(2)}`:`${t}:${e}`};var Gc=class{static build(e=`rest`){if(e===`rest`)return new cs;if(e===`soap`)return new Pc;throw Error(`Unknown request client type: ${e}`)}};export{ot as CUSTOM_ERROR_CONFIG_SCHEMA,at as ConcurrencyManager,xe as EventClient,Wo as HttpClient,Ko as HttpClientManager,st as HttpErrorMessages,qo as HttpMethods,ct as HttpResponseError,ft as HttpTransportFactory,mt as InstanceManager,oe as LockManager,_e as MemoryStore,ze as QueueManager,Ro as RateLimitManager,we as RedisClient,Gc as RequestClientFactory,ts as RequestParameterLocations,Oe as ScriptManager,ke as SubscriptionManager,Go as buildHttpClientInstance,re as createAuthorizationHeaders,Bo as getTransportInstance,$o as getTransportManagers,Xo as initializeTransportSystem,os as isFailedStatusCode,ss as isInfoStatusCode,rs as isSuccessStatusCode,Qo as isTransportSystemReady,es as parseRequestParameters,dt as serializeHttpResponseError,Zo as shutdownTransportSystem};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/transport",
3
- "version": "2.2.1",
3
+ "version": "2.2.4",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",