@stackone/transport 2.1.2 → 2.1.3

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.d.mts CHANGED
@@ -167,10 +167,10 @@ interface RedisClientConfig {
167
167
  reconnect?: boolean;
168
168
  database?: number;
169
169
  }
170
- type RedisClientBuilder = (config: RedisClientConfig, logger?: ILogger) => Promise<ICacheClient<RedisClientType> | undefined>;
170
+ type RedisClientBuilder = (config: RedisClientConfig, logger?: ILogger, invoker?: string) => Promise<ICacheClient<RedisClientType> | undefined>;
171
171
  //#endregion
172
172
  //#region src/redisClient/index.d.ts
173
- declare const buildRedisClientInstance: (config: RedisClientConfig, logger?: ILogger) => Promise<ICacheClient<RedisClientType> | undefined>;
173
+ declare const buildRedisClientInstance: (config: RedisClientConfig, logger?: ILogger, invoker?: string) => Promise<ICacheClient<RedisClientType> | undefined>;
174
174
  declare class RedisClient implements ICacheClient<RedisClientType> {
175
175
  #private;
176
176
  static build({
@@ -180,7 +180,7 @@ declare class RedisClient implements ICacheClient<RedisClientType> {
180
180
  tls,
181
181
  reconnect,
182
182
  database
183
- }: RedisClientConfig, logger?: ILogger): Promise<ICacheClient<RedisClientType> | null>;
183
+ }: RedisClientConfig, logger?: ILogger, invoker?: string): Promise<ICacheClient<RedisClientType> | null>;
184
184
  getData<T>(key: string): Promise<T | null>;
185
185
  setData<T>({
186
186
  key,
package/dist/index.d.ts CHANGED
@@ -167,10 +167,10 @@ interface RedisClientConfig {
167
167
  reconnect?: boolean;
168
168
  database?: number;
169
169
  }
170
- type RedisClientBuilder = (config: RedisClientConfig, logger?: ILogger) => Promise<ICacheClient<RedisClientType> | undefined>;
170
+ type RedisClientBuilder = (config: RedisClientConfig, logger?: ILogger, invoker?: string) => Promise<ICacheClient<RedisClientType> | undefined>;
171
171
  //#endregion
172
172
  //#region src/redisClient/index.d.ts
173
- declare const buildRedisClientInstance: (config: RedisClientConfig, logger?: ILogger) => Promise<ICacheClient<RedisClientType> | undefined>;
173
+ declare const buildRedisClientInstance: (config: RedisClientConfig, logger?: ILogger, invoker?: string) => Promise<ICacheClient<RedisClientType> | undefined>;
174
174
  declare class RedisClient implements ICacheClient<RedisClientType> {
175
175
  #private;
176
176
  static build({
@@ -180,7 +180,7 @@ declare class RedisClient implements ICacheClient<RedisClientType> {
180
180
  tls,
181
181
  reconnect,
182
182
  database
183
- }: RedisClientConfig, logger?: ILogger): Promise<ICacheClient<RedisClientType> | null>;
183
+ }: RedisClientConfig, logger?: ILogger, invoker?: string): Promise<ICacheClient<RedisClientType> | null>;
184
184
  getData<T>(key: string): Promise<T | null>;
185
185
  setData<T>({
186
186
  key,
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,E=w*10,re=C,D=10;let O=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var ie=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??E,this.truncateThreshold=e?.truncateThreshold??re,this.truncationPercentage=e?.truncationPercentage??D,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:O.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 ae=1e3,oe=6e4;let se=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var ce=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 ie(i),this.promiseStore=new ie(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/ae;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??oe),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:se.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}},le=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 k=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 ue=async(e,t)=>{try{let n=await de.build(e,t);return n??void 0}catch(e){let n=e;t?.error({message:`Error building Cache Manager`,error:n,code:k.RedisClientError,category:`buildRedisClientInstance`});return}};var de=class e{#redisClient;#logger;static async build({getRedisClient:t=u.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s){let c=new e;c.#logger=s;try{c.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let s=pe(e.name,c.#logger);return fe(c.#redisClient,s),await c.#redisClient.connect(),c}catch(t){let n=t;return c.#logger?.error({message:`Error building Cache Manager.`,error:n,code:k.RedisClientError,category:e.name}),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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.RedisClientDeleteError,category:e.name}),!1}}};const fe=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},pe=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:k.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 me=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var he=class extends le{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 ue(e,i);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:me.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:me.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&(0,l.notMissing)(this.cacheClient)}},ge=class{options={getCacheClient:ue};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 ie({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)??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 _e=6e4,ve=15e3,ye=!1,be=6e4,xe=15e3,Se=1e4,Ce=1;let we=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),A=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var j=class extends he{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 ge({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:be,truncateThreshold:Se,truncationPercentage:Ce}),await this.subscriptionManager?.initialize(),this.eventClient=new ce({instantiator:this.name,timeoutResolveValue:ye},{instantiator:this.name,evictionFrequency:xe,truncateThreshold:Se,truncationPercentage:Ce},{instantiator:this.name,evictionFrequency:xe,truncateThreshold:Se,truncationPercentage:Ce}),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?A.lPush:A.rPush,[e],[t,_e.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,ve),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:we.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(A.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:we.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(A.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:we.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 Te=5,Ee=12e4,De=1e4,Oe=1,ke=60,Ae=90,je=`__keyevent@0__:`,Me=`${je}set`,Ne=`${je}expire`,Pe=`${je}expired`,Fe=`${je}srem`,Ie=`config_check_test_key`,Le=[Me,Ne,Pe],Re=1,ze=1e4,Be={mainMaxConcurrency:30};let Ve=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),He=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const Ue={[He.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,E=w*10,re=C,D=10;let O=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var ie=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??E,this.truncateThreshold=e?.truncateThreshold??re,this.truncationPercentage=e?.truncationPercentage??D,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:O.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 ae=1e3,oe=6e4;let se=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var ce=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 ie(i),this.promiseStore=new ie(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/ae;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??oe),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:se.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}},le=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 k=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 ue=async(e,t,n)=>{try{let r=await de.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:k.RedisClientError,category:n??`buildRedisClientInstance`});return}};var de=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=pe(c??`RedisClient`,l.#logger);return fe(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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.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:k.RedisClientDeleteError,category:e.name}),!1}}};const fe=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},pe=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:k.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 me=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var he=class extends le{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 ue(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:me.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:me.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&(0,l.notMissing)(this.cacheClient)}},ge=class{options={getCacheClient:ue};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 ie({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 _e=6e4,ve=15e3,ye=!1,be=6e4,xe=15e3,Se=1e4,Ce=1;let we=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),A=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var j=class extends he{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 ge({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:be,truncateThreshold:Se,truncationPercentage:Ce}),await this.subscriptionManager?.initialize(),this.eventClient=new ce({instantiator:this.name,timeoutResolveValue:ye},{instantiator:this.name,evictionFrequency:xe,truncateThreshold:Se,truncationPercentage:Ce},{instantiator:this.name,evictionFrequency:xe,truncateThreshold:Se,truncationPercentage:Ce}),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?A.lPush:A.rPush,[e],[t,_e.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,ve),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:we.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(A.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:we.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(A.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:we.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 Te=5,Ee=12e4,De=1e4,Oe=1,ke=60,Ae=90,je=`__keyevent@0__:`,Me=`${je}set`,Ne=`${je}expire`,Pe=`${je}expired`,Fe=`${je}srem`,Ie=`config_check_test_key`,Le=[Me,Ne,Pe],Re=1,ze=1e4,Be={mainMaxConcurrency:30};let Ve=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),He=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const Ue={[He.tryConcurrency]:`
2
2
  local requestId = KEYS[1]
3
3
  local targetKey = KEYS[2]
4
4
  local queueKey = KEYS[3]
@@ -128,7 +128,7 @@ var Dr=9e15,Or=1e9,kr=`0123456789abcdef`,Ar=`2.302585092994045684017991454684364
128
128
  * Copyright (c) 2023, Robert Eisele (robert@raw.org)
129
129
  * Dual licensed under the MIT or GPL Version 2 licenses.
130
130
  **/
131
- (function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function a(e,t){if(isNaN(e=parseInt(e,10)))throw h();return e*t}function o(e,t){if(t===0)throw m();var n=Object.create(p.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=f(e,t);return n.n=e/r,n.d=t/r,n}function s(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var c=function(e,t){var n=0,r=1,o=1,s=0,c=0,l=0,u=1,d=1,f=0,p=1,_=1,v=1,y=1e7,b;if(e!=null)if(t!==void 0){if(n=e,r=t,o=n*r,n%1!=0||r%1!=0)throw g()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw h();o=n*r;break;case`number`:if(e<0&&(o=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(d=10**Math.floor(1+Math.log(e)/Math.LN10),e/=d);p<=y&&v<=y;)if(b=(f+_)/(p+v),e===b){p+v<=y?(n=f+_,r=p+v):v>p?(n=_,r=v):(n=f,r=p);break}else e>b?(f+=_,p+=v):(_+=f,v+=p),p>y?(n=_,r=v):(n=f,r=p);n*=d}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(p=e.match(/\d+|./g),p===null)throw h();if(p[f]===`-`?(o=-1,f++):p[f]===`+`&&f++,p.length===f+1?c=a(p[f++],o):p[f+1]===`.`||p[f]===`.`?(p[f]!==`.`&&(s=a(p[f++],o)),f++,(f+1===p.length||p[f+1]===`(`&&p[f+3]===`)`||p[f+1]===`'`&&p[f+3]===`'`)&&(c=a(p[f],o),u=10**p[f].length,f++),(p[f]===`(`&&p[f+2]===`)`||p[f]===`'`&&p[f+2]===`'`)&&(l=a(p[f+1],o),d=10**p[f+1].length-1,f+=3)):p[f+1]===`/`||p[f+1]===`:`?(c=a(p[f],o),u=a(p[f+2],1),f+=3):p[f+3]===`/`&&p[f+1]===` `&&(s=a(p[f],o),c=a(p[f+2],o),u=a(p[f+4],1),f+=5),p.length<=f){r=u*d,o=n=l+r*s+d*c;break}default:throw h()}if(r===0)throw m();i.s=o<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)};function l(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function u(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function d(e,t,n){for(var r=1,i=l(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function f(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function p(e,t){if(c(e,t),this instanceof p)e=f(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return o(i.s*i.n,i.d)}var m=function(){return Error(`Division by Zero`)},h=function(){return Error(`Invalid argument`)},g=function(){return Error(`Parameters must be integer`)};p.prototype={s:1,n:0,d:1,abs:function(){return o(this.n,this.d)},neg:function(){return o(-this.s*this.n,this.d)},add:function(e,t){return c(e,t),o(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return c(e,t),o(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return o(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new p(NaN);if(e===void 0)return o(this.s*this.n%this.d,1);if(c(e,t),i.n===0&&this.d===0)throw m();return o(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return c(e,t),o(f(i.n,this.n)*f(i.d,this.d),i.d*this.d)},lcm:function(e,t){return c(e,t),i.n===0&&this.n===0?o(0,1):o(i.n*this.n,f(i.n,this.n)*f(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return o(this.s*this.d,this.n)},pow:function(e,t){if(c(e,t),i.d===1)return i.s<0?o((this.s*this.d)**+i.n,this.n**+i.n):o((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=s(this.n),r=s(this.d),a=1,l=1;for(var u in n){if(u===`1`)continue;if(u===`0`){a=0;break}if(n[u]*=i.n,n[u]%i.d===0)n[u]/=i.d;else return null;a*=u**+n[u]}for(var u in r){if(u===`1`)continue;if(r[u]*=i.n,r[u]%i.d===0)r[u]/=i.d;else return null;l*=u**+r[u]}return i.s<0?o(l,a):o(a,l)},equals:function(e,t){return c(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){c(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=o(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return c(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=u(t,n),i=d(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof exports==`object`?(Object.defineProperty(p,`__esModule`,{value:!0}),p.default=p,p.Fraction=p,t.exports=p):n.Fraction=p})(exports)})),ha=c(ma(),1),ga=`Fraction`,_a=[],va=ar(ga,_a,()=>(Object.defineProperty(ha.default,`name`,{value:`Fraction`}),ha.default.prototype.constructor=ha.default,ha.default.prototype.type=`Fraction`,ha.default.prototype.isFraction=!0,ha.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},ha.default.fromJSON=function(e){return new ha.default(e)},ha.default),{isClass:!0}),ya=`Matrix`,ba=[],xa=ar(ya,ba,()=>{function e(){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`)}return e.prototype.type=`Matrix`,e.prototype.isMatrix=!0,e.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},e.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},e.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},e.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},e.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},e.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},e.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},e.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},e.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},e.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},e.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},e.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},e.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},e.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},e.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},e.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},e.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},e},{isClass:!0});function Sa(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Ca=`DenseMatrix`,wa=[`Matrix`],Ta=ar(Ca,wa,e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!wt(t))throw Error(`Invalid datatype: `+t);if(Tt(e))e.type===`DenseMatrix`?(this._data=an(e._data),this._size=an(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&N(e.data)&&N(e.size))this._data=e.data,this._size=e.size,Vn(this._data,this._size),this._datatype=t||e.datatype;else if(N(e))this._data=l(e),this._size=zn(this._data),Vn(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+rn(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}n.prototype=new t,n.prototype.createDenseMatrix=function(e,t){return new n(e,t)},Object.defineProperty(n,`name`,{value:`DenseMatrix`}),n.prototype.constructor=n,n.prototype.type=`DenseMatrix`,n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return Zn(this._data,rn)},n.prototype.storage=function(){return`dense`},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(e,t){return new n(e,t)},n.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return r(this,e);case 2:case 3:return a(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},n.prototype.get=function(e){if(!N(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new F(e.length,this._size.length);for(var t=0;t<e.length;t++)I(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];I(a,n.length),n=n[a]}return n},n.prototype.set=function(e,t,n){if(!N(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new F(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});c(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],I(a,s.length),s=s[a];return a=e[e.length-1],I(a,s.length),s[a]=t,this};function r(e,t){if(!At(t))throw TypeError(`Invalid index`);var r=t.isScalar();if(r)return e.get(t.min());var a=t.size();if(a.length!==e._size.length)throw new F(a.length,e._size.length);for(var o=t.min(),s=t.max(),c=0,l=e._size.length;c<l;c++)I(o[c],e._size[c]),I(s[c],e._size[c]);return new n(i(e._data,t,a.length,0),e._datatype)}function i(e,t,n,r){var a=r===n-1,o=t.dimension(r);return a?o.map(function(t){return I(t,e.length),e[t]}).valueOf():o.map(function(a){I(a,e.length);var o=e[a];return i(o,t,n,r+1)}).valueOf()}function a(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),s;if(Tt(n)?(s=n.size(),n=n.valueOf()):s=zn(n),a){if(s.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!sn(s,i))try{n=s.length===0?nr([n],i):nr(n,i),s=zn(n)}catch{}if(i.length<e._size.length)throw new F(i.length,e._size.length,`<`);if(s.length<i.length){for(var l=0,u=0;i[l]===1&&s[l]===1;)l++;for(;i[l]===1;)u++,l++;n=Jn(n,i.length,u,s)}if(!sn(i,s))throw new F(i,s,`>`);var d=t.max().map(function(e){return e+1});c(e,d,r);var f=i.length,p=0;o(e._data,t,n,f,p)}return e}function o(e,t,n,r,i){var a=i===r-1,s=t.dimension(i);a?s.forEach(function(t,r){I(t),e[t]=n[r[0]]}):s.forEach(function(a,s){I(a),o(e[a],t,n[s[0]],r,i+1)})}n.prototype.resize=function(e,t,n){if(!Et(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e),i=n?this.clone():this;return s(i,r,t)};function s(e,t,n){if(t.length===0){for(var r=e._data;N(r);)r=r[0];return r}return e._size=t.slice(0),e._data=Hn(e._data,e._size,n),e}n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=Wn(n._data,e);var r=n._size.reduce((e,t)=>e*t);return n._size=Gn(e,r),n};function c(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&s(e,r,n)}n.prototype.clone=function(){var e=new n({data:an(this._data),size:an(this._size),datatype:this._datatype});return e},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=Sa(e),i=function n(i,a){return N(i)?i.map(function(e,t){return n(e,a.concat(t))}):r===1?e(i):r===2?e(i,a):e(i,a,t)},a=i(this._data,[]),o=this._datatype===void 0?void 0:Zn(a,rn);return new n(a,o)},n.prototype.forEach=function(e){var t=this,n=function n(r,i){N(r)?r.forEach(function(e,t){n(e,i.concat(t))}):e(r,i,t)};n(this._data,[])},n.prototype[Symbol.iterator]=function*(){var e=function*e(t,n){if(N(t))for(var r=0;r<t.length;r++)yield*e(t[r],n.concat(r));else yield{value:t,index:n}};yield*e(this._data,[])},n.prototype.rows=function(){var e=[],t=this.size();if(t.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);var r=this._data;for(var i of r)e.push(new n([i],this._datatype));return e},n.prototype.columns=function(){var e=this,t=[],r=this.size();if(r.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var i=this._data,a=function(r){var a=i.map(e=>[e[r]]);t.push(new n(a,e._datatype))},o=0;o<r[1];o++)a(o);return t},n.prototype.toArray=function(){return an(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(e){return jn(this._data,e)},n.prototype.toString=function(){return jn(this._data)},n.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(e){if(e){if(bt(e)&&(e=e.toNumber()),!M(e)||!P(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,r=e<0?-e:0,i=this._size[0],a=this._size[1],o=Math.min(i-r,a-t),s=[],c=0;c<o;c++)s[c]=this._data[c+r][c+t];return new n({data:s,size:[o],datatype:this._datatype})},n.diagonal=function(e,t,r,i){if(!N(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(bt(e)&&(e=e.toNumber()),!M(e)||!P(e)||e<1)throw Error(`Size values must be positive integers`);return e}),r){if(bt(r)&&(r=r.toNumber()),!M(r)||!P(r))throw TypeError(`The parameter k must be an integer number`)}else r=0;var a=r>0?r:0,o=r<0?-r:0,s=e[0],c=e[1],l=Math.min(s-o,c-a),u;if(N(t)){if(t.length!==l)throw Error(`Invalid value array length`);u=function(e){return t[e]}}else if(Tt(t)){var d=t.size();if(d.length!==1||d[0]!==l)throw Error(`Invalid matrix length`);u=function(e){return t.get([e])}}else u=function(){return t};i||=bt(u(0))?u(0).mul(0):0;var f=[];if(e.length>0){f=Hn(f,e,i);for(var p=0;p<l;p++)f[p+o][p+a]=u(p)}return new n({data:f,size:[s,c]})},n.fromJSON=function(e){return new n(e)},n.prototype.swapRows=function(e,t){if(!M(e)||!P(e)||!M(t)||!P(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return I(e,this._size[0]),I(t,this._size[0]),n._swapRows(e,t,this._data),this},n._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function l(e){return Tt(e)?l(e.valueOf()):N(e)?e.map(l):e}return n},{isClass:!0});function Ea(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return Ea(e,t,n)}):t(e)}var Da=`isNumeric`,Oa=[`typed`],ka=ar(Da,Oa,e=>{var{typed:t}=e;return t(Da,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>Ea(t,e))})}),Aa=`hasNumericValue`,ja=[`typed`,`isNumeric`],Ma=ar(Aa,ja,e=>{var{typed:t,isNumeric:n}=e;return t(Aa,{boolean:()=>!0,string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})}),Na=ia({config:pn}),Pa=pa({}),Fa=va({}),Ia=xa({}),La=Ta({Matrix:Ia}),Ra=Sr({BigNumber:Na,Complex:Pa,DenseMatrix:La,Fraction:Fa}),za=ka({typed:Ra}),Ba=Ma({isNumeric:za,typed:Ra});const Va=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},Ha=e=>{let t=Number(e),n=Date.now();if(Number.isNaN(t))return n+gt;if(!Va(t)&&(0,l.isFutureUnixTimestamp)(t))return _t(t);if(Va(t))return n+t;{let e=t*mt;return n+e}},Ua=`ratelimitlimit`,Wa=`ratelimitremaining`,Ga=`ratelimitreset`,Ka=`ratelimitconcurrencylimit`,qa=`ratelimitconcurrencyremaining`,Ja=`ratelimitconcurrencyreset`,Ya=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``),i=Ba(r)?Number(r):null;t[e]=i}return t},Xa=e=>{let t=Ya(e);return{rateLimitLimit:t[Ua],rateLimitRemaining:t[Wa],rateLimitReset:Ha(t[Ga]),concurrencyLimit:t[Ka],concurrencyRemaining:t[qa],concurrencyReset:Ha(t[Ja])}},Za=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:s}=e??{};return[t,n,r,o].some(l.isMissing)?null:[t,n,r,i,a,o,...s??[]].filter(Boolean).join(`-`)},Qa=(e,t=dt,n=ut)=>{let r=Date.now();return(0,l.isFutureUnixTimestamp)(e)||(0,l.isNumber)(e)?$a(Number(e),r,t,n):wt(e)&&e!==``?eo(e,r,t,n):n},$a=(e,t,n=dt,r=ut)=>{if(e<n)return e;let i=_t(e);if(i>t){let e=Math.floor((i-t)/mt);return e>0&&e<n?e:r}return r},eo=(e,t,n=dt,r=ut)=>{if(ht.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/mt);return e>0&&e<n?e:r}return r},to=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let i=async i=>{let{response:a,config:o}=i,s=o?.signal;if(s?.aborted)return Promise.reject(ot(`Request aborted`,o,`ERR_CANCELED`,a));let{status:c,retryAfter:u}=no(a,r,n,t);if(c===429&&(0,l.notMissing)(o)){let n=Qa(u);if(o._retryCount>=ft)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${o?.url}. Aborting.`,context:{...r??{},retryAfterHeader:u,retryAfterAsNumber:n}}),Promise.reject(i);let s=o._retryCount??0,c={...o,_retryCount:s+1},d=u?n*mt:(0,l.exponentialBackoffInMS)(c._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${o?.url}`,context:{...r??{},retryAfterHeader:u,calculatedRetryAfter:d}}),await st(d*1e3,o,a),e?.request(c)}return Promise.reject(i)};return i},no=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:s}=e??{},{retryafter:c}=Ya(o??{});if((0,l.isMissing)(i)||(0,l.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,l.isMissing)(e),providerIsMissing:(0,l.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:c??`undefined`}}),{status:a,retryAfter:c};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,l.notMissing)(u)&&(0,l.notMissing)(s))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=(0,l.isObject)(s)?h.default.query(s,f)[0]:s,m=ro(p,r);if(t===a&&m){let e=d??io(o,i),t=ao(e,u);return{status:429,retryAfter:c??t}}}return{status:a,retryAfter:c}},ro=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,io=(e,t)=>(0,l.notMissing)(t)&&(0,l.notMissing)(e)?h.default.query(e,t)[0]:null,ao=(e,t=`seconds`)=>(0,l.notMissing)(e)?oo(e,t):null,oo=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`){let t=typeof e==`string`?parseFloat(e):e;return t/mt}if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},so=`rateLimitErrorInterceptor`,co=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let a=async a=>{let{response:o,config:s}=a,c=s?.signal;if((0,l.isMissing)(r)||(0,l.isMissing)(s))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:so,...s,headers:void 0,hasContext:(0,l.notMissing)(r),hasConfig:(0,l.notMissing)(s)},code:at.InterceptorContextNotPresent}),Promise.reject(a);if((0,l.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:so,...s,headers:void 0,concurrencyManagerInitialized:(0,l.notMissing)(i)},code:at.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p}=s?.requestMetadata??{},m=(0,l.notMissing)(u)&&(0,l.notMissing)(d)?await i.releaseRequest(u,d):!1;if(!m&&(0,l.notMissing)(s?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:so,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:at.RateLimiterReleaseRequestFailed}),c?.aborted)return Promise.reject(ot(`Request aborted`,s,`ERR_CANCELED`,o));let{status:h,retryAfter:g}=no(o,r,n,t);if(h===429&&(0,l.notMissing)(s)){let n=Qa(g);if(s._retryCount>=ft)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${s.url}. Aborting.`,context:{...r??{},...s.requestMetadata??{},retryAfterHeader:g,retryAfterAsNumber:n}}),Promise.reject(a);let i=s?._retryCount??0,c={...s,_retryCount:i+1},u=g?n*mt:(0,l.exponentialBackoffInMS)(c._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${s.url}`,context:{...r,retryAfterHeader:g,calculatedRetryAfter:u}}),await st(u*1e3,s,o),e?.request(c)}return Promise.reject(a)};return a},lo=`rateLimitResponseInterceptor`,uo=({logger:e,context:t,concurrencyManager:n})=>{let r=async r=>{let i=r?.config,a=i?.signal;if((0,l.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{...i,interceptor:lo,headers:void 0}});else if((0,l.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:lo,...i,headers:void 0,concurrencyManagerInitialized:(0,l.notMissing)(n)},code:at.RateLimitOrConcurrencyManagerNotInitialized}),r;else if((0,l.notMissing)(t.provider)&&(0,l.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,l.notMissing)(t)){let n=Xa(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:lo,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:u}=i?.requestMetadata??{},d=await n.releaseRequest(o,s);if(d||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:lo,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:u},code:at.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(ot(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return r},fo=e=>(e.validateStatus??=e=>e>=200&&e<300,e),po=[{onFulfilled:fo,onRejected:null,options:void 0}],mo=[{onFulfilled:null,onRejected:to},{onFulfilled:null,onRejected:tt}],ho=[{onFulfilled:fo,onRejected:null,options:void 0},{onFulfilled:lt,onRejected:null,options:void 0}],go=[{onFulfilled:uo,onRejected:co},{onFulfilled:null,onRejected:tt}],_o=1,vo=1e3,yo=0,bo=59,xo=.8,So=500;var Co=class extends he{name=`RateLimitManager`;async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=bo,i=xo,a=So){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=yo)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=yo)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=Math.min(o,s/(a/vo)),u=_o/l,d=Math.max(nt,c*u);return Math.min(c,d)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,l.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=c.map(e=>e.key),d=c.map(e=>e.rateLimit);return await this.executeScript(it.incr,[a,...u],[o.toString(),...d.map(String)])??0}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},$=class{static instances=new Map;static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,l.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,l.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){let t=this.instances.get(e);return t?.getInstanceIfReady?.()??null}static reset(e){let t=this.instances.get(e);t?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let wo=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const To=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,s=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=s.includes(`RETRY`)?Do(e,n):Eo(e,n),(0,l.isMissing)(n?.service)||(0,l.isMissing)(n?.organizationId)||o===`test`||(0,l.isMissing)(t)||(0,l.isMissing)(e))return a;let c=$.getIfReady(Co)??void 0,u=$.getIfReady(We)??void 0,d=c?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(s.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...ho),m.push(...go)}let h=Za(n);if((0,l.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,l.notMissing)(a)}}),a;let g=await et.get(h);if((0,l.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:c},v=Ze.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await et.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,l.notMissing)(a)},error:t,code:wo.HttpTransportInstanceCreateError}),(0,l.notMissing)(a)?a:Oo()}},Eo=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return Ze.createInstance(n)??Oo()},Do=(e,t)=>{let n={interceptors:{requestConfigs:po,responseConfigs:mo},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return Ze.createInstance(n)??Oo()},Oo=()=>{let e=d.default.create({maxBodyLength:1/0});return e};var ko=class e{#transportFactory;#getRedisClient;#logger;#redisClientConfig;#errorMappingFn;#redisClient;constructor({transportFactory:e=To,getRedisClient:t=ue,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.#transportFactory=e,this.#getRedisClient=t,this.#logger=n,this.#redisClientConfig=r,this.#errorMappingFn=i}#generateCacheKey({url:e,payload:t,method:n,context:r}){let i=20;if(!r?.accountSecureId||r.accountSecureId.length<i||!e||!n)return null;let a=t?(0,l.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#getCachedResponse({url:t,payload:n,method:r,cacheTTL:i,context:a}){if(!this.#redisClient||!i||i<=0)return null;let o=this.#generateCacheKey({url:t,payload:n,method:r,context:a});if(!o)return null;let s=await this.#redisClient.getData(o);return s?(this.#logger?.debug({category:e.name,message:`Cache hit for key [${o}].`}),s):(this.#logger?.debug({category:e.name,message:`Cache miss for key [${o}].`}),null)}async#cacheResponse({url:t,payload:n,method:r,cacheTTL:i,context:a,response:o}){if(!this.#redisClient||!i||i<=0)return!1;let s=this.#generateCacheKey({url:t,payload:n,method:r,context:a});return s?(this.#logger?.debug({category:e.name,message:`Caching result for key [${s}].`}),this.#redisClient.setData({key:s,value:o,cacheTTL:i*60})):!1}async request({headers:t={},url:n,method:r=`get`,queryParams:i,maxRedirects:a=0,responseType:o,cacheTTL:s,context:c,traceId:u,payload:d,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:h}){try{(0,l.notMissing)(this.#redisClientConfig)&&(0,l.isMissing)(this.#redisClient)&&(this.#redisClient=await this.#getRedisClient(this.#redisClientConfig,this.#logger));let e=this.#buildUrlWithQueryParams(n,i),g=this.#normalizeHeaders(t),_=this.#getSafePayload(d,t),v=await this.#getCachedResponse({url:e,payload:_,method:r,cacheTTL:s,context:c});if(v)return{...v,responseTime:new Date};let y=$e.getInstance(),b=(0,l.notMissing)(u)?await y.get(u):null,x=b?.signal,S=await this.#transportFactory({redisClientConfig:this.#redisClientConfig,logger:this.#logger,context:c,requestConfig:m,httpsAgentConfig:h}),ee=await S.request({headers:g,url:e,method:r,maxRedirects:a,responseType:o,data:_,httpsAgent:f,httpAgent:p,signal:x}),C={data:ee.data,status:ee.status,body:_,method:r,headers:this.#extractAxiosHeaders(ee.headers),requestUrl:n,responseType:ee?.config?.responseType,responseTime:new Date};return await this.#cacheResponse({url:e,payload:_,method:r,cacheTTL:s,context:c,response:C}),C}catch(t){let i=t;i.url=(0,g.redactUrl)(n),this.#logger?.warning({category:e.name,message:`Request error [${r?.toUpperCase()} ${i.url}]: ${i.message}.`,error:i});let a=this.#mapErrorToHttpException(i);throw(0,l.notMissing)(a)?a:t}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}#normalizeHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#extractAxiosHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#isFormUrlEncoded(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#getSafePayload(e,t){if(!((0,l.isMissing)(e)||(0,l.isObject)(e)&&Object.keys(e).length===0))return this.#isFormUrlEncoded(t)?_.default.stringify(e):e}#mapErrorToHttpException(e){if((0,d.isAxiosError)(e)&&this.#errorMappingFn)return this.#errorMappingFn(e)}#buildUrlWithQueryParams(e,t){if((0,l.isMissing)(t)||Object.keys(t).length===0)return e;let n=_.default.stringify(t);return`${e}?${n}`}};const Ao=(e,t,n)=>new ko({redisClientConfig:e,logger:t,errorMappingFn:n});var jo=class{static httpClientInstance=null;static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=Ao}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const Mo=[`get`,`post`,`put`,`delete`,`patch`],No={[A.rPush]:`
131
+ (function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function a(e,t){if(isNaN(e=parseInt(e,10)))throw h();return e*t}function o(e,t){if(t===0)throw m();var n=Object.create(p.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=f(e,t);return n.n=e/r,n.d=t/r,n}function s(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var c=function(e,t){var n=0,r=1,o=1,s=0,c=0,l=0,u=1,d=1,f=0,p=1,_=1,v=1,y=1e7,b;if(e!=null)if(t!==void 0){if(n=e,r=t,o=n*r,n%1!=0||r%1!=0)throw g()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw h();o=n*r;break;case`number`:if(e<0&&(o=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(d=10**Math.floor(1+Math.log(e)/Math.LN10),e/=d);p<=y&&v<=y;)if(b=(f+_)/(p+v),e===b){p+v<=y?(n=f+_,r=p+v):v>p?(n=_,r=v):(n=f,r=p);break}else e>b?(f+=_,p+=v):(_+=f,v+=p),p>y?(n=_,r=v):(n=f,r=p);n*=d}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(p=e.match(/\d+|./g),p===null)throw h();if(p[f]===`-`?(o=-1,f++):p[f]===`+`&&f++,p.length===f+1?c=a(p[f++],o):p[f+1]===`.`||p[f]===`.`?(p[f]!==`.`&&(s=a(p[f++],o)),f++,(f+1===p.length||p[f+1]===`(`&&p[f+3]===`)`||p[f+1]===`'`&&p[f+3]===`'`)&&(c=a(p[f],o),u=10**p[f].length,f++),(p[f]===`(`&&p[f+2]===`)`||p[f]===`'`&&p[f+2]===`'`)&&(l=a(p[f+1],o),d=10**p[f+1].length-1,f+=3)):p[f+1]===`/`||p[f+1]===`:`?(c=a(p[f],o),u=a(p[f+2],1),f+=3):p[f+3]===`/`&&p[f+1]===` `&&(s=a(p[f],o),c=a(p[f+2],o),u=a(p[f+4],1),f+=5),p.length<=f){r=u*d,o=n=l+r*s+d*c;break}default:throw h()}if(r===0)throw m();i.s=o<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)};function l(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function u(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function d(e,t,n){for(var r=1,i=l(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function f(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function p(e,t){if(c(e,t),this instanceof p)e=f(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return o(i.s*i.n,i.d)}var m=function(){return Error(`Division by Zero`)},h=function(){return Error(`Invalid argument`)},g=function(){return Error(`Parameters must be integer`)};p.prototype={s:1,n:0,d:1,abs:function(){return o(this.n,this.d)},neg:function(){return o(-this.s*this.n,this.d)},add:function(e,t){return c(e,t),o(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return c(e,t),o(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return o(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new p(NaN);if(e===void 0)return o(this.s*this.n%this.d,1);if(c(e,t),i.n===0&&this.d===0)throw m();return o(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return c(e,t),o(f(i.n,this.n)*f(i.d,this.d),i.d*this.d)},lcm:function(e,t){return c(e,t),i.n===0&&this.n===0?o(0,1):o(i.n*this.n,f(i.n,this.n)*f(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return o(this.s*this.d,this.n)},pow:function(e,t){if(c(e,t),i.d===1)return i.s<0?o((this.s*this.d)**+i.n,this.n**+i.n):o((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=s(this.n),r=s(this.d),a=1,l=1;for(var u in n){if(u===`1`)continue;if(u===`0`){a=0;break}if(n[u]*=i.n,n[u]%i.d===0)n[u]/=i.d;else return null;a*=u**+n[u]}for(var u in r){if(u===`1`)continue;if(r[u]*=i.n,r[u]%i.d===0)r[u]/=i.d;else return null;l*=u**+r[u]}return i.s<0?o(l,a):o(a,l)},equals:function(e,t){return c(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){c(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=o(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return c(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=u(t,n),i=d(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof exports==`object`?(Object.defineProperty(p,`__esModule`,{value:!0}),p.default=p,p.Fraction=p,t.exports=p):n.Fraction=p})(exports)})),ha=c(ma(),1),ga=`Fraction`,_a=[],va=ar(ga,_a,()=>(Object.defineProperty(ha.default,`name`,{value:`Fraction`}),ha.default.prototype.constructor=ha.default,ha.default.prototype.type=`Fraction`,ha.default.prototype.isFraction=!0,ha.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},ha.default.fromJSON=function(e){return new ha.default(e)},ha.default),{isClass:!0}),ya=`Matrix`,ba=[],xa=ar(ya,ba,()=>{function e(){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`)}return e.prototype.type=`Matrix`,e.prototype.isMatrix=!0,e.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},e.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},e.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},e.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},e.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},e.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},e.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},e.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},e.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},e.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},e.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},e.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},e.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},e.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},e.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},e.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},e.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},e},{isClass:!0});function Sa(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Ca=`DenseMatrix`,wa=[`Matrix`],Ta=ar(Ca,wa,e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!wt(t))throw Error(`Invalid datatype: `+t);if(Tt(e))e.type===`DenseMatrix`?(this._data=an(e._data),this._size=an(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&N(e.data)&&N(e.size))this._data=e.data,this._size=e.size,Vn(this._data,this._size),this._datatype=t||e.datatype;else if(N(e))this._data=l(e),this._size=zn(this._data),Vn(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+rn(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}n.prototype=new t,n.prototype.createDenseMatrix=function(e,t){return new n(e,t)},Object.defineProperty(n,`name`,{value:`DenseMatrix`}),n.prototype.constructor=n,n.prototype.type=`DenseMatrix`,n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return Zn(this._data,rn)},n.prototype.storage=function(){return`dense`},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(e,t){return new n(e,t)},n.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return r(this,e);case 2:case 3:return a(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},n.prototype.get=function(e){if(!N(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new F(e.length,this._size.length);for(var t=0;t<e.length;t++)I(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];I(a,n.length),n=n[a]}return n},n.prototype.set=function(e,t,n){if(!N(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new F(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});c(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],I(a,s.length),s=s[a];return a=e[e.length-1],I(a,s.length),s[a]=t,this};function r(e,t){if(!At(t))throw TypeError(`Invalid index`);var r=t.isScalar();if(r)return e.get(t.min());var a=t.size();if(a.length!==e._size.length)throw new F(a.length,e._size.length);for(var o=t.min(),s=t.max(),c=0,l=e._size.length;c<l;c++)I(o[c],e._size[c]),I(s[c],e._size[c]);return new n(i(e._data,t,a.length,0),e._datatype)}function i(e,t,n,r){var a=r===n-1,o=t.dimension(r);return a?o.map(function(t){return I(t,e.length),e[t]}).valueOf():o.map(function(a){I(a,e.length);var o=e[a];return i(o,t,n,r+1)}).valueOf()}function a(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),s;if(Tt(n)?(s=n.size(),n=n.valueOf()):s=zn(n),a){if(s.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!sn(s,i))try{n=s.length===0?nr([n],i):nr(n,i),s=zn(n)}catch{}if(i.length<e._size.length)throw new F(i.length,e._size.length,`<`);if(s.length<i.length){for(var l=0,u=0;i[l]===1&&s[l]===1;)l++;for(;i[l]===1;)u++,l++;n=Jn(n,i.length,u,s)}if(!sn(i,s))throw new F(i,s,`>`);var d=t.max().map(function(e){return e+1});c(e,d,r);var f=i.length,p=0;o(e._data,t,n,f,p)}return e}function o(e,t,n,r,i){var a=i===r-1,s=t.dimension(i);a?s.forEach(function(t,r){I(t),e[t]=n[r[0]]}):s.forEach(function(a,s){I(a),o(e[a],t,n[s[0]],r,i+1)})}n.prototype.resize=function(e,t,n){if(!Et(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e),i=n?this.clone():this;return s(i,r,t)};function s(e,t,n){if(t.length===0){for(var r=e._data;N(r);)r=r[0];return r}return e._size=t.slice(0),e._data=Hn(e._data,e._size,n),e}n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=Wn(n._data,e);var r=n._size.reduce((e,t)=>e*t);return n._size=Gn(e,r),n};function c(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&s(e,r,n)}n.prototype.clone=function(){var e=new n({data:an(this._data),size:an(this._size),datatype:this._datatype});return e},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=Sa(e),i=function n(i,a){return N(i)?i.map(function(e,t){return n(e,a.concat(t))}):r===1?e(i):r===2?e(i,a):e(i,a,t)},a=i(this._data,[]),o=this._datatype===void 0?void 0:Zn(a,rn);return new n(a,o)},n.prototype.forEach=function(e){var t=this,n=function n(r,i){N(r)?r.forEach(function(e,t){n(e,i.concat(t))}):e(r,i,t)};n(this._data,[])},n.prototype[Symbol.iterator]=function*(){var e=function*e(t,n){if(N(t))for(var r=0;r<t.length;r++)yield*e(t[r],n.concat(r));else yield{value:t,index:n}};yield*e(this._data,[])},n.prototype.rows=function(){var e=[],t=this.size();if(t.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);var r=this._data;for(var i of r)e.push(new n([i],this._datatype));return e},n.prototype.columns=function(){var e=this,t=[],r=this.size();if(r.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var i=this._data,a=function(r){var a=i.map(e=>[e[r]]);t.push(new n(a,e._datatype))},o=0;o<r[1];o++)a(o);return t},n.prototype.toArray=function(){return an(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(e){return jn(this._data,e)},n.prototype.toString=function(){return jn(this._data)},n.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(e){if(e){if(bt(e)&&(e=e.toNumber()),!M(e)||!P(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,r=e<0?-e:0,i=this._size[0],a=this._size[1],o=Math.min(i-r,a-t),s=[],c=0;c<o;c++)s[c]=this._data[c+r][c+t];return new n({data:s,size:[o],datatype:this._datatype})},n.diagonal=function(e,t,r,i){if(!N(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(bt(e)&&(e=e.toNumber()),!M(e)||!P(e)||e<1)throw Error(`Size values must be positive integers`);return e}),r){if(bt(r)&&(r=r.toNumber()),!M(r)||!P(r))throw TypeError(`The parameter k must be an integer number`)}else r=0;var a=r>0?r:0,o=r<0?-r:0,s=e[0],c=e[1],l=Math.min(s-o,c-a),u;if(N(t)){if(t.length!==l)throw Error(`Invalid value array length`);u=function(e){return t[e]}}else if(Tt(t)){var d=t.size();if(d.length!==1||d[0]!==l)throw Error(`Invalid matrix length`);u=function(e){return t.get([e])}}else u=function(){return t};i||=bt(u(0))?u(0).mul(0):0;var f=[];if(e.length>0){f=Hn(f,e,i);for(var p=0;p<l;p++)f[p+o][p+a]=u(p)}return new n({data:f,size:[s,c]})},n.fromJSON=function(e){return new n(e)},n.prototype.swapRows=function(e,t){if(!M(e)||!P(e)||!M(t)||!P(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return I(e,this._size[0]),I(t,this._size[0]),n._swapRows(e,t,this._data),this},n._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function l(e){return Tt(e)?l(e.valueOf()):N(e)?e.map(l):e}return n},{isClass:!0});function Ea(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return Ea(e,t,n)}):t(e)}var Da=`isNumeric`,Oa=[`typed`],ka=ar(Da,Oa,e=>{var{typed:t}=e;return t(Da,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>Ea(t,e))})}),Aa=`hasNumericValue`,ja=[`typed`,`isNumeric`],Ma=ar(Aa,ja,e=>{var{typed:t,isNumeric:n}=e;return t(Aa,{boolean:()=>!0,string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})}),Na=ia({config:pn}),Pa=pa({}),Fa=va({}),Ia=xa({}),La=Ta({Matrix:Ia}),Ra=Sr({BigNumber:Na,Complex:Pa,DenseMatrix:La,Fraction:Fa}),za=ka({typed:Ra}),Ba=Ma({isNumeric:za,typed:Ra});const Va=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},Ha=e=>{let t=Number(e),n=Date.now();if(Number.isNaN(t))return n+gt;if(!Va(t)&&(0,l.isFutureUnixTimestamp)(t))return _t(t);if(Va(t))return n+t;{let e=t*mt;return n+e}},Ua=`ratelimitlimit`,Wa=`ratelimitremaining`,Ga=`ratelimitreset`,Ka=`ratelimitconcurrencylimit`,qa=`ratelimitconcurrencyremaining`,Ja=`ratelimitconcurrencyreset`,Ya=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``),i=Ba(r)?Number(r):null;t[e]=i}return t},Xa=e=>{let t=Ya(e);return{rateLimitLimit:t[Ua],rateLimitRemaining:t[Wa],rateLimitReset:Ha(t[Ga]),concurrencyLimit:t[Ka],concurrencyRemaining:t[qa],concurrencyReset:Ha(t[Ja])}},Za=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:s}=e??{};return[t,n,r,o].some(l.isMissing)?null:[t,n,r,i,a,o,...s??[]].filter(Boolean).join(`-`)},Qa=(e,t=dt,n=ut)=>{let r=Date.now();return(0,l.isFutureUnixTimestamp)(e)||(0,l.isNumber)(e)?$a(Number(e),r,t,n):wt(e)&&e!==``?eo(e,r,t,n):n},$a=(e,t,n=dt,r=ut)=>{if(e<n)return e;let i=_t(e);if(i>t){let e=Math.floor((i-t)/mt);return e>0&&e<n?e:r}return r},eo=(e,t,n=dt,r=ut)=>{if(ht.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/mt);return e>0&&e<n?e:r}return r},to=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let i=async i=>{let{response:a,config:o}=i,s=o?.signal;if(s?.aborted)return Promise.reject(ot(`Request aborted`,o,`ERR_CANCELED`,a));let{status:c,retryAfter:u}=no(a,r,n,t);if(c===429&&(0,l.notMissing)(o)){let n=Qa(u);if(o._retryCount>=ft)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${o?.url}. Aborting.`,context:{...r??{},retryAfterHeader:u,retryAfterAsNumber:n}}),Promise.reject(i);let s=o._retryCount??0,c={...o,_retryCount:s+1},d=u?n*mt:(0,l.exponentialBackoffInMS)(c._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${o?.url}`,context:{...r??{},retryAfterHeader:u,calculatedRetryAfter:d}}),await st(d*1e3,o,a),e?.request(c)}return Promise.reject(i)};return i},no=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:s}=e??{},{retryafter:c}=Ya(o??{});if((0,l.isMissing)(i)||(0,l.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,l.isMissing)(e),providerIsMissing:(0,l.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:c??`undefined`}}),{status:a,retryAfter:c};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,l.notMissing)(u)&&(0,l.notMissing)(s))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=(0,l.isObject)(s)?h.default.query(s,f)[0]:s,m=ro(p,r);if(t===a&&m){let e=d??io(o,i),t=ao(e,u);return{status:429,retryAfter:c??t}}}return{status:a,retryAfter:c}},ro=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,io=(e,t)=>(0,l.notMissing)(t)&&(0,l.notMissing)(e)?h.default.query(e,t)[0]:null,ao=(e,t=`seconds`)=>(0,l.notMissing)(e)?oo(e,t):null,oo=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`){let t=typeof e==`string`?parseFloat(e):e;return t/mt}if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},so=`rateLimitErrorInterceptor`,co=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let a=async a=>{let{response:o,config:s}=a,c=s?.signal;if((0,l.isMissing)(r)||(0,l.isMissing)(s))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:so,...s,headers:void 0,hasContext:(0,l.notMissing)(r),hasConfig:(0,l.notMissing)(s)},code:at.InterceptorContextNotPresent}),Promise.reject(a);if((0,l.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:so,...s,headers:void 0,concurrencyManagerInitialized:(0,l.notMissing)(i)},code:at.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p}=s?.requestMetadata??{},m=(0,l.notMissing)(u)&&(0,l.notMissing)(d)?await i.releaseRequest(u,d):!1;if(!m&&(0,l.notMissing)(s?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:so,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:at.RateLimiterReleaseRequestFailed}),c?.aborted)return Promise.reject(ot(`Request aborted`,s,`ERR_CANCELED`,o));let{status:h,retryAfter:g}=no(o,r,n,t);if(h===429&&(0,l.notMissing)(s)){let n=Qa(g);if(s._retryCount>=ft)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${s.url}. Aborting.`,context:{...r??{},...s.requestMetadata??{},retryAfterHeader:g,retryAfterAsNumber:n}}),Promise.reject(a);let i=s?._retryCount??0,c={...s,_retryCount:i+1},u=g?n*mt:(0,l.exponentialBackoffInMS)(c._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${s.url}`,context:{...r,retryAfterHeader:g,calculatedRetryAfter:u}}),await st(u*1e3,s,o),e?.request(c)}return Promise.reject(a)};return a},lo=`rateLimitResponseInterceptor`,uo=({logger:e,context:t,concurrencyManager:n})=>{let r=async r=>{let i=r?.config,a=i?.signal;if((0,l.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{...i,interceptor:lo,headers:void 0}});else if((0,l.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:lo,...i,headers:void 0,concurrencyManagerInitialized:(0,l.notMissing)(n)},code:at.RateLimitOrConcurrencyManagerNotInitialized}),r;else if((0,l.notMissing)(t.provider)&&(0,l.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,l.notMissing)(t)){let n=Xa(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:lo,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:u}=i?.requestMetadata??{},d=await n.releaseRequest(o,s);if(d||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:lo,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:u},code:at.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(ot(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return r},fo=e=>(e.validateStatus??=e=>e>=200&&e<300,e),po=[{onFulfilled:fo,onRejected:null,options:void 0}],mo=[{onFulfilled:null,onRejected:to},{onFulfilled:null,onRejected:tt}],ho=[{onFulfilled:fo,onRejected:null,options:void 0},{onFulfilled:lt,onRejected:null,options:void 0}],go=[{onFulfilled:uo,onRejected:co},{onFulfilled:null,onRejected:tt}],_o=1,vo=1e3,yo=0,bo=59,xo=.8,So=500;var Co=class extends he{name=`RateLimitManager`;async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=bo,i=xo,a=So){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=yo)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=yo)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=Math.min(o,s/(a/vo)),u=_o/l,d=Math.max(nt,c*u);return Math.min(c,d)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,l.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=c.map(e=>e.key),d=c.map(e=>e.rateLimit);return await this.executeScript(it.incr,[a,...u],[o.toString(),...d.map(String)])??0}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},$=class{static instances=new Map;static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,l.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,l.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){let t=this.instances.get(e);return t?.getInstanceIfReady?.()??null}static reset(e){let t=this.instances.get(e);t?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let wo=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const To=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,s=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=s.includes(`RETRY`)?Do(e,n):Eo(e,n),(0,l.isMissing)(n?.service)||(0,l.isMissing)(n?.organizationId)||o===`test`||(0,l.isMissing)(t)||(0,l.isMissing)(e))return a;let c=$.getIfReady(Co)??void 0,u=$.getIfReady(We)??void 0,d=c?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(s.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...ho),m.push(...go)}let h=Za(n);if((0,l.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,l.notMissing)(a)}}),a;let g=await et.get(h);if((0,l.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:c},v=Ze.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await et.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,l.notMissing)(a)},error:t,code:wo.HttpTransportInstanceCreateError}),(0,l.notMissing)(a)?a:Oo()}},Eo=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return Ze.createInstance(n)??Oo()},Do=(e,t)=>{let n={interceptors:{requestConfigs:po,responseConfigs:mo},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return Ze.createInstance(n)??Oo()},Oo=()=>{let e=d.default.create({maxBodyLength:1/0});return e};var ko=class e{#transportFactory;#getRedisClient;#logger;#redisClientConfig;#errorMappingFn;#redisClient;constructor({transportFactory:e=To,getRedisClient:t=ue,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.#transportFactory=e,this.#getRedisClient=t,this.#logger=n,this.#redisClientConfig=r,this.#errorMappingFn=i}#generateCacheKey({url:e,payload:t,method:n,context:r}){let i=20;if(!r?.accountSecureId||r.accountSecureId.length<i||!e||!n)return null;let a=t?(0,l.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#getCachedResponse({url:t,payload:n,method:r,cacheTTL:i,context:a}){if(!this.#redisClient||!i||i<=0)return null;let o=this.#generateCacheKey({url:t,payload:n,method:r,context:a});if(!o)return null;let s=await this.#redisClient.getData(o);return s?(this.#logger?.debug({category:e.name,message:`Cache hit for key [${o}].`}),s):(this.#logger?.debug({category:e.name,message:`Cache miss for key [${o}].`}),null)}async#cacheResponse({url:t,payload:n,method:r,cacheTTL:i,context:a,response:o}){if(!this.#redisClient||!i||i<=0)return!1;let s=this.#generateCacheKey({url:t,payload:n,method:r,context:a});return s?(this.#logger?.debug({category:e.name,message:`Caching result for key [${s}].`}),this.#redisClient.setData({key:s,value:o,cacheTTL:i*60})):!1}async request({headers:t={},url:n,method:r=`get`,queryParams:i,maxRedirects:a=0,responseType:o,cacheTTL:s,context:c,traceId:u,payload:d,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:h}){try{(0,l.notMissing)(this.#redisClientConfig)&&(0,l.isMissing)(this.#redisClient)&&(this.#redisClient=await this.#getRedisClient(this.#redisClientConfig,this.#logger,`HttpClient`));let e=this.#buildUrlWithQueryParams(n,i),g=this.#normalizeHeaders(t),_=this.#getSafePayload(d,t),v=await this.#getCachedResponse({url:e,payload:_,method:r,cacheTTL:s,context:c});if(v)return{...v,responseTime:new Date};let y=$e.getInstance(),b=(0,l.notMissing)(u)?await y.get(u):null,x=b?.signal,S=await this.#transportFactory({redisClientConfig:this.#redisClientConfig,logger:this.#logger,context:c,requestConfig:m,httpsAgentConfig:h}),ee=await S.request({headers:g,url:e,method:r,maxRedirects:a,responseType:o,data:_,httpsAgent:f,httpAgent:p,signal:x}),C={data:ee.data,status:ee.status,body:_,method:r,headers:this.#extractAxiosHeaders(ee.headers),requestUrl:n,responseType:ee?.config?.responseType,responseTime:new Date};return await this.#cacheResponse({url:e,payload:_,method:r,cacheTTL:s,context:c,response:C}),C}catch(t){let i=t;i.url=(0,g.redactUrl)(n),this.#logger?.warning({category:e.name,message:`Request error [${r?.toUpperCase()} ${i.url}]: ${i.message}.`,error:i});let a=this.#mapErrorToHttpException(i);throw(0,l.notMissing)(a)?a:t}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}#normalizeHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#extractAxiosHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#isFormUrlEncoded(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#getSafePayload(e,t){if(!((0,l.isMissing)(e)||(0,l.isObject)(e)&&Object.keys(e).length===0))return this.#isFormUrlEncoded(t)?_.default.stringify(e):e}#mapErrorToHttpException(e){if((0,d.isAxiosError)(e)&&this.#errorMappingFn)return this.#errorMappingFn(e)}#buildUrlWithQueryParams(e,t){if((0,l.isMissing)(t)||Object.keys(t).length===0)return e;let n=_.default.stringify(t);return`${e}?${n}`}};const Ao=(e,t,n)=>new ko({redisClientConfig:e,logger:t,errorMappingFn:n});var jo=class{static httpClientInstance=null;static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=Ao}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const Mo=[`get`,`post`,`put`,`delete`,`patch`],No={[A.rPush]:`
132
132
  local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
133
133
 
134
134
  redis.call('PEXPIRE', KEYS[1], ARGV[2])
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{safeEvaluate as S}from"@stackone/expressions";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,D=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty,O=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),te=(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],!ee.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(D(e)),te(t||!e||!e.__esModule?w(n,`default`,{value:e,enumerable:!0}):n,e));const A=e=>{switch(e.type){case`none`:return{};case`basic`:return ne(e);case`bearer`:return re(e);case`oauth2`:return re(e);default:throw Error(`Invalid authentication type`)}},ne=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},re=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var ie=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 ae=1e3,oe=100,se=60,ce=6e4,le=se,ue=ce,de=ce*10,fe=oe,pe=10;let me=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var he=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 ie,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??ue,this.staleDataThreshold=e?.staleDataThreshold??de,this.truncateThreshold=e?.truncateThreshold??fe,this.truncationPercentage=e?.truncationPercentage??pe,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=le}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),u(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*ae,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/oe;(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:me.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 ge=1e3,_e=6e4;let ve=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var ye=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 he(i),this.promiseStore=new he(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/ge;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??_e),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:ve.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}},be=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 j=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 xe=async(e,t)=>{try{let n=await Se.build(e,t);return n??void 0}catch(e){let n=e;t?.error({message:`Error building Cache Manager`,error:n,code:j.RedisClientError,category:`buildRedisClientInstance`});return}};var Se=class e{#redisClient;#logger;static async build({getRedisClient:t=p.createClient,host:n,port:r,tls:i,reconnect:a=!0,database:o},s){let c=new e;c.#logger=s;try{c.#redisClient=t({socket:{reconnectStrategy:a?e=>Math.min(e*20,5e3):!1,host:n,port:r,tls:i},database:o,disableOfflineQueue:!0});let s=we(e.name,c.#logger);return Ce(c.#redisClient,s),await c.#redisClient.connect(),c}catch(t){let n=t;return c.#logger?.error({message:`Error building Cache Manager.`,error:n,code:j.RedisClientError,category:e.name}),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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.RedisClientDeleteError,category:e.name}),!1}}};const Ce=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},we=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:j.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 Te=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var Ee=class extends be{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 xe(e,i);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:Te.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:Te.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&u(this.cacheClient)}},De=class{options={getCacheClient:xe};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 he({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)??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 Oe=6e4,ke=15e3,Ae=!1,je=6e4,Me=15e3,Ne=1e4,Pe=1;let Fe=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),Ie=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var Le=class extends Ee{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 De({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:je,truncateThreshold:Ne,truncationPercentage:Pe}),await this.subscriptionManager?.initialize(),this.eventClient=new ye({instantiator:this.name,timeoutResolveValue:Ae},{instantiator:this.name,evictionFrequency:Me,truncateThreshold:Ne,truncationPercentage:Pe},{instantiator:this.name,evictionFrequency:Me,truncateThreshold:Ne,truncationPercentage:Pe}),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?Ie.lPush:Ie.rPush,[e],[t,Oe.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,ke),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:Fe.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(Ie.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Fe.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(Ie.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Fe.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 Re=5,ze=12e4,Be=1e4,Ve=1,He=60,Ue=90,We=`__keyevent@0__:`,Ge=`${We}set`,Ke=`${We}expire`,qe=`${We}expired`,Je=`${We}srem`,Ye=`config_check_test_key`,Xe=[Ge,Ke,qe],Ze=1,Qe=1e4,$e={mainMaxConcurrency:30};let et=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),tt=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const nt={[tt.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{safeEvaluate as S}from"@stackone/expressions";var C=Object.create,w=Object.defineProperty,T=Object.getOwnPropertyDescriptor,E=Object.getOwnPropertyNames,D=Object.getPrototypeOf,ee=Object.prototype.hasOwnProperty,O=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),te=(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],!ee.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(D(e)),te(t||!e||!e.__esModule?w(n,`default`,{value:e,enumerable:!0}):n,e));const A=e=>{switch(e.type){case`none`:return{};case`basic`:return ne(e);case`bearer`:return re(e);case`oauth2`:return re(e);default:throw Error(`Invalid authentication type`)}},ne=({username:e=``,password:t=``,encoding:n=`base64`})=>{let r=n,i=Buffer.from(`${e}:${t}`).toString(r);return{authorization:`Basic ${i}`}},re=({token:e,includeBearer:t})=>({authorization:`${t?`Bearer `:``}${e}`});var ie=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 ae=1e3,oe=100,se=60,ce=6e4,le=se,ue=ce,de=ce*10,fe=oe,pe=10;let me=function(e){return e.MemoryStorePruneError=`MemoryStorePruneError`,e}({});var he=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 ie,this.expiryMap=e?.expiryMap??new Map,this.evictionFrequency=e?.evictionFrequency??ue,this.staleDataThreshold=e?.staleDataThreshold??de,this.truncateThreshold=e?.truncateThreshold??fe,this.truncationPercentage=e?.truncationPercentage??pe,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=le}){if(this.isReady()||this.initialize(),this.updateLastAccessedAt(),u(this.typeGuard)&&!this.typeGuard(t))return!1;let r=n*ae,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/oe;(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:me.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 ge=1e3,_e=6e4;let ve=function(e){return e.EventClientResolveError=`EventClientResolveError`,e}({});var ye=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 he(i),this.promiseStore=new he(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/ge;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??_e),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:ve.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}},be=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 j=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 xe=async(e,t,n)=>{try{let r=await Se.build(e,t,n);return r??void 0}catch(e){let r=e;t?.error({message:`Error building Cache Manager`,error:r,code:j.RedisClientError,category:n??`buildRedisClientInstance`});return}};var Se=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=we(c??`RedisClient`,l.#logger);return Ce(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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.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:j.RedisClientDeleteError,category:e.name}),!1}}};const Ce=(e,t)=>{t.forEach(({eventName:t,listener:n})=>{e.on(t,n)})},we=(e=`RedisClient`,t)=>[{eventName:`error`,listener:n=>{t?.error({message:`Redis client error ${n.message}`,error:n,code:j.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 Te=function(e){return e.ScriptManagerExecutionError=`ScriptManagerExecutionError`,e.ScriptManagerLoadingError=`ScriptManagerLoadingError`,e}({});var Ee=class extends be{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 xe(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:Te.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:Te.ScriptManagerExecutionError}),r}}isRedisReady(){return this.isReady()&&u(this.cacheClient)}},De=class{options={getCacheClient:xe};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 he({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 Oe=6e4,ke=15e3,Ae=!1,je=6e4,Me=15e3,Ne=1e4,Pe=1;let Fe=function(e){return e.QueueManagerInitializationError=`QueueManagerInitializationError`,e.QueueManagerJoinAndWaitTurnError=`QueueManagerJoinAndWaitTurnError`,e.QueueManagerLengthError=`QueueManagerLengthError`,e.QueueManagerPopError=`QueueManagerPopError`,e}({}),Ie=function(e){return e.rPush=`rPush`,e.lPush=`lPush`,e.lPop=`lPop`,e.llen=`llen`,e}({});var Le=class extends Ee{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 De({config:this.redisClientConfig,instantiator:this.name,subscriptionTTL:je,truncateThreshold:Ne,truncationPercentage:Pe}),await this.subscriptionManager?.initialize(),this.eventClient=new ye({instantiator:this.name,timeoutResolveValue:Ae},{instantiator:this.name,evictionFrequency:Me,truncateThreshold:Ne,truncationPercentage:Pe},{instantiator:this.name,evictionFrequency:Me,truncateThreshold:Ne,truncationPercentage:Pe}),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?Ie.lPush:Ie.rPush,[e],[t,Oe.toString()]),s=o===1,c=i?!s:!0;return c&&await this.eventClient?.waitForEvent(a,ke),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:Fe.QueueManagerJoinAndWaitTurnError,context:{queueName:e,value:t}}),n}}async pop(e){try{return await this.executeScript(Ie.lPop,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in pop`,category:this.name,error:t,code:Fe.QueueManagerPopError,context:{queueName:e}}),t}}async length(e){try{return await this.executeScript(Ie.llen,[e],[])}catch(t){throw t instanceof Error&&this.logger?.error({message:`Error in length`,category:this.name,error:t,code:Fe.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 Re=5,ze=12e4,Be=1e4,Ve=1,He=60,Ue=90,We=`__keyevent@0__:`,Ge=`${We}set`,Ke=`${We}expire`,qe=`${We}expired`,Je=`${We}srem`,Ye=`config_check_test_key`,Xe=[Ge,Ke,qe],Ze=1,Qe=1e4,$e={mainMaxConcurrency:30};let et=function(e){return e.ConcurrencyManagerInitializationError=`ConcurrencyManagerInitializationError`,e.ConcurrencyManagerRedisEventsEmitError=`ConcurrencyManagerRedisEventsEmitError`,e.ConcurrencyManagerRegistrationFailed=`ConcurrencyManagerRegistrationFailed`,e}({}),tt=function(e){return e.tryConcurrency=`tryConcurrency`,e.removeFromSet=`removeFromSet`,e.publishNextItem=`publishNextItem`,e}({});const nt={[tt.tryConcurrency]:`
2
2
  local requestId = KEYS[1]
3
3
  local targetKey = KEYS[2]
4
4
  local queueKey = KEYS[3]
@@ -128,7 +128,7 @@ var Rr=9e15,zr=1e9,Br=`0123456789abcdef`,Vr=`2.302585092994045684017991454684364
128
128
  * Copyright (c) 2023, Robert Eisele (robert@raw.org)
129
129
  * Dual licensed under the MIT or GPL Version 2 licenses.
130
130
  **/
131
- (function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function a(e,t){if(isNaN(e=parseInt(e,10)))throw h();return e*t}function o(e,t){if(t===0)throw m();var n=Object.create(p.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=f(e,t);return n.n=e/r,n.d=t/r,n}function s(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var c=function(e,t){var n=0,r=1,o=1,s=0,c=0,l=0,u=1,d=1,f=0,p=1,_=1,v=1,y=1e7,b;if(e!=null)if(t!==void 0){if(n=e,r=t,o=n*r,n%1!=0||r%1!=0)throw g()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw h();o=n*r;break;case`number`:if(e<0&&(o=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(d=10**Math.floor(1+Math.log(e)/Math.LN10),e/=d);p<=y&&v<=y;)if(b=(f+_)/(p+v),e===b){p+v<=y?(n=f+_,r=p+v):v>p?(n=_,r=v):(n=f,r=p);break}else e>b?(f+=_,p+=v):(_+=f,v+=p),p>y?(n=_,r=v):(n=f,r=p);n*=d}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(p=e.match(/\d+|./g),p===null)throw h();if(p[f]===`-`?(o=-1,f++):p[f]===`+`&&f++,p.length===f+1?c=a(p[f++],o):p[f+1]===`.`||p[f]===`.`?(p[f]!==`.`&&(s=a(p[f++],o)),f++,(f+1===p.length||p[f+1]===`(`&&p[f+3]===`)`||p[f+1]===`'`&&p[f+3]===`'`)&&(c=a(p[f],o),u=10**p[f].length,f++),(p[f]===`(`&&p[f+2]===`)`||p[f]===`'`&&p[f+2]===`'`)&&(l=a(p[f+1],o),d=10**p[f+1].length-1,f+=3)):p[f+1]===`/`||p[f+1]===`:`?(c=a(p[f],o),u=a(p[f+2],1),f+=3):p[f+3]===`/`&&p[f+1]===` `&&(s=a(p[f],o),c=a(p[f+2],o),u=a(p[f+4],1),f+=5),p.length<=f){r=u*d,o=n=l+r*s+d*c;break}default:throw h()}if(r===0)throw m();i.s=o<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)};function l(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function u(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function d(e,t,n){for(var r=1,i=l(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function f(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function p(e,t){if(c(e,t),this instanceof p)e=f(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return o(i.s*i.n,i.d)}var m=function(){return Error(`Division by Zero`)},h=function(){return Error(`Invalid argument`)},g=function(){return Error(`Parameters must be integer`)};p.prototype={s:1,n:0,d:1,abs:function(){return o(this.n,this.d)},neg:function(){return o(-this.s*this.n,this.d)},add:function(e,t){return c(e,t),o(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return c(e,t),o(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return o(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new p(NaN);if(e===void 0)return o(this.s*this.n%this.d,1);if(c(e,t),i.n===0&&this.d===0)throw m();return o(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return c(e,t),o(f(i.n,this.n)*f(i.d,this.d),i.d*this.d)},lcm:function(e,t){return c(e,t),i.n===0&&this.n===0?o(0,1):o(i.n*this.n,f(i.n,this.n)*f(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return o(this.s*this.d,this.n)},pow:function(e,t){if(c(e,t),i.d===1)return i.s<0?o((this.s*this.d)**+i.n,this.n**+i.n):o((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=s(this.n),r=s(this.d),a=1,l=1;for(var u in n){if(u===`1`)continue;if(u===`0`){a=0;break}if(n[u]*=i.n,n[u]%i.d===0)n[u]/=i.d;else return null;a*=u**+n[u]}for(var u in r){if(u===`1`)continue;if(r[u]*=i.n,r[u]%i.d===0)r[u]/=i.d;else return null;l*=u**+r[u]}return i.s<0?o(l,a):o(a,l)},equals:function(e,t){return c(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){c(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=o(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return c(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=u(t,n),i=d(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof exports==`object`?(Object.defineProperty(p,`__esModule`,{value:!0}),p.default=p,p.Fraction=p,t.exports=p):n.Fraction=p})(exports)})),Da=k(Ea(),1),Oa=`Fraction`,ka=[],Aa=gr(Oa,ka,()=>(Object.defineProperty(Da.default,`name`,{value:`Fraction`}),Da.default.prototype.constructor=Da.default,Da.default.prototype.type=`Fraction`,Da.default.prototype.isFraction=!0,Da.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},Da.default.fromJSON=function(e){return new Da.default(e)},Da.default),{isClass:!0}),ja=`Matrix`,Ma=[],Na=gr(ja,Ma,()=>{function e(){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`)}return e.prototype.type=`Matrix`,e.prototype.isMatrix=!0,e.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},e.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},e.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},e.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},e.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},e.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},e.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},e.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},e.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},e.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},e.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},e.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},e.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},e.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},e.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},e.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},e.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},e},{isClass:!0});function Pa(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Fa=`DenseMatrix`,Ia=[`Matrix`],La=gr(Fa,Ia,e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!It(t))throw Error(`Invalid datatype: `+t);if(Lt(e))e.type===`DenseMatrix`?(this._data=_n(e._data),this._size=_n(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&P(e.data)&&P(e.size))this._data=e.data,this._size=e.size,Qn(this._data,this._size),this._datatype=t||e.datatype;else if(P(e))this._data=l(e),this._size=Xn(this._data),Qn(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+gn(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}n.prototype=new t,n.prototype.createDenseMatrix=function(e,t){return new n(e,t)},Object.defineProperty(n,`name`,{value:`DenseMatrix`}),n.prototype.constructor=n,n.prototype.type=`DenseMatrix`,n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return cr(this._data,gn)},n.prototype.storage=function(){return`dense`},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(e,t){return new n(e,t)},n.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return r(this,e);case 2:case 3:return a(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},n.prototype.get=function(e){if(!P(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new I(e.length,this._size.length);for(var t=0;t<e.length;t++)L(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];L(a,n.length),n=n[a]}return n},n.prototype.set=function(e,t,n){if(!P(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new I(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});c(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],L(a,s.length),s=s[a];return a=e[e.length-1],L(a,s.length),s[a]=t,this};function r(e,t){if(!Ht(t))throw TypeError(`Invalid index`);var r=t.isScalar();if(r)return e.get(t.min());var a=t.size();if(a.length!==e._size.length)throw new I(a.length,e._size.length);for(var o=t.min(),s=t.max(),c=0,l=e._size.length;c<l;c++)L(o[c],e._size[c]),L(s[c],e._size[c]);return new n(i(e._data,t,a.length,0),e._datatype)}function i(e,t,n,r){var a=r===n-1,o=t.dimension(r);return a?o.map(function(t){return L(t,e.length),e[t]}).valueOf():o.map(function(a){L(a,e.length);var o=e[a];return i(o,t,n,r+1)}).valueOf()}function a(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),s;if(Lt(n)?(s=n.size(),n=n.valueOf()):s=Xn(n),a){if(s.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!yn(s,i))try{n=s.length===0?pr([n],i):pr(n,i),s=Xn(n)}catch{}if(i.length<e._size.length)throw new I(i.length,e._size.length,`<`);if(s.length<i.length){for(var l=0,u=0;i[l]===1&&s[l]===1;)l++;for(;i[l]===1;)u++,l++;n=ar(n,i.length,u,s)}if(!yn(i,s))throw new I(i,s,`>`);var d=t.max().map(function(e){return e+1});c(e,d,r);var f=i.length,p=0;o(e._data,t,n,f,p)}return e}function o(e,t,n,r,i){var a=i===r-1,s=t.dimension(i);a?s.forEach(function(t,r){L(t),e[t]=n[r[0]]}):s.forEach(function(a,s){L(a),o(e[a],t,n[s[0]],r,i+1)})}n.prototype.resize=function(e,t,n){if(!Rt(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e),i=n?this.clone():this;return s(i,r,t)};function s(e,t,n){if(t.length===0){for(var r=e._data;P(r);)r=r[0];return r}return e._size=t.slice(0),e._data=$n(e._data,e._size,n),e}n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=tr(n._data,e);var r=n._size.reduce((e,t)=>e*t);return n._size=nr(e,r),n};function c(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&s(e,r,n)}n.prototype.clone=function(){var e=new n({data:_n(this._data),size:_n(this._size),datatype:this._datatype});return e},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=Pa(e),i=function n(i,a){return P(i)?i.map(function(e,t){return n(e,a.concat(t))}):r===1?e(i):r===2?e(i,a):e(i,a,t)},a=i(this._data,[]),o=this._datatype===void 0?void 0:cr(a,gn);return new n(a,o)},n.prototype.forEach=function(e){var t=this,n=function n(r,i){P(r)?r.forEach(function(e,t){n(e,i.concat(t))}):e(r,i,t)};n(this._data,[])},n.prototype[Symbol.iterator]=function*(){var e=function*e(t,n){if(P(t))for(var r=0;r<t.length;r++)yield*e(t[r],n.concat(r));else yield{value:t,index:n}};yield*e(this._data,[])},n.prototype.rows=function(){var e=[],t=this.size();if(t.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);var r=this._data;for(var i of r)e.push(new n([i],this._datatype));return e},n.prototype.columns=function(){var e=this,t=[],r=this.size();if(r.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var i=this._data,a=function(r){var a=i.map(e=>[e[r]]);t.push(new n(a,e._datatype))},o=0;o<r[1];o++)a(o);return t},n.prototype.toArray=function(){return _n(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(e){return Hn(this._data,e)},n.prototype.toString=function(){return Hn(this._data)},n.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(e){if(e){if(N(e)&&(e=e.toNumber()),!M(e)||!F(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,r=e<0?-e:0,i=this._size[0],a=this._size[1],o=Math.min(i-r,a-t),s=[],c=0;c<o;c++)s[c]=this._data[c+r][c+t];return new n({data:s,size:[o],datatype:this._datatype})},n.diagonal=function(e,t,r,i){if(!P(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(N(e)&&(e=e.toNumber()),!M(e)||!F(e)||e<1)throw Error(`Size values must be positive integers`);return e}),r){if(N(r)&&(r=r.toNumber()),!M(r)||!F(r))throw TypeError(`The parameter k must be an integer number`)}else r=0;var a=r>0?r:0,o=r<0?-r:0,s=e[0],c=e[1],l=Math.min(s-o,c-a),u;if(P(t)){if(t.length!==l)throw Error(`Invalid value array length`);u=function(e){return t[e]}}else if(Lt(t)){var d=t.size();if(d.length!==1||d[0]!==l)throw Error(`Invalid matrix length`);u=function(e){return t.get([e])}}else u=function(){return t};i||=N(u(0))?u(0).mul(0):0;var f=[];if(e.length>0){f=$n(f,e,i);for(var p=0;p<l;p++)f[p+o][p+a]=u(p)}return new n({data:f,size:[s,c]})},n.fromJSON=function(e){return new n(e)},n.prototype.swapRows=function(e,t){if(!M(e)||!F(e)||!M(t)||!F(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return L(e,this._size[0]),L(t,this._size[0]),n._swapRows(e,t,this._data),this},n._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function l(e){return Lt(e)?l(e.valueOf()):P(e)?e.map(l):e}return n},{isClass:!0});function Ra(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return Ra(e,t,n)}):t(e)}var za=`isNumeric`,Ba=[`typed`],Va=gr(za,Ba,e=>{var{typed:t}=e;return t(za,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>Ra(t,e))})}),Ha=`hasNumericValue`,Ua=[`typed`,`isNumeric`],Wa=gr(Ha,Ua,e=>{var{typed:t,isNumeric:n}=e;return t(Ha,{boolean:()=>!0,string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})}),Ga=ga({config:Tn}),Ka=Ta({}),qa=Aa({}),Ja=Na({}),Ya=La({Matrix:Ja}),Xa=Nr({BigNumber:Ga,Complex:Ka,DenseMatrix:Ya,Fraction:qa}),Za=Va({typed:Xa}),Qa=Wa({isNumeric:Za,typed:Xa});const $a=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},eo=e=>{let t=Number(e),n=Date.now();if(Number.isNaN(t))return n+kt;if(!$a(t)&&a(t))return At(t);if($a(t))return n+t;{let e=t*Dt;return n+e}},to=`ratelimitlimit`,no=`ratelimitremaining`,ro=`ratelimitreset`,io=`ratelimitconcurrencylimit`,ao=`ratelimitconcurrencyremaining`,oo=`ratelimitconcurrencyreset`,so=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``),i=Qa(r)?Number(r):null;t[e]=i}return t},co=e=>{let t=so(e);return{rateLimitLimit:t[to],rateLimitRemaining:t[no],rateLimitReset:eo(t[ro]),concurrencyLimit:t[io],concurrencyRemaining:t[ao],concurrencyReset:eo(t[oo])}},lo=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},uo=(e,t=wt,n=Ct)=>{let r=Date.now();return a(e)||s(e)?fo(Number(e),r,t,n):It(e)&&e!==``?po(e,r,t,n):n},fo=(e,t,n=wt,r=Ct)=>{if(e<n)return e;let i=At(e);if(i>t){let e=Math.floor((i-t)/Dt);return e>0&&e<n?e:r}return r},po=(e,t,n=wt,r=Ct)=>{if(Ot.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/Dt);return e>0&&e<n?e:r}return r},mo=({axiosInstance:e,logger:n,requestConfig:r,context:i})=>{let a=async a=>{let{response:o,config:s}=a,c=s?.signal;if(c?.aborted)return Promise.reject(yt(`Request aborted`,s,`ERR_CANCELED`,o));let{status:l,retryAfter:d}=ho(o,i,r,n);if(l===429&&u(s)){let r=uo(d);if(s._retryCount>=Tt)return n?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:d,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,l={...s,_retryCount:c+1},u=d?r*Dt:t(l._retryCount);return n?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:d,calculatedRetryAfter:u}}),await bt(u*1e3,s,o),e?.request(l)}return Promise.reject(a)};return a},ho=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:l}=e??{},{retryafter:d}=so(s??{});if(o(i)||o(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:o(e),providerIsMissing:o(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:d??`undefined`}}),{status:a,retryAfter:d};let f=n?.rateLimits?.mappedRateLimitErrors;if(u(f)&&u(l))for(let e of f){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:o,retryAfterValue:u}=e;if(t!==a)continue;let f=n??`message`,p=c(l)?y.query(l,f)[0]:l,m=go(p,r);if(t===a&&m){let e=u??_o(s,i),t=vo(e,o);return{status:429,retryAfter:d??t}}}return{status:a,retryAfter:d}},go=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,_o=(e,t)=>u(t)&&u(e)?y.query(e,t)[0]:null,vo=(e,t=`seconds`)=>u(e)?yo(e,t):null,yo=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`){let t=typeof e==`string`?parseFloat(e):e;return t/Dt}if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},bo=`rateLimitErrorInterceptor`,xo=({axiosInstance:e,logger:n,requestConfig:r,context:i,concurrencyManager:a})=>{let s=async s=>{let{response:c,config:l}=s,d=l?.signal;if(o(i)||o(l))return n?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:bo,...l,headers:void 0,hasContext:u(i),hasConfig:u(l)},code:vt.InterceptorContextNotPresent}),Promise.reject(s);if(o(a))return n?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:bo,...l,headers:void 0,concurrencyManagerInitialized:u(a)},code:vt.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(s);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h}=l?.requestMetadata??{},g=u(f)&&u(p)?await a.releaseRequest(f,p):!1;if(!g&&u(l?.requestMetadata)&&n?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:bo,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:vt.RateLimiterReleaseRequestFailed}),d?.aborted)return Promise.reject(yt(`Request aborted`,l,`ERR_CANCELED`,c));let{status:_,retryAfter:v}=ho(c,i,r,n);if(_===429&&u(l)){let r=uo(v);if(l._retryCount>=Tt)return n?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:v,retryAfterAsNumber:r}}),Promise.reject(s);let a=l?._retryCount??0,o={...l,_retryCount:a+1},u=v?r*Dt:t(o._retryCount);return n?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:v,calculatedRetryAfter:u}}),await bt(u*1e3,l,c),e?.request(o)}return Promise.reject(s)};return s},So=`rateLimitResponseInterceptor`,Co=({logger:e,context:t,concurrencyManager:n})=>{let r=async r=>{let i=r?.config,a=i?.signal;if(o(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{...i,interceptor:So,headers:void 0}});else if(o(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:So,...i,headers:void 0,concurrencyManagerInitialized:u(n)},code:vt.RateLimitOrConcurrencyManagerNotInitialized}),r;else if(u(t.provider)&&u(t.accountSecureId)){let t=r?.headers;if(u(t)){let n=co(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:So,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l}=i?.requestMetadata??{},d=await n.releaseRequest(o,s);if(d||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:So,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:vt.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(yt(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return r},wo=e=>(e.validateStatus??=e=>e>=200&&e<300,e),To=[{onFulfilled:wo,onRejected:null,options:void 0}],Eo=[{onFulfilled:null,onRejected:mo},{onFulfilled:null,onRejected:mt}],Do=[{onFulfilled:wo,onRejected:null,options:void 0},{onFulfilled:St,onRejected:null,options:void 0}],Oo=[{onFulfilled:Co,onRejected:xo},{onFulfilled:null,onRejected:mt}],ko=1,Ao=1e3,jo=0,Mo=59,No=.8,Po=500;var Fo=class extends Ee{name=`RateLimitManager`;async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=Mo,i=No,a=Po){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=jo)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=jo)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=Math.min(o,s/(a/Ao)),u=ko/l,d=Math.max(ht,c*u);return Math.min(c,d)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=u(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),d=c.map(e=>e.rateLimit);return await this.executeScript(_t.incr,[a,...l],[o.toString(),...d.map(String)])??0}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},$=class{static instances=new Map;static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(o(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(u(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){let t=this.instances.get(e);return t?.getInstanceIfReady?.()??null}static reset(e){let t=this.instances.get(e);t?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let Io=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const Lo=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?zo(e,n):Ro(e,n),o(n?.service)||o(n?.organizationId)||s===`test`||o(t)||o(e))return a;let l=$.getIfReady(Fo)??void 0,d=$.getIfReady(rt)??void 0,f=l?.isReady(),p=d?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...Do),h.push(...Oo)}let g=lo(n);if(o(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:u(a)}}),a;let _=await pt.get(g);if(u(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:d,rateLimitManager:l},y=ut.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await pt.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:u(a)},error:t,code:Io.HttpTransportInstanceCreateError}),u(a)?a:Bo()}},Ro=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return ut.createInstance(n)??Bo()},zo=(e,t)=>{let n={interceptors:{requestConfigs:To,responseConfigs:Eo},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return ut.createInstance(n)??Bo()},Bo=()=>{let e=m.create({maxBodyLength:1/0});return e};var Vo=class e{#transportFactory;#getRedisClient;#logger;#redisClientConfig;#errorMappingFn;#redisClient;constructor({transportFactory:e=Lo,getRedisClient:t=xe,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.#transportFactory=e,this.#getRedisClient=t,this.#logger=n,this.#redisClientConfig=r,this.#errorMappingFn=i}#generateCacheKey({url:e,payload:t,method:n,context:i}){let a=20;if(!i?.accountSecureId||i.accountSecureId.length<a||!e||!n)return null;let o=t?r(t):``;return`${i.accountSecureId}-${n.toUpperCase()}${o}-${e}`}async#getCachedResponse({url:t,payload:n,method:r,cacheTTL:i,context:a}){if(!this.#redisClient||!i||i<=0)return null;let o=this.#generateCacheKey({url:t,payload:n,method:r,context:a});if(!o)return null;let s=await this.#redisClient.getData(o);return s?(this.#logger?.debug({category:e.name,message:`Cache hit for key [${o}].`}),s):(this.#logger?.debug({category:e.name,message:`Cache miss for key [${o}].`}),null)}async#cacheResponse({url:t,payload:n,method:r,cacheTTL:i,context:a,response:o}){if(!this.#redisClient||!i||i<=0)return!1;let s=this.#generateCacheKey({url:t,payload:n,method:r,context:a});return s?(this.#logger?.debug({category:e.name,message:`Caching result for key [${s}].`}),this.#redisClient.setData({key:s,value:o,cacheTTL:i*60})):!1}async request({headers:t={},url:n,method:r=`get`,queryParams:i,maxRedirects:a=0,responseType:s,cacheTTL:c,context:l,traceId:d,payload:f,httpsAgent:p,httpAgent:m,requestConfig:h,httpsAgentConfig:g}){try{u(this.#redisClientConfig)&&o(this.#redisClient)&&(this.#redisClient=await this.#getRedisClient(this.#redisClientConfig,this.#logger));let e=this.#buildUrlWithQueryParams(n,i),_=this.#normalizeHeaders(t),v=this.#getSafePayload(f,t),y=await this.#getCachedResponse({url:e,payload:v,method:r,cacheTTL:c,context:l});if(y)return{...y,responseTime:new Date};let b=ft.getInstance(),x=u(d)?await b.get(d):null,S=x?.signal,C=await this.#transportFactory({redisClientConfig:this.#redisClientConfig,logger:this.#logger,context:l,requestConfig:h,httpsAgentConfig:g}),w=await C.request({headers:_,url:e,method:r,maxRedirects:a,responseType:s,data:v,httpsAgent:p,httpAgent:m,signal:S}),T={data:w.data,status:w.status,body:v,method:r,headers:this.#extractAxiosHeaders(w.headers),requestUrl:n,responseType:w?.config?.responseType,responseTime:new Date};return await this.#cacheResponse({url:e,payload:v,method:r,cacheTTL:c,context:l,response:T}),T}catch(t){let i=t;i.url=b(n),this.#logger?.warning({category:e.name,message:`Request error [${r?.toUpperCase()} ${i.url}]: ${i.message}.`,error:i});let a=this.#mapErrorToHttpException(i);throw u(a)?a:t}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}#normalizeHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#extractAxiosHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#isFormUrlEncoded(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#getSafePayload(e,t){if(!(o(e)||c(e)&&Object.keys(e).length===0))return this.#isFormUrlEncoded(t)?x.stringify(e):e}#mapErrorToHttpException(e){if(h(e)&&this.#errorMappingFn)return this.#errorMappingFn(e)}#buildUrlWithQueryParams(e,t){if(o(t)||Object.keys(t).length===0)return e;let n=x.stringify(t);return`${e}?${n}`}};const Ho=(e,t,n)=>new Vo({redisClientConfig:e,logger:t,errorMappingFn:n});var Uo=class{static httpClientInstance=null;static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=Ho}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const Wo=[`get`,`post`,`put`,`delete`,`patch`],Go={[Ie.rPush]:`
131
+ (function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function a(e,t){if(isNaN(e=parseInt(e,10)))throw h();return e*t}function o(e,t){if(t===0)throw m();var n=Object.create(p.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=f(e,t);return n.n=e/r,n.d=t/r,n}function s(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var c=function(e,t){var n=0,r=1,o=1,s=0,c=0,l=0,u=1,d=1,f=0,p=1,_=1,v=1,y=1e7,b;if(e!=null)if(t!==void 0){if(n=e,r=t,o=n*r,n%1!=0||r%1!=0)throw g()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw h();o=n*r;break;case`number`:if(e<0&&(o=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(d=10**Math.floor(1+Math.log(e)/Math.LN10),e/=d);p<=y&&v<=y;)if(b=(f+_)/(p+v),e===b){p+v<=y?(n=f+_,r=p+v):v>p?(n=_,r=v):(n=f,r=p);break}else e>b?(f+=_,p+=v):(_+=f,v+=p),p>y?(n=_,r=v):(n=f,r=p);n*=d}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(p=e.match(/\d+|./g),p===null)throw h();if(p[f]===`-`?(o=-1,f++):p[f]===`+`&&f++,p.length===f+1?c=a(p[f++],o):p[f+1]===`.`||p[f]===`.`?(p[f]!==`.`&&(s=a(p[f++],o)),f++,(f+1===p.length||p[f+1]===`(`&&p[f+3]===`)`||p[f+1]===`'`&&p[f+3]===`'`)&&(c=a(p[f],o),u=10**p[f].length,f++),(p[f]===`(`&&p[f+2]===`)`||p[f]===`'`&&p[f+2]===`'`)&&(l=a(p[f+1],o),d=10**p[f+1].length-1,f+=3)):p[f+1]===`/`||p[f+1]===`:`?(c=a(p[f],o),u=a(p[f+2],1),f+=3):p[f+3]===`/`&&p[f+1]===` `&&(s=a(p[f],o),c=a(p[f+2],o),u=a(p[f+4],1),f+=5),p.length<=f){r=u*d,o=n=l+r*s+d*c;break}default:throw h()}if(r===0)throw m();i.s=o<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)};function l(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function u(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function d(e,t,n){for(var r=1,i=l(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function f(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function p(e,t){if(c(e,t),this instanceof p)e=f(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return o(i.s*i.n,i.d)}var m=function(){return Error(`Division by Zero`)},h=function(){return Error(`Invalid argument`)},g=function(){return Error(`Parameters must be integer`)};p.prototype={s:1,n:0,d:1,abs:function(){return o(this.n,this.d)},neg:function(){return o(-this.s*this.n,this.d)},add:function(e,t){return c(e,t),o(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return c(e,t),o(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return c(e,t),o(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return o(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new p(NaN);if(e===void 0)return o(this.s*this.n%this.d,1);if(c(e,t),i.n===0&&this.d===0)throw m();return o(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return c(e,t),o(f(i.n,this.n)*f(i.d,this.d),i.d*this.d)},lcm:function(e,t){return c(e,t),i.n===0&&this.n===0?o(0,1):o(i.n*this.n,f(i.n,this.n)*f(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new p(NaN):o(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return o(this.s*this.d,this.n)},pow:function(e,t){if(c(e,t),i.d===1)return i.s<0?o((this.s*this.d)**+i.n,this.n**+i.n):o((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=s(this.n),r=s(this.d),a=1,l=1;for(var u in n){if(u===`1`)continue;if(u===`0`){a=0;break}if(n[u]*=i.n,n[u]%i.d===0)n[u]/=i.d;else return null;a*=u**+n[u]}for(var u in r){if(u===`1`)continue;if(r[u]*=i.n,r[u]%i.d===0)r[u]/=i.d;else return null;l*=u**+r[u]}return i.s<0?o(l,a):o(a,l)},equals:function(e,t){return c(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){c(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=o(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return c(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=u(t,n),i=d(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof exports==`object`?(Object.defineProperty(p,`__esModule`,{value:!0}),p.default=p,p.Fraction=p,t.exports=p):n.Fraction=p})(exports)})),Da=k(Ea(),1),Oa=`Fraction`,ka=[],Aa=gr(Oa,ka,()=>(Object.defineProperty(Da.default,`name`,{value:`Fraction`}),Da.default.prototype.constructor=Da.default,Da.default.prototype.type=`Fraction`,Da.default.prototype.isFraction=!0,Da.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},Da.default.fromJSON=function(e){return new Da.default(e)},Da.default),{isClass:!0}),ja=`Matrix`,Ma=[],Na=gr(ja,Ma,()=>{function e(){if(!(this instanceof e))throw SyntaxError(`Constructor must be called with the new operator`)}return e.prototype.type=`Matrix`,e.prototype.isMatrix=!0,e.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},e.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},e.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},e.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},e.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},e.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},e.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},e.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},e.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},e.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},e.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},e.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},e.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},e.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},e.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},e.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},e.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},e},{isClass:!0});function Pa(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Fa=`DenseMatrix`,Ia=[`Matrix`],La=gr(Fa,Ia,e=>{var{Matrix:t}=e;function n(e,t){if(!(this instanceof n))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!It(t))throw Error(`Invalid datatype: `+t);if(Lt(e))e.type===`DenseMatrix`?(this._data=_n(e._data),this._size=_n(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&P(e.data)&&P(e.size))this._data=e.data,this._size=e.size,Qn(this._data,this._size),this._datatype=t||e.datatype;else if(P(e))this._data=l(e),this._size=Xn(this._data),Qn(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+gn(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}n.prototype=new t,n.prototype.createDenseMatrix=function(e,t){return new n(e,t)},Object.defineProperty(n,`name`,{value:`DenseMatrix`}),n.prototype.constructor=n,n.prototype.type=`DenseMatrix`,n.prototype.isDenseMatrix=!0,n.prototype.getDataType=function(){return cr(this._data,gn)},n.prototype.storage=function(){return`dense`},n.prototype.datatype=function(){return this._datatype},n.prototype.create=function(e,t){return new n(e,t)},n.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return r(this,e);case 2:case 3:return a(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},n.prototype.get=function(e){if(!P(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new I(e.length,this._size.length);for(var t=0;t<e.length;t++)L(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];L(a,n.length),n=n[a]}return n},n.prototype.set=function(e,t,n){if(!P(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new I(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});c(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],L(a,s.length),s=s[a];return a=e[e.length-1],L(a,s.length),s[a]=t,this};function r(e,t){if(!Ht(t))throw TypeError(`Invalid index`);var r=t.isScalar();if(r)return e.get(t.min());var a=t.size();if(a.length!==e._size.length)throw new I(a.length,e._size.length);for(var o=t.min(),s=t.max(),c=0,l=e._size.length;c<l;c++)L(o[c],e._size[c]),L(s[c],e._size[c]);return new n(i(e._data,t,a.length,0),e._datatype)}function i(e,t,n,r){var a=r===n-1,o=t.dimension(r);return a?o.map(function(t){return L(t,e.length),e[t]}).valueOf():o.map(function(a){L(a,e.length);var o=e[a];return i(o,t,n,r+1)}).valueOf()}function a(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),s;if(Lt(n)?(s=n.size(),n=n.valueOf()):s=Xn(n),a){if(s.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!yn(s,i))try{n=s.length===0?pr([n],i):pr(n,i),s=Xn(n)}catch{}if(i.length<e._size.length)throw new I(i.length,e._size.length,`<`);if(s.length<i.length){for(var l=0,u=0;i[l]===1&&s[l]===1;)l++;for(;i[l]===1;)u++,l++;n=ar(n,i.length,u,s)}if(!yn(i,s))throw new I(i,s,`>`);var d=t.max().map(function(e){return e+1});c(e,d,r);var f=i.length,p=0;o(e._data,t,n,f,p)}return e}function o(e,t,n,r,i){var a=i===r-1,s=t.dimension(i);a?s.forEach(function(t,r){L(t),e[t]=n[r[0]]}):s.forEach(function(a,s){L(a),o(e[a],t,n[s[0]],r,i+1)})}n.prototype.resize=function(e,t,n){if(!Rt(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e),i=n?this.clone():this;return s(i,r,t)};function s(e,t,n){if(t.length===0){for(var r=e._data;P(r);)r=r[0];return r}return e._size=t.slice(0),e._data=$n(e._data,e._size,n),e}n.prototype.reshape=function(e,t){var n=t?this.clone():this;n._data=tr(n._data,e);var r=n._size.reduce((e,t)=>e*t);return n._size=nr(e,r),n};function c(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&s(e,r,n)}n.prototype.clone=function(){var e=new n({data:_n(this._data),size:_n(this._size),datatype:this._datatype});return e},n.prototype.size=function(){return this._size.slice(0)},n.prototype.map=function(e){var t=this,r=Pa(e),i=function n(i,a){return P(i)?i.map(function(e,t){return n(e,a.concat(t))}):r===1?e(i):r===2?e(i,a):e(i,a,t)},a=i(this._data,[]),o=this._datatype===void 0?void 0:cr(a,gn);return new n(a,o)},n.prototype.forEach=function(e){var t=this,n=function n(r,i){P(r)?r.forEach(function(e,t){n(e,i.concat(t))}):e(r,i,t)};n(this._data,[])},n.prototype[Symbol.iterator]=function*(){var e=function*e(t,n){if(P(t))for(var r=0;r<t.length;r++)yield*e(t[r],n.concat(r));else yield{value:t,index:n}};yield*e(this._data,[])},n.prototype.rows=function(){var e=[],t=this.size();if(t.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);var r=this._data;for(var i of r)e.push(new n([i],this._datatype));return e},n.prototype.columns=function(){var e=this,t=[],r=this.size();if(r.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var i=this._data,a=function(r){var a=i.map(e=>[e[r]]);t.push(new n(a,e._datatype))},o=0;o<r[1];o++)a(o);return t},n.prototype.toArray=function(){return _n(this._data)},n.prototype.valueOf=function(){return this._data},n.prototype.format=function(e){return Hn(this._data,e)},n.prototype.toString=function(){return Hn(this._data)},n.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},n.prototype.diagonal=function(e){if(e){if(N(e)&&(e=e.toNumber()),!M(e)||!F(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,r=e<0?-e:0,i=this._size[0],a=this._size[1],o=Math.min(i-r,a-t),s=[],c=0;c<o;c++)s[c]=this._data[c+r][c+t];return new n({data:s,size:[o],datatype:this._datatype})},n.diagonal=function(e,t,r,i){if(!P(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(N(e)&&(e=e.toNumber()),!M(e)||!F(e)||e<1)throw Error(`Size values must be positive integers`);return e}),r){if(N(r)&&(r=r.toNumber()),!M(r)||!F(r))throw TypeError(`The parameter k must be an integer number`)}else r=0;var a=r>0?r:0,o=r<0?-r:0,s=e[0],c=e[1],l=Math.min(s-o,c-a),u;if(P(t)){if(t.length!==l)throw Error(`Invalid value array length`);u=function(e){return t[e]}}else if(Lt(t)){var d=t.size();if(d.length!==1||d[0]!==l)throw Error(`Invalid matrix length`);u=function(e){return t.get([e])}}else u=function(){return t};i||=N(u(0))?u(0).mul(0):0;var f=[];if(e.length>0){f=$n(f,e,i);for(var p=0;p<l;p++)f[p+o][p+a]=u(p)}return new n({data:f,size:[s,c]})},n.fromJSON=function(e){return new n(e)},n.prototype.swapRows=function(e,t){if(!M(e)||!F(e)||!M(t)||!F(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return L(e,this._size[0]),L(t,this._size[0]),n._swapRows(e,t,this._data),this},n._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function l(e){return Lt(e)?l(e.valueOf()):P(e)?e.map(l):e}return n},{isClass:!0});function Ra(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return Ra(e,t,n)}):t(e)}var za=`isNumeric`,Ba=[`typed`],Va=gr(za,Ba,e=>{var{typed:t}=e;return t(za,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>Ra(t,e))})}),Ha=`hasNumericValue`,Ua=[`typed`,`isNumeric`],Wa=gr(Ha,Ua,e=>{var{typed:t,isNumeric:n}=e;return t(Ha,{boolean:()=>!0,string:function(e){return e.trim().length>0&&!isNaN(Number(e))},any:function(e){return n(e)}})}),Ga=ga({config:Tn}),Ka=Ta({}),qa=Aa({}),Ja=Na({}),Ya=La({Matrix:Ja}),Xa=Nr({BigNumber:Ga,Complex:Ka,DenseMatrix:Ya,Fraction:qa}),Za=Va({typed:Xa}),Qa=Wa({isNumeric:Za,typed:Xa});const $a=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},eo=e=>{let t=Number(e),n=Date.now();if(Number.isNaN(t))return n+kt;if(!$a(t)&&a(t))return At(t);if($a(t))return n+t;{let e=t*Dt;return n+e}},to=`ratelimitlimit`,no=`ratelimitremaining`,ro=`ratelimitreset`,io=`ratelimitconcurrencylimit`,ao=`ratelimitconcurrencyremaining`,oo=`ratelimitconcurrencyreset`,so=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``),i=Qa(r)?Number(r):null;t[e]=i}return t},co=e=>{let t=so(e);return{rateLimitLimit:t[to],rateLimitRemaining:t[no],rateLimitReset:eo(t[ro]),concurrencyLimit:t[io],concurrencyRemaining:t[ao],concurrencyReset:eo(t[oo])}},lo=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},uo=(e,t=wt,n=Ct)=>{let r=Date.now();return a(e)||s(e)?fo(Number(e),r,t,n):It(e)&&e!==``?po(e,r,t,n):n},fo=(e,t,n=wt,r=Ct)=>{if(e<n)return e;let i=At(e);if(i>t){let e=Math.floor((i-t)/Dt);return e>0&&e<n?e:r}return r},po=(e,t,n=wt,r=Ct)=>{if(Ot.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/Dt);return e>0&&e<n?e:r}return r},mo=({axiosInstance:e,logger:n,requestConfig:r,context:i})=>{let a=async a=>{let{response:o,config:s}=a,c=s?.signal;if(c?.aborted)return Promise.reject(yt(`Request aborted`,s,`ERR_CANCELED`,o));let{status:l,retryAfter:d}=ho(o,i,r,n);if(l===429&&u(s)){let r=uo(d);if(s._retryCount>=Tt)return n?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:d,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,l={...s,_retryCount:c+1},u=d?r*Dt:t(l._retryCount);return n?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:d,calculatedRetryAfter:u}}),await bt(u*1e3,s,o),e?.request(l)}return Promise.reject(a)};return a},ho=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:l}=e??{},{retryafter:d}=so(s??{});if(o(i)||o(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:o(e),providerIsMissing:o(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:d??`undefined`}}),{status:a,retryAfter:d};let f=n?.rateLimits?.mappedRateLimitErrors;if(u(f)&&u(l))for(let e of f){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:o,retryAfterValue:u}=e;if(t!==a)continue;let f=n??`message`,p=c(l)?y.query(l,f)[0]:l,m=go(p,r);if(t===a&&m){let e=u??_o(s,i),t=vo(e,o);return{status:429,retryAfter:d??t}}}return{status:a,retryAfter:d}},go=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,_o=(e,t)=>u(t)&&u(e)?y.query(e,t)[0]:null,vo=(e,t=`seconds`)=>u(e)?yo(e,t):null,yo=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`){let t=typeof e==`string`?parseFloat(e):e;return t/Dt}if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},bo=`rateLimitErrorInterceptor`,xo=({axiosInstance:e,logger:n,requestConfig:r,context:i,concurrencyManager:a})=>{let s=async s=>{let{response:c,config:l}=s,d=l?.signal;if(o(i)||o(l))return n?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:bo,...l,headers:void 0,hasContext:u(i),hasConfig:u(l)},code:vt.InterceptorContextNotPresent}),Promise.reject(s);if(o(a))return n?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:bo,...l,headers:void 0,concurrencyManagerInitialized:u(a)},code:vt.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(s);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h}=l?.requestMetadata??{},g=u(f)&&u(p)?await a.releaseRequest(f,p):!1;if(!g&&u(l?.requestMetadata)&&n?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:bo,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:vt.RateLimiterReleaseRequestFailed}),d?.aborted)return Promise.reject(yt(`Request aborted`,l,`ERR_CANCELED`,c));let{status:_,retryAfter:v}=ho(c,i,r,n);if(_===429&&u(l)){let r=uo(v);if(l._retryCount>=Tt)return n?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:v,retryAfterAsNumber:r}}),Promise.reject(s);let a=l?._retryCount??0,o={...l,_retryCount:a+1},u=v?r*Dt:t(o._retryCount);return n?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:v,calculatedRetryAfter:u}}),await bt(u*1e3,l,c),e?.request(o)}return Promise.reject(s)};return s},So=`rateLimitResponseInterceptor`,Co=({logger:e,context:t,concurrencyManager:n})=>{let r=async r=>{let i=r?.config,a=i?.signal;if(o(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{...i,interceptor:So,headers:void 0}});else if(o(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:So,...i,headers:void 0,concurrencyManagerInitialized:u(n)},code:vt.RateLimitOrConcurrencyManagerNotInitialized}),r;else if(u(t.provider)&&u(t.accountSecureId)){let t=r?.headers;if(u(t)){let n=co(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:So,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l}=i?.requestMetadata??{},d=await n.releaseRequest(o,s);if(d||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:So,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:vt.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(yt(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return r},wo=e=>(e.validateStatus??=e=>e>=200&&e<300,e),To=[{onFulfilled:wo,onRejected:null,options:void 0}],Eo=[{onFulfilled:null,onRejected:mo},{onFulfilled:null,onRejected:mt}],Do=[{onFulfilled:wo,onRejected:null,options:void 0},{onFulfilled:St,onRejected:null,options:void 0}],Oo=[{onFulfilled:Co,onRejected:xo},{onFulfilled:null,onRejected:mt}],ko=1,Ao=1e3,jo=0,Mo=59,No=.8,Po=500;var Fo=class extends Ee{name=`RateLimitManager`;async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=Mo,i=No,a=Po){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=jo)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=jo)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=Math.min(o,s/(a/Ao)),u=ko/l,d=Math.max(ht,c*u);return Math.min(c,d)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=u(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),d=c.map(e=>e.rateLimit);return await this.executeScript(_t.incr,[a,...l],[o.toString(),...d.map(String)])??0}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},$=class{static instances=new Map;static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(o(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(u(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){let t=this.instances.get(e);return t?.getInstanceIfReady?.()??null}static reset(e){let t=this.instances.get(e);t?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};let Io=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const Lo=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?zo(e,n):Ro(e,n),o(n?.service)||o(n?.organizationId)||s===`test`||o(t)||o(e))return a;let l=$.getIfReady(Fo)??void 0,d=$.getIfReady(rt)??void 0,f=l?.isReady(),p=d?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...Do),h.push(...Oo)}let g=lo(n);if(o(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:u(a)}}),a;let _=await pt.get(g);if(u(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:d,rateLimitManager:l},y=ut.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await pt.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:u(a)},error:t,code:Io.HttpTransportInstanceCreateError}),u(a)?a:Bo()}},Ro=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return ut.createInstance(n)??Bo()},zo=(e,t)=>{let n={interceptors:{requestConfigs:To,responseConfigs:Eo},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return ut.createInstance(n)??Bo()},Bo=()=>{let e=m.create({maxBodyLength:1/0});return e};var Vo=class e{#transportFactory;#getRedisClient;#logger;#redisClientConfig;#errorMappingFn;#redisClient;constructor({transportFactory:e=Lo,getRedisClient:t=xe,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.#transportFactory=e,this.#getRedisClient=t,this.#logger=n,this.#redisClientConfig=r,this.#errorMappingFn=i}#generateCacheKey({url:e,payload:t,method:n,context:i}){let a=20;if(!i?.accountSecureId||i.accountSecureId.length<a||!e||!n)return null;let o=t?r(t):``;return`${i.accountSecureId}-${n.toUpperCase()}${o}-${e}`}async#getCachedResponse({url:t,payload:n,method:r,cacheTTL:i,context:a}){if(!this.#redisClient||!i||i<=0)return null;let o=this.#generateCacheKey({url:t,payload:n,method:r,context:a});if(!o)return null;let s=await this.#redisClient.getData(o);return s?(this.#logger?.debug({category:e.name,message:`Cache hit for key [${o}].`}),s):(this.#logger?.debug({category:e.name,message:`Cache miss for key [${o}].`}),null)}async#cacheResponse({url:t,payload:n,method:r,cacheTTL:i,context:a,response:o}){if(!this.#redisClient||!i||i<=0)return!1;let s=this.#generateCacheKey({url:t,payload:n,method:r,context:a});return s?(this.#logger?.debug({category:e.name,message:`Caching result for key [${s}].`}),this.#redisClient.setData({key:s,value:o,cacheTTL:i*60})):!1}async request({headers:t={},url:n,method:r=`get`,queryParams:i,maxRedirects:a=0,responseType:s,cacheTTL:c,context:l,traceId:d,payload:f,httpsAgent:p,httpAgent:m,requestConfig:h,httpsAgentConfig:g}){try{u(this.#redisClientConfig)&&o(this.#redisClient)&&(this.#redisClient=await this.#getRedisClient(this.#redisClientConfig,this.#logger,`HttpClient`));let e=this.#buildUrlWithQueryParams(n,i),_=this.#normalizeHeaders(t),v=this.#getSafePayload(f,t),y=await this.#getCachedResponse({url:e,payload:v,method:r,cacheTTL:c,context:l});if(y)return{...y,responseTime:new Date};let b=ft.getInstance(),x=u(d)?await b.get(d):null,S=x?.signal,C=await this.#transportFactory({redisClientConfig:this.#redisClientConfig,logger:this.#logger,context:l,requestConfig:h,httpsAgentConfig:g}),w=await C.request({headers:_,url:e,method:r,maxRedirects:a,responseType:s,data:v,httpsAgent:p,httpAgent:m,signal:S}),T={data:w.data,status:w.status,body:v,method:r,headers:this.#extractAxiosHeaders(w.headers),requestUrl:n,responseType:w?.config?.responseType,responseTime:new Date};return await this.#cacheResponse({url:e,payload:v,method:r,cacheTTL:c,context:l,response:T}),T}catch(t){let i=t;i.url=b(n),this.#logger?.warning({category:e.name,message:`Request error [${r?.toUpperCase()} ${i.url}]: ${i.message}.`,error:i});let a=this.#mapErrorToHttpException(i);throw u(a)?a:t}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}#normalizeHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#extractAxiosHeaders(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#isFormUrlEncoded(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#getSafePayload(e,t){if(!(o(e)||c(e)&&Object.keys(e).length===0))return this.#isFormUrlEncoded(t)?x.stringify(e):e}#mapErrorToHttpException(e){if(h(e)&&this.#errorMappingFn)return this.#errorMappingFn(e)}#buildUrlWithQueryParams(e,t){if(o(t)||Object.keys(t).length===0)return e;let n=x.stringify(t);return`${e}?${n}`}};const Ho=(e,t,n)=>new Vo({redisClientConfig:e,logger:t,errorMappingFn:n});var Uo=class{static httpClientInstance=null;static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=Ho}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const Wo=[`get`,`post`,`put`,`delete`,`patch`],Go={[Ie.rPush]:`
132
132
  local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
133
133
 
134
134
  redis.call('PEXPIRE', KEYS[1], ARGV[2])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/transport",
3
- "version": "2.1.2",
3
+ "version": "2.1.3",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",