@stackone/transport 2.29.0 → 2.30.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +7 -7
- package/dist/index.d.cts +17 -4
- package/dist/index.d.mts +17 -4
- package/dist/index.mjs +5 -5
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -94,14 +94,14 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
94
94
|
|
|
95
95
|
redis.call('publish', nextItemKey, nextItem)
|
|
96
96
|
end
|
|
97
|
-
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==E)return;let n=this.leaseRegistry.get(e);if(!(0,o.isMissing)(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==D)return;let n=this.setRemovalRegistry.get(e);if(!(0,o.isMissing)(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??o.generateRequestId,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if((0,o.isMissing)(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return(0,o.isMissing)(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(w)&&n.includes(T)&&n.includes(E)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(O.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(E,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(D,this.setRemovalDispatcher)??!1}async registerRequest(e,t,n,r,i=b*5,a){let s=`concurrency:${e}`,c=`queue:${e}`,l=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(r??``):r?.includes(e.urlPattern))?.subPoolKey,u=(0,o.notMissing)(l)?`${s}-${l}`:s,{mainMaxConcurrency:d,subPools:f}=t,p=[{key:s,maxConcurrency:d},...f?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${s}-${t}`,maxConcurrency:n}})??[]],m=p.map(e=>e.key),h=p.map(e=>e.maxConcurrency),[g,_]=await Promise.all([this.subscribeToLeaseExpiry(n,u),this.subscribeToSetRemoval(u,c)]),v={requestId:n,targetConcurrencyKey:u,leaseSubscription:g,setRemovalSubscription:_,queueKey:c,acquired:!1},y=!1,x=!1;try{let e=await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]);if((0,o.notMissing)(e)&&e[0])return y=!0,{...v,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let t=0,r=i,s=[],isAborted=()=>a?.aborted===!0;for(;r>0&&t<5&&!isAborted();){let e=t>1,i=Math.min(b,r);x=!0;let l=await this.queueManager?.joinAndWaitTurn(c,n,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]),!1,i,a);r-=i;let f=(0,o.notMissing)(l)?l[0]:!1,p=(0,o.notMissing)(l)?l[1]:``;if((0,o.notMissing)(p)&&p!==``&&s.push(p),t++,f)return y=!0,t>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${t} attempts.`,context:{...v,registerAttempts:t,joinCondition:`attempts`,failureMessages:s}}),{...v,joinCondition:`attempts`,acquired:!0};let g=(0,o.exponentialBackoffInMS)(t,100);if(r-=g,r<=0||isAborted())break;await(0,o.delay)(g)}return this.logger?.error({category:this.name,message:`Failed to register request after ${t} attempts.`,context:{...v,registerAttempts:t,joinCondition:`failed`,failureMessages:s},code:`ConcurrencyManagerRegistrationFailed`}),{...v,joinCondition:`failed`}}finally{if(!y&&(this.leaseRegistry.delete(buildLeaseKey(u,n)),x))try{await this.queueManager?.remove(c,n)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...v,queueKey:c},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if((0,o.isString)(t)&&(0,o.isString)(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const j={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if((0,o.isMissing)(t)||t?.length===0||(0,o.isMissing)(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=(0,c.safeEvaluate)(r,n?{...e,credentials:n}:e)===!0;if((0,o.isMissing)(r)||i){let n=t?.message,r;return r=(0,o.isMissing)(n)?j[t.targetStatus]??`Unknown error`:String((0,c.safeEvaluate)(n,e)??j[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},ee=(0,o.zStrictObject)({receivedStatus:o.z.number(),targetStatus:o.z.number(),message:o.z.string().optional(),condition:o.z.string().optional()});var M=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new u.default.Agent(n),d=l.default.create({...t,httpsAgent:c});if(d.close=()=>{c.destroy()},e){let t={axiosInstance:d,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(d,e,t)}return d}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return(0,o.notMissing)(e)&&(0,o.isFunction)(e)&&typeof e(t)==`function`?e(t):e??null}},N=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return(0,o.isMissing)(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>(0,o.notMissing)(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:(0,o.notMissing)(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return(0,o.notMissing)(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const P=N.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},F={mainRatelimit:25},createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&(0,f.clearTimeout)(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},I=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:I,...a,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(t),hasConfig:(0,o.notMissing)(a)},code:`InterceptorContextNotPresent`});else if((0,o.isMissing)(i)||(0,o.isMissing)(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:I,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:(0,o.notMissing)(i),concurrencyManagerInitialized:(0,o.notMissing)(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let o=(0,d.randomUUID)(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??F,u=n?.concurrency??k,f=await i.getDynamicMaxWaitTime(l,u,a.url),register=async e=>r.registerRequest(`${c}-${s}`,u,o,a.url,Math.max((f-e)*1e3,0),a.signal),p,m=0;for(;m<=f;){let n=await i.getWaitTime(`${c}-${s}`,l,a.url)??0;if(n<=0){p=await register(m);break}let r=Math.min(Math.max(n,1),f-m);if(await abortableDelay(r*1e3,a),m+=r,m>=f){p=await register(m),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:I,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:f},code:`InterceptorMaxWaitTimeExceeded`});break}}return{...a,requestMetadata:p}}return a};return checkConcurrencyInterceptor},L=1e3,R=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*L:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&(0,o.isFutureUnixTimestamp)(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*L},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=(0,p.hasNumericValue)(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o.isMissing)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return(0,o.isFutureUnixTimestamp)(e)||(0,o.isNumber)(e)?evaluateRetryAfterNumber(Number(e),r,t,n):(0,p.isString)(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/L);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(R.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/L);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let retryErrorInterceptor=async i=>{let{response:a,config:s}=i;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,a));let{status:c,retryAfter:l}=convertError(a,r,n,t);if(c===429&&(0,o.notMissing)(s)){let n=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...r??{},retryAfterHeader:l,retryAfterAsNumber:n}}),Promise.reject(i);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?n*L:(0,o.exponentialBackoffInMS)(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...r??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,a),e?.request(u)}return Promise.reject(i)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:c}=e??{},{retryafter:l}=superNormalizeHeaders(s??{});if((0,o.isMissing)(i)||(0,o.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,o.isMissing)(e),providerIsMissing:(0,o.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:l??`undefined`}}),{status:a,retryAfter:l};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,o.notMissing)(u)&&(0,o.notMissing)(c))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=testMessage((0,o.isObject)(c)?(0,m.JSONPath)({path:f,json:c})[0]:c,r);if(t===a&&p){let e=convertRetryAfter(d??extractRetryAfter(s,i),u);return{status:429,retryAfter:l??e}}}return{status:a,retryAfter:l}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>(0,o.notMissing)(t)&&(0,o.notMissing)(e)?(0,m.JSONPath)({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>(0,o.notMissing)(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/L;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},z=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let rateLimitErrorInterceptor=async a=>{let{response:s,config:c}=a,l=c?.signal;if((0,o.isMissing)(r)||(0,o.isMissing)(c))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:`InterceptorContextNotPresent`}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:z,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p,acquired:m}=c?.requestMetadata??{},h=m!==!1&&(0,o.notMissing)(u)&&(0,o.notMissing)(d);if(!(h&&await i.releaseRequest(u,d))&&h&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:z,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:`RateLimiterReleaseRequestFailed`}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:g,retryAfter:_}=convertError(s,r,n,t);if(g===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(_);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=_?n*L:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},B=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0}});else if((0,o.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:B,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,o.notMissing)(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:B,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u,acquired:d}=i?.requestMetadata??{},f=d!==!1&&(0,o.notMissing)(s)&&(0,o.notMissing)(c);if(!(f&&await n.releaseRequest(s,c))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:B,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),V=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],H=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],U=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],W=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,o.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:s,subPools:c}=t,l=[{key:r,rateLimit:s},...c?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=l.map(e=>e.key),d=l.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...u],[s.toString(),...d.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,o.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,o.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||s===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=l?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(c.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...U),m.push(...W)}let h=generateRequestKey(n);if((0,o.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,o.notMissing)(a)}}),a;let g=await P.get(h);if((0,o.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},v=HttpTransportFactory.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await P.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(a)},error:t,code:`HttpTransportInstanceCreateError`}),(0,o.notMissing)(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:V,responseConfigs:H},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=(0,h.redactFields)(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?(0,o.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:s,context:c,traceId:l,payload:u,httpsAgent:d,httpAgent:f,requestConfig:p,httpsAgentConfig:m}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let h=this.#v(t,r),g=this.#l(e),_=this.#h(u,e),v=await this.#s({url:h,payload:_,method:n,cacheTTL:s,context:c});if(v)return{...v,responseTime:new Date};let y=N.getInstance(),b=((0,o.notMissing)(l)?await y.get(l):null)?.signal,x=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:c,requestConfig:p,httpsAgentConfig:m})).request({headers:g,url:h,method:n,maxRedirects:i,responseType:a,data:_,httpsAgent:d,httpAgent:f,signal:b}),S={data:x.data,status:x.status,body:_,method:n,headers:this.#u(x.headers),requestHeaders:buildSafeRequestHeaders(g),requestUrl:h,responseType:x?.config?.responseType,responseTime:new Date};return await this.#c({url:h,payload:_,method:n,cacheTTL:s,context:c,response:S}),S}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:d,httpsAgentConfig:f}){try{let p=this.#v(t,r),m=this.#l(e),h=this.#h(c,e),g=N.getInstance(),_=((0,o.notMissing)(s)?await g.get(s):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:d,httpsAgentConfig:f})).request({headers:m,url:p,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:l,httpAgent:u,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?g.default.stringify(e):e}#g(e){if((0,l.isAxiosError)(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t){if((0,o.isMissing)(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={},s={};for(let[e,o]of Object.entries(t))if(this.#_(o)){let t=o.arrayFormat,c=o.value;t===`repeat`?r[e]=Array.isArray(c)?c:[c]:t===`brackets`?i[e]=Array.isArray(c)?c:[c]:t===`comma`?a[e]=Array.isArray(c)?c:[c]:t===`stringify`?s[e]=JSON.stringify(Array.isArray(c)?c:[c]):n[e]=c}else n[e]=o;let c=[];Object.keys(n).length>0&&c.push(g.default.stringify(n)),Object.keys(r).length>0&&c.push(g.default.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&c.push(g.default.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&c.push(g.default.stringify(a,{arrayFormat:`comma`})),Object.keys(s).length>0&&c.push(g.default.stringify(s));let l=c.join(`&`);return(0,o.notMissing)(l)?`${e}?${l}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const G=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
97
|
+
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==E)return;let n=this.leaseRegistry.get(e);if(!(0,o.isMissing)(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==D)return;let n=this.setRemovalRegistry.get(e);if(!(0,o.isMissing)(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??o.generateRequestId,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if((0,o.isMissing)(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return(0,o.isMissing)(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(w)&&n.includes(T)&&n.includes(E)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(O.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(E,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(D,this.setRemovalDispatcher)??!1}async registerRequest(e,t,n,r,i=b*5,a){let s=`concurrency:${e}`,c=`queue:${e}`,l=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(r??``):r?.includes(e.urlPattern))?.subPoolKey,u=(0,o.notMissing)(l)?`${s}-${l}`:s,{mainMaxConcurrency:d,subPools:f}=t,p=[{key:s,maxConcurrency:d},...f?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${s}-${t}`,maxConcurrency:n}})??[]],m=p.map(e=>e.key),h=p.map(e=>e.maxConcurrency),[g,_]=await Promise.all([this.subscribeToLeaseExpiry(n,u),this.subscribeToSetRemoval(u,c)]),v={requestId:n,targetConcurrencyKey:u,leaseSubscription:g,setRemovalSubscription:_,queueKey:c,acquired:!1},y=!1,x=!1;try{let e=await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]);if((0,o.notMissing)(e)&&e[0])return y=!0,{...v,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let t=0,r=i,s=[],isAborted=()=>a?.aborted===!0;for(;r>0&&t<5&&!isAborted();){let e=t>1,i=Math.min(b,r);x=!0;let l=await this.queueManager?.joinAndWaitTurn(c,n,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[n,u,c,...m],[`60`,d.toString(),`90`,...h.map(String)]),!1,i,a);r-=i;let f=(0,o.notMissing)(l)?l[0]:!1,p=(0,o.notMissing)(l)?l[1]:``;if((0,o.notMissing)(p)&&p!==``&&s.push(p),t++,f)return y=!0,t>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${t} attempts.`,context:{...v,registerAttempts:t,joinCondition:`attempts`,failureMessages:s}}),{...v,joinCondition:`attempts`,acquired:!0};let g=(0,o.exponentialBackoffInMS)(t,100);if(r-=g,r<=0||isAborted())break;await(0,o.delay)(g)}return this.logger?.error({category:this.name,message:`Failed to register request after ${t} attempts.`,context:{...v,registerAttempts:t,joinCondition:`failed`,failureMessages:s},code:`ConcurrencyManagerRegistrationFailed`}),{...v,joinCondition:`failed`}}finally{if(!y&&(this.leaseRegistry.delete(buildLeaseKey(u,n)),x))try{await this.queueManager?.remove(c,n)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...v,queueKey:c},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if((0,o.isString)(t)&&(0,o.isString)(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const j={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if((0,o.isMissing)(t)||t?.length===0||(0,o.isMissing)(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=(0,c.safeEvaluate)(r,n?{...e,credentials:n}:e)===!0;if((0,o.isMissing)(r)||i){let n=t?.message,r;return r=(0,o.isMissing)(n)?j[t.targetStatus]??`Unknown error`:String((0,c.safeEvaluate)(n,e)??j[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},ee=(0,o.zStrictObject)({receivedStatus:o.z.number(),targetStatus:o.z.number(),message:o.z.string().optional(),condition:o.z.string().optional()});var M=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new u.default.Agent(n),d=l.default.create({...t,httpsAgent:c});if(d.close=()=>{c.destroy()},e){let t={axiosInstance:d,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(d,e,t)}return d}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return(0,o.notMissing)(e)&&(0,o.isFunction)(e)&&typeof e(t)==`function`?e(t):e??null}},N=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return(0,o.isMissing)(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>(0,o.notMissing)(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:(0,o.notMissing)(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return(0,o.notMissing)(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const P=N.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},F={mainRatelimit:25},createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&(0,f.clearTimeout)(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},I=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:I,...a,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(t),hasConfig:(0,o.notMissing)(a)},code:`InterceptorContextNotPresent`});else if((0,o.isMissing)(i)||(0,o.isMissing)(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:I,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:(0,o.notMissing)(i),concurrencyManagerInitialized:(0,o.notMissing)(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let o=(0,d.randomUUID)(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??F,u=n?.concurrency??k,f=await i.getDynamicMaxWaitTime(l,u,a.url),register=async e=>r.registerRequest(`${c}-${s}`,u,o,a.url,Math.max((f-e)*1e3,0),a.signal),p,m=0;for(;m<=f;){let n=await i.getWaitTime(`${c}-${s}`,l,a.url)??0;if(n<=0){p=await register(m);break}let r=Math.min(Math.max(n,1),f-m);if(await abortableDelay(r*1e3,a),m+=r,m>=f){p=await register(m),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:I,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:f},code:`InterceptorMaxWaitTimeExceeded`});break}}return{...a,requestMetadata:p}}return a};return checkConcurrencyInterceptor},L=1e3,te=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*L:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&(0,o.isFutureUnixTimestamp)(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*L},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=(0,p.hasNumericValue)(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:s,behaviours:c}=e??{};return[t,n,r,s].some(o.isMissing)?null:[t,n,r,i,a,s,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return(0,o.isFutureUnixTimestamp)(e)||(0,o.isNumber)(e)?evaluateRetryAfterNumber(Number(e),r,t,n):(0,p.isString)(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/L);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(te.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/L);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>{let retryErrorInterceptor=async i=>{let{response:a,config:s}=i;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,a));let{status:c,retryAfter:l}=convertError(a,r,n,t);if(c===429&&(0,o.notMissing)(s)){let n=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...r??{},retryAfterHeader:l,retryAfterAsNumber:n}}),Promise.reject(i);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?n*L:(0,o.exponentialBackoffInMS)(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...r??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,a),e?.request(u)}return Promise.reject(i)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:s,data:c}=e??{},{retryafter:l}=superNormalizeHeaders(s??{});if((0,o.isMissing)(i)||(0,o.isMissing)(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:(0,o.isMissing)(e),providerIsMissing:(0,o.isMissing)(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:l??`undefined`}}),{status:a,retryAfter:l};let u=n?.rateLimits?.mappedRateLimitErrors;if((0,o.notMissing)(u)&&(0,o.notMissing)(c))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:u,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=testMessage((0,o.isObject)(c)?(0,m.JSONPath)({path:f,json:c})[0]:c,r);if(t===a&&p){let e=convertRetryAfter(d??extractRetryAfter(s,i),u);return{status:429,retryAfter:l??e}}}return{status:a,retryAfter:l}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>(0,o.notMissing)(t)&&(0,o.notMissing)(e)?(0,m.JSONPath)({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>(0,o.notMissing)(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/L;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},R=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>{let rateLimitErrorInterceptor=async a=>{let{response:s,config:c}=a,l=c?.signal;if((0,o.isMissing)(r)||(0,o.isMissing)(c))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:R,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:`InterceptorContextNotPresent`}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:R,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p,acquired:m}=c?.requestMetadata??{},h=m!==!1&&(0,o.notMissing)(u)&&(0,o.notMissing)(d);if(!(h&&await i.releaseRequest(u,d))&&h&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:R,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:`RateLimiterReleaseRequestFailed`}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:g,retryAfter:_}=convertError(s,r,n,t);if(g===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(_);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=_?n*L:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)};return rateLimitErrorInterceptor},z=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if((0,o.isMissing)(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:z,...i,httpsAgent:void 0,headers:void 0}});else if((0,o.isMissing)(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:z,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if((0,o.notMissing)(t.provider)&&(0,o.notMissing)(t.accountSecureId)){let t=r?.headers;if((0,o.notMissing)(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:z,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u,acquired:d}=i?.requestMetadata??{},f=d!==!1&&(0,o.notMissing)(s)&&(0,o.notMissing)(c);if(!(f&&await n.releaseRequest(s,c))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:z,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),B=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],V=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],H=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],U=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=(0,o.notMissing)(i)?`${r}-${i}`:r,{mainRatelimit:s,subPools:c}=t,l=[{key:r,rateLimit:s},...c?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],u=l.map(e=>e.key),d=l.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...u],[s.toString(),...d.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if((0,o.isMissing)(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if((0,o.notMissing)(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:s}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),(0,o.isMissing)(n?.service)||(0,o.isMissing)(n?.organizationId)||s===`test`||(0,o.isMissing)(t)||(0,o.isMissing)(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=l?.isReady(),f=u?.isRedisConfigured(),p=[],m=[];if(c.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);p.push(...H),m.push(...U)}let h=generateRequestKey(n);if((0,o.isMissing)(h))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:(0,o.notMissing)(a)}}),a;let g=await P.get(h);if((0,o.notMissing)(g))return g;let _={interceptors:{requestConfigs:p,responseConfigs:m},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},v=HttpTransportFactory.createInstance(_);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${h}]`,context:{...n}}),await P.set(h,v),v}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:(0,o.notMissing)(a)},error:t,code:`HttpTransportInstanceCreateError`}),(0,o.notMissing)(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:B,responseConfigs:V},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=(0,h.redactFields)(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let i=t?(0,o.getContentHash)(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${i}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,responseType:s,cacheTTL:c,context:l,traceId:u,payload:d,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:g}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let h=this.#v(t,r,i),_=this.#l(e),v=this.#h(d,e),y=await this.#s({url:h,payload:v,method:n,cacheTTL:c,context:l});if(y)return{...y,responseTime:new Date};let b=N.getInstance(),x=((0,o.notMissing)(u)?await b.get(u):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:m,httpsAgentConfig:g})).request({headers:_,url:h,method:n,maxRedirects:a,responseType:s,data:v,httpsAgent:f,httpAgent:p,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#u(S.headers),requestHeaders:buildSafeRequestHeaders(_),requestUrl:h,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:h,payload:v,method:n,cacheTTL:c,context:l,response:C}),C}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,context:s,traceId:c,payload:l,httpsAgent:u,httpAgent:d,requestConfig:f,httpsAgentConfig:p}){try{let m=this.#v(t,r,i),h=this.#l(e),g=this.#h(l,e),_=N.getInstance(),v=((0,o.notMissing)(c)?await _.get(c):null)?.signal,y=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:f,httpsAgentConfig:p})).request({headers:h,url:m,method:n,maxRedirects:a,responseType:`stream`,data:g,httpsAgent:u,httpAgent:d,signal:v});return{status:y.status,headers:this.#u(y.headers),stream:y.data,requestUrl:t}}catch(e){let r=e;r.url=(0,h.redactUrl)(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw(0,o.notMissing)(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return(0,o.isString)(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return(0,o.isMissing)(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?g.default.stringify(e):e}#g(e){if((0,l.isAxiosError)(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t,n){if((0,o.isMissing)(t)||Object.keys(t).length===0)return e;let r={},i={},a={},s={},c={};for(let[e,n]of Object.entries(t))if(this.#_(n)){let t=n.arrayFormat,o=n.value;t===`repeat`?i[e]=Array.isArray(o)?o:[o]:t===`brackets`?a[e]=Array.isArray(o)?o:[o]:t===`comma`?s[e]=Array.isArray(o)?o:[o]:t===`stringify`?c[e]=JSON.stringify(Array.isArray(o)?o:[o]):r[e]=o}else r[e]=n;let l=n===!1?{encode:!1}:{},u=[];Object.keys(r).length>0&&u.push(g.default.stringify(r,l)),Object.keys(i).length>0&&u.push(g.default.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(g.default.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(s).length>0&&u.push(g.default.stringify(s,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(g.default.stringify(c,l));let d=u.join(`&`);return(0,o.notMissing)(d)?`${e}?${d}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const W=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
98
98
|
`).replace(/\r\n/g,`
|
|
99
99
|
`).replace(/\r/g,`
|
|
100
100
|
`).trim();t=t.replace(/(-----BEGIN [A-Z0-9 ]+-----) +/g,`$1
|
|
101
101
|
`),t=t.replace(/ +(-----END [A-Z0-9 ]+-----)/g,`
|
|
102
102
|
$1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+-----)/);if(n){let[,e,r,i]=n;if(!r.includes(`
|
|
103
103
|
`)&&r.includes(` `)){let n=r.replace(/ /g,``);t=`${e}\n${n.match(/.{1,64}/g)?.join(`
|
|
104
|
-
`)??n}\n${i}`}}return t},decodeCertOrKey=e=>{if(!e||e.length===0)return e;let t=normalizePem(e);if(isPemFormat(t))return t;try{let e=Buffer.from(t,`base64`).toString(`utf-8`);return isPemFormat(e)?normalizePem(e):t}catch{return t}},buildHttpsAgent=e=>{if(!e)return;let{certs:t,keys:n}=e;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(e=>typeof e==`string`&&e.trim().length>0),i=n.filter(e=>typeof e==`string`&&e.trim().length>0);if(r.length===0||i.length===0)return;let a=r.map(decodeCertOrKey),o=i.map(decodeCertOrKey);return new u.default.Agent({cert:a,key:o})},
|
|
104
|
+
`)??n}\n${i}`}}return t},decodeCertOrKey=e=>{if(!e||e.length===0)return e;let t=normalizePem(e);if(isPemFormat(t))return t;try{let e=Buffer.from(t,`base64`).toString(`utf-8`);return isPemFormat(e)?normalizePem(e):t}catch{return t}},buildHttpsAgent=e=>{if(!e)return;let{certs:t,keys:n}=e;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(e=>typeof e==`string`&&e.trim().length>0),i=n.filter(e=>typeof e==`string`&&e.trim().length>0);if(r.length===0||i.length===0)return;let a=r.map(decodeCertOrKey),o=i.map(decodeCertOrKey);return new u.default.Agent({cert:a,key:o})},G={rPush:`
|
|
105
105
|
-- Drop any stale copy first so a retrying request holds at most one queue slot.
|
|
106
106
|
redis.call('LREM', KEYS[1], 0, ARGV[1])
|
|
107
107
|
|
|
@@ -126,7 +126,7 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
126
126
|
local queueKey = KEYS[1]
|
|
127
127
|
|
|
128
128
|
return redis.call("lpop", queueKey)
|
|
129
|
-
`,llen:`return redis.call("llen", KEYS[1])`},
|
|
129
|
+
`,llen:`return redis.call("llen", KEYS[1])`},K={incr:`
|
|
130
130
|
local targetKey = KEYS[1]
|
|
131
131
|
local totalLimit = tonumber(ARGV[1])
|
|
132
132
|
|
|
@@ -168,8 +168,8 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
168
168
|
end
|
|
169
169
|
|
|
170
170
|
return nil
|
|
171
|
-
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],[a,o]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:K,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:te,logger:n})]),s=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:A,logger:n,additionalArgs:e}),c=[{name:`ConcurrencyManager`,ready:s.isReady()},{name:`QueueManager`,ready:a.isReady()},{name:`RateLimitManager`,ready:o.isReady()}],l=c.filter(e=>!e.ready);if(l.length>0){let e=l.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:c.map(e=>e.name)}}),{concurrencyManager:s,queueManager:a,rateLimitManager:o}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},ne=__name(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),q=__name(e=>Array.isArray(e)?e:[e],`toStringArray`),toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=q(t);if(ne(e))return{value:[...q(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...q(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),re=[`query`,`body`,`headers`],ie=[`repeat`,`brackets`,`comma`,`stringify`],J={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},ae=new _.XMLBuilder(J),getContentType=e=>{let t=Object.entries(e).find(([e])=>e.toLowerCase()===`content-type`)?.[1];return typeof t==`string`?t.toLowerCase():``},isXmlContentTypeValue=e=>e.includes(`application/xml`)||e.includes(`text/xml`)||/application\/\S+\+xml/.test(e),isXmlContentType=e=>isXmlContentTypeValue(getContentType(e)),serializeBodyToXml=e=>{try{return ae.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?g.default.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>(0,o.notMissing)(e)&&e>=200&&e<=299,isFailedStatusCode=e=>(0,o.notMissing)(e)&&e>=400&&e<=599,isInfoStatusCode=e=>(0,o.notMissing)(e)&&e>=100&&e<=199;let Y;const getXmlParser=()=>(Y??=new _.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),Y);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c,httpsAgent:l,credentials:u}){let d,f=a;if(isXmlContentType(r))if(typeof a==`string`)f=a;else if(Array.isArray(a))throw Error(`Cannot serialize an array body to XML: XML requires a single root element. Wrap the array in an object with a root key.`);else a!=null&&(f=serializeBodyToXml(a));try{d=await e?.request({method:n,url:t,headers:r,queryParams:i,maxRedirects:0,payload:f,requestConfig:c,httpsAgent:l})}catch(e){if((0,o.isMissing)(e?.response))throw e;d=e.response}if(typeof d.data==`string`&&d.data.length>0&&d.headers&&isXmlContentType(d.headers)){let e=_.XMLValidator.validate(d.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);d={...d,data:getXmlParser().parse(d.data)}}let p=translateCustomError(d,s,u);if(isFailedStatusCode(p?.status))throw new M(p,p.message);return p}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:s,requestConfig:c,credentials:l}){let u;if(u=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?X.build(c.envelope):await buildEnvelope(a,c),_.XMLValidator.validate(u,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let d,f={"Content-Type":`application/xml`,...r};c?.soapAction&&(f.SOAPAction=c.soapAction);try{d=await e?.request({method:n,url:t,headers:f,queryParams:i,maxRedirects:0,payload:u,requestConfig:c})}catch(e){if((0,o.isMissing)(e?.response))throw e;d=e.response}let p=oe.parse(d.data),m=p.Envelope||p,h=m.Body||m,g=h.Fault;if(g)throw new M({...d,status:500,data:g,message:g.faultstring??g.faultcode??`SOAP Fault`},g.faultstring??`SOAP Fault occurred`);d.data=h;let v=translateCustomError(d,s,l);if(isFailedStatusCode(v?.status))throw new M(v,v.message);return v}};const X=new _.XMLBuilder(J),oe=new _.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if((0,o.notMissing)(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:X.build(t.envelope);if(_.XMLValidator.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=X.build(n);if(_.XMLValidator.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await(0,c.evaluate)(e.namespaceIdentifier),namespace:await(0,c.evaluate)(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if((0,o.isMissing)(e)||(0,o.isMissing)(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if((0,o.isMissing)(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if((0,o.isMissing)(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};const arrayFormatToPairs=(e,t,n)=>n===`brackets`?t.map(t=>[`${e}[]`,t]):n===`comma`?[[e,t.join(`,`)]]:n===`stringify`?[[e,JSON.stringify(t)]]:t.map(t=>[e,t]),toStringArray=e=>Array.isArray(e)?e:[e],isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),flattenQueryParams=e=>{if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))r!=null&&(isHttpQueryParamValue(r)?t.push(...arrayFormatToPairs(n,toStringArray(r.value),r.arrayFormat)):t.push(...arrayFormatToPairs(n,toStringArray(r),void 0)));return t},hmac=(e,t)=>(0,d.createHmac)(`sha256`,e).update(t).digest(),hash=e=>(0,d.createHash)(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),Z=__name(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),Q=__name((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),f=u.slice(0,8),p=new URL(e.url),m=p.pathname.split(`/`).map(e=>{try{return Z(decodeURIComponent(e))}catch{return Z(e)}}).join(`/`)||`/`,h=[];for(let[e,t]of p.searchParams.entries())h.push([e,t]);h.push(...flattenQueryParams(e.query)),h.sort(([e,t],[n,r])=>{let i=Q(e,n);return i===0?Q(t,r):i});let g=h.map(([e,t])=>`${Z(e)}=${Z(t)}`).join(`&`),_=serializeRequestBodyForSigning(e.body,e.headers??{}),v=(0,d.createHash)(`sha256`).update(_).digest(),y=v.toString(`hex`),b={host:p.host,"x-amz-content-sha256":y,"x-amz-date":u};a&&(b[`x-amz-security-token`]=a);for(let[t,n]of Object.entries(e.headers??{})){let e=t.toLowerCase();e!==`authorization`&&e!==`x-amz-date`&&e!==`x-amz-content-sha256`&&e!==`x-amz-security-token`&&(b[e]=n)}let x=Object.keys(b).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),S=_.length>0&&!x,C;S&&(C=v.toString(`base64`),b[`x-amz-checksum-sha256`]=C);let w=Object.keys(b).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),T=w.map(e=>`${e}:${canonicalHeaderValue(b[e])}\n`).join(``),E=w.join(`;`),D=[e.method.toUpperCase(),m,g,T,E,y].join(`
|
|
171
|
+
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],[a,o]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:G,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:K,logger:n})]),s=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:A,logger:n,additionalArgs:e}),c=[{name:`ConcurrencyManager`,ready:s.isReady()},{name:`QueueManager`,ready:a.isReady()},{name:`RateLimitManager`,ready:o.isReady()}],l=c.filter(e=>!e.ready);if(l.length>0){let e=l.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:c.map(e=>e.name)}}),{concurrencyManager:s,queueManager:a,rateLimitManager:o}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},ne=__name(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),q=__name(e=>Array.isArray(e)?e:[e],`toStringArray`),toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=q(t);if(ne(e))return{value:[...q(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...q(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),re=[`query`,`body`,`headers`],ie=[`repeat`,`brackets`,`comma`,`stringify`],J={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},ae=new _.XMLBuilder(J),getContentType=e=>{let t=Object.entries(e).find(([e])=>e.toLowerCase()===`content-type`)?.[1];return typeof t==`string`?t.toLowerCase():``},isXmlContentTypeValue=e=>e.includes(`application/xml`)||e.includes(`text/xml`)||/application\/\S+\+xml/.test(e),isXmlContentType=e=>isXmlContentTypeValue(getContentType(e)),serializeBodyToXml=e=>{try{return ae.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?g.default.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>(0,o.notMissing)(e)&&e>=200&&e<=299,isFailedStatusCode=e=>(0,o.notMissing)(e)&&e>=400&&e<=599,isInfoStatusCode=e=>(0,o.notMissing)(e)&&e>=100&&e<=199,oe=[`arraybuffer`,`blob`,`document`,`text`];let Y;const getXmlParser=()=>(Y??=new _.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),Y);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:s,customErrorConfigs:c,requestConfig:l,httpsAgent:u,credentials:d,responseType:f}){let p,m=s;if(isXmlContentType(r))if(typeof s==`string`)m=s;else if(Array.isArray(s))throw Error(`Cannot serialize an array body to XML: XML requires a single root element. Wrap the array in an object with a root key.`);else s!=null&&(m=serializeBodyToXml(s));try{p=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:m,requestConfig:l,httpsAgent:u,responseType:f})}catch(e){if((0,o.isMissing)(e?.response))throw e;p=e.response}if(typeof p.data==`string`&&/\S/.test(p.data)&&p.headers&&isXmlContentType(p.headers)&&(!f||!oe.includes(f))){let e=_.XMLValidator.validate(p.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);p={...p,data:getXmlParser().parse(p.data)}}let h=translateCustomError(p,c,d);if(isFailedStatusCode(h?.status))throw new M(h,h.message);return h}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:s,customErrorConfigs:c,requestConfig:l,credentials:u}){let d;if(d=typeof l?.envelope==`string`?l.envelope:typeof l?.envelope==`object`?X.build(l.envelope):await buildEnvelope(s,l),_.XMLValidator.validate(d,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let f,p={"Content-Type":`application/xml`,...r};l?.soapAction&&(p.SOAPAction=l.soapAction);try{f=await e?.request({method:n,url:t,headers:p,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:d,requestConfig:l})}catch(e){if((0,o.isMissing)(e?.response))throw e;f=e.response}let m=se.parse(f.data),h=m.Envelope||m,g=h.Body||h,v=g.Fault;if(v)throw new M({...f,status:500,data:v,message:v.faultstring??v.faultcode??`SOAP Fault`},v.faultstring??`SOAP Fault occurred`);f.data=g;let y=translateCustomError(f,c,u);if(isFailedStatusCode(y?.status))throw new M(y,y.message);return y}};const X=new _.XMLBuilder(J),se=new _.XMLParser({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if((0,o.notMissing)(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:X.build(t.envelope);if(_.XMLValidator.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=X.build(n);if(_.XMLValidator.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await(0,c.evaluate)(e.namespaceIdentifier),namespace:await(0,c.evaluate)(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if((0,o.isMissing)(e)||(0,o.isMissing)(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if((0,o.isMissing)(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if((0,o.isMissing)(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};const arrayFormatToPairs=(e,t,n)=>n===`brackets`?t.map(t=>[`${e}[]`,t]):n===`comma`?[[e,t.join(`,`)]]:n===`stringify`?[[e,JSON.stringify(t)]]:t.map(t=>[e,t]),toStringArray=e=>Array.isArray(e)?e:[e],isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),flattenQueryParams=e=>{if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))r!=null&&(isHttpQueryParamValue(r)?t.push(...arrayFormatToPairs(n,toStringArray(r.value),r.arrayFormat)):t.push(...arrayFormatToPairs(n,toStringArray(r),void 0)));return t},hmac=(e,t)=>(0,d.createHmac)(`sha256`,e).update(t).digest(),hash=e=>(0,d.createHash)(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),Z=__name(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),Q=__name((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),f=u.slice(0,8),p=new URL(e.url),m=p.pathname.split(`/`).map(e=>{try{return Z(decodeURIComponent(e))}catch{return Z(e)}}).join(`/`)||`/`,h=[];for(let[e,t]of p.searchParams.entries())h.push([e,t]);h.push(...flattenQueryParams(e.query)),h.sort(([e,t],[n,r])=>{let i=Q(e,n);return i===0?Q(t,r):i});let g=h.map(([e,t])=>`${Z(e)}=${Z(t)}`).join(`&`),_=serializeRequestBodyForSigning(e.body,e.headers??{}),v=(0,d.createHash)(`sha256`).update(_).digest(),y=v.toString(`hex`),b={host:p.host,"x-amz-content-sha256":y,"x-amz-date":u};a&&(b[`x-amz-security-token`]=a);for(let[t,n]of Object.entries(e.headers??{})){let e=t.toLowerCase();e!==`authorization`&&e!==`x-amz-date`&&e!==`x-amz-content-sha256`&&e!==`x-amz-security-token`&&(b[e]=n)}let x=Object.keys(b).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),S=_.length>0&&!x,C;S&&(C=v.toString(`base64`),b[`x-amz-checksum-sha256`]=C);let w=Object.keys(b).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),T=w.map(e=>`${e}:${canonicalHeaderValue(b[e])}\n`).join(``),E=w.join(`;`),D=[e.method.toUpperCase(),m,g,T,E,y].join(`
|
|
172
172
|
`),O=`${f}/${l}/${s}/aws4_request`,k=[`AWS4-HMAC-SHA256`,u,O,hash(D)].join(`
|
|
173
|
-
`),A={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${O}, SignedHeaders=${E}, Signature=${(0,d.createHmac)(`sha256`,getSigningKey(i,f,l,s)).update(k).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":y};return a&&(A[`x-amz-security-token`]=a),C!==void 0&&(A[`x-amz-checksum-sha256`]=C),A},
|
|
174
|
-
`),v=(0,d.createHmac)(c,r).update(_).digest(`hex`);return{[l]:`${u} ${v}`,"X-Timestamp":f}},
|
|
175
|
-
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${y}`).toString(`base64`)}`,Date:h}:{[i??`X-Signature`]:`${a??`hmac-${f}`} ${y}`,"X-Timestamp":h}}const $={},registerSigningStrategy=(e,t)=>{$[e]=t},getSigningStrategy=e=>$[e];registerSigningStrategy(`aws4`,aws4SigningStrategy),registerSigningStrategy(`hmac`,hmacSigningStrategy),exports.CUSTOM_ERROR_CONFIG_SCHEMA=ee,exports.ConcurrencyManager=ConcurrencyManager,exports.EventClient=EventClient,exports.HttpClient=HttpClient,exports.HttpClientManager=HttpClientManager,exports.HttpErrorMessages=j,exports.HttpMethods=
|
|
173
|
+
`),A={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${O}, SignedHeaders=${E}, Signature=${(0,d.createHmac)(`sha256`,getSigningKey(i,f,l,s)).update(k).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":y};return a&&(A[`x-amz-security-token`]=a),C!==void 0&&(A[`x-amz-checksum-sha256`]=C),A},ce=[`sha256`,`sha512`],isValidAlgorithm=e=>ce.includes(e),hashPayload=e=>(0,d.createHash)(`sha256`).update(e).digest(`hex`),byteCompare=(e,t)=>e<t?-1:+(e>t),rfc3986Encode=e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),hmacSigningStrategy=(e,t,n)=>{if(n.strategy!==`hmac`)throw Error(`hmacSigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let r=t.secretKey;if(!r)throw Error(`HMAC signing requires secretKey in credentials`);let i=n;if(requiresExtendedSigning(i))return signWithExtendedOptions(e,r,i);let{algorithm:a,headerName:o,prefix:s}=i;if(a!==void 0&&!isValidAlgorithm(a))throw Error(`Unsupported HMAC algorithm "${a}". Use "sha256" or "sha512".`);let c=a??`sha256`,l=o??`X-Signature`,u=s??`hmac-${c}`,f=new Date().toISOString(),p=new URL(e.url),m=[];for(let[e,t]of p.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=byteCompare(e,n);return i===0?byteCompare(t,r):i});let h=m.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),g=hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})),_=[f,e.method.toUpperCase(),p.pathname,h,g].join(`
|
|
174
|
+
`),v=(0,d.createHmac)(c,r).update(_).digest(`hex`);return{[l]:`${u} ${v}`,"X-Timestamp":f}},le=[`sha1`,`sha256`,`sha512`],formatRfc2822Date=e=>e.toUTCString().replace(`GMT`,`-0000`),extractBodyParams=e=>{let t=[];for(let[n,r]of Object.entries(e)){if(r==null)continue;let e=Array.isArray(r)?r:[r];for(let r of e)t.push([n,String(r)])}return t};function requiresExtendedSigning(e){let{algorithm:t,dateFormat:n,includeHost:r,includeBodyHash:i,outputFormat:a,username:o}=e;return!!(n===`rfc2822`||r===!0||i===!1||a===`basic`||o||t===`sha1`)}function signWithExtendedOptions(e,t,n){let{algorithm:r,headerName:i,prefix:a,dateFormat:o=`iso8601`,includeHost:s=!1,includeBodyHash:c=!0,outputFormat:l=`header`,username:u}=n;if(r&&!le.includes(r))throw Error(`Unsupported HMAC algorithm "${r}". Use "sha1", "sha256", or "sha512".`);if(l===`basic`&&!u)throw Error(`HMAC signing with outputFormat "basic" requires username`);if(u&&/[:\r\n]/.test(u))throw Error(`HMAC signing username cannot contain ":", "\\r", or "\\n"`);let f=r??`sha256`,p=new URL(e.url),m=new Date,h=o===`rfc2822`?formatRfc2822Date(m):m.toISOString(),g=[...p.searchParams.entries(),...flattenQueryParams(e.query)];!c&&e.body&&typeof e.body==`object`&&!Array.isArray(e.body)&&(e.headers?.[`content-type`]??e.headers?.[`Content-Type`]??``).toLowerCase().includes(`application/x-www-form-urlencoded`)&&g.push(...extractBodyParams(e.body)),g.sort(([e,t],[n,r])=>byteCompare(e,n)||byteCompare(t,r));let _=g.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),v=[h,e.method.toUpperCase()];s&&v.push(p.hostname.toLowerCase()),v.push(p.pathname,_),c&&v.push(hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})));let y=(0,d.createHmac)(f,t).update(v.join(`
|
|
175
|
+
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${y}`).toString(`base64`)}`,Date:h}:{[i??`X-Signature`]:`${a??`hmac-${f}`} ${y}`,"X-Timestamp":h}}const $={},registerSigningStrategy=(e,t)=>{$[e]=t},getSigningStrategy=e=>$[e];registerSigningStrategy(`aws4`,aws4SigningStrategy),registerSigningStrategy(`hmac`,hmacSigningStrategy),exports.CUSTOM_ERROR_CONFIG_SCHEMA=ee,exports.ConcurrencyManager=ConcurrencyManager,exports.EventClient=EventClient,exports.HttpClient=HttpClient,exports.HttpClientManager=HttpClientManager,exports.HttpErrorMessages=j,exports.HttpMethods=W,exports.HttpResponseError=M,exports.HttpTransportFactory=HttpTransportFactory,exports.InstanceManager=N,exports.LockManager=LockManager,exports.MemoryStore=MemoryStore,exports.QueryArrayFormats=ie,exports.QueueManager=QueueManager,exports.RateLimitManager=RateLimitManager,exports.RedisClient=y,exports.RequestClientFactory=RequestClientFactory,exports.RequestParameterLocations=re,exports.ScriptManager=ScriptManager,exports.SubscriptionManager=SubscriptionManager,exports.buildHttpClientInstance=buildHttpClientInstance,exports.buildHttpsAgent=buildHttpsAgent,exports.convertError=convertError,exports.createAuthorizationHeaders=createAuthorizationHeaders,exports.getRetryAfterWaitTime=getRetryAfterWaitTime,exports.getSigningStrategy=getSigningStrategy,exports.getTransportInstance=getTransportInstance,exports.getTransportManagers=getTransportManagers,exports.initializeTransportSystem=initializeTransportSystem,exports.isFailedStatusCode=isFailedStatusCode,exports.isInfoStatusCode=isInfoStatusCode,exports.isSuccessStatusCode=isSuccessStatusCode,exports.isTransportSystemReady=isTransportSystemReady,exports.parseRequestParameters=parseRequestParameters,exports.registerSigningStrategy=registerSigningStrategy,exports.serializeHttpResponseError=serializeHttpResponseError,exports.shutdownTransportSystem=shutdownTransportSystem,exports.superNormalizeHeaders=superNormalizeHeaders,exports.translateCustomError=translateCustomError;
|
package/dist/index.d.cts
CHANGED
|
@@ -383,6 +383,7 @@ type HttpQueryParams = {
|
|
|
383
383
|
};
|
|
384
384
|
declare const HttpMethods: readonly ["get", "post", "put", "delete", "patch"];
|
|
385
385
|
type HttpMethod = (typeof HttpMethods)[number];
|
|
386
|
+
type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text';
|
|
386
387
|
type HttpResponse<T = any, P = any> = {
|
|
387
388
|
data: T;
|
|
388
389
|
status: number;
|
|
@@ -410,6 +411,7 @@ interface IHttpClient {
|
|
|
410
411
|
url,
|
|
411
412
|
method,
|
|
412
413
|
queryParams,
|
|
414
|
+
encodeQueryParams,
|
|
413
415
|
maxRedirects,
|
|
414
416
|
responseType,
|
|
415
417
|
cacheTTL,
|
|
@@ -424,8 +426,9 @@ interface IHttpClient {
|
|
|
424
426
|
url: string;
|
|
425
427
|
method?: HttpMethod;
|
|
426
428
|
queryParams?: HttpQueryParams;
|
|
429
|
+
encodeQueryParams?: boolean;
|
|
427
430
|
maxRedirects?: number;
|
|
428
|
-
responseType?:
|
|
431
|
+
responseType?: ResponseType;
|
|
429
432
|
cacheTTL?: number;
|
|
430
433
|
context?: RequestContext;
|
|
431
434
|
payload?: P;
|
|
@@ -473,6 +476,7 @@ interface IHttpClient {
|
|
|
473
476
|
url,
|
|
474
477
|
method,
|
|
475
478
|
queryParams,
|
|
479
|
+
encodeQueryParams,
|
|
476
480
|
maxRedirects,
|
|
477
481
|
context,
|
|
478
482
|
traceId,
|
|
@@ -486,6 +490,7 @@ interface IHttpClient {
|
|
|
486
490
|
url: string;
|
|
487
491
|
method?: HttpMethod;
|
|
488
492
|
queryParams?: HttpQueryParams;
|
|
493
|
+
encodeQueryParams?: boolean;
|
|
489
494
|
maxRedirects?: number;
|
|
490
495
|
context?: RequestContext;
|
|
491
496
|
traceId?: string;
|
|
@@ -726,6 +731,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
|
|
|
726
731
|
url,
|
|
727
732
|
method,
|
|
728
733
|
queryParams,
|
|
734
|
+
encodeQueryParams,
|
|
729
735
|
maxRedirects,
|
|
730
736
|
responseType,
|
|
731
737
|
cacheTTL,
|
|
@@ -741,8 +747,9 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
|
|
|
741
747
|
url: string;
|
|
742
748
|
method?: HttpMethod;
|
|
743
749
|
queryParams?: HttpQueryParams;
|
|
750
|
+
encodeQueryParams?: boolean;
|
|
744
751
|
maxRedirects?: number;
|
|
745
|
-
responseType?:
|
|
752
|
+
responseType?: ResponseType;
|
|
746
753
|
cacheTTL?: number;
|
|
747
754
|
context?: RequestContext;
|
|
748
755
|
traceId?: string;
|
|
@@ -795,6 +802,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
|
|
|
795
802
|
url,
|
|
796
803
|
method,
|
|
797
804
|
queryParams,
|
|
805
|
+
encodeQueryParams,
|
|
798
806
|
maxRedirects,
|
|
799
807
|
context,
|
|
800
808
|
traceId,
|
|
@@ -808,6 +816,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
|
|
|
808
816
|
url: string;
|
|
809
817
|
method?: HttpMethod;
|
|
810
818
|
queryParams?: HttpQueryParams;
|
|
819
|
+
encodeQueryParams?: boolean;
|
|
811
820
|
maxRedirects?: number;
|
|
812
821
|
context?: RequestContext;
|
|
813
822
|
traceId?: string;
|
|
@@ -1051,21 +1060,25 @@ interface IRequestClient<RequestConfig$1 = RequestConfig> {
|
|
|
1051
1060
|
method,
|
|
1052
1061
|
headers,
|
|
1053
1062
|
queryParams,
|
|
1063
|
+
encodeQueryParams,
|
|
1054
1064
|
body,
|
|
1055
1065
|
customErrorConfigs,
|
|
1056
1066
|
requestConfig,
|
|
1057
|
-
httpsAgent
|
|
1067
|
+
httpsAgent,
|
|
1068
|
+
responseType
|
|
1058
1069
|
}: {
|
|
1059
1070
|
httpClient: IHttpClient;
|
|
1060
1071
|
url: string;
|
|
1061
1072
|
method: HttpMethod;
|
|
1062
1073
|
headers: HttpHeaders;
|
|
1063
1074
|
queryParams?: HttpQueryParams;
|
|
1075
|
+
encodeQueryParams?: boolean;
|
|
1064
1076
|
body: unknown;
|
|
1065
1077
|
customErrorConfigs?: CustomErrorConfig[];
|
|
1066
1078
|
requestConfig?: RequestConfig$1;
|
|
1067
1079
|
httpsAgent?: https.Agent;
|
|
1068
1080
|
credentials?: Record<string, unknown>;
|
|
1081
|
+
responseType?: ResponseType;
|
|
1069
1082
|
}) => Promise<HttpResponse>;
|
|
1070
1083
|
}
|
|
1071
1084
|
type RequestClientType = 'rest' | 'soap';
|
|
@@ -1126,4 +1139,4 @@ type LockEntry = {
|
|
|
1126
1139
|
unlock: Unlock;
|
|
1127
1140
|
};
|
|
1128
1141
|
//#endregion
|
|
1129
|
-
export { type AxiosErrorWithRequestMetadata, type AxiosErrorWithRetryCount, CUSTOM_ERROR_CONFIG_SCHEMA, type CertificatesInput, type ConcurrencyConfig, ConcurrencyManager, type CustomErrorConfig, type ErrorInterceptor, type ErrorMappingFn, EventClient, HttpClient, HttpClientManager, HttpErrorMessages, type HttpHeader, type HttpHeaders, type HttpMethod, HttpMethods, type HttpParameters, type HttpQueryParamValue, type HttpQueryParams, type HttpResponse, HttpResponseError, HttpTransportFactory, type HttpTransportInstanceConfig, type ICacheClient, type IHttpClient, type IRequestClient, type InitializedTransportManagers, InstanceManager, type Interceptor, type InterceptorConfigs, type InterceptorDependencies, type InterceptorDependencyInjector, type InterceptorManager, type Lock, type LockEntry, LockManager, MemoryStore, type MemoryStoreConfig, type OnFulfilledInterceptors, type PruneCount, type PubSubListener, type QueryArrayFormat, QueryArrayFormats, QueueManager, type RateLimitConfig, RateLimitManager, RedisClient, type RedisClientConfig, type RedisClientType, RequestClientFactory, type RequestConfig, type RequestContext, type RequestInterceptor, type RequestInterceptorConfig, type RequestInterceptorTuple, type RequestParameter, RequestParameterLocations, type ResponseInterceptor, type ResponseInterceptorConfig, type ResponseInterceptorTuple, ScriptManager, type SigningCredentials, type SigningOptions, type SigningRequest, type SigningStrategy, type StreamHttpResponse, SubscriptionManager, type TransportInitializationOptions, type Unlock, buildHttpClientInstance, buildHttpsAgent, convertError, createAuthorizationHeaders, getRetryAfterWaitTime, getSigningStrategy, getTransportInstance, getTransportManagers, initializeTransportSystem, isFailedStatusCode, isInfoStatusCode, isSuccessStatusCode, isTransportSystemReady, parseRequestParameters, registerSigningStrategy, serializeHttpResponseError, shutdownTransportSystem, superNormalizeHeaders, translateCustomError };
|
|
1142
|
+
export { type AxiosErrorWithRequestMetadata, type AxiosErrorWithRetryCount, CUSTOM_ERROR_CONFIG_SCHEMA, type CertificatesInput, type ConcurrencyConfig, ConcurrencyManager, type CustomErrorConfig, type ErrorInterceptor, type ErrorMappingFn, EventClient, HttpClient, HttpClientManager, HttpErrorMessages, type HttpHeader, type HttpHeaders, type HttpMethod, HttpMethods, type HttpParameters, type HttpQueryParamValue, type HttpQueryParams, type HttpResponse, HttpResponseError, HttpTransportFactory, type HttpTransportInstanceConfig, type ICacheClient, type IHttpClient, type IRequestClient, type InitializedTransportManagers, InstanceManager, type Interceptor, type InterceptorConfigs, type InterceptorDependencies, type InterceptorDependencyInjector, type InterceptorManager, type Lock, type LockEntry, LockManager, MemoryStore, type MemoryStoreConfig, type OnFulfilledInterceptors, type PruneCount, type PubSubListener, type QueryArrayFormat, QueryArrayFormats, QueueManager, type RateLimitConfig, RateLimitManager, RedisClient, type RedisClientConfig, type RedisClientType, RequestClientFactory, type RequestConfig, type RequestContext, type RequestInterceptor, type RequestInterceptorConfig, type RequestInterceptorTuple, type RequestParameter, RequestParameterLocations, type ResponseInterceptor, type ResponseInterceptorConfig, type ResponseInterceptorTuple, type ResponseType, ScriptManager, type SigningCredentials, type SigningOptions, type SigningRequest, type SigningStrategy, type StreamHttpResponse, SubscriptionManager, type TransportInitializationOptions, type Unlock, buildHttpClientInstance, buildHttpsAgent, convertError, createAuthorizationHeaders, getRetryAfterWaitTime, getSigningStrategy, getTransportInstance, getTransportManagers, initializeTransportSystem, isFailedStatusCode, isInfoStatusCode, isSuccessStatusCode, isTransportSystemReady, parseRequestParameters, registerSigningStrategy, serializeHttpResponseError, shutdownTransportSystem, superNormalizeHeaders, translateCustomError };
|
package/dist/index.d.mts
CHANGED
|
@@ -382,6 +382,7 @@ type HttpQueryParams = {
|
|
|
382
382
|
};
|
|
383
383
|
declare const HttpMethods: readonly ["get", "post", "put", "delete", "patch"];
|
|
384
384
|
type HttpMethod = (typeof HttpMethods)[number];
|
|
385
|
+
type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text';
|
|
385
386
|
type HttpResponse<T = any, P = any> = {
|
|
386
387
|
data: T;
|
|
387
388
|
status: number;
|
|
@@ -409,6 +410,7 @@ interface IHttpClient {
|
|
|
409
410
|
url,
|
|
410
411
|
method,
|
|
411
412
|
queryParams,
|
|
413
|
+
encodeQueryParams,
|
|
412
414
|
maxRedirects,
|
|
413
415
|
responseType,
|
|
414
416
|
cacheTTL,
|
|
@@ -423,8 +425,9 @@ interface IHttpClient {
|
|
|
423
425
|
url: string;
|
|
424
426
|
method?: HttpMethod;
|
|
425
427
|
queryParams?: HttpQueryParams;
|
|
428
|
+
encodeQueryParams?: boolean;
|
|
426
429
|
maxRedirects?: number;
|
|
427
|
-
responseType?:
|
|
430
|
+
responseType?: ResponseType;
|
|
428
431
|
cacheTTL?: number;
|
|
429
432
|
context?: RequestContext;
|
|
430
433
|
payload?: P;
|
|
@@ -472,6 +475,7 @@ interface IHttpClient {
|
|
|
472
475
|
url,
|
|
473
476
|
method,
|
|
474
477
|
queryParams,
|
|
478
|
+
encodeQueryParams,
|
|
475
479
|
maxRedirects,
|
|
476
480
|
context,
|
|
477
481
|
traceId,
|
|
@@ -485,6 +489,7 @@ interface IHttpClient {
|
|
|
485
489
|
url: string;
|
|
486
490
|
method?: HttpMethod;
|
|
487
491
|
queryParams?: HttpQueryParams;
|
|
492
|
+
encodeQueryParams?: boolean;
|
|
488
493
|
maxRedirects?: number;
|
|
489
494
|
context?: RequestContext;
|
|
490
495
|
traceId?: string;
|
|
@@ -725,6 +730,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
|
|
|
725
730
|
url,
|
|
726
731
|
method,
|
|
727
732
|
queryParams,
|
|
733
|
+
encodeQueryParams,
|
|
728
734
|
maxRedirects,
|
|
729
735
|
responseType,
|
|
730
736
|
cacheTTL,
|
|
@@ -740,8 +746,9 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
|
|
|
740
746
|
url: string;
|
|
741
747
|
method?: HttpMethod;
|
|
742
748
|
queryParams?: HttpQueryParams;
|
|
749
|
+
encodeQueryParams?: boolean;
|
|
743
750
|
maxRedirects?: number;
|
|
744
|
-
responseType?:
|
|
751
|
+
responseType?: ResponseType;
|
|
745
752
|
cacheTTL?: number;
|
|
746
753
|
context?: RequestContext;
|
|
747
754
|
traceId?: string;
|
|
@@ -794,6 +801,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
|
|
|
794
801
|
url,
|
|
795
802
|
method,
|
|
796
803
|
queryParams,
|
|
804
|
+
encodeQueryParams,
|
|
797
805
|
maxRedirects,
|
|
798
806
|
context,
|
|
799
807
|
traceId,
|
|
@@ -807,6 +815,7 @@ declare class HttpClient<TError extends Error = Error> implements IHttpClient {
|
|
|
807
815
|
url: string;
|
|
808
816
|
method?: HttpMethod;
|
|
809
817
|
queryParams?: HttpQueryParams;
|
|
818
|
+
encodeQueryParams?: boolean;
|
|
810
819
|
maxRedirects?: number;
|
|
811
820
|
context?: RequestContext;
|
|
812
821
|
traceId?: string;
|
|
@@ -1050,21 +1059,25 @@ interface IRequestClient<RequestConfig$1 = RequestConfig> {
|
|
|
1050
1059
|
method,
|
|
1051
1060
|
headers,
|
|
1052
1061
|
queryParams,
|
|
1062
|
+
encodeQueryParams,
|
|
1053
1063
|
body,
|
|
1054
1064
|
customErrorConfigs,
|
|
1055
1065
|
requestConfig,
|
|
1056
|
-
httpsAgent
|
|
1066
|
+
httpsAgent,
|
|
1067
|
+
responseType
|
|
1057
1068
|
}: {
|
|
1058
1069
|
httpClient: IHttpClient;
|
|
1059
1070
|
url: string;
|
|
1060
1071
|
method: HttpMethod;
|
|
1061
1072
|
headers: HttpHeaders;
|
|
1062
1073
|
queryParams?: HttpQueryParams;
|
|
1074
|
+
encodeQueryParams?: boolean;
|
|
1063
1075
|
body: unknown;
|
|
1064
1076
|
customErrorConfigs?: CustomErrorConfig[];
|
|
1065
1077
|
requestConfig?: RequestConfig$1;
|
|
1066
1078
|
httpsAgent?: https.Agent;
|
|
1067
1079
|
credentials?: Record<string, unknown>;
|
|
1080
|
+
responseType?: ResponseType;
|
|
1068
1081
|
}) => Promise<HttpResponse>;
|
|
1069
1082
|
}
|
|
1070
1083
|
type RequestClientType = 'rest' | 'soap';
|
|
@@ -1125,4 +1138,4 @@ type LockEntry = {
|
|
|
1125
1138
|
unlock: Unlock;
|
|
1126
1139
|
};
|
|
1127
1140
|
//#endregion
|
|
1128
|
-
export { type AxiosErrorWithRequestMetadata, type AxiosErrorWithRetryCount, CUSTOM_ERROR_CONFIG_SCHEMA, type CertificatesInput, type ConcurrencyConfig, ConcurrencyManager, type CustomErrorConfig, type ErrorInterceptor, type ErrorMappingFn, EventClient, HttpClient, HttpClientManager, HttpErrorMessages, type HttpHeader, type HttpHeaders, type HttpMethod, HttpMethods, type HttpParameters, type HttpQueryParamValue, type HttpQueryParams, type HttpResponse, HttpResponseError, HttpTransportFactory, type HttpTransportInstanceConfig, type ICacheClient, type IHttpClient, type IRequestClient, type InitializedTransportManagers, InstanceManager, type Interceptor, type InterceptorConfigs, type InterceptorDependencies, type InterceptorDependencyInjector, type InterceptorManager, type Lock, type LockEntry, LockManager, MemoryStore, type MemoryStoreConfig, type OnFulfilledInterceptors, type PruneCount, type PubSubListener, type QueryArrayFormat, QueryArrayFormats, QueueManager, type RateLimitConfig, RateLimitManager, RedisClient, type RedisClientConfig, type RedisClientType, RequestClientFactory, type RequestConfig, type RequestContext, type RequestInterceptor, type RequestInterceptorConfig, type RequestInterceptorTuple, type RequestParameter, RequestParameterLocations, type ResponseInterceptor, type ResponseInterceptorConfig, type ResponseInterceptorTuple, ScriptManager, type SigningCredentials, type SigningOptions, type SigningRequest, type SigningStrategy, type StreamHttpResponse, SubscriptionManager, type TransportInitializationOptions, type Unlock, buildHttpClientInstance, buildHttpsAgent, convertError, createAuthorizationHeaders, getRetryAfterWaitTime, getSigningStrategy, getTransportInstance, getTransportManagers, initializeTransportSystem, isFailedStatusCode, isInfoStatusCode, isSuccessStatusCode, isTransportSystemReady, parseRequestParameters, registerSigningStrategy, serializeHttpResponseError, shutdownTransportSystem, superNormalizeHeaders, translateCustomError };
|
|
1141
|
+
export { type AxiosErrorWithRequestMetadata, type AxiosErrorWithRetryCount, CUSTOM_ERROR_CONFIG_SCHEMA, type CertificatesInput, type ConcurrencyConfig, ConcurrencyManager, type CustomErrorConfig, type ErrorInterceptor, type ErrorMappingFn, EventClient, HttpClient, HttpClientManager, HttpErrorMessages, type HttpHeader, type HttpHeaders, type HttpMethod, HttpMethods, type HttpParameters, type HttpQueryParamValue, type HttpQueryParams, type HttpResponse, HttpResponseError, HttpTransportFactory, type HttpTransportInstanceConfig, type ICacheClient, type IHttpClient, type IRequestClient, type InitializedTransportManagers, InstanceManager, type Interceptor, type InterceptorConfigs, type InterceptorDependencies, type InterceptorDependencyInjector, type InterceptorManager, type Lock, type LockEntry, LockManager, MemoryStore, type MemoryStoreConfig, type OnFulfilledInterceptors, type PruneCount, type PubSubListener, type QueryArrayFormat, QueryArrayFormats, QueueManager, type RateLimitConfig, RateLimitManager, RedisClient, type RedisClientConfig, type RedisClientType, RequestClientFactory, type RequestConfig, type RequestContext, type RequestInterceptor, type RequestInterceptorConfig, type RequestInterceptorTuple, type RequestParameter, RequestParameterLocations, type ResponseInterceptor, type ResponseInterceptorConfig, type ResponseInterceptorTuple, type ResponseType, ScriptManager, type SigningCredentials, type SigningOptions, type SigningRequest, type SigningStrategy, type StreamHttpResponse, SubscriptionManager, type TransportInitializationOptions, type Unlock, buildHttpClientInstance, buildHttpsAgent, convertError, createAuthorizationHeaders, getRetryAfterWaitTime, getSigningStrategy, getTransportInstance, getTransportManagers, initializeTransportSystem, isFailedStatusCode, isInfoStatusCode, isSuccessStatusCode, isTransportSystemReady, parseRequestParameters, registerSigningStrategy, serializeHttpResponseError, shutdownTransportSystem, superNormalizeHeaders, translateCustomError };
|
package/dist/index.mjs
CHANGED
|
@@ -94,7 +94,7 @@ import{t as e}from"./chunk-BhWHdk3m.mjs";import{delay as t,exponentialBackoffInM
|
|
|
94
94
|
|
|
95
95
|
redis.call('publish', nextItemKey, nextItem)
|
|
96
96
|
end
|
|
97
|
-
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==B)return;let n=this.leaseRegistry.get(e);if(!s(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==V)return;let n=this.setRemovalRegistry.get(e);if(!s(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??r,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(s(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return s(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(z)&&n.includes(ee)&&n.includes(B)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(te.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(B,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(V,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=F*5,s){let c=`concurrency:${e}`,l=`queue:${e}`,u=r.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,f=d(u)?`${c}-${u}`:c,{mainMaxConcurrency:p,subPools:m}=r,h=[{key:c,maxConcurrency:p},...m?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${c}-${t}`,maxConcurrency:n}})??[]],g=h.map(e=>e.key),_=h.map(e=>e.maxConcurrency),[v,y]=await Promise.all([this.subscribeToLeaseExpiry(i,f),this.subscribeToSetRemoval(f,l)]),b={requestId:i,targetConcurrencyKey:f,leaseSubscription:v,setRemovalSubscription:y,queueKey:l,acquired:!1},x=!1,S=!1;try{let e=await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]);if(d(e)&&e[0])return x=!0,{...b,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let r=0,a=o,c=[],isAborted=()=>s?.aborted===!0;for(;a>0&&r<5&&!isAborted();){let e=r>1,o=Math.min(F,a);S=!0;let u=await this.queueManager?.joinAndWaitTurn(l,i,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]),!1,o,s);a-=o;let m=d(u)?u[0]:!1,h=d(u)?u[1]:``;if(d(h)&&h!==``&&c.push(h),r++,m)return x=!0,r>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${r} attempts.`,context:{...b,registerAttempts:r,joinCondition:`attempts`,failureMessages:c}}),{...b,joinCondition:`attempts`,acquired:!0};let v=n(r,100);if(a-=v,a<=0||isAborted())break;await t(v)}return this.logger?.error({category:this.name,message:`Failed to register request after ${r} attempts.`,context:{...b,registerAttempts:r,joinCondition:`failed`,failureMessages:c},code:`ConcurrencyManagerRegistrationFailed`}),{...b,joinCondition:`failed`}}finally{if(!x&&(this.leaseRegistry.delete(buildLeaseKey(f,i)),S))try{await this.queueManager?.remove(l,i)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...b,queueKey:l},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if(u(t)&&u(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const H={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if(s(t)||t?.length===0||s(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=g(r,n?{...e,credentials:n}:e)===!0;if(s(r)||i){let n=t?.message,r;return r=s(n)?H[t.targetStatus]??`Unknown error`:String(g(n,e)??H[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},ie=p({receivedStatus:f.number(),targetStatus:f.number(),message:f.string().optional(),condition:f.string().optional()});var U=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new y.Agent(n),l=_.create({...t,httpsAgent:c});if(l.close=()=>{c.destroy()},e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return d(e)&&a(e)&&typeof e(t)==`function`?e(t):e??null}},W=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return s(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>d(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:d(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return d(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const G=W.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},ae={mainRatelimit:25},createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&C(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},K=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if(s(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:K,...a,httpsAgent:void 0,headers:void 0,hasContext:d(t),hasConfig:d(a)},code:`InterceptorContextNotPresent`});else if(s(i)||s(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:K,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:d(i),concurrencyManagerInitialized:d(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if(d(t.provider)&&d(t.accountSecureId)){let o=S(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??ae,u=n?.concurrency??ne,d=await i.getDynamicMaxWaitTime(l,u,a.url),register=async e=>r.registerRequest(`${c}-${s}`,u,o,a.url,Math.max((d-e)*1e3,0),a.signal),f,p=0;for(;p<=d;){let n=await i.getWaitTime(`${c}-${s}`,l,a.url)??0;if(n<=0){f=await register(p);break}let r=Math.min(Math.max(n,1),d-p);if(await abortableDelay(r*1e3,a),p+=r,p>=d){f=await register(p),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:K,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:d},code:`InterceptorMaxWaitTimeExceeded`});break}}return{...a,requestMetadata:f}}return a};return checkConcurrencyInterceptor},q=1e3,oe=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*q:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&o(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*q},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=w(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:c}=e??{};return[t,n,r,o].some(s)?null:[t,n,r,i,a,o,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return o(e)||c(e)?evaluateRetryAfterNumber(Number(e),r,t,n):T(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/q);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(oe.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/q);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i})=>{let retryErrorInterceptor=async a=>{let{response:o,config:s}=a;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,i,r,t);if(c===429&&d(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*q:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),e?.request(u)}return Promise.reject(a)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:c}=e??{},{retryafter:u}=superNormalizeHeaders(o??{});if(s(i)||s(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:s(e),providerIsMissing:s(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:u??`undefined`}}),{status:a,retryAfter:u};let f=n?.rateLimits?.mappedRateLimitErrors;if(d(f)&&d(c))for(let e of f){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:s,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=testMessage(l(c)?E({path:f,json:c})[0]:c,r);if(t===a&&p){let e=convertRetryAfter(d??extractRetryAfter(o,i),s);return{status:429,retryAfter:u??e}}}return{status:a,retryAfter:u}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>d(t)&&d(e)?E({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>d(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/q;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},J=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i,concurrencyManager:a})=>{let rateLimitErrorInterceptor=async o=>{let{response:c,config:l}=o,u=l?.signal;if(s(i)||s(l))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:J,...l,httpsAgent:void 0,headers:void 0,hasContext:d(i),hasConfig:d(l)},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(a))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:J,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(a)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(o);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h,acquired:g}=l?.requestMetadata??{},_=g!==!1&&d(f)&&d(p);if(!(_&&await a.releaseRequest(f,p))&&_&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:J,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:`RateLimiterReleaseRequestFailed`}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,l,`ERR_CANCELED`,c));let{status:v,retryAfter:y}=convertError(c,i,r,t);if(v===429&&d(l)){let r=getRetryAfterWaitTime(y);if(l._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:y,retryAfterAsNumber:r}}),Promise.reject(o);let a=l?._retryCount??0,s={...l,_retryCount:a+1},u=y?r*q:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:y,calculatedRetryAfter:u}}),await abortableDelay(u,l,c),e?.request(s)}return Promise.reject(o)};return rateLimitErrorInterceptor},Y=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if(s(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:Y,...i,httpsAgent:void 0,headers:void 0}});else if(s(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:Y,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if(d(t.provider)&&d(t.accountSecureId)){let t=r?.headers;if(d(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:Y,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l,acquired:u}=i?.requestMetadata??{},f=u!==!1&&d(o)&&d(s);if(!(f&&await n.releaseRequest(o,s))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:Y,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),se=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ce=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],le=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],ue=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=d(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),u=c.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(s(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(d(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),s(n?.service)||s(n?.organizationId)||o===`test`||s(t)||s(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=l?.isReady(),p=u?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...le),h.push(...ue)}let g=generateRequestKey(n);if(s(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:d(a)}}),a;let _=await G.get(g);if(d(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await G.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(a)},error:t,code:`HttpTransportInstanceCreateError`}),d(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:se,responseConfigs:ce},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>_.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=D(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?i(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,responseType:a,cacheTTL:o,context:c,traceId:l,payload:u,httpsAgent:f,httpAgent:p,requestConfig:m,httpsAgentConfig:h}){try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let g=this.#v(t,r),_=this.#l(e),v=this.#h(u,e),y=await this.#s({url:g,payload:v,method:n,cacheTTL:o,context:c});if(y)return{...y,responseTime:new Date};let b=W.getInstance(),x=(d(l)?await b.get(l):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:c,requestConfig:m,httpsAgentConfig:h})).request({headers:_,url:g,method:n,maxRedirects:i,responseType:a,data:v,httpsAgent:f,httpAgent:p,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#u(S.headers),requestHeaders:buildSafeRequestHeaders(_),requestUrl:g,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:g,payload:v,method:n,cacheTTL:o,context:c,response:C}),C}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw d(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,maxRedirects:i=0,context:a,traceId:o,payload:s,httpsAgent:c,httpAgent:l,requestConfig:u,httpsAgentConfig:f}){try{let p=this.#v(t,r),m=this.#l(e),h=this.#h(s,e),g=W.getInstance(),_=(d(o)?await g.get(o):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:u,httpsAgentConfig:f})).request({headers:m,url:p,method:n,maxRedirects:i,responseType:`stream`,data:h,httpsAgent:c,httpAgent:l,signal:_});return{status:v.status,headers:this.#u(v.headers),stream:v.data,requestUrl:t}}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw d(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?k.stringify(e):e}#g(e){if(v(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t){if(s(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={},o={};for(let[e,s]of Object.entries(t))if(this.#_(s)){let t=s.arrayFormat,c=s.value;t===`repeat`?r[e]=Array.isArray(c)?c:[c]:t===`brackets`?i[e]=Array.isArray(c)?c:[c]:t===`comma`?a[e]=Array.isArray(c)?c:[c]:t===`stringify`?o[e]=JSON.stringify(Array.isArray(c)?c:[c]):n[e]=c}else n[e]=s;let c=[];Object.keys(n).length>0&&c.push(k.stringify(n)),Object.keys(r).length>0&&c.push(k.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&c.push(k.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&c.push(k.stringify(a,{arrayFormat:`comma`})),Object.keys(o).length>0&&c.push(k.stringify(o));let l=c.join(`&`);return d(l)?`${e}?${l}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const de=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
97
|
+
`};var ConcurrencyManager=class extends ScriptManager{constructor(...e){super(...e),this.hasValidRedisConfig=!1,this.subscriptionManager=null,this.queueManager=null,this.leaseRegistry=new Map,this.setRemovalRegistry=new Map,this.leaseExpiryDispatcher=async(e,t)=>{if(t!==B)return;let n=this.leaseRegistry.get(e);if(!s(n)){this.leaseRegistry.delete(e);try{await this.releaseRequest(n.requestId,n.targetConcurrencyKey)}catch(e){this.logger?.error({message:`Failed to release request on lease expiry - Redis may not be ready`,category:this.name,context:n,error:e,code:`ConcurrencyManagerReleaseRequestFailed`})}}},this.setRemovalDispatcher=async(e,t)=>{if(t!==V)return;let n=this.setRemovalRegistry.get(e);if(!s(n))for(let t of n)try{await this.executeScript(`publishNextItem`,[t],[])}catch(n){this.logger?.error({message:`Failed to publish next item from queue - Redis may not be ready`,category:this.name,context:{queueKey:t,targetConcurrencyKey:e},error:n,code:`ConcurrencyManagerPublishNextItemFailed`})}},this.name=`ConcurrencyManager`}async additionalInitialization(e,t){if(this.generateUUID=e??r,this.subscriptionManager=new SubscriptionManager({config:this.redisClientConfig,logger:this.logger,instantiator:this.name,subscriptionTTL:12e4,truncateThreshold:1e4,truncationPercentage:1}),await this.subscriptionManager?.initialize(),t?.skipStartupCheck)this.hasValidRedisConfig=!0,this.logger?.info({category:this.name,message:`Skipping Redis startup check (skipStartupCheck enabled)`});else if(this.hasValidRedisConfig=await this.checkRedisEventsEmit(),!this.hasValidRedisConfig)throw Error(`Failed to validate Redis configuration for ConcurrencyManager`);if(s(this.getSingleton))throw Error(`getSingleton method not available`);this.queueManager=this.getSingleton?.(QueueManager)}async addTestSubscription(e,t,n,r){return s(this.subscriptionManager)?!1:this.subscriptionManager.subscribe(e,async(i,a)=>{a===e&&i.includes(t)&&(n.push(a),n.includes(z)&&n.includes(ee)&&n.includes(B)&&(r(),n.length=0))})}async checkRedisEventsEmit(){let e=[],t=Date.now(),checkHandler=async(n,r)=>{let checkCallback=()=>{let r=Date.now()-t;this.logger?.info({category:this.name,message:`All Redis events received successfully.`,context:{receivedEventCount:e.length,elapsedTimeMs:r}}),n(!0)},i=`config_check_test_key:${this.generateUUID()}`;if(!(await Promise.all(te.map(async t=>this.addTestSubscription(t,i,e,checkCallback)))).every(Boolean))return r(Error(`Failed to subscribe to event channels.`));await this.cacheClient?.setData({key:i,value:`test`,cacheTTL:1}),setTimeout(()=>{let e=Date.now()-t;r(Error(`Timeout waiting for Redis events to emit after ${e}ms.`))},2e4)};try{return await new Promise(checkHandler)}catch(n){let r=Date.now()-t;return this.logger?.error({category:this.name,message:`Redis events failed to emit.`,context:{receivedEventCount:e.length,elapsedTimeMs:r,reason:n?.message},error:n,code:`ConcurrencyManagerRedisEventsEmitError`}),!1}}isRedisConfigured(){return this.hasValidRedisConfig}async subscribeToLeaseExpiry(e,t){return this.leaseRegistry.set(buildLeaseKey(t,e),{requestId:e,targetConcurrencyKey:t}),await this.subscriptionManager?.subscribe(B,this.leaseExpiryDispatcher)??!1}async subscribeToSetRemoval(e,t){let n=this.setRemovalRegistry.get(e)??new Set;return n.add(t),this.setRemovalRegistry.set(e,n),await this.subscriptionManager?.subscribe(V,this.setRemovalDispatcher)??!1}async registerRequest(e,r,i,a,o=F*5,s){let c=`concurrency:${e}`,l=`queue:${e}`,u=r.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(a??``):a?.includes(e.urlPattern))?.subPoolKey,f=d(u)?`${c}-${u}`:c,{mainMaxConcurrency:p,subPools:m}=r,h=[{key:c,maxConcurrency:p},...m?.map(e=>{let{subPoolKey:t,maxConcurrency:n}=e;return{key:`${c}-${t}`,maxConcurrency:n}})??[]],g=h.map(e=>e.key),_=h.map(e=>e.maxConcurrency),[v,y]=await Promise.all([this.subscribeToLeaseExpiry(i,f),this.subscribeToSetRemoval(f,l)]),b={requestId:i,targetConcurrencyKey:f,leaseSubscription:v,setRemovalSubscription:y,queueKey:l,acquired:!1},x=!1,S=!1;try{let e=await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]);if(d(e)&&e[0])return x=!0,{...b,joinCondition:`optimistic`,acquired:!0,failureReason:e[1]};let r=0,a=o,c=[],isAborted=()=>s?.aborted===!0;for(;a>0&&r<5&&!isAborted();){let e=r>1,o=Math.min(F,a);S=!0;let u=await this.queueManager?.joinAndWaitTurn(l,i,e,async(e,t)=>await this.executeScript(`tryConcurrency`,[i,f,l,...g],[`60`,p.toString(),`90`,..._.map(String)]),!1,o,s);a-=o;let m=d(u)?u[0]:!1,h=d(u)?u[1]:``;if(d(h)&&h!==``&&c.push(h),r++,m)return x=!0,r>1&&this.logger?.warning({category:this.name,message:`Register request succeeded after ${r} attempts.`,context:{...b,registerAttempts:r,joinCondition:`attempts`,failureMessages:c}}),{...b,joinCondition:`attempts`,acquired:!0};let v=n(r,100);if(a-=v,a<=0||isAborted())break;await t(v)}return this.logger?.error({category:this.name,message:`Failed to register request after ${r} attempts.`,context:{...b,registerAttempts:r,joinCondition:`failed`,failureMessages:c},code:`ConcurrencyManagerRegistrationFailed`}),{...b,joinCondition:`failed`}}finally{if(!x&&(this.leaseRegistry.delete(buildLeaseKey(f,i)),S))try{await this.queueManager?.remove(l,i)}catch(e){this.logger?.error({category:this.name,message:`Failed to remove terminal request from concurrency queue`,context:{...b,queueKey:l},error:e,code:`ConcurrencyManagerQueueCleanupFailed`})}}}async releaseRequest(e,t){if(u(t)&&u(e)){let n=!!await this.executeScript(`removeFromSet`,[t],[e]);return n&&this.leaseRegistry.delete(buildLeaseKey(t,e)),n}return!1}isReady(){return this.subscriptionManager!==null&&this.cacheClient!==null&&this.scriptMap!==null&&this.scriptMap.size>0&&this.hasValidRedisConfig}close(){this.subscriptionManager?.close(),this.queueManager?.close(),this.scriptMap?.clear(),this.leaseRegistry.clear(),this.setRemovalRegistry.clear(),this.hasValidRedisConfig=!1}};const H={100:`Continue`,101:`Switching Protocols`,102:`Processing`,200:`OK`,201:`Created`,202:`Accepted`,203:`Non-Authoritative Information`,204:`No Content`,205:`Reset Content`,206:`Partial Content`,207:`Multi-Status`,208:`Already Reported`,226:`IM Used`,300:`Multiple Choices`,301:`Moved Permanently`,302:`Found`,303:`See Other`,304:`Not Modified`,305:`Use Proxy`,307:`Temporary Redirect`,308:`Permanent Redirect`,400:`Bad request`,401:`Unauthorized`,402:`Payment Required`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,406:`Not Acceptable`,407:`Proxy Authentication Required`,408:`Request Timeout`,409:`Conflict`,410:`Gone`,411:`Length Required`,412:`Precondition Failed`,413:`Payload Too Large`,414:`URI Too Long`,415:`Unsupported Media Type`,416:`Range Not Satisfiable`,417:`Expectation Failed`,418:`I'm a teapot`,421:`Misdirected Request`,422:`Unprocessable Entity`,423:`Locked`,424:`Failed Dependency`,425:`Too Early`,426:`Upgrade Required`,428:`Precondition Required`,429:`Too many Requests`,431:`Request Header Fields Too Large`,451:`Unavailable For Legal Reasons`,499:`Client Closed Request`,500:`Internal server error`,501:`Not Implemented`,502:`Bad Gateway`,503:`Unavailable`,504:`Gateway Timeout`,505:`HTTP Version Not Supported`,506:`Variant Also Negotiates`,507:`Insufficient Storage`,508:`Loop Detected`,510:`Not Extended`,511:`Network Authentication Required`},translateCustomError=(e,t,n)=>{if(s(t)||t?.length===0||s(e))return{data:e.data,status:e.status,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,message:e.message};let r=t?.filter(t=>t.receivedStatus===e.status);if(r?.length)for(let t of r){let r=t.condition,i=g(r,n?{...e,credentials:n}:e)===!0;if(s(r)||i){let n=t?.message,r;return r=s(n)?H[t.targetStatus]??`Unknown error`:String(g(n,e)??H[t.targetStatus]??`Unknown error`),{data:e.data,headers:e.headers,requestUrl:e.requestUrl,responseType:e.responseType,responseTime:e.responseTime,status:t.targetStatus,message:r}}}return e},ie=p({receivedStatus:f.number(),targetStatus:f.number(),message:f.string().optional(),condition:f.string().optional()});var U=class HttpResponseError extends Error{constructor(e,t){super(t),this.name=`HttpResponseError`,this.response=e,this.message=t??`HTTP error: ${e.status}`,Error.captureStackTrace&&Error.captureStackTrace(this,HttpResponseError)}toString(){let e=this.message?`: ${this.message}`:``;return`${this.name} [${this.response.status}]${e}`}};const isHttpResponseError=e=>e instanceof Error&&e.name===`HttpResponseError`&&`response`in e&&typeof e.response==`object`&&e.response!==null,safeSerialize=(e,t=new WeakSet)=>{if(typeof e!=`object`||!e)return typeof e==`bigint`?e.toString():e;if(t.has(e))return`[Circular Reference]`;if(e instanceof Date)return e.toISOString();if(Array.isArray(e)){t.add(e);let n=e.map(e=>safeSerialize(e,t));return t.delete(e),n}let n=e,r={};t.add(n);for(let[e,i]of Object.entries(n))r[e]=safeSerialize(i,t);return t.delete(n),r},serializeHttpResponseError=e=>{if(isHttpResponseError(e)){let t=e.response;return{name:e.name,message:e.message,stack:e.stack,response:safeSerialize(t)}}return e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:{error:String(e)}};var HttpTransportFactory=class{static createInstance({interceptors:e,instanceConfig:t,httpsAgentConfig:n,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s}){let c=new y.Agent(n),l=_.create({...t,httpsAgent:c});if(l.close=()=>{c.destroy()},e){let t={axiosInstance:l,logger:r,context:i,requestConfig:a,concurrencyManager:o,rateLimitManager:s};this.applyInterceptors(l,e,t)}return l}static applyInterceptors(e,t,n){let{requestConfigs:r=[],responseConfigs:i=[]}=t;[{type:`request`,configs:r},{type:`response`,configs:i}].forEach(t=>{let{configs:r,type:i}=t;r.forEach(t=>{let{onFulfilled:r,onRejected:a,options:o}=t;if(i===`request`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n),o];e.interceptors.request.use(...t)}if(i===`response`){let t=[this.resolveInterceptorInstance(r,n),this.resolveInterceptorInstance(a,n)];e.interceptors.response.use(...t)}})})}static resolveInterceptorInstance(e,t){return d(e)&&a(e)&&typeof e(t)==`function`?e(t):e??null}},W=class InstanceManager{static{this.instance=null}static{this.logger=null}constructor(e={}){this.dataStore=null,this.options=e,this.initialize()}static getInstance(e={}){return s(InstanceManager.instance)&&(InstanceManager.instance=new InstanceManager(e)),InstanceManager.instance}initialize(){let{logger:e,staleDataThreshold:t,truncateThreshold:n}=this.options;this.dataStore=new MemoryStore({instantiator:InstanceManager.name,logger:e,staleDataThreshold:t,truncateThreshold:n,typeGuard:e=>d(e),dispose:async(t,n)=>{try{await n?.close?.()}catch(n){e?.error({message:`Failed to close evicted instance "${t}"`,category:InstanceManager.name,error:n,code:`InstanceManagerDisposeError`})}}}),InstanceManager.logger=e??null,InstanceManager.logger?.info({category:InstanceManager.name,message:`InstanceManager initialized.`})}async get(e){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.getData(e)??null}async set(e,t,n){return this.ensureReady(),await InstanceManager.getInstance().dataStore?.setData({key:e,value:t,cacheTTL:d(n)?n:300})??!1}ensureReady(){this.isReady()||this.initialize()}isReady(){return d(this?.dataStore)}close(){let e=this.dataStore;InstanceManager.instance=null,this.dataStore=null,e?.close?.()}};const G=W.getInstance({staleDataThreshold:6048e5,truncateThreshold:100}),abortErrorInterceptor=()=>{let abortErrorInterceptor=e=>{let{response:t}=e;return e?.code===`ERR_CANCELED`&&(e.response={...t,status:499,statusText:`Request aborted`}),Promise.reject(e)};return abortErrorInterceptor},ae={mainRatelimit:25},createAxiosError=(e,t,n,r)=>{let i=Error(e);return i.config={...t,headers:{}},i.code=n,i.response=r,i.isAxiosError=!0,i},abortableDelay=(e,t,n)=>{let r=t.signal;return r?r.aborted?Promise.reject(createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n)):new Promise((i,a)=>{let o=!1,s,c=createAxiosError(`Request aborted`,t,`ERR_CANCELED`,n),cleanup=()=>{if(!o){o=!0,s&&C(s);try{r.removeEventListener?.(`abort`,onAbort)}catch{}}},onAbort=()=>{cleanup(),a(c)},onTimeout=()=>{cleanup(),i()};try{r.addEventListener?.(`abort`,onAbort,{once:!0})}catch{s=setTimeout(()=>{i()},e);return}if(r.aborted){cleanup(),a(c);return}s=setTimeout(onTimeout,e)}):new Promise(t=>setTimeout(t,e))},K=`checkConcurrencyInterceptor`,checkConcurrencyInterceptor=({logger:e,context:t,requestConfig:n,concurrencyManager:r,rateLimitManager:i})=>{let checkConcurrencyInterceptor=async a=>{if(a.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,a,`ERR_CANCELED`));if(s(t))e?.warning({category:`HttpClient`,message:`No context for this request - that doesn't seem right.`,context:{interceptor:K,...a,httpsAgent:void 0,headers:void 0,hasContext:d(t),hasConfig:d(a)},code:`InterceptorContextNotPresent`});else if(s(i)||s(r))e?.error({category:`HttpClient`,message:`RateLimitManager or ConcurrencyManager is not initialized`,context:{interceptor:K,...a,httpsAgent:void 0,headers:void 0,rateLimitManagerInitialized:d(i),concurrencyManagerInitialized:d(r)},code:`RateLimitOrConcurrencyManagerNotInitialized`});else if(d(t.provider)&&d(t.accountSecureId)){let o=S(),{provider:s,accountSecureId:c}=t,l=n?.rateLimits??ae,u=n?.concurrency??ne,d=await i.getDynamicMaxWaitTime(l,u,a.url),register=async e=>r.registerRequest(`${c}-${s}`,u,o,a.url,Math.max((d-e)*1e3,0),a.signal),f,p=0;for(;p<=d;){let n=await i.getWaitTime(`${c}-${s}`,l,a.url)??0;if(n<=0){f=await register(p);break}let r=Math.min(Math.max(n,1),d-p);if(await abortableDelay(r*1e3,a),p+=r,p>=d){f=await register(p),e?.warning({category:`HttpClient`,message:`Max Wait Time Exceeded for ${s} - Account: ${c}`,context:{...t,interceptor:K,...a,httpsAgent:void 0,headers:void 0,dynamicMaxWaitTime:d},code:`InterceptorMaxWaitTimeExceeded`});break}}return{...a,requestMetadata:f}}return a};return checkConcurrencyInterceptor},q=1e3,oe=/^\d+(\.\d+)?$/,adjustUnixTimestamp=e=>e<3250368e4?e*q:e,shortTimePeriodIsMilliseconds=e=>{let t=Number(e);return Number.isNaN(t)?!1:t>=120&&t<=36e4},resolveWaitTimeMs=e=>{let t=Number(e),n=Date.now();return Number.isNaN(t)?n+1e3:!shortTimePeriodIsMilliseconds(t)&&o(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*q},superNormalizeHeaders=e=>{let t={};for(let[n,r]of Object.entries(e)){let e=n.toLowerCase().replace(/^x-/,``).replace(/concurren.+-/g,`concurrency-`).replace(/-/g,``);t[e]=w(r)?Number(r):null}return t},extractRateLimitHeaders=e=>{let t=superNormalizeHeaders(e);return{rateLimitLimit:t.ratelimitlimit,rateLimitRemaining:t.ratelimitremaining,rateLimitReset:resolveWaitTimeMs(t.ratelimitreset),concurrencyLimit:t.ratelimitconcurrencylimit,concurrencyRemaining:t.ratelimitconcurrencyremaining,concurrencyReset:resolveWaitTimeMs(t.ratelimitconcurrencyreset)}},generateRequestKey=e=>{let{accountSecureId:t,service:n,resource:r,subResource:i,childResource:a,action:o,behaviours:c}=e??{};return[t,n,r,o].some(s)?null:[t,n,r,i,a,o,...c??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return o(e)||c(e)?evaluateRetryAfterNumber(Number(e),r,t,n):T(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<=0)return r;if(e<31536e3)return Math.min(e,n);let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/q);return e>0?Math.min(e,n):r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(oe.test(e)){let t=parseFloat(e);return t>0?Math.min(t,n):r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/q);return e>0?Math.min(e,n):r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i})=>{let retryErrorInterceptor=async a=>{let{response:o,config:s}=a;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,i,r,t);if(c===429&&d(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return t?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...i??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(a);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*q:n(u._retryCount);return t?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...i??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),e?.request(u)}return Promise.reject(a)};return retryErrorInterceptor},convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:c}=e??{},{retryafter:u}=superNormalizeHeaders(o??{});if(s(i)||s(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:s(e),providerIsMissing:s(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:u??`undefined`}}),{status:a,retryAfter:u};let f=n?.rateLimits?.mappedRateLimitErrors;if(d(f)&&d(c))for(let e of f){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:s,retryAfterValue:d}=e;if(t!==a)continue;let f=n??`message`,p=testMessage(l(c)?E({path:f,json:c})[0]:c,r);if(t===a&&p){let e=convertRetryAfter(d??extractRetryAfter(o,i),s);return{status:429,retryAfter:u??e}}}return{status:a,retryAfter:u}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>d(t)&&d(e)?E({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>d(e)?transformToSeconds(e,t):null,transformToSeconds=(e,t)=>{if(t===`seconds`)return typeof e==`string`?parseFloat(e):e;if(t===`milliseconds`)return(typeof e==`string`?parseFloat(e):e)/q;if(t===`date`){let t=typeof e==`string`&&!isNaN(Number(e))?parseFloat(e):e,n=new Date(t);if(isNaN(n.getTime()))throw Error(`Invalid date value`);return n.getTime()}throw Error(`Invalid type`)},J=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:r,context:i,concurrencyManager:a})=>{let rateLimitErrorInterceptor=async o=>{let{response:c,config:l}=o,u=l?.signal;if(s(i)||s(l))return t?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:J,...l,httpsAgent:void 0,headers:void 0,hasContext:d(i),hasConfig:d(l)},code:`InterceptorContextNotPresent`}),Promise.reject(o);if(s(a))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:J,...l,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(a)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),Promise.reject(o);let{requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h,acquired:g}=l?.requestMetadata??{},_=g!==!1&&d(f)&&d(p);if(!(_&&await a.releaseRequest(f,p))&&_&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...i,interceptor:J,requestId:f,targetConcurrencyKey:p,leaseSubscription:m,setRemovalSubscription:h},code:`RateLimiterReleaseRequestFailed`}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,l,`ERR_CANCELED`,c));let{status:v,retryAfter:y}=convertError(c,i,r,t);if(v===429&&d(l)){let r=getRetryAfterWaitTime(y);if(l._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${l.url}. Aborting.`,context:{...i??{},...l.requestMetadata??{},retryAfterHeader:y,retryAfterAsNumber:r}}),Promise.reject(o);let a=l?._retryCount??0,s={...l,_retryCount:a+1},u=y?r*q:n(s._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${l.url}`,context:{...i,retryAfterHeader:y,calculatedRetryAfter:u}}),await abortableDelay(u,l,c),e?.request(s)}return Promise.reject(o)};return rateLimitErrorInterceptor},Y=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>{let rateLimitResponseInterceptor=async r=>{let i=r?.config,a=i?.signal;if(s(t))e?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:Y,...i,httpsAgent:void 0,headers:void 0}});else if(s(n))return e?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:Y,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:d(n)},code:`RateLimitOrConcurrencyManagerNotInitialized`}),r;else if(d(t.provider)&&d(t.accountSecureId)){let t=r?.headers;if(d(t)){let n=extractRateLimitHeaders(t);e?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:Y,rateLimitHeaders:n}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l,acquired:u}=i?.requestMetadata??{},f=u!==!1&&d(o)&&d(s);if(!(f&&await n.releaseRequest(o,s))&&f&&e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:Y,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:`RateLimiterReleaseRequestFailed`}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r};return rateLimitResponseInterceptor},validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),se=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],ce=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],le=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],ue=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}];var RateLimitManager=class extends ScriptManager{constructor(...e){super(...e),this.name=`RateLimitManager`}async additionalInitialization(){}getDynamicMaxWaitTime(e,t,n,r=59,i=.8,a=500){this.readyCheck();let o=e.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.rateLimit??e.mainRatelimit;if(o<=0)throw Error(`Requests per second (rps) must be greater than 0.`);let s=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.maxConcurrency??t.mainMaxConcurrency;if(s<=0)throw Error(`Concurrency must be greater than 0.`);let c=r*i,l=1/Math.min(o,s/(a/1e3)),u=Math.max(7.5,c*l);return Math.min(c,u)}async getWaitTime(e,t,n){this.readyCheck();let r=`rateLimit:${e}`,i=t.subPools?.find(e=>e.urlPattern instanceof RegExp?e.urlPattern.test(n??``):n?.includes(e.urlPattern))?.subPoolKey,a=d(i)?`${r}-${i}`:r,{mainRatelimit:o,subPools:s}=t,c=[{key:r,rateLimit:o},...s?.map(e=>{let{subPoolKey:t,rateLimit:n}=e;return{key:`${r}-${t}`,rateLimit:n}})??[]],l=c.map(e=>e.key),u=c.map(e=>e.rateLimit);return await this.executeScript(`incr`,[a,...l],[o.toString(),...u.map(String)])}readyCheck(){if(!this.cacheClient||!this.scriptMap?.size)throw Error(`RateLimitManager not ready`)}isReady(){return!!this?.cacheClient&&!!this?.scriptMap?.size}close(){this.scriptMap?.clear(),this.reset()}},SingletonManager=class{static{this.instances=new Map}static async prepare(e,t,...n){if(!this.instances.has(e)){let t=new e;t.getSingleton=e=>{let t=this.instances.get(e);if(s(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(d(n))return n;throw Error(`${e.name} not ready`)},this.instances.set(e,t)}let r=this.instances.get(e);try{return await r.getInstance(t,...n)}catch(t){throw r.hasInitFailed?.()&&this.instances.delete(e),t}}static getIfReady(e){return this.instances.get(e)?.getInstanceIfReady?.()??null}static reset(e){this.instances.get(e)?.reset?.(),this.instances.delete(e)}static cleanupFailed(){let e=0;for(let[t,n]of this.instances){let r=n;r?.hasInitFailed?.()&&(r?.reset?.(),this.instances.delete(t),e++)}return e}};const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,c=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=c.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),s(n?.service)||s(n?.organizationId)||o===`test`||s(t)||s(e))return a;let l=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,f=l?.isReady(),p=u?.isRedisConfigured(),m=[],h=[];if(c.includes(`CONCURRENCY`)){if(!p)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!f)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...le),h.push(...ue)}let g=generateRequestKey(n);if(s(g))return e?.warning({category:`http-transport`,message:`Unable to create a key for transport instance - Invalid state. Using base default instance.`,context:{...n,defaultInstanceInitialized:d(a)}}),a;let _=await G.get(g);if(d(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:l},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await G.set(g,y),y}catch(t){return e?.error({category:`http-transport`,message:`Failed to create advanced transport instance. Using default instance.`,context:{...n,usingDefaultInstance:d(a)},error:t,code:`HttpTransportInstanceCreateError`}),d(a)?a:createAxiosInstance()}},createDefaultInstance=(e,t)=>{let n={instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createDefaultRetryInstance=(e,t)=>{let n={interceptors:{requestConfigs:se,responseConfigs:ce},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>_.create({maxBodyLength:1/0});function buildSafeRequestHeaders(e){let t=D(e),n=Object.entries(t??{}).reduce((t,[n,r])=>(r===e[n]&&(t[n]=r),t),{});return Object.keys(n).length>0?n:void 0}var HttpClient=class{#e;#t;#n;#r;#i;#a;constructor({transportFactory:e=getTransportInstance,getRedisClient:t=buildRedisClientInstance,logger:n,redisClientConfig:r,errorMappingFn:i}={}){this.name=`HttpClient`,this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}#o({url:e,payload:t,method:n,context:r}){if(!r?.accountSecureId||r.accountSecureId.length<20||!e||!n)return null;let a=t?i(t):``;return`${r.accountSecureId}-${n.toUpperCase()}${a}-${e}`}async#s({url:e,payload:t,method:n,cacheTTL:r,context:i}){if(!this.#a||!r||r<=0)return null;let a=this.#o({url:e,payload:t,method:n,context:i});if(!a)return null;let o=await this.#a.getData(a);return o?(this.#n?.debug({category:this.name,message:`Cache hit for key [${a}].`}),o):(this.#n?.debug({category:this.name,message:`Cache miss for key [${a}].`}),null)}async#c({url:e,payload:t,method:n,cacheTTL:r,context:i,response:a}){if(!this.#a||!r||r<=0)return!1;let o=this.#o({url:e,payload:t,method:n,context:i});return o?(this.#n?.debug({category:this.name,message:`Caching result for key [${o}].`}),this.#a.setData({key:o,value:a,cacheTTL:r*60})):!1}async request({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,responseType:o,cacheTTL:c,context:l,traceId:u,payload:f,httpsAgent:p,httpAgent:m,requestConfig:h,httpsAgentConfig:g}){try{d(this.#r)&&s(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let _=this.#v(t,r,i),v=this.#l(e),y=this.#h(f,e),b=await this.#s({url:_,payload:y,method:n,cacheTTL:c,context:l});if(b)return{...b,responseTime:new Date};let x=W.getInstance(),S=(d(u)?await x.get(u):null)?.signal,C=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:l,requestConfig:h,httpsAgentConfig:g})).request({headers:v,url:_,method:n,maxRedirects:a,responseType:o,data:y,httpsAgent:p,httpAgent:m,signal:S}),w={data:C.data,status:C.status,body:y,method:n,headers:this.#u(C.headers),requestHeaders:buildSafeRequestHeaders(v),requestUrl:_,responseType:C?.config?.responseType,responseTime:new Date};return await this.#c({url:_,payload:y,method:n,cacheTTL:c,context:l,response:w}),w}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw d(i)?i:e}}async get({headers:e,url:t,queryParams:n,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s}){return this.request({url:t,method:`get`,queryParams:n,headers:e,maxRedirects:r,cacheTTL:i,context:a,traceId:o,requestConfig:s})}async post({headers:e,url:t,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s}){return this.request({url:t,method:`post`,headers:e,maxRedirects:n,cacheTTL:r,context:i,traceId:a,payload:o,requestConfig:s})}async requestStream({headers:e={},url:t,method:n=`get`,queryParams:r,encodeQueryParams:i,maxRedirects:a=0,context:o,traceId:s,payload:c,httpsAgent:l,httpAgent:u,requestConfig:f,httpsAgentConfig:p}){try{let m=this.#v(t,r,i),h=this.#l(e),g=this.#h(c,e),_=W.getInstance(),v=(d(s)?await _.get(s):null)?.signal,y=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:o,requestConfig:f,httpsAgentConfig:p})).request({headers:h,url:m,method:n,maxRedirects:a,responseType:`stream`,data:g,httpsAgent:l,httpAgent:u,signal:v});return{status:y.status,headers:this.#u(y.headers),stream:y.data,requestUrl:t}}catch(e){let r=e;r.url=O(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw d(i)?i:e}}#l(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n.toLowerCase()]=e[n]||``}),t}#u(e){if(!e)return{};let t={};return Object.keys(e).forEach(n=>{t[n]=e[n]||``}),t}#d(e){return e[`content-type`]===`application/x-www-form-urlencoded`}#f(e){return u(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return s(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!(s(e)||l(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?k.stringify(e):e}#g(e){if(v(e)&&this.#i)return this.#i(e)}#_(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#v(e,t,n){if(s(t)||Object.keys(t).length===0)return e;let r={},i={},a={},o={},c={};for(let[e,n]of Object.entries(t))if(this.#_(n)){let t=n.arrayFormat,s=n.value;t===`repeat`?i[e]=Array.isArray(s)?s:[s]:t===`brackets`?a[e]=Array.isArray(s)?s:[s]:t===`comma`?o[e]=Array.isArray(s)?s:[s]:t===`stringify`?c[e]=JSON.stringify(Array.isArray(s)?s:[s]):r[e]=s}else r[e]=n;let l=n===!1?{encode:!1}:{},u=[];Object.keys(r).length>0&&u.push(k.stringify(r,l)),Object.keys(i).length>0&&u.push(k.stringify(i,{...l,arrayFormat:`repeat`})),Object.keys(a).length>0&&u.push(k.stringify(a,{...l,arrayFormat:`brackets`})),Object.keys(o).length>0&&u.push(k.stringify(o,{...l,arrayFormat:`comma`})),Object.keys(c).length>0&&u.push(k.stringify(c,l));let f=u.join(`&`);return d(f)?`${e}?${f}`:e}};const buildHttpClientInstance=(e,t,n)=>new HttpClient({redisClientConfig:e,logger:t,errorMappingFn:n});var HttpClientManager=class{static{this.httpClientInstance=null}static async getInstance({redisClientConfig:e,logger:t,errorMappingFn:n,getHttpClient:r=buildHttpClientInstance}){return this.httpClientInstance??=r(e,t,n),this.httpClientInstance}static resetInstance(){this.httpClientInstance=null}};const de=[`get`,`post`,`put`,`delete`,`patch`],isPemFormat=e=>e.includes(`-----BEGIN `),normalizePem=e=>{let t=e.replace(/\\n/g,`
|
|
98
98
|
`).replace(/\r\n/g,`
|
|
99
99
|
`).replace(/\r/g,`
|
|
100
100
|
`).trim();t=t.replace(/(-----BEGIN [A-Z0-9 ]+-----) +/g,`$1
|
|
@@ -168,8 +168,8 @@ $1`);let n=t.match(/(-----BEGIN [A-Z0-9 ]+-----)\n?([^-]+)(-----END [A-Z0-9 ]+--
|
|
|
168
168
|
end
|
|
169
169
|
|
|
170
170
|
return nil
|
|
171
|
-
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],[a,o]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:fe,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:pe,logger:n})]),s=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:re,logger:n,additionalArgs:e}),c=[{name:`ConcurrencyManager`,ready:s.isReady()},{name:`QueueManager`,ready:a.isReady()},{name:`RateLimitManager`,ready:o.isReady()}],l=c.filter(e=>!e.ready);if(l.length>0){let e=l.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:c.map(e=>e.name)}}),{concurrencyManager:s,queueManager:a,rateLimitManager:o}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},me=e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),X=e(e=>Array.isArray(e)?e:[e],`toStringArray`),toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=X(t);if(me(e))return{value:[...X(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...X(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),he=[`query`,`body`,`headers`],ge=[`repeat`,`brackets`,`comma`,`stringify`],Z={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},_e=new A(Z),getContentType=e=>{let t=Object.entries(e).find(([e])=>e.toLowerCase()===`content-type`)?.[1];return typeof t==`string`?t.toLowerCase():``},isXmlContentTypeValue=e=>e.includes(`application/xml`)||e.includes(`text/xml`)||/application\/\S+\+xml/.test(e),isXmlContentType=e=>isXmlContentTypeValue(getContentType(e)),serializeBodyToXml=e=>{try{return _e.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?k.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>d(e)&&e>=200&&e<=299,isFailedStatusCode=e=>d(e)&&e>=400&&e<=599,isInfoStatusCode=e=>d(e)&&e>=100&&e<=199;let ve;const getXmlParser=()=>(ve??=new j({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),ve);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:c,httpsAgent:l,credentials:u}){let d,f=a;if(isXmlContentType(r))if(typeof a==`string`)f=a;else if(Array.isArray(a))throw Error(`Cannot serialize an array body to XML: XML requires a single root element. Wrap the array in an object with a root key.`);else a!=null&&(f=serializeBodyToXml(a));try{d=await e?.request({method:n,url:t,headers:r,queryParams:i,maxRedirects:0,payload:f,requestConfig:c,httpsAgent:l})}catch(e){if(s(e?.response))throw e;d=e.response}if(typeof d.data==`string`&&d.data.length>0&&d.headers&&isXmlContentType(d.headers)){let e=M.validate(d.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);d={...d,data:getXmlParser().parse(d.data)}}let p=translateCustomError(d,o,u);if(isFailedStatusCode(p?.status))throw new U(p,p.message);return p}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,body:a,customErrorConfigs:o,requestConfig:c,credentials:l}){let u;if(u=typeof c?.envelope==`string`?c.envelope:typeof c?.envelope==`object`?Q.build(c.envelope):await buildEnvelope(a,c),M.validate(u,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let d,f={"Content-Type":`application/xml`,...r};c?.soapAction&&(f.SOAPAction=c.soapAction);try{d=await e?.request({method:n,url:t,headers:f,queryParams:i,maxRedirects:0,payload:u,requestConfig:c})}catch(e){if(s(e?.response))throw e;d=e.response}let p=ye.parse(d.data),m=p.Envelope||p,h=m.Body||m,g=h.Fault;if(g)throw new U({...d,status:500,data:g,message:g.faultstring??g.faultcode??`SOAP Fault`},g.faultstring??`SOAP Fault occurred`);d.data=h;let _=translateCustomError(d,o,l);if(isFailedStatusCode(_?.status))throw new U(_,_.message);return _}};const Q=new A(Z),ye=new j({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if(d(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Q.build(t.envelope);if(M.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Q.build(n);if(M.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await h(e.namespaceIdentifier),namespace:await h(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(s(e)||s(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if(s(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if(s(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};const arrayFormatToPairs=(e,t,n)=>n===`brackets`?t.map(t=>[`${e}[]`,t]):n===`comma`?[[e,t.join(`,`)]]:n===`stringify`?[[e,JSON.stringify(t)]]:t.map(t=>[e,t]),toStringArray=e=>Array.isArray(e)?e:[e],isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),flattenQueryParams=e=>{if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))r!=null&&(isHttpQueryParamValue(r)?t.push(...arrayFormatToPairs(n,toStringArray(r.value),r.arrayFormat)):t.push(...arrayFormatToPairs(n,toStringArray(r),void 0)));return t},hmac=(e,t)=>x(`sha256`,e).update(t).digest(),hash=e=>b(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),$=e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),be=e((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),d=u.slice(0,8),f=new URL(e.url),p=f.pathname.split(`/`).map(e=>{try{return $(decodeURIComponent(e))}catch{return $(e)}}).join(`/`)||`/`,m=[];for(let[e,t]of f.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=be(e,n);return i===0?be(t,r):i});let h=m.map(([e,t])=>`${$(e)}=${$(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=b(`sha256`).update(g).digest(),v=_.toString(`hex`),y={host:f.host,"x-amz-content-sha256":v,"x-amz-date":u};a&&(y[`x-amz-security-token`]=a);for(let[t,n]of Object.entries(e.headers??{})){let e=t.toLowerCase();e!==`authorization`&&e!==`x-amz-date`&&e!==`x-amz-content-sha256`&&e!==`x-amz-security-token`&&(y[e]=n)}let S=Object.keys(y).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),C=g.length>0&&!S,w;C&&(w=_.toString(`base64`),y[`x-amz-checksum-sha256`]=w);let T=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),E=T.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),D=T.join(`;`),O=[e.method.toUpperCase(),p,h,E,D,v].join(`
|
|
171
|
+
`},initializeTransportSystem=async e=>{let{redisClientConfig:t,logger:n,generateUUID:r,skipStartupCheck:i}=e;try{n?.info({category:`TransportInitialization`,message:`Starting transport system initialization`});let e=[r,{skipStartupCheck:i??!1}],[a,o]=await Promise.all([SingletonManager.prepare(QueueManager,{redisClientConfig:t,scripts:fe,logger:n}),SingletonManager.prepare(RateLimitManager,{redisClientConfig:t,scripts:pe,logger:n})]),s=await SingletonManager.prepare(ConcurrencyManager,{redisClientConfig:t,scripts:re,logger:n,additionalArgs:e}),c=[{name:`ConcurrencyManager`,ready:s.isReady()},{name:`QueueManager`,ready:a.isReady()},{name:`RateLimitManager`,ready:o.isReady()}],l=c.filter(e=>!e.ready);if(l.length>0){let e=l.map(e=>e.name).join(`, `);throw Error(`Failed to initialize managers: ${e}`)}return n?.info({category:`TransportInitialization`,message:`Transport system initialization completed successfully`,context:{initializedManagers:c.map(e=>e.name)}}),{concurrencyManager:s,queueManager:a,rateLimitManager:o}}catch(e){n?.error({category:`TransportInitialization`,message:`Failed to initialize transport system`,code:`TRANSPORT_INIT_ERROR`,error:e});let t=SingletonManager.cleanupFailed();throw t>0&&n?.info({category:`TransportInitialization`,message:`Cleaned up ${t} failed singleton instances`}),e}},shutdownTransportSystem=e=>{try{e?.info({category:`TransportInitialization`,message:`Starting transport system shutdown`});let t=SingletonManager.getIfReady(ConcurrencyManager),n=SingletonManager.getIfReady(QueueManager),r=SingletonManager.getIfReady(RateLimitManager);t?.close(),n?.close(),r?.close(),SingletonManager.reset(ConcurrencyManager),SingletonManager.reset(QueueManager),SingletonManager.reset(RateLimitManager),e?.info({category:`TransportInitialization`,message:`Transport system shutdown completed`})}catch(t){e?.error({category:`TransportInitialization`,message:`Error during transport system shutdown`,code:`TRANSPORT_SHUTDOWN_ERROR`,error:t})}},isTransportSystemReady=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return!!(e?.isReady()&&t?.isReady()&&n?.isReady())},getTransportManagers=()=>{let e=SingletonManager.getIfReady(ConcurrencyManager),t=SingletonManager.getIfReady(QueueManager),n=SingletonManager.getIfReady(RateLimitManager);return e&&t&&n?{concurrencyManager:e,queueManager:t,rateLimitManager:n}:null},me=e(e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),`isHttpQueryParamValue`),X=e(e=>Array.isArray(e)?e:[e],`toStringArray`),toQueryValue=e=>Array.isArray(e)?e.map(String):String(e),mergeQueryValues=(e,t,n)=>{let r=X(t);if(me(e))return{value:[...X(e.value),...r],arrayFormat:n??e.arrayFormat};let i=[...X(e),...r];return n?{value:i,arrayFormat:n}:i},parseQueryParam=(e,t,n)=>{let r=toQueryValue(t);return e===void 0?n?{value:r,arrayFormat:n}:r:mergeQueryValues(e,r,n)},parseBodyParam=(e,t)=>Array.isArray(e)?e.concat(t):typeof e==`object`&&e&&typeof t==`object`&&t?{...e,...t}:t,parseRequestParameters=e=>e.reduce((e,t)=>{if(t.in===`query`){let n=e.query[t.name];e.query[t.name]=parseQueryParam(n,t.value,t.arrayFormat)}else if(t.in===`body`)if(t.spread)Array.isArray(t.value)?Array.isArray(e.body)?e.body=e.body.concat(t.value):e.body=t.value:typeof t.value==`object`&&t.value!==null&&(e.body={...e.body,...t.value});else{let n=e.body[t.name];e.body[t.name]=parseBodyParam(n,t.value)}else e.headers[t.name]=String(t.value);return e},{query:{},body:{},headers:{}}),he=[`query`,`body`,`headers`],ge=[`repeat`,`brackets`,`comma`,`stringify`],Z={ignoreAttributes:!1,attributeNamePrefix:`@_`,suppressBooleanAttributes:!1},_e=new A(Z),getContentType=e=>{let t=Object.entries(e).find(([e])=>e.toLowerCase()===`content-type`)?.[1];return typeof t==`string`?t.toLowerCase():``},isXmlContentTypeValue=e=>e.includes(`application/xml`)||e.includes(`text/xml`)||/application\/\S+\+xml/.test(e),isXmlContentType=e=>isXmlContentTypeValue(getContentType(e)),serializeBodyToXml=e=>{try{return _e.build(e)}catch(e){throw Error(`Failed to serialize request body to XML: ${e instanceof Error?e.message:String(e)}`)}},serializeRequestBodyForSigning=(e,t={})=>{if(e==null)return``;if(typeof e==`string`)return e;let n=getContentType(t);return n.includes(`application/x-www-form-urlencoded`)?k.stringify(e):isXmlContentTypeValue(n)?serializeBodyToXml(e):JSON.stringify(e)},isSuccessStatusCode=e=>d(e)&&e>=200&&e<=299,isFailedStatusCode=e=>d(e)&&e>=400&&e<=599,isInfoStatusCode=e=>d(e)&&e>=100&&e<=199,ve=[`arraybuffer`,`blob`,`document`,`text`];let ye;const getXmlParser=()=>(ye??=new j({ignoreAttributes:!1,attributeNamePrefix:`@_`,parseAttributeValue:!1,removeNSPrefix:!1,numberParseOptions:{leadingZeros:!1,hex:!1}}),ye);var RestClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,httpsAgent:u,credentials:d,responseType:f}){let p,m=o;if(isXmlContentType(r))if(typeof o==`string`)m=o;else if(Array.isArray(o))throw Error(`Cannot serialize an array body to XML: XML requires a single root element. Wrap the array in an object with a root key.`);else o!=null&&(m=serializeBodyToXml(o));try{p=await e?.request({method:n,url:t,headers:r,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:m,requestConfig:l,httpsAgent:u,responseType:f})}catch(e){if(s(e?.response))throw e;p=e.response}if(typeof p.data==`string`&&/\S/.test(p.data)&&p.headers&&isXmlContentType(p.headers)&&(!f||!ve.includes(f))){let e=M.validate(p.data);if(e!==!0)throw Error(`Invalid XML response from ${t}: ${e.err.msg} at line ${e.err.line}`);p={...p,data:getXmlParser().parse(p.data)}}let h=translateCustomError(p,c,d);if(isFailedStatusCode(h?.status))throw new U(h,h.message);return h}},SoapClient=class{async performRequest({httpClient:e,url:t,method:n,headers:r,queryParams:i,encodeQueryParams:a,body:o,customErrorConfigs:c,requestConfig:l,credentials:u}){let d;if(d=typeof l?.envelope==`string`?l.envelope:typeof l?.envelope==`object`?Q.build(l.envelope):await buildEnvelope(o,l),M.validate(d,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);let f,p={"Content-Type":`application/xml`,...r};l?.soapAction&&(p.SOAPAction=l.soapAction);try{f=await e?.request({method:n,url:t,headers:p,queryParams:i,encodeQueryParams:a,maxRedirects:0,payload:d,requestConfig:l})}catch(e){if(s(e?.response))throw e;f=e.response}let m=be.parse(f.data),h=m.Envelope||m,g=h.Body||h,_=g.Fault;if(_)throw new U({...f,status:500,data:_,message:_.faultstring??_.faultcode??`SOAP Fault`},_.faultstring??`SOAP Fault occurred`);f.data=g;let v=translateCustomError(f,c,u);if(isFailedStatusCode(v?.status))throw new U(v,v.message);return v}};const Q=new A(Z),be=new j({ignoreAttributes:!1,attributeNamePrefix:`_`,removeNSPrefix:!0,numberParseOptions:{leadingZeros:!1,hex:!1}}),buildEnvelope=async(e,t)=>{if(d(t?.envelope)){let e=typeof t.envelope==`string`?t.envelope:Q.build(t.envelope);if(M.validate(e,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return e}let n=await buildSoapEnvelope(t,e),r=Q.build(n);if(M.validate(r,{allowBooleanAttributes:!0})!==!0)throw Error(`Invalid XML envelope`);return r},buildSoapEnvelope=async(e,t)=>{let n=await Promise.all((e?.namespaces||[]).map(async e=>({identifier:await h(e.namespaceIdentifier),namespace:await h(e.namespace)})));n.forEach(({identifier:e,namespace:t})=>{if(s(e)||s(t)||e===``||t===``)throw Error(`Invalid namespace config: both identifier and namespace are required`)});let r=n.reduce((e,{identifier:t,namespace:n})=>(e[`@_xmlns:${t}`]=n,e),{});return{"soapenv:Envelope":{"soapenv:Header":await buildSoapHeaders(t,e??{}),"soapenv:Body":await buildSoapBody(t,e?.soapOperation??``,n[0]?.identifier??``),"@_xmlns:soapenv":`http://schemas.xmlsoap.org/soap/envelope/`,...r}}},buildSoapHeaders=async(e,t)=>[await buildSoapSecurity(e,t)],buildSoapSecurity=async(e,t)=>{if(s(t.soapContext))return{};let{username:n,password:r}=t.soapContext;return{"wsse:Security":{"wsse:UsernameToken":{"wsse:Username":n,"wsse:Password":{"#text":r,"@_Type":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText`}},"@_soapenv:mustUnderstand":`1`,"@_xmlns:wsse":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd`,"@_xmlns:wsu":`http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd`}}},buildSoapBody=async(e,t,n)=>{if(s(t))throw Error(`Missing soapOperation in config`);let r=expandArrayAttributes({[t]:e});return(Array.isArray(r)?r:[r]).map(e=>applyNamespace(e,n))},expandArrayAttributes=e=>{if(typeof e!=`object`||!e)return e;if(Array.isArray(e)){if(e.length===1){let t=e[0];if(typeof t==`object`&&t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith(`@_`));if(e.length===1){let n=e[0],r=t[n];if(typeof r==`object`&&r&&!Array.isArray(r)){let e=Object.keys(r),t=e.filter(e=>e.startsWith(`@_`)),i=e.filter(e=>!e.startsWith(`@_`)),a=t.find(e=>Array.isArray(r[e]));if(a&&i.length===0){let e=r[a],i=t.filter(e=>e!==a),o=e.map(e=>{let t={[a]:e};for(let e of i)t[e]=r[e];return t});return{[n]:o}}}}}}return e.map(e=>expandArrayAttributes(e))}let t={};for(let n of Object.keys(e)){let r=e[n];t[n]=expandArrayAttributes(r)}return t},applyNamespace=(e,t)=>{if(typeof e!=`object`)return e;if(Array.isArray(e))return e.map(e=>applyNamespace(e,t));let n={};for(let r in e){let i=applyNamespaceToKey(r,t);n[i]=applyNamespace(e[r],t)}return n},applyNamespaceToKey=(e,t)=>{let n=e.split(`:`);return n.length>1&&n[0]||e.indexOf(`${t}:`)===0||e===`#text`?e:e.startsWith(`@_`)?`@_${t}:${e.slice(2)}`:`${t}:${e}`};var RequestClientFactory=class{static build(e=`rest`){if(e===`rest`)return new RestClient;if(e===`soap`)return new SoapClient;throw Error(`Unknown request client type: ${e}`)}};const arrayFormatToPairs=(e,t,n)=>n===`brackets`?t.map(t=>[`${e}[]`,t]):n===`comma`?[[e,t.join(`,`)]]:n===`stringify`?[[e,JSON.stringify(t)]]:t.map(t=>[e,t]),toStringArray=e=>Array.isArray(e)?e:[e],isHttpQueryParamValue=e=>typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value)),flattenQueryParams=e=>{if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))r!=null&&(isHttpQueryParamValue(r)?t.push(...arrayFormatToPairs(n,toStringArray(r.value),r.arrayFormat)):t.push(...arrayFormatToPairs(n,toStringArray(r),void 0)));return t},hmac=(e,t)=>x(`sha256`,e).update(t).digest(),hash=e=>b(`sha256`).update(e).digest(`hex`),getSigningKey=(e,t,n,r)=>hmac(hmac(hmac(hmac(`AWS4${e}`,t),n),r),`aws4_request`),$=e(e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),`rfc3986Encode`),xe=e((e,t)=>e<t?-1:+(e>t),`byteCompare`),aws4SigningStrategy=(e,t,n)=>{if(n.strategy!==`aws4`)throw Error(`aws4SigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let{accessKeyId:r,secretAccessKey:i,sessionToken:a,region:o}=t;if(!r||!i)throw Error(`AWS SigV4 requires accessKeyId and secretAccessKey`);let{service:s,region:c}=n,l=c??o??`us-east-1`,u=new Date().toISOString().replace(/[:-]|\.\d{3}/g,``),d=u.slice(0,8),f=new URL(e.url),p=f.pathname.split(`/`).map(e=>{try{return $(decodeURIComponent(e))}catch{return $(e)}}).join(`/`)||`/`,m=[];for(let[e,t]of f.searchParams.entries())m.push([e,t]);m.push(...flattenQueryParams(e.query)),m.sort(([e,t],[n,r])=>{let i=xe(e,n);return i===0?xe(t,r):i});let h=m.map(([e,t])=>`${$(e)}=${$(t)}`).join(`&`),g=serializeRequestBodyForSigning(e.body,e.headers??{}),_=b(`sha256`).update(g).digest(),v=_.toString(`hex`),y={host:f.host,"x-amz-content-sha256":v,"x-amz-date":u};a&&(y[`x-amz-security-token`]=a);for(let[t,n]of Object.entries(e.headers??{})){let e=t.toLowerCase();e!==`authorization`&&e!==`x-amz-date`&&e!==`x-amz-content-sha256`&&e!==`x-amz-security-token`&&(y[e]=n)}let S=Object.keys(y).some(e=>e===`content-md5`||e.startsWith(`x-amz-checksum-`)),C=g.length>0&&!S,w;C&&(w=_.toString(`base64`),y[`x-amz-checksum-sha256`]=w);let T=Object.keys(y).sort(),canonicalHeaderValue=e=>e.trim().replace(/\s+/g,` `),E=T.map(e=>`${e}:${canonicalHeaderValue(y[e])}\n`).join(``),D=T.join(`;`),O=[e.method.toUpperCase(),p,h,E,D,v].join(`
|
|
172
172
|
`),k=`${d}/${l}/${s}/aws4_request`,A=[`AWS4-HMAC-SHA256`,u,k,hash(O)].join(`
|
|
173
|
-
`),j={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${k}, SignedHeaders=${D}, Signature=${x(`sha256`,getSigningKey(i,d,l,s)).update(A).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":v};return a&&(j[`x-amz-security-token`]=a),w!==void 0&&(j[`x-amz-checksum-sha256`]=w),j},
|
|
174
|
-
`),_=x(c,r).update(g).digest(`hex`);return{[l]:`${u} ${_}`,"X-Timestamp":d}},
|
|
175
|
-
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${v}`).toString(`base64`)}`,Date:m}:{[i??`X-Signature`]:`${a??`hmac-${d}`} ${v}`,"X-Timestamp":m}}const
|
|
173
|
+
`),j={Authorization:`AWS4-HMAC-SHA256 Credential=${r}/${k}, SignedHeaders=${D}, Signature=${x(`sha256`,getSigningKey(i,d,l,s)).update(A).digest(`hex`)}`,"x-amz-date":u,"x-amz-content-sha256":v};return a&&(j[`x-amz-security-token`]=a),w!==void 0&&(j[`x-amz-checksum-sha256`]=w),j},Se=[`sha256`,`sha512`],isValidAlgorithm=e=>Se.includes(e),hashPayload=e=>b(`sha256`).update(e).digest(`hex`),byteCompare=(e,t)=>e<t?-1:+(e>t),rfc3986Encode=e=>encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),hmacSigningStrategy=(e,t,n)=>{if(n.strategy!==`hmac`)throw Error(`hmacSigningStrategy invoked with strategy "${n.strategy}" — registry misconfiguration`);let r=t.secretKey;if(!r)throw Error(`HMAC signing requires secretKey in credentials`);let i=n;if(requiresExtendedSigning(i))return signWithExtendedOptions(e,r,i);let{algorithm:a,headerName:o,prefix:s}=i;if(a!==void 0&&!isValidAlgorithm(a))throw Error(`Unsupported HMAC algorithm "${a}". Use "sha256" or "sha512".`);let c=a??`sha256`,l=o??`X-Signature`,u=s??`hmac-${c}`,d=new Date().toISOString(),f=new URL(e.url),p=[];for(let[e,t]of f.searchParams.entries())p.push([e,t]);p.push(...flattenQueryParams(e.query)),p.sort(([e,t],[n,r])=>{let i=byteCompare(e,n);return i===0?byteCompare(t,r):i});let m=p.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),h=hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})),g=[d,e.method.toUpperCase(),f.pathname,m,h].join(`
|
|
174
|
+
`),_=x(c,r).update(g).digest(`hex`);return{[l]:`${u} ${_}`,"X-Timestamp":d}},Ce=[`sha1`,`sha256`,`sha512`],formatRfc2822Date=e=>e.toUTCString().replace(`GMT`,`-0000`),extractBodyParams=e=>{let t=[];for(let[n,r]of Object.entries(e)){if(r==null)continue;let e=Array.isArray(r)?r:[r];for(let r of e)t.push([n,String(r)])}return t};function requiresExtendedSigning(e){let{algorithm:t,dateFormat:n,includeHost:r,includeBodyHash:i,outputFormat:a,username:o}=e;return!!(n===`rfc2822`||r===!0||i===!1||a===`basic`||o||t===`sha1`)}function signWithExtendedOptions(e,t,n){let{algorithm:r,headerName:i,prefix:a,dateFormat:o=`iso8601`,includeHost:s=!1,includeBodyHash:c=!0,outputFormat:l=`header`,username:u}=n;if(r&&!Ce.includes(r))throw Error(`Unsupported HMAC algorithm "${r}". Use "sha1", "sha256", or "sha512".`);if(l===`basic`&&!u)throw Error(`HMAC signing with outputFormat "basic" requires username`);if(u&&/[:\r\n]/.test(u))throw Error(`HMAC signing username cannot contain ":", "\\r", or "\\n"`);let d=r??`sha256`,f=new URL(e.url),p=new Date,m=o===`rfc2822`?formatRfc2822Date(p):p.toISOString(),h=[...f.searchParams.entries(),...flattenQueryParams(e.query)];!c&&e.body&&typeof e.body==`object`&&!Array.isArray(e.body)&&(e.headers?.[`content-type`]??e.headers?.[`Content-Type`]??``).toLowerCase().includes(`application/x-www-form-urlencoded`)&&h.push(...extractBodyParams(e.body)),h.sort(([e,t],[n,r])=>byteCompare(e,n)||byteCompare(t,r));let g=h.map(([e,t])=>`${rfc3986Encode(e)}=${rfc3986Encode(t)}`).join(`&`),_=[m,e.method.toUpperCase()];s&&_.push(f.hostname.toLowerCase()),_.push(f.pathname,g),c&&_.push(hashPayload(serializeRequestBodyForSigning(e.body,e.headers??{})));let v=x(d,t).update(_.join(`
|
|
175
|
+
`)).digest(`hex`);return l===`basic`?{Authorization:`Basic ${Buffer.from(`${u}:${v}`).toString(`base64`)}`,Date:m}:{[i??`X-Signature`]:`${a??`hmac-${d}`} ${v}`,"X-Timestamp":m}}const we={},registerSigningStrategy=(e,t)=>{we[e]=t},getSigningStrategy=e=>we[e];registerSigningStrategy(`aws4`,aws4SigningStrategy),registerSigningStrategy(`hmac`,hmacSigningStrategy);export{ie as CUSTOM_ERROR_CONFIG_SCHEMA,ConcurrencyManager,EventClient,HttpClient,HttpClientManager,H as HttpErrorMessages,de as HttpMethods,U as HttpResponseError,HttpTransportFactory,W as InstanceManager,LockManager,MemoryStore,ge as QueryArrayFormats,QueueManager,RateLimitManager,P as RedisClient,RequestClientFactory,he as RequestParameterLocations,ScriptManager,SubscriptionManager,buildHttpClientInstance,buildHttpsAgent,convertError,createAuthorizationHeaders,getRetryAfterWaitTime,getSigningStrategy,getTransportInstance,getTransportManagers,initializeTransportSystem,isFailedStatusCode,isInfoStatusCode,isSuccessStatusCode,isTransportSystemReady,parseRequestParameters,registerSigningStrategy,serializeHttpResponseError,shutdownTransportSystem,superNormalizeHeaders,translateCustomError};
|