@stackone/transport 2.13.1 → 2.14.0

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 CHANGED
@@ -110,7 +110,7 @@ Example:
110
110
  * Copyright (c) 2023, Robert Eisele (robert@raw.org)
111
111
  * Dual licensed under the MIT or GPL Version 2 licenses.
112
112
  **/
113
- (function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function assign(e,t){if(isNaN(e=parseInt(e,10)))throw InvalidParameter();return e*t}function newFraction(e,t){if(t===0)throw DivisionByZero();var n=Object.create(Fraction$2.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=gcd(e,t);return n.n=e/r,n.d=t/r,n}function factorize(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var a=__name(function(e,t){var n=0,r=1,a=1,o=0,s=0,c=0,l=1,u=1,d=0,f=1,p=1,m=1,h=1e7,g;if(e!=null)if(t!==void 0){if(n=e,r=t,a=n*r,n%1!=0||r%1!=0)throw NonIntegerParameter()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw InvalidParameter();a=n*r;break;case`number`:if(e<0&&(a=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(u=10**Math.floor(1+Math.log(e)/Math.LN10),e/=u);f<=h&&m<=h;)if(g=(d+p)/(f+m),e===g){f+m<=h?(n=d+p,r=f+m):m>f?(n=p,r=m):(n=d,r=f);break}else e>g?(d+=p,f+=m):(p+=d,m+=f),f>h?(n=p,r=m):(n=d,r=f);n*=u}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(f=e.match(/\d+|./g),f===null)throw InvalidParameter();if(f[d]===`-`?(a=-1,d++):f[d]===`+`&&d++,f.length===d+1?s=assign(f[d++],a):f[d+1]===`.`||f[d]===`.`?(f[d]!==`.`&&(o=assign(f[d++],a)),d++,(d+1===f.length||f[d+1]===`(`&&f[d+3]===`)`||f[d+1]===`'`&&f[d+3]===`'`)&&(s=assign(f[d],a),l=10**f[d].length,d++),(f[d]===`(`&&f[d+2]===`)`||f[d]===`'`&&f[d+2]===`'`)&&(c=assign(f[d+1],a),u=10**f[d+1].length-1,d+=3)):f[d+1]===`/`||f[d+1]===`:`?(s=assign(f[d],a),l=assign(f[d+2],1),d+=3):f[d+3]===`/`&&f[d+1]===` `&&(o=assign(f[d],a),s=assign(f[d+2],a),l=assign(f[d+4],1),d+=5),f.length<=d){r=l*u,a=n=c+r*o+u*s;break}default:throw InvalidParameter()}if(r===0)throw DivisionByZero();i.s=a<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)},`parse`);function modpow(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function cycleLen(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function cycleStart(e,t,n){for(var r=1,i=modpow(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function gcd(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function Fraction$2(e,t){if(a(e,t),this instanceof Fraction$2)e=gcd(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return newFraction(i.s*i.n,i.d)}__name(Fraction$2,`Fraction`);var DivisionByZero=function(){return Error(`Division by Zero`)},InvalidParameter=function(){return Error(`Invalid argument`)},NonIntegerParameter=function(){return Error(`Parameters must be integer`)};Fraction$2.prototype={s:1,n:0,d:1,abs:function(){return newFraction(this.n,this.d)},neg:function(){return newFraction(-this.s*this.n,this.d)},add:function(e,t){return a(e,t),newFraction(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return a(e,t),newFraction(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return a(e,t),newFraction(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return a(e,t),newFraction(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return newFraction(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new Fraction$2(NaN);if(e===void 0)return newFraction(this.s*this.n%this.d,1);if(a(e,t),i.n===0&&this.d===0)throw DivisionByZero();return newFraction(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return a(e,t),newFraction(gcd(i.n,this.n)*gcd(i.d,this.d),i.d*this.d)},lcm:function(e,t){return a(e,t),i.n===0&&this.n===0?newFraction(0,1):newFraction(i.n*this.n,gcd(i.n,this.n)*gcd(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return newFraction(this.s*this.d,this.n)},pow:function(e,t){if(a(e,t),i.d===1)return i.s<0?newFraction((this.s*this.d)**+i.n,this.n**+i.n):newFraction((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=factorize(this.n),r=factorize(this.d),o=1,s=1;for(var c in n)if(c!==`1`){if(c===`0`){o=0;break}if(n[c]*=i.n,n[c]%i.d===0)n[c]/=i.d;else return null;o*=c**+n[c]}for(var c in r)if(c!==`1`){if(r[c]*=i.n,r[c]%i.d===0)r[c]/=i.d;else return null;s*=c**+r[c]}return i.s<0?newFraction(s,o):newFraction(o,s)},equals:function(e,t){return a(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){a(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=newFraction(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return a(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=cycleLen(t,n),i=cycleStart(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof e==`object`?(Object.defineProperty(Fraction$2,`__esModule`,{value:!0}),Fraction$2.default=Fraction$2,Fraction$2.Fraction=Fraction$2,t.exports=Fraction$2):n.Fraction=Fraction$2})(e)})),$=__toESM(Et(),1),Dt=`Fraction`,Ot=[],kt=factory(Dt,Ot,()=>(Object.defineProperty($.default,`name`,{value:`Fraction`}),$.default.prototype.constructor=$.default,$.default.prototype.type=`Fraction`,$.default.prototype.isFraction=!0,$.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},$.default.fromJSON=function(e){return new $.default(e)},$.default),{isClass:!0}),At=`Matrix`,jt=[],Mt=factory(At,jt,()=>{function Matrix$1(){if(!(this instanceof Matrix$1))throw SyntaxError(`Constructor must be called with the new operator`)}return __name(Matrix$1,`Matrix`),Matrix$1.prototype.type=`Matrix`,Matrix$1.prototype.isMatrix=!0,Matrix$1.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},Matrix$1.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},Matrix$1.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},Matrix$1.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},Matrix$1.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},Matrix$1.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},Matrix$1.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},Matrix$1.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},Matrix$1.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},Matrix$1.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},Matrix$1.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},Matrix$1.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},Matrix$1.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},Matrix$1.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},Matrix$1.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},Matrix$1.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},Matrix$1.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},Matrix$1},{isClass:!0});function maxArgumentCount(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Nt=`DenseMatrix`,Pt=[`Matrix`],Ft=factory(Nt,Pt,e=>{var{Matrix:t}=e;function DenseMatrix$1(e,t){if(!(this instanceof DenseMatrix$1))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!isString$1(t))throw Error(`Invalid datatype: `+t);if(isMatrix(e))e.type===`DenseMatrix`?(this._data=clone$2(e._data),this._size=clone$2(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&L(e.data)&&L(e.size))this._data=e.data,this._size=e.size,validate$1(this._data,this._size),this._datatype=t||e.datatype;else if(L(e))this._data=preprocess(e),this._size=arraySize(this._data),validate$1(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+typeOf(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}__name(DenseMatrix$1,`DenseMatrix`),DenseMatrix$1.prototype=new t,DenseMatrix$1.prototype.createDenseMatrix=function(e,t){return new DenseMatrix$1(e,t)},Object.defineProperty(DenseMatrix$1,`name`,{value:`DenseMatrix`}),DenseMatrix$1.prototype.constructor=DenseMatrix$1,DenseMatrix$1.prototype.type=`DenseMatrix`,DenseMatrix$1.prototype.isDenseMatrix=!0,DenseMatrix$1.prototype.getDataType=function(){return getArrayDataType(this._data,typeOf)},DenseMatrix$1.prototype.storage=function(){return`dense`},DenseMatrix$1.prototype.datatype=function(){return this._datatype},DenseMatrix$1.prototype.create=function(e,t){return new DenseMatrix$1(e,t)},DenseMatrix$1.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return _get(this,e);case 2:case 3:return _set(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},DenseMatrix$1.prototype.get=function(e){if(!L(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;t<e.length;t++)validateIndex(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];validateIndex(a,n.length),n=n[a]}return n},DenseMatrix$1.prototype.set=function(e,t,n){if(!L(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new DimensionError(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});_fit(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],validateIndex(a,s.length),s=s[a];return a=e[e.length-1],validateIndex(a,s.length),s[a]=t,this};function _get(e,t){if(!isIndex(t))throw TypeError(`Invalid index`);if(t.isScalar())return e.get(t.min());var n=t.size();if(n.length!==e._size.length)throw new DimensionError(n.length,e._size.length);for(var r=t.min(),i=t.max(),a=0,o=e._size.length;a<o;a++)validateIndex(r[a],e._size[a]),validateIndex(i[a],e._size[a]);return new DenseMatrix$1(_getSubmatrix(e._data,t,n.length,0),e._datatype)}function _getSubmatrix(e,t,n,r){var i=r===n-1,a=t.dimension(r);return i?a.map(function(t){return validateIndex(t,e.length),e[t]}).valueOf():a.map(function(i){validateIndex(i,e.length);var a=e[i];return _getSubmatrix(a,t,n,r+1)}).valueOf()}function _set(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(isMatrix(n)?(o=n.size(),n=n.valueOf()):o=arraySize(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!deepStrictEqual(o,i))try{n=o.length===0?broadcastTo([n],i):broadcastTo(n,i),o=arraySize(n)}catch{}if(i.length<e._size.length)throw new DimensionError(i.length,e._size.length,`<`);if(o.length<i.length){for(var s=0,c=0;i[s]===1&&o[s]===1;)s++;for(;i[s]===1;)c++,s++;n=unsqueeze(n,i.length,c,o)}if(!deepStrictEqual(i,o))throw new DimensionError(i,o,`>`);_fit(e,t.max().map(function(e){return e+1}),r);var l=i.length;_setSubmatrix(e._data,t,n,l,0)}return e}function _setSubmatrix(e,t,n,r,i){var a=i===r-1,o=t.dimension(i);a?o.forEach(function(t,r){validateIndex(t),e[t]=n[r[0]]}):o.forEach(function(a,o){validateIndex(a),_setSubmatrix(e[a],t,n[o[0]],r,i+1)})}DenseMatrix$1.prototype.resize=function(e,t,n){if(!isCollection(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);return _resize$1(n?this.clone():this,r,t)};function _resize$1(e,t,n){if(t.length===0){for(var r=e._data;L(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize(e._data,e._size,n),e}__name(_resize$1,`_resize`),DenseMatrix$1.prototype.reshape=function(e,t){var n=t?this.clone():this;return n._data=reshape(n._data,e),n._size=processSizesWildcard(e,n._size.reduce((e,t)=>e*t)),n};function _fit(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&_resize$1(e,r,n)}DenseMatrix$1.prototype.clone=function(){return new DenseMatrix$1({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},DenseMatrix$1.prototype.size=function(){return this._size.slice(0)},DenseMatrix$1.prototype.map=function(e){var t=this,n=maxArgumentCount(e),r=function recurse(r,i){return L(r)?r.map(function(e,t){return recurse(e,i.concat(t))}):n===1?e(r):n===2?e(r,i):e(r,i,t)}(this._data,[]);return new DenseMatrix$1(r,this._datatype===void 0?void 0:getArrayDataType(r,typeOf))},DenseMatrix$1.prototype.forEach=function(e){var t=this;(function recurse(n,r){L(n)?n.forEach(function(e,t){recurse(e,r.concat(t))}):e(n,r,t)})(this._data,[])},DenseMatrix$1.prototype[Symbol.iterator]=function*(){yield*function*recurse(e,t){if(L(e))for(var n=0;n<e.length;n++)yield*recurse(e[n],t.concat(n));else yield{value:e,index:t}}(this._data,[])},DenseMatrix$1.prototype.rows=function(){var e=[];if(this.size().length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var t of this._data)e.push(new DenseMatrix$1([t],this._datatype));return e},DenseMatrix$1.prototype.columns=function(){var e=this,t=[],n=this.size();if(n.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var r=this._data,i=function _loop$1(n){var i=r.map(e=>[e[n]]);t.push(new DenseMatrix$1(i,e._datatype))},a=0;a<n[1];a++)i(a);return t},DenseMatrix$1.prototype.toArray=function(){return clone$2(this._data)},DenseMatrix$1.prototype.valueOf=function(){return this._data},DenseMatrix$1.prototype.format=function(e){return format(this._data,e)},DenseMatrix$1.prototype.toString=function(){return format(this._data)},DenseMatrix$1.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},DenseMatrix$1.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],a=Math.min(r-n,i-t),o=[],s=0;s<a;s++)o[s]=this._data[s+n][s+t];return new DenseMatrix$1({data:o,size:[a],datatype:this._datatype})},DenseMatrix$1.diagonal=function(e,t,n,r){if(!L(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e)||e<1)throw Error(`Size values must be positive integers`);return e}),n){if(isBigNumber(n)&&(n=n.toNumber()),!isNumber$1(n)||!isInteger(n))throw TypeError(`The parameter k must be an integer number`)}else n=0;var i=n>0?n:0,a=n<0?-n:0,o=e[0],s=e[1],c=Math.min(o-a,s-i),l;if(L(t)){if(t.length!==c)throw Error(`Invalid value array length`);l=function _value$1(e){return t[e]}}else if(isMatrix(t)){var u=t.size();if(u.length!==1||u[0]!==c)throw Error(`Invalid matrix length`);l=function _value$1(e){return t.get([e])}}else l=function _value$1(){return t};r||=isBigNumber(l(0))?l(0).mul(0):0;var d=[];if(e.length>0){d=resize(d,e,r);for(var f=0;f<c;f++)d[f+a][f+i]=l(f)}return new DenseMatrix$1({data:d,size:[o,s]})},DenseMatrix$1.fromJSON=function(e){return new DenseMatrix$1(e)},DenseMatrix$1.prototype.swapRows=function(e,t){if(!isNumber$1(e)||!isInteger(e)||!isNumber$1(t)||!isInteger(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return validateIndex(e,this._size[0]),validateIndex(t,this._size[0]),DenseMatrix$1._swapRows(e,t,this._data),this},DenseMatrix$1._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function preprocess(e){return isMatrix(e)?preprocess(e.valueOf()):L(e)?e.map(preprocess):e}return DenseMatrix$1},{isClass:!0});function deepMap(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return deepMap(e,t,n)}):t(e)}var It=`isNumeric`,Lt=[`typed`],Rt=factory(It,Lt,e=>{var{typed:t}=e;return t(It,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>deepMap(t,e))})}),zt=`hasNumericValue`,Bt=[`typed`,`isNumeric`],Vt=factory(zt,Bt,e=>{var{typed:t,isNumeric:n}=e;return t(zt,{boolean:()=>!0,string:function string(e){return e.trim().length>0&&!isNaN(Number(e))},any:function any(e){return n(e)}})}),Ht=xt({config:qe}),Ut=Tt({}),Wt=kt({}),Gt=Mt({}),Kt=Ft({Matrix:Gt}),qt=nt({BigNumber:Ht,Complex:Ut,DenseMatrix:Kt,Fraction:Wt}),Jt=Rt({typed:qt}),Yt=Vt({isNumeric:Jt,typed:qt});const 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*I},Xt=`ratelimitlimit`,Zt=`ratelimitremaining`,Qt=`ratelimitreset`,$t=`ratelimitconcurrencylimit`,en=`ratelimitconcurrencyremaining`,tn=`ratelimitconcurrencyreset`,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]=Yt(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):isString$1(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<n)return e;let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0&&e<n?e:r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Be.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/I);return e>0&&e<n?e:r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>__name(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*I:(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)},`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`,m=testMessage((0,o.isObject)(c)?(0,p.JSONPath)({path:f,json:c})[0]:c,r);if(t===a&&m){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,p.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)/I;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`)},nn=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>__name(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:nn,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:F.InterceptorContextNotPresent}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:nn,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p}=c?.requestMetadata??{};if(!((0,o.notMissing)(u)&&(0,o.notMissing)(d)&&await i.releaseRequest(u,d))&&(0,o.notMissing)(c?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:nn,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:F.RateLimiterReleaseRequestFailed}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:m,retryAfter:h}=convertError(s,r,n,t);if(m===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(h);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:h,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=h?n*I:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:h,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)},`rateLimitErrorInterceptor`),rn=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>__name(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:rn,...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:rn,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:F.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:rn,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u}=i?.requestMetadata??{};if(await n.releaseRequest(s,c)||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:rn,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:F.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r},`rateLimitResponseInterceptor`),validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),an=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],on=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],sn=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],cn=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],un=1,dn=1e3,fn=0,pn=59,mn=.8,hn=500;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(Pe.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}};let gn=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,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(...sn),m.push(...cn)}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 je.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 je.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:gn.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:an,responseConfigs:on},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/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:h}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let m=this.#_(t,r),g=this.#l(e),_=this.#m(u,e),v=await this.#s({url:m,payload:_,method:n,cacheTTL:s,context:c});if(v)return{...v,responseTime:new Date};let y=P.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:h})).request({headers:g,url:m,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),requestUrl:t,responseType:x?.config?.responseType,responseTime:new Date};return await this.#c({url:m,payload:_,method:n,cacheTTL:s,context:c,response:S}),S}catch(e){let r=e;r.url=(0,m.redactUrl)(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#h(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.#_(t,r),m=this.#l(e),h=this.#m(c,e),g=P.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,m.redactUrl)(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#h(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,t){if(!((0,o.isMissing)(e)||(0,o.isObject)(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)?e:this.#d(t)?h.default.stringify(e):e}#h(e){if((0,l.isAxiosError)(e)&&this.#i)return this.#i(e)}#g(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#_(e,t){if((0,o.isMissing)(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={};for(let[e,o]of Object.entries(t))if(this.#g(o)){let t=o.arrayFormat,s=o.value;t===`repeat`?r[e]=Array.isArray(s)?s:[s]:t===`brackets`?i[e]=Array.isArray(s)?s:[s]:t===`comma`?a[e]=Array.isArray(s)?s:[s]:n[e]=s}else n[e]=o;let s=[];Object.keys(n).length>0&&s.push(h.default.stringify(n)),Object.keys(r).length>0&&s.push(h.default.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&s.push(h.default.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&s.push(h.default.stringify(a,{arrayFormat:`comma`}));let c=s.join(`&`);return(0,o.notMissing)(c)?`${e}?${c}`: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 _n=[`get`,`post`,`put`,`delete`,`patch`],vn={[k.rPush]:`
113
+ (function(n){"use strict";var r=2e3,i={s:1,n:0,d:1};function assign(e,t){if(isNaN(e=parseInt(e,10)))throw InvalidParameter();return e*t}function newFraction(e,t){if(t===0)throw DivisionByZero();var n=Object.create(Fraction$2.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=gcd(e,t);return n.n=e/r,n.d=t/r,n}function factorize(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var a=__name(function(e,t){var n=0,r=1,a=1,o=0,s=0,c=0,l=1,u=1,d=0,f=1,p=1,m=1,h=1e7,g;if(e!=null)if(t!==void 0){if(n=e,r=t,a=n*r,n%1!=0||r%1!=0)throw NonIntegerParameter()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw InvalidParameter();a=n*r;break;case`number`:if(e<0&&(a=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(u=10**Math.floor(1+Math.log(e)/Math.LN10),e/=u);f<=h&&m<=h;)if(g=(d+p)/(f+m),e===g){f+m<=h?(n=d+p,r=f+m):m>f?(n=p,r=m):(n=d,r=f);break}else e>g?(d+=p,f+=m):(p+=d,m+=f),f>h?(n=p,r=m):(n=d,r=f);n*=u}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(f=e.match(/\d+|./g),f===null)throw InvalidParameter();if(f[d]===`-`?(a=-1,d++):f[d]===`+`&&d++,f.length===d+1?s=assign(f[d++],a):f[d+1]===`.`||f[d]===`.`?(f[d]!==`.`&&(o=assign(f[d++],a)),d++,(d+1===f.length||f[d+1]===`(`&&f[d+3]===`)`||f[d+1]===`'`&&f[d+3]===`'`)&&(s=assign(f[d],a),l=10**f[d].length,d++),(f[d]===`(`&&f[d+2]===`)`||f[d]===`'`&&f[d+2]===`'`)&&(c=assign(f[d+1],a),u=10**f[d+1].length-1,d+=3)):f[d+1]===`/`||f[d+1]===`:`?(s=assign(f[d],a),l=assign(f[d+2],1),d+=3):f[d+3]===`/`&&f[d+1]===` `&&(o=assign(f[d],a),s=assign(f[d+2],a),l=assign(f[d+4],1),d+=5),f.length<=d){r=l*u,a=n=c+r*o+u*s;break}default:throw InvalidParameter()}if(r===0)throw DivisionByZero();i.s=a<0?-1:1,i.n=Math.abs(n),i.d=Math.abs(r)},`parse`);function modpow(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function cycleLen(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,i=1;n!==1;i++)if(n=n*10%t,i>r)return 0;return i}function cycleStart(e,t,n){for(var r=1,i=modpow(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function gcd(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function Fraction$2(e,t){if(a(e,t),this instanceof Fraction$2)e=gcd(i.d,i.n),this.s=i.s,this.n=i.n/e,this.d=i.d/e;else return newFraction(i.s*i.n,i.d)}__name(Fraction$2,`Fraction`);var DivisionByZero=function(){return Error(`Division by Zero`)},InvalidParameter=function(){return Error(`Invalid argument`)},NonIntegerParameter=function(){return Error(`Parameters must be integer`)};Fraction$2.prototype={s:1,n:0,d:1,abs:function(){return newFraction(this.n,this.d)},neg:function(){return newFraction(-this.s*this.n,this.d)},add:function(e,t){return a(e,t),newFraction(this.s*this.n*i.d+i.s*this.d*i.n,this.d*i.d)},sub:function(e,t){return a(e,t),newFraction(this.s*this.n*i.d-i.s*this.d*i.n,this.d*i.d)},mul:function(e,t){return a(e,t),newFraction(this.s*i.s*this.n*i.n,this.d*i.d)},div:function(e,t){return a(e,t),newFraction(this.s*i.s*this.n*i.d,this.d*i.n)},clone:function(){return newFraction(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new Fraction$2(NaN);if(e===void 0)return newFraction(this.s*this.n%this.d,1);if(a(e,t),i.n===0&&this.d===0)throw DivisionByZero();return newFraction(this.s*(i.d*this.n)%(i.n*this.d),i.d*this.d)},gcd:function(e,t){return a(e,t),newFraction(gcd(i.n,this.n)*gcd(i.d,this.d),i.d*this.d)},lcm:function(e,t){return a(e,t),i.n===0&&this.n===0?newFraction(0,1):newFraction(i.n*this.n,gcd(i.n,this.n)*gcd(i.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return newFraction(this.s*this.d,this.n)},pow:function(e,t){if(a(e,t),i.d===1)return i.s<0?newFraction((this.s*this.d)**+i.n,this.n**+i.n):newFraction((this.s*this.n)**+i.n,this.d**+i.n);if(this.s<0)return null;var n=factorize(this.n),r=factorize(this.d),o=1,s=1;for(var c in n)if(c!==`1`){if(c===`0`){o=0;break}if(n[c]*=i.n,n[c]%i.d===0)n[c]/=i.d;else return null;o*=c**+n[c]}for(var c in r)if(c!==`1`){if(r[c]*=i.n,r[c]%i.d===0)r[c]/=i.d;else return null;s*=c**+r[c]}return i.s<0?newFraction(s,o):newFraction(o,s)},equals:function(e,t){return a(e,t),this.s*this.n*i.d===i.s*i.n*this.d},compare:function(e,t){a(e,t);var n=this.s*this.n*i.d-i.s*i.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=newFraction(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return a(e,t),!(!(i.n*this.d)||this.n*i.d%(i.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=cycleLen(t,n),i=cycleStart(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof e==`object`?(Object.defineProperty(Fraction$2,`__esModule`,{value:!0}),Fraction$2.default=Fraction$2,Fraction$2.Fraction=Fraction$2,t.exports=Fraction$2):n.Fraction=Fraction$2})(e)})),$=__toESM(Et(),1),Dt=`Fraction`,Ot=[],kt=factory(Dt,Ot,()=>(Object.defineProperty($.default,`name`,{value:`Fraction`}),$.default.prototype.constructor=$.default,$.default.prototype.type=`Fraction`,$.default.prototype.isFraction=!0,$.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},$.default.fromJSON=function(e){return new $.default(e)},$.default),{isClass:!0}),At=`Matrix`,jt=[],Mt=factory(At,jt,()=>{function Matrix$1(){if(!(this instanceof Matrix$1))throw SyntaxError(`Constructor must be called with the new operator`)}return __name(Matrix$1,`Matrix`),Matrix$1.prototype.type=`Matrix`,Matrix$1.prototype.isMatrix=!0,Matrix$1.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},Matrix$1.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},Matrix$1.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},Matrix$1.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},Matrix$1.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},Matrix$1.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},Matrix$1.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},Matrix$1.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},Matrix$1.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},Matrix$1.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},Matrix$1.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},Matrix$1.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},Matrix$1.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},Matrix$1.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},Matrix$1.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},Matrix$1.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},Matrix$1.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},Matrix$1},{isClass:!0});function maxArgumentCount(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var Nt=`DenseMatrix`,Pt=[`Matrix`],Ft=factory(Nt,Pt,e=>{var{Matrix:t}=e;function DenseMatrix$1(e,t){if(!(this instanceof DenseMatrix$1))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!isString$1(t))throw Error(`Invalid datatype: `+t);if(isMatrix(e))e.type===`DenseMatrix`?(this._data=clone$2(e._data),this._size=clone$2(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&L(e.data)&&L(e.size))this._data=e.data,this._size=e.size,validate$1(this._data,this._size),this._datatype=t||e.datatype;else if(L(e))this._data=preprocess(e),this._size=arraySize(this._data),validate$1(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+typeOf(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}__name(DenseMatrix$1,`DenseMatrix`),DenseMatrix$1.prototype=new t,DenseMatrix$1.prototype.createDenseMatrix=function(e,t){return new DenseMatrix$1(e,t)},Object.defineProperty(DenseMatrix$1,`name`,{value:`DenseMatrix`}),DenseMatrix$1.prototype.constructor=DenseMatrix$1,DenseMatrix$1.prototype.type=`DenseMatrix`,DenseMatrix$1.prototype.isDenseMatrix=!0,DenseMatrix$1.prototype.getDataType=function(){return getArrayDataType(this._data,typeOf)},DenseMatrix$1.prototype.storage=function(){return`dense`},DenseMatrix$1.prototype.datatype=function(){return this._datatype},DenseMatrix$1.prototype.create=function(e,t){return new DenseMatrix$1(e,t)},DenseMatrix$1.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return _get(this,e);case 2:case 3:return _set(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},DenseMatrix$1.prototype.get=function(e){if(!L(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;t<e.length;t++)validateIndex(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];validateIndex(a,n.length),n=n[a]}return n},DenseMatrix$1.prototype.set=function(e,t,n){if(!L(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new DimensionError(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});_fit(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],validateIndex(a,s.length),s=s[a];return a=e[e.length-1],validateIndex(a,s.length),s[a]=t,this};function _get(e,t){if(!isIndex(t))throw TypeError(`Invalid index`);if(t.isScalar())return e.get(t.min());var n=t.size();if(n.length!==e._size.length)throw new DimensionError(n.length,e._size.length);for(var r=t.min(),i=t.max(),a=0,o=e._size.length;a<o;a++)validateIndex(r[a],e._size[a]),validateIndex(i[a],e._size[a]);return new DenseMatrix$1(_getSubmatrix(e._data,t,n.length,0),e._datatype)}function _getSubmatrix(e,t,n,r){var i=r===n-1,a=t.dimension(r);return i?a.map(function(t){return validateIndex(t,e.length),e[t]}).valueOf():a.map(function(i){validateIndex(i,e.length);var a=e[i];return _getSubmatrix(a,t,n,r+1)}).valueOf()}function _set(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(isMatrix(n)?(o=n.size(),n=n.valueOf()):o=arraySize(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!deepStrictEqual(o,i))try{n=o.length===0?broadcastTo([n],i):broadcastTo(n,i),o=arraySize(n)}catch{}if(i.length<e._size.length)throw new DimensionError(i.length,e._size.length,`<`);if(o.length<i.length){for(var s=0,c=0;i[s]===1&&o[s]===1;)s++;for(;i[s]===1;)c++,s++;n=unsqueeze(n,i.length,c,o)}if(!deepStrictEqual(i,o))throw new DimensionError(i,o,`>`);_fit(e,t.max().map(function(e){return e+1}),r);var l=i.length;_setSubmatrix(e._data,t,n,l,0)}return e}function _setSubmatrix(e,t,n,r,i){var a=i===r-1,o=t.dimension(i);a?o.forEach(function(t,r){validateIndex(t),e[t]=n[r[0]]}):o.forEach(function(a,o){validateIndex(a),_setSubmatrix(e[a],t,n[o[0]],r,i+1)})}DenseMatrix$1.prototype.resize=function(e,t,n){if(!isCollection(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);return _resize$1(n?this.clone():this,r,t)};function _resize$1(e,t,n){if(t.length===0){for(var r=e._data;L(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize(e._data,e._size,n),e}__name(_resize$1,`_resize`),DenseMatrix$1.prototype.reshape=function(e,t){var n=t?this.clone():this;return n._data=reshape(n._data,e),n._size=processSizesWildcard(e,n._size.reduce((e,t)=>e*t)),n};function _fit(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&_resize$1(e,r,n)}DenseMatrix$1.prototype.clone=function(){return new DenseMatrix$1({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},DenseMatrix$1.prototype.size=function(){return this._size.slice(0)},DenseMatrix$1.prototype.map=function(e){var t=this,n=maxArgumentCount(e),r=function recurse(r,i){return L(r)?r.map(function(e,t){return recurse(e,i.concat(t))}):n===1?e(r):n===2?e(r,i):e(r,i,t)}(this._data,[]);return new DenseMatrix$1(r,this._datatype===void 0?void 0:getArrayDataType(r,typeOf))},DenseMatrix$1.prototype.forEach=function(e){var t=this;(function recurse(n,r){L(n)?n.forEach(function(e,t){recurse(e,r.concat(t))}):e(n,r,t)})(this._data,[])},DenseMatrix$1.prototype[Symbol.iterator]=function*(){yield*function*recurse(e,t){if(L(e))for(var n=0;n<e.length;n++)yield*recurse(e[n],t.concat(n));else yield{value:e,index:t}}(this._data,[])},DenseMatrix$1.prototype.rows=function(){var e=[];if(this.size().length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var t of this._data)e.push(new DenseMatrix$1([t],this._datatype));return e},DenseMatrix$1.prototype.columns=function(){var e=this,t=[],n=this.size();if(n.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var r=this._data,i=function _loop$1(n){var i=r.map(e=>[e[n]]);t.push(new DenseMatrix$1(i,e._datatype))},a=0;a<n[1];a++)i(a);return t},DenseMatrix$1.prototype.toArray=function(){return clone$2(this._data)},DenseMatrix$1.prototype.valueOf=function(){return this._data},DenseMatrix$1.prototype.format=function(e){return format(this._data,e)},DenseMatrix$1.prototype.toString=function(){return format(this._data)},DenseMatrix$1.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},DenseMatrix$1.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],a=Math.min(r-n,i-t),o=[],s=0;s<a;s++)o[s]=this._data[s+n][s+t];return new DenseMatrix$1({data:o,size:[a],datatype:this._datatype})},DenseMatrix$1.diagonal=function(e,t,n,r){if(!L(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e)||e<1)throw Error(`Size values must be positive integers`);return e}),n){if(isBigNumber(n)&&(n=n.toNumber()),!isNumber$1(n)||!isInteger(n))throw TypeError(`The parameter k must be an integer number`)}else n=0;var i=n>0?n:0,a=n<0?-n:0,o=e[0],s=e[1],c=Math.min(o-a,s-i),l;if(L(t)){if(t.length!==c)throw Error(`Invalid value array length`);l=function _value$1(e){return t[e]}}else if(isMatrix(t)){var u=t.size();if(u.length!==1||u[0]!==c)throw Error(`Invalid matrix length`);l=function _value$1(e){return t.get([e])}}else l=function _value$1(){return t};r||=isBigNumber(l(0))?l(0).mul(0):0;var d=[];if(e.length>0){d=resize(d,e,r);for(var f=0;f<c;f++)d[f+a][f+i]=l(f)}return new DenseMatrix$1({data:d,size:[o,s]})},DenseMatrix$1.fromJSON=function(e){return new DenseMatrix$1(e)},DenseMatrix$1.prototype.swapRows=function(e,t){if(!isNumber$1(e)||!isInteger(e)||!isNumber$1(t)||!isInteger(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return validateIndex(e,this._size[0]),validateIndex(t,this._size[0]),DenseMatrix$1._swapRows(e,t,this._data),this},DenseMatrix$1._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function preprocess(e){return isMatrix(e)?preprocess(e.valueOf()):L(e)?e.map(preprocess):e}return DenseMatrix$1},{isClass:!0});function deepMap(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return deepMap(e,t,n)}):t(e)}var It=`isNumeric`,Lt=[`typed`],Rt=factory(It,Lt,e=>{var{typed:t}=e;return t(It,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>deepMap(t,e))})}),zt=`hasNumericValue`,Bt=[`typed`,`isNumeric`],Vt=factory(zt,Bt,e=>{var{typed:t,isNumeric:n}=e;return t(zt,{boolean:()=>!0,string:function string(e){return e.trim().length>0&&!isNaN(Number(e))},any:function any(e){return n(e)}})}),Ht=xt({config:qe}),Ut=Tt({}),Wt=kt({}),Gt=Mt({}),Kt=Ft({Matrix:Gt}),qt=nt({BigNumber:Ht,Complex:Ut,DenseMatrix:Kt,Fraction:Wt}),Jt=Rt({typed:qt}),Yt=Vt({isNumeric:Jt,typed:qt});const 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*I},Xt=`ratelimitlimit`,Zt=`ratelimitremaining`,Qt=`ratelimitreset`,$t=`ratelimitconcurrencylimit`,en=`ratelimitconcurrencyremaining`,tn=`ratelimitconcurrencyreset`,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]=Yt(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):isString$1(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<n)return e;let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0&&e<n?e:r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(Be.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/I);return e>0&&e<n?e:r}return r},retryErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r})=>__name(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*I:(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)},`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`,m=testMessage((0,o.isObject)(c)?(0,p.JSONPath)({path:f,json:c})[0]:c,r);if(t===a&&m){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,p.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)/I;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`)},nn=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:e,logger:t,requestConfig:n,context:r,concurrencyManager:i})=>__name(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:nn,...c,httpsAgent:void 0,headers:void 0,hasContext:(0,o.notMissing)(r),hasConfig:(0,o.notMissing)(c)},code:F.InterceptorContextNotPresent}),Promise.reject(a);if((0,o.isMissing)(i))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:nn,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(i)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(a);let{requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p}=c?.requestMetadata??{};if(!((0,o.notMissing)(u)&&(0,o.notMissing)(d)&&await i.releaseRequest(u,d))&&(0,o.notMissing)(c?.requestMetadata)&&t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...r,interceptor:nn,requestId:u,targetConcurrencyKey:d,leaseSubscription:f,setRemovalSubscription:p},code:F.RateLimiterReleaseRequestFailed}),l?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:m,retryAfter:h}=convertError(s,r,n,t);if(m===429&&(0,o.notMissing)(c)){let n=getRetryAfterWaitTime(h);if(c._retryCount>=5)return t?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...r??{},...c.requestMetadata??{},retryAfterHeader:h,retryAfterAsNumber:n}}),Promise.reject(a);let i=c?._retryCount??0,l={...c,_retryCount:i+1},u=h?n*I:(0,o.exponentialBackoffInMS)(l._retryCount);return t?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...r,retryAfterHeader:h,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),e?.request(l)}return Promise.reject(a)},`rateLimitErrorInterceptor`),rn=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:e,context:t,concurrencyManager:n})=>__name(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:rn,...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:rn,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:(0,o.notMissing)(n)},code:F.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:rn,rateLimitHeaders:n}})}let{requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u}=i?.requestMetadata??{};if(await n.releaseRequest(s,c)||e?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:rn,requestId:s,targetConcurrencyKey:c,leaseSubscription:l,setRemovalSubscription:u},code:F.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,r))}return r},`rateLimitResponseInterceptor`),validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),an=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],on=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],sn=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],cn=[{onFulfilled:rateLimitResponseInterceptor,onRejected:rateLimitErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],un=1,dn=1e3,fn=0,pn=59,mn=.8,hn=500;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(Pe.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}};let gn=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,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(...sn),m.push(...cn)}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 je.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 je.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:gn.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:an,responseConfigs:on},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>l.default.create({maxBodyLength:1/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:h}){try{(0,o.notMissing)(this.#r)&&(0,o.isMissing)(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let m=this.#v(t,r),g=this.#l(e),_=this.#h(u,e),v=await this.#s({url:m,payload:_,method:n,cacheTTL:s,context:c});if(v)return{...v,responseTime:new Date};let y=P.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:h})).request({headers:g,url:m,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),requestUrl:t,responseType:x?.config?.responseType,responseTime:new Date};return await this.#c({url:m,payload:_,method:n,cacheTTL:s,context:c,response:S}),S}catch(e){let r=e;r.url=(0,m.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=P.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,m.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)?h.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={};for(let[e,o]of Object.entries(t))if(this.#_(o)){let t=o.arrayFormat,s=o.value;t===`repeat`?r[e]=Array.isArray(s)?s:[s]:t===`brackets`?i[e]=Array.isArray(s)?s:[s]:t===`comma`?a[e]=Array.isArray(s)?s:[s]:n[e]=s}else n[e]=o;let s=[];Object.keys(n).length>0&&s.push(h.default.stringify(n)),Object.keys(r).length>0&&s.push(h.default.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&s.push(h.default.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&s.push(h.default.stringify(a,{arrayFormat:`comma`}));let c=s.join(`&`);return(0,o.notMissing)(c)?`${e}?${c}`: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 _n=[`get`,`post`,`put`,`delete`,`patch`],vn={[k.rPush]:`
114
114
  local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
115
115
 
116
116
  redis.call('PEXPIRE', KEYS[1], ARGV[2])
package/dist/index.mjs CHANGED
@@ -110,7 +110,7 @@ Example:
110
110
  * Copyright (c) 2023, Robert Eisele (robert@raw.org)
111
111
  * Dual licensed under the MIT or GPL Version 2 licenses.
112
112
  **/
113
- (function(r){var i=2e3,a={s:1,n:0,d:1};function assign(e,t){if(isNaN(e=parseInt(e,10)))throw InvalidParameter();return e*t}function newFraction(e,t){if(t===0)throw DivisionByZero();var n=Object.create(Fraction$2.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=gcd(e,t);return n.n=e/r,n.d=t/r,n}function factorize(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var o=e(function(e,t){var n=0,r=1,i=1,o=0,s=0,c=0,l=1,u=1,d=0,f=1,p=1,m=1,h=1e7,g;if(e!=null)if(t!==void 0){if(n=e,r=t,i=n*r,n%1!=0||r%1!=0)throw NonIntegerParameter()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw InvalidParameter();i=n*r;break;case`number`:if(e<0&&(i=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(u=10**Math.floor(1+Math.log(e)/Math.LN10),e/=u);f<=h&&m<=h;)if(g=(d+p)/(f+m),e===g){f+m<=h?(n=d+p,r=f+m):m>f?(n=p,r=m):(n=d,r=f);break}else e>g?(d+=p,f+=m):(p+=d,m+=f),f>h?(n=p,r=m):(n=d,r=f);n*=u}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(f=e.match(/\d+|./g),f===null)throw InvalidParameter();if(f[d]===`-`?(i=-1,d++):f[d]===`+`&&d++,f.length===d+1?s=assign(f[d++],i):f[d+1]===`.`||f[d]===`.`?(f[d]!==`.`&&(o=assign(f[d++],i)),d++,(d+1===f.length||f[d+1]===`(`&&f[d+3]===`)`||f[d+1]===`'`&&f[d+3]===`'`)&&(s=assign(f[d],i),l=10**f[d].length,d++),(f[d]===`(`&&f[d+2]===`)`||f[d]===`'`&&f[d+2]===`'`)&&(c=assign(f[d+1],i),u=10**f[d+1].length-1,d+=3)):f[d+1]===`/`||f[d+1]===`:`?(s=assign(f[d],i),l=assign(f[d+2],1),d+=3):f[d+3]===`/`&&f[d+1]===` `&&(o=assign(f[d],i),s=assign(f[d+2],i),l=assign(f[d+4],1),d+=5),f.length<=d){r=l*u,i=n=c+r*o+u*s;break}default:throw InvalidParameter()}if(r===0)throw DivisionByZero();a.s=i<0?-1:1,a.n=Math.abs(n),a.d=Math.abs(r)},`parse`);function modpow(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function cycleLen(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,r=1;n!==1;r++)if(n=n*10%t,r>i)return 0;return r}function cycleStart(e,t,n){for(var r=1,i=modpow(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function gcd(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function Fraction$2(e,t){if(o(e,t),this instanceof Fraction$2)e=gcd(a.d,a.n),this.s=a.s,this.n=a.n/e,this.d=a.d/e;else return newFraction(a.s*a.n,a.d)}e(Fraction$2,`Fraction`);var DivisionByZero=function(){return Error(`Division by Zero`)},InvalidParameter=function(){return Error(`Invalid argument`)},NonIntegerParameter=function(){return Error(`Parameters must be integer`)};Fraction$2.prototype={s:1,n:0,d:1,abs:function(){return newFraction(this.n,this.d)},neg:function(){return newFraction(-this.s*this.n,this.d)},add:function(e,t){return o(e,t),newFraction(this.s*this.n*a.d+a.s*this.d*a.n,this.d*a.d)},sub:function(e,t){return o(e,t),newFraction(this.s*this.n*a.d-a.s*this.d*a.n,this.d*a.d)},mul:function(e,t){return o(e,t),newFraction(this.s*a.s*this.n*a.n,this.d*a.d)},div:function(e,t){return o(e,t),newFraction(this.s*a.s*this.n*a.d,this.d*a.n)},clone:function(){return newFraction(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new Fraction$2(NaN);if(e===void 0)return newFraction(this.s*this.n%this.d,1);if(o(e,t),a.n===0&&this.d===0)throw DivisionByZero();return newFraction(this.s*(a.d*this.n)%(a.n*this.d),a.d*this.d)},gcd:function(e,t){return o(e,t),newFraction(gcd(a.n,this.n)*gcd(a.d,this.d),a.d*this.d)},lcm:function(e,t){return o(e,t),a.n===0&&this.n===0?newFraction(0,1):newFraction(a.n*this.n,gcd(a.n,this.n)*gcd(a.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return newFraction(this.s*this.d,this.n)},pow:function(e,t){if(o(e,t),a.d===1)return a.s<0?newFraction((this.s*this.d)**+a.n,this.n**+a.n):newFraction((this.s*this.n)**+a.n,this.d**+a.n);if(this.s<0)return null;var n=factorize(this.n),r=factorize(this.d),i=1,s=1;for(var c in n)if(c!==`1`){if(c===`0`){i=0;break}if(n[c]*=a.n,n[c]%a.d===0)n[c]/=a.d;else return null;i*=c**+n[c]}for(var c in r)if(c!==`1`){if(r[c]*=a.n,r[c]%a.d===0)r[c]/=a.d;else return null;s*=c**+r[c]}return a.s<0?newFraction(s,i):newFraction(i,s)},equals:function(e,t){return o(e,t),this.s*this.n*a.d===a.s*a.n*this.d},compare:function(e,t){o(e,t);var n=this.s*this.n*a.d-a.s*a.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=newFraction(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return o(e,t),!(!(a.n*this.d)||this.n*a.d%(a.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=cycleLen(t,n),i=cycleStart(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof t==`object`?(Object.defineProperty(Fraction$2,`__esModule`,{value:!0}),Fraction$2.default=Fraction$2,Fraction$2.Fraction=Fraction$2,n.exports=Fraction$2):r.Fraction=Fraction$2})(t)}))(),1),$e=factory(`Fraction`,[],()=>(Object.defineProperty($.default,`name`,{value:`Fraction`}),$.default.prototype.constructor=$.default,$.default.prototype.type=`Fraction`,$.default.prototype.isFraction=!0,$.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},$.default.fromJSON=function(e){return new $.default(e)},$.default),{isClass:!0}),et=factory(`Matrix`,[],()=>{function Matrix$1(){if(!(this instanceof Matrix$1))throw SyntaxError(`Constructor must be called with the new operator`)}return e(Matrix$1,`Matrix`),Matrix$1.prototype.type=`Matrix`,Matrix$1.prototype.isMatrix=!0,Matrix$1.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},Matrix$1.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},Matrix$1.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},Matrix$1.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},Matrix$1.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},Matrix$1.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},Matrix$1.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},Matrix$1.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},Matrix$1.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},Matrix$1.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},Matrix$1.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},Matrix$1.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},Matrix$1.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},Matrix$1.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},Matrix$1.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},Matrix$1.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},Matrix$1.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},Matrix$1},{isClass:!0});function maxArgumentCount(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var tt=factory(`DenseMatrix`,[`Matrix`],t=>{var{Matrix:n}=t;function DenseMatrix$1(e,t){if(!(this instanceof DenseMatrix$1))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!isString$1(t))throw Error(`Invalid datatype: `+t);if(isMatrix(e))e.type===`DenseMatrix`?(this._data=clone$2(e._data),this._size=clone$2(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&L(e.data)&&L(e.size))this._data=e.data,this._size=e.size,validate$1(this._data,this._size),this._datatype=t||e.datatype;else if(L(e))this._data=preprocess(e),this._size=arraySize(this._data),validate$1(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+typeOf(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}e(DenseMatrix$1,`DenseMatrix`),DenseMatrix$1.prototype=new n,DenseMatrix$1.prototype.createDenseMatrix=function(e,t){return new DenseMatrix$1(e,t)},Object.defineProperty(DenseMatrix$1,`name`,{value:`DenseMatrix`}),DenseMatrix$1.prototype.constructor=DenseMatrix$1,DenseMatrix$1.prototype.type=`DenseMatrix`,DenseMatrix$1.prototype.isDenseMatrix=!0,DenseMatrix$1.prototype.getDataType=function(){return getArrayDataType(this._data,typeOf)},DenseMatrix$1.prototype.storage=function(){return`dense`},DenseMatrix$1.prototype.datatype=function(){return this._datatype},DenseMatrix$1.prototype.create=function(e,t){return new DenseMatrix$1(e,t)},DenseMatrix$1.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return _get(this,e);case 2:case 3:return _set(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},DenseMatrix$1.prototype.get=function(e){if(!L(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;t<e.length;t++)validateIndex(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];validateIndex(a,n.length),n=n[a]}return n},DenseMatrix$1.prototype.set=function(e,t,n){if(!L(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new DimensionError(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});_fit(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],validateIndex(a,s.length),s=s[a];return a=e[e.length-1],validateIndex(a,s.length),s[a]=t,this};function _get(e,t){if(!isIndex(t))throw TypeError(`Invalid index`);if(t.isScalar())return e.get(t.min());var n=t.size();if(n.length!==e._size.length)throw new DimensionError(n.length,e._size.length);for(var r=t.min(),i=t.max(),a=0,o=e._size.length;a<o;a++)validateIndex(r[a],e._size[a]),validateIndex(i[a],e._size[a]);return new DenseMatrix$1(_getSubmatrix(e._data,t,n.length,0),e._datatype)}function _getSubmatrix(e,t,n,r){var i=r===n-1,a=t.dimension(r);return i?a.map(function(t){return validateIndex(t,e.length),e[t]}).valueOf():a.map(function(i){validateIndex(i,e.length);var a=e[i];return _getSubmatrix(a,t,n,r+1)}).valueOf()}function _set(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(isMatrix(n)?(o=n.size(),n=n.valueOf()):o=arraySize(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!deepStrictEqual(o,i))try{n=o.length===0?broadcastTo([n],i):broadcastTo(n,i),o=arraySize(n)}catch{}if(i.length<e._size.length)throw new DimensionError(i.length,e._size.length,`<`);if(o.length<i.length){for(var s=0,c=0;i[s]===1&&o[s]===1;)s++;for(;i[s]===1;)c++,s++;n=unsqueeze(n,i.length,c,o)}if(!deepStrictEqual(i,o))throw new DimensionError(i,o,`>`);_fit(e,t.max().map(function(e){return e+1}),r);var l=i.length;_setSubmatrix(e._data,t,n,l,0)}return e}function _setSubmatrix(e,t,n,r,i){var a=i===r-1,o=t.dimension(i);a?o.forEach(function(t,r){validateIndex(t),e[t]=n[r[0]]}):o.forEach(function(a,o){validateIndex(a),_setSubmatrix(e[a],t,n[o[0]],r,i+1)})}DenseMatrix$1.prototype.resize=function(e,t,n){if(!isCollection(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);return _resize$1(n?this.clone():this,r,t)};function _resize$1(e,t,n){if(t.length===0){for(var r=e._data;L(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize(e._data,e._size,n),e}e(_resize$1,`_resize`),DenseMatrix$1.prototype.reshape=function(e,t){var n=t?this.clone():this;return n._data=reshape(n._data,e),n._size=processSizesWildcard(e,n._size.reduce((e,t)=>e*t)),n};function _fit(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&_resize$1(e,r,n)}DenseMatrix$1.prototype.clone=function(){return new DenseMatrix$1({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},DenseMatrix$1.prototype.size=function(){return this._size.slice(0)},DenseMatrix$1.prototype.map=function(e){var t=this,n=maxArgumentCount(e),r=function recurse(r,i){return L(r)?r.map(function(e,t){return recurse(e,i.concat(t))}):n===1?e(r):n===2?e(r,i):e(r,i,t)}(this._data,[]);return new DenseMatrix$1(r,this._datatype===void 0?void 0:getArrayDataType(r,typeOf))},DenseMatrix$1.prototype.forEach=function(e){var t=this;(function recurse(n,r){L(n)?n.forEach(function(e,t){recurse(e,r.concat(t))}):e(n,r,t)})(this._data,[])},DenseMatrix$1.prototype[Symbol.iterator]=function*(){yield*function*recurse(e,t){if(L(e))for(var n=0;n<e.length;n++)yield*recurse(e[n],t.concat(n));else yield{value:e,index:t}}(this._data,[])},DenseMatrix$1.prototype.rows=function(){var e=[];if(this.size().length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var t of this._data)e.push(new DenseMatrix$1([t],this._datatype));return e},DenseMatrix$1.prototype.columns=function(){var e=this,t=[],n=this.size();if(n.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var r=this._data,i=function _loop$1(n){var i=r.map(e=>[e[n]]);t.push(new DenseMatrix$1(i,e._datatype))},a=0;a<n[1];a++)i(a);return t},DenseMatrix$1.prototype.toArray=function(){return clone$2(this._data)},DenseMatrix$1.prototype.valueOf=function(){return this._data},DenseMatrix$1.prototype.format=function(e){return format(this._data,e)},DenseMatrix$1.prototype.toString=function(){return format(this._data)},DenseMatrix$1.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},DenseMatrix$1.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],a=Math.min(r-n,i-t),o=[],s=0;s<a;s++)o[s]=this._data[s+n][s+t];return new DenseMatrix$1({data:o,size:[a],datatype:this._datatype})},DenseMatrix$1.diagonal=function(e,t,n,r){if(!L(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e)||e<1)throw Error(`Size values must be positive integers`);return e}),n){if(isBigNumber(n)&&(n=n.toNumber()),!isNumber$1(n)||!isInteger(n))throw TypeError(`The parameter k must be an integer number`)}else n=0;var i=n>0?n:0,a=n<0?-n:0,o=e[0],s=e[1],c=Math.min(o-a,s-i),l;if(L(t)){if(t.length!==c)throw Error(`Invalid value array length`);l=function _value$1(e){return t[e]}}else if(isMatrix(t)){var u=t.size();if(u.length!==1||u[0]!==c)throw Error(`Invalid matrix length`);l=function _value$1(e){return t.get([e])}}else l=function _value$1(){return t};r||=isBigNumber(l(0))?l(0).mul(0):0;var d=[];if(e.length>0){d=resize(d,e,r);for(var f=0;f<c;f++)d[f+a][f+i]=l(f)}return new DenseMatrix$1({data:d,size:[o,s]})},DenseMatrix$1.fromJSON=function(e){return new DenseMatrix$1(e)},DenseMatrix$1.prototype.swapRows=function(e,t){if(!isNumber$1(e)||!isInteger(e)||!isNumber$1(t)||!isInteger(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return validateIndex(e,this._size[0]),validateIndex(t,this._size[0]),DenseMatrix$1._swapRows(e,t,this._data),this},DenseMatrix$1._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function preprocess(e){return isMatrix(e)?preprocess(e.valueOf()):L(e)?e.map(preprocess):e}return DenseMatrix$1},{isClass:!0});function deepMap(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return deepMap(e,t,n)}):t(e)}var nt=`isNumeric`,rt=factory(nt,[`typed`],e=>{var{typed:t}=e;return t(nt,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>deepMap(t,e))})}),it=`hasNumericValue`,at=factory(it,[`typed`,`isNumeric`],e=>{var{typed:t,isNumeric:n}=e;return t(it,{boolean:()=>!0,string:function string(e){return e.trim().length>0&&!isNaN(Number(e))},any:function any(e){return n(e)}})}),ot=Ne({BigNumber:Xe({config:Ee}),Complex:Qe({}),DenseMatrix:tt({Matrix:et({})}),Fraction:$e({})}),st=at({isNumeric:rt({typed:ot}),typed:ot});const 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)&&c(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*I},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]=st(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:s}=e??{};return[t,n,r,o].some(l)?null:[t,n,r,i,a,o,...s??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return c(e)||u(e)?evaluateRetryAfterNumber(Number(e),r,t,n):isString$1(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<n)return e;let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0&&e<n?e:r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(be.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/I);return e>0&&e<n?e:r}return r},retryErrorInterceptor=({axiosInstance:t,logger:n,requestConfig:r,context:a})=>e(async e=>{let{response:o,config:s}=e;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,a,r,n);if(c===429&&p(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return n?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...a??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(e);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*I:i(u._retryCount);return n?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...a??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),t?.request(u)}return Promise.reject(e)},`retryErrorInterceptor`),convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:s}=e??{},{retryafter:c}=superNormalizeHeaders(o??{});if(l(i)||l(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:l(e),providerIsMissing:l(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:c??`undefined`}}),{status:a,retryAfter:c};let u=n?.rateLimits?.mappedRateLimitErrors;if(p(u)&&p(s))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:l,retryAfterValue:u}=e;if(t!==a)continue;let f=n??`message`,p=testMessage(d(s)?w({path:f,json:s})[0]:s,r);if(t===a&&p){let e=convertRetryAfter(u??extractRetryAfter(o,i),l);return{status:429,retryAfter:c??e}}}return{status:a,retryAfter:c}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>p(t)&&p(e)?w({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>p(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)/I;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`)},ct=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:t,logger:n,requestConfig:r,context:a,concurrencyManager:o})=>e(async e=>{let{response:s,config:c}=e,u=c?.signal;if(l(a)||l(c))return n?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:ct,...c,httpsAgent:void 0,headers:void 0,hasContext:p(a),hasConfig:p(c)},code:F.InterceptorContextNotPresent}),Promise.reject(e);if(l(o))return n?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:ct,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:p(o)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(e);let{requestId:d,targetConcurrencyKey:f,leaseSubscription:m,setRemovalSubscription:h}=c?.requestMetadata??{};if(!(p(d)&&p(f)&&await o.releaseRequest(d,f))&&p(c?.requestMetadata)&&n?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...a,interceptor:ct,requestId:d,targetConcurrencyKey:f,leaseSubscription:m,setRemovalSubscription:h},code:F.RateLimiterReleaseRequestFailed}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:g,retryAfter:_}=convertError(s,a,r,n);if(g===429&&p(c)){let r=getRetryAfterWaitTime(_);if(c._retryCount>=5)return n?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...a??{},...c.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:r}}),Promise.reject(e);let o=c?._retryCount??0,l={...c,_retryCount:o+1},u=_?r*I:i(l._retryCount);return n?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...a,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),t?.request(l)}return Promise.reject(e)},`rateLimitErrorInterceptor`),lt=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:t,context:n,concurrencyManager:r})=>e(async e=>{let i=e?.config,a=i?.signal;if(l(n))t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:lt,...i,httpsAgent:void 0,headers:void 0}});else if(l(r))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:lt,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:p(r)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),e;else if(p(n.provider)&&p(n.accountSecureId)){let n=e?.headers;if(p(n)){let e=extractRateLimitHeaders(n);t?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:lt,rateLimitHeaders:e}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l}=i?.requestMetadata??{};if(await r.releaseRequest(o,s)||t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:lt,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:F.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,e))}return e},`rateLimitResponseInterceptor`),validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),ut=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],dt=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],ft=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],pt=[{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=p(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(ve.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(l(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(p(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}};let mt=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,s=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=s.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),l(n?.service)||l(n?.organizationId)||o===`test`||l(t)||l(e))return a;let c=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=c?.isReady(),f=u?.isRedisConfigured(),m=[],h=[];if(s.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...ft),h.push(...pt)}let g=generateRequestKey(n);if(l(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:p(a)}}),a;let _=await ge.get(g);if(p(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:c},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await ge.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:p(a)},error:t,code:mt.HttpTransportInstanceCreateError}),p(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:ut,responseConfigs:dt},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>y.create({maxBodyLength:1/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?o(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:o,context:s,traceId:c,payload:u,httpsAgent:d,httpAgent:f,requestConfig:m,httpsAgentConfig:h}){try{p(this.#r)&&l(this.#a)&&(this.#a=await this.#t(this.#r,this.#n,`HttpClient`));let g=this.#_(t,r),_=this.#l(e),v=this.#m(u,e),y=await this.#s({url:g,payload:v,method:n,cacheTTL:o,context:s});if(y)return{...y,responseTime:new Date};let b=he.getInstance(),x=(p(c)?await b.get(c):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:m,httpsAgentConfig:h})).request({headers:_,url:g,method:n,maxRedirects:i,responseType:a,data:v,httpsAgent:d,httpAgent:f,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#u(S.headers),requestUrl:t,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:g,payload:v,method:n,cacheTTL:o,context:s,response:C}),C}catch(e){let r=e;r.url=T(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#h(r);throw p(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:d}){try{let f=this.#_(t,r),m=this.#l(e),h=this.#m(s,e),g=he.getInstance(),_=(p(o)?await g.get(o):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:u,httpsAgentConfig:d})).request({headers:m,url:f,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=T(t),this.#n?.warning({category:this.name,message:`Stream request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#h(r);throw p(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 f(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return l(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e,t){if(!(l(e)||d(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)?e:this.#d(t)?E.stringify(e):e}#h(e){if(b(e)&&this.#i)return this.#i(e)}#g(e){return typeof e==`object`&&!!e&&`value`in e&&(typeof e.value==`string`||Array.isArray(e.value))}#_(e,t){if(l(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={};for(let[e,o]of Object.entries(t))if(this.#g(o)){let t=o.arrayFormat,s=o.value;t===`repeat`?r[e]=Array.isArray(s)?s:[s]:t===`brackets`?i[e]=Array.isArray(s)?s:[s]:t===`comma`?a[e]=Array.isArray(s)?s:[s]:n[e]=s}else n[e]=o;let o=[];Object.keys(n).length>0&&o.push(E.stringify(n)),Object.keys(r).length>0&&o.push(E.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&o.push(E.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&o.push(E.stringify(a,{arrayFormat:`comma`}));let s=o.join(`&`);return p(s)?`${e}?${s}`: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 ht=[`get`,`post`,`put`,`delete`,`patch`],gt={[A.rPush]:`
113
+ (function(r){var i=2e3,a={s:1,n:0,d:1};function assign(e,t){if(isNaN(e=parseInt(e,10)))throw InvalidParameter();return e*t}function newFraction(e,t){if(t===0)throw DivisionByZero();var n=Object.create(Fraction$2.prototype);n.s=e<0?-1:1,e=e<0?-e:e;var r=gcd(e,t);return n.n=e/r,n.d=t/r,n}function factorize(e){for(var t={},n=e,r=2,i=4;i<=n;){for(;n%r===0;)n/=r,t[r]=(t[r]||0)+1;i+=1+2*r++}return n===e?t[e]=(t[e]||0)+1:n>1&&(t[n]=(t[n]||0)+1),t}var o=e(function(e,t){var n=0,r=1,i=1,o=0,s=0,c=0,l=1,u=1,d=0,f=1,p=1,m=1,h=1e7,g;if(e!=null)if(t!==void 0){if(n=e,r=t,i=n*r,n%1!=0||r%1!=0)throw NonIntegerParameter()}else switch(typeof e){case`object`:if(`d`in e&&`n`in e)n=e.n,r=e.d,`s`in e&&(n*=e.s);else if(0 in e)n=e[0],1 in e&&(r=e[1]);else throw InvalidParameter();i=n*r;break;case`number`:if(e<0&&(i=e,e=-e),e%1==0)n=e;else if(e>0){for(e>=1&&(u=10**Math.floor(1+Math.log(e)/Math.LN10),e/=u);f<=h&&m<=h;)if(g=(d+p)/(f+m),e===g){f+m<=h?(n=d+p,r=f+m):m>f?(n=p,r=m):(n=d,r=f);break}else e>g?(d+=p,f+=m):(p+=d,m+=f),f>h?(n=p,r=m):(n=d,r=f);n*=u}else (isNaN(e)||isNaN(t))&&(r=n=NaN);break;case`string`:if(f=e.match(/\d+|./g),f===null)throw InvalidParameter();if(f[d]===`-`?(i=-1,d++):f[d]===`+`&&d++,f.length===d+1?s=assign(f[d++],i):f[d+1]===`.`||f[d]===`.`?(f[d]!==`.`&&(o=assign(f[d++],i)),d++,(d+1===f.length||f[d+1]===`(`&&f[d+3]===`)`||f[d+1]===`'`&&f[d+3]===`'`)&&(s=assign(f[d],i),l=10**f[d].length,d++),(f[d]===`(`&&f[d+2]===`)`||f[d]===`'`&&f[d+2]===`'`)&&(c=assign(f[d+1],i),u=10**f[d+1].length-1,d+=3)):f[d+1]===`/`||f[d+1]===`:`?(s=assign(f[d],i),l=assign(f[d+2],1),d+=3):f[d+3]===`/`&&f[d+1]===` `&&(o=assign(f[d],i),s=assign(f[d+2],i),l=assign(f[d+4],1),d+=5),f.length<=d){r=l*u,i=n=c+r*o+u*s;break}default:throw InvalidParameter()}if(r===0)throw DivisionByZero();a.s=i<0?-1:1,a.n=Math.abs(n),a.d=Math.abs(r)},`parse`);function modpow(e,t,n){for(var r=1;t>0;e=e*e%n,t>>=1)t&1&&(r=r*e%n);return r}function cycleLen(e,t){for(;t%2==0;t/=2);for(;t%5==0;t/=5);if(t===1)return 0;for(var n=10%t,r=1;n!==1;r++)if(n=n*10%t,r>i)return 0;return r}function cycleStart(e,t,n){for(var r=1,i=modpow(10,n,t),a=0;a<300;a++){if(r===i)return a;r=r*10%t,i=i*10%t}return 0}function gcd(e,t){if(!e)return t;if(!t)return e;for(;;){if(e%=t,!e)return t;if(t%=e,!t)return e}}function Fraction$2(e,t){if(o(e,t),this instanceof Fraction$2)e=gcd(a.d,a.n),this.s=a.s,this.n=a.n/e,this.d=a.d/e;else return newFraction(a.s*a.n,a.d)}e(Fraction$2,`Fraction`);var DivisionByZero=function(){return Error(`Division by Zero`)},InvalidParameter=function(){return Error(`Invalid argument`)},NonIntegerParameter=function(){return Error(`Parameters must be integer`)};Fraction$2.prototype={s:1,n:0,d:1,abs:function(){return newFraction(this.n,this.d)},neg:function(){return newFraction(-this.s*this.n,this.d)},add:function(e,t){return o(e,t),newFraction(this.s*this.n*a.d+a.s*this.d*a.n,this.d*a.d)},sub:function(e,t){return o(e,t),newFraction(this.s*this.n*a.d-a.s*this.d*a.n,this.d*a.d)},mul:function(e,t){return o(e,t),newFraction(this.s*a.s*this.n*a.n,this.d*a.d)},div:function(e,t){return o(e,t),newFraction(this.s*a.s*this.n*a.d,this.d*a.n)},clone:function(){return newFraction(this.s*this.n,this.d)},mod:function(e,t){if(isNaN(this.n)||isNaN(this.d))return new Fraction$2(NaN);if(e===void 0)return newFraction(this.s*this.n%this.d,1);if(o(e,t),a.n===0&&this.d===0)throw DivisionByZero();return newFraction(this.s*(a.d*this.n)%(a.n*this.d),a.d*this.d)},gcd:function(e,t){return o(e,t),newFraction(gcd(a.n,this.n)*gcd(a.d,this.d),a.d*this.d)},lcm:function(e,t){return o(e,t),a.n===0&&this.n===0?newFraction(0,1):newFraction(a.n*this.n,gcd(a.n,this.n)*gcd(a.d,this.d))},ceil:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.ceil(e*this.s*this.n/this.d),e)},floor:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.floor(e*this.s*this.n/this.d),e)},round:function(e){return e=10**(e||0),isNaN(this.n)||isNaN(this.d)?new Fraction$2(NaN):newFraction(Math.round(e*this.s*this.n/this.d),e)},inverse:function(){return newFraction(this.s*this.d,this.n)},pow:function(e,t){if(o(e,t),a.d===1)return a.s<0?newFraction((this.s*this.d)**+a.n,this.n**+a.n):newFraction((this.s*this.n)**+a.n,this.d**+a.n);if(this.s<0)return null;var n=factorize(this.n),r=factorize(this.d),i=1,s=1;for(var c in n)if(c!==`1`){if(c===`0`){i=0;break}if(n[c]*=a.n,n[c]%a.d===0)n[c]/=a.d;else return null;i*=c**+n[c]}for(var c in r)if(c!==`1`){if(r[c]*=a.n,r[c]%a.d===0)r[c]/=a.d;else return null;s*=c**+r[c]}return a.s<0?newFraction(s,i):newFraction(i,s)},equals:function(e,t){return o(e,t),this.s*this.n*a.d===a.s*a.n*this.d},compare:function(e,t){o(e,t);var n=this.s*this.n*a.d-a.s*a.n*this.d;return(0<n)-(n<0)},simplify:function(e){if(isNaN(this.n)||isNaN(this.d))return this;e||=.001;for(var t=this.abs(),n=t.toContinued(),r=1;r<n.length;r++){for(var i=newFraction(n[r-1],1),a=r-2;a>=0;a--)i=i.inverse().add(n[a]);if(Math.abs(i.sub(t).valueOf())<e)return i.mul(this.s)}return this},divisible:function(e,t){return o(e,t),!(!(a.n*this.d)||this.n*a.d%(a.n*this.d))},valueOf:function(){return this.s*this.n/this.d},toFraction:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,n+=` `,r%=i),n+=r,n+=`/`,n+=i),n},toLatex:function(e){var t,n=``,r=this.n,i=this.d;return this.s<0&&(n+=`-`),i===1?n+=r:(e&&(t=Math.floor(r/i))>0&&(n+=t,r%=i),n+=`\\frac{`,n+=r,n+=`}{`,n+=i,n+=`}`),n},toContinued:function(){var e,t=this.n,n=this.d,r=[];if(isNaN(t)||isNaN(n))return r;do r.push(Math.floor(t/n)),e=t%n,t=n,n=e;while(t!==1);return r},toString:function(e){var t=this.n,n=this.d;if(isNaN(t)||isNaN(n))return`NaN`;e||=15;var r=cycleLen(t,n),i=cycleStart(t,n,r),a=this.s<0?`-`:``;if(a+=t/n|0,t%=n,t*=10,t&&(a+=`.`),r){for(var o=i;o--;)a+=t/n|0,t%=n,t*=10;a+=`(`;for(var o=r;o--;)a+=t/n|0,t%=n,t*=10;a+=`)`}else for(var o=e;t&&o--;)a+=t/n|0,t%=n,t*=10;return a}},typeof t==`object`?(Object.defineProperty(Fraction$2,`__esModule`,{value:!0}),Fraction$2.default=Fraction$2,Fraction$2.Fraction=Fraction$2,n.exports=Fraction$2):r.Fraction=Fraction$2})(t)}))(),1),$e=factory(`Fraction`,[],()=>(Object.defineProperty($.default,`name`,{value:`Fraction`}),$.default.prototype.constructor=$.default,$.default.prototype.type=`Fraction`,$.default.prototype.isFraction=!0,$.default.prototype.toJSON=function(){return{mathjs:`Fraction`,n:this.s*this.n,d:this.d}},$.default.fromJSON=function(e){return new $.default(e)},$.default),{isClass:!0}),et=factory(`Matrix`,[],()=>{function Matrix$1(){if(!(this instanceof Matrix$1))throw SyntaxError(`Constructor must be called with the new operator`)}return e(Matrix$1,`Matrix`),Matrix$1.prototype.type=`Matrix`,Matrix$1.prototype.isMatrix=!0,Matrix$1.prototype.storage=function(){throw Error(`Cannot invoke storage on a Matrix interface`)},Matrix$1.prototype.datatype=function(){throw Error(`Cannot invoke datatype on a Matrix interface`)},Matrix$1.prototype.create=function(e,t){throw Error(`Cannot invoke create on a Matrix interface`)},Matrix$1.prototype.subset=function(e,t,n){throw Error(`Cannot invoke subset on a Matrix interface`)},Matrix$1.prototype.get=function(e){throw Error(`Cannot invoke get on a Matrix interface`)},Matrix$1.prototype.set=function(e,t,n){throw Error(`Cannot invoke set on a Matrix interface`)},Matrix$1.prototype.resize=function(e,t){throw Error(`Cannot invoke resize on a Matrix interface`)},Matrix$1.prototype.reshape=function(e,t){throw Error(`Cannot invoke reshape on a Matrix interface`)},Matrix$1.prototype.clone=function(){throw Error(`Cannot invoke clone on a Matrix interface`)},Matrix$1.prototype.size=function(){throw Error(`Cannot invoke size on a Matrix interface`)},Matrix$1.prototype.map=function(e,t){throw Error(`Cannot invoke map on a Matrix interface`)},Matrix$1.prototype.forEach=function(e){throw Error(`Cannot invoke forEach on a Matrix interface`)},Matrix$1.prototype[Symbol.iterator]=function(){throw Error(`Cannot iterate a Matrix interface`)},Matrix$1.prototype.toArray=function(){throw Error(`Cannot invoke toArray on a Matrix interface`)},Matrix$1.prototype.valueOf=function(){throw Error(`Cannot invoke valueOf on a Matrix interface`)},Matrix$1.prototype.format=function(e){throw Error(`Cannot invoke format on a Matrix interface`)},Matrix$1.prototype.toString=function(){throw Error(`Cannot invoke toString on a Matrix interface`)},Matrix$1},{isClass:!0});function maxArgumentCount(e){return Object.keys(e.signatures||{}).reduce(function(e,t){var n=(t.match(/,/g)||[]).length+1;return Math.max(e,n)},-1)}var tt=factory(`DenseMatrix`,[`Matrix`],t=>{var{Matrix:n}=t;function DenseMatrix$1(e,t){if(!(this instanceof DenseMatrix$1))throw SyntaxError(`Constructor must be called with the new operator`);if(t&&!isString$1(t))throw Error(`Invalid datatype: `+t);if(isMatrix(e))e.type===`DenseMatrix`?(this._data=clone$2(e._data),this._size=clone$2(e._size),this._datatype=t||e._datatype):(this._data=e.toArray(),this._size=e.size(),this._datatype=t||e._datatype);else if(e&&L(e.data)&&L(e.size))this._data=e.data,this._size=e.size,validate$1(this._data,this._size),this._datatype=t||e.datatype;else if(L(e))this._data=preprocess(e),this._size=arraySize(this._data),validate$1(this._data,this._size),this._datatype=t;else if(e)throw TypeError(`Unsupported type of data (`+typeOf(e)+`)`);else this._data=[],this._size=[0],this._datatype=t}e(DenseMatrix$1,`DenseMatrix`),DenseMatrix$1.prototype=new n,DenseMatrix$1.prototype.createDenseMatrix=function(e,t){return new DenseMatrix$1(e,t)},Object.defineProperty(DenseMatrix$1,`name`,{value:`DenseMatrix`}),DenseMatrix$1.prototype.constructor=DenseMatrix$1,DenseMatrix$1.prototype.type=`DenseMatrix`,DenseMatrix$1.prototype.isDenseMatrix=!0,DenseMatrix$1.prototype.getDataType=function(){return getArrayDataType(this._data,typeOf)},DenseMatrix$1.prototype.storage=function(){return`dense`},DenseMatrix$1.prototype.datatype=function(){return this._datatype},DenseMatrix$1.prototype.create=function(e,t){return new DenseMatrix$1(e,t)},DenseMatrix$1.prototype.subset=function(e,t,n){switch(arguments.length){case 1:return _get(this,e);case 2:case 3:return _set(this,e,t,n);default:throw SyntaxError(`Wrong number of arguments`)}},DenseMatrix$1.prototype.get=function(e){if(!L(e))throw TypeError(`Array expected`);if(e.length!==this._size.length)throw new DimensionError(e.length,this._size.length);for(var t=0;t<e.length;t++)validateIndex(e[t],this._size[t]);for(var n=this._data,r=0,i=e.length;r<i;r++){var a=e[r];validateIndex(a,n.length),n=n[a]}return n},DenseMatrix$1.prototype.set=function(e,t,n){if(!L(e))throw TypeError(`Array expected`);if(e.length<this._size.length)throw new DimensionError(e.length,this._size.length,`<`);var r,i,a,o=e.map(function(e){return e+1});_fit(this,o,n);var s=this._data;for(r=0,i=e.length-1;r<i;r++)a=e[r],validateIndex(a,s.length),s=s[a];return a=e[e.length-1],validateIndex(a,s.length),s[a]=t,this};function _get(e,t){if(!isIndex(t))throw TypeError(`Invalid index`);if(t.isScalar())return e.get(t.min());var n=t.size();if(n.length!==e._size.length)throw new DimensionError(n.length,e._size.length);for(var r=t.min(),i=t.max(),a=0,o=e._size.length;a<o;a++)validateIndex(r[a],e._size[a]),validateIndex(i[a],e._size[a]);return new DenseMatrix$1(_getSubmatrix(e._data,t,n.length,0),e._datatype)}function _getSubmatrix(e,t,n,r){var i=r===n-1,a=t.dimension(r);return i?a.map(function(t){return validateIndex(t,e.length),e[t]}).valueOf():a.map(function(i){validateIndex(i,e.length);var a=e[i];return _getSubmatrix(a,t,n,r+1)}).valueOf()}function _set(e,t,n,r){if(!t||t.isIndex!==!0)throw TypeError(`Invalid index`);var i=t.size(),a=t.isScalar(),o;if(isMatrix(n)?(o=n.size(),n=n.valueOf()):o=arraySize(n),a){if(o.length!==0)throw TypeError(`Scalar expected`);e.set(t.min(),n,r)}else{if(!deepStrictEqual(o,i))try{n=o.length===0?broadcastTo([n],i):broadcastTo(n,i),o=arraySize(n)}catch{}if(i.length<e._size.length)throw new DimensionError(i.length,e._size.length,`<`);if(o.length<i.length){for(var s=0,c=0;i[s]===1&&o[s]===1;)s++;for(;i[s]===1;)c++,s++;n=unsqueeze(n,i.length,c,o)}if(!deepStrictEqual(i,o))throw new DimensionError(i,o,`>`);_fit(e,t.max().map(function(e){return e+1}),r);var l=i.length;_setSubmatrix(e._data,t,n,l,0)}return e}function _setSubmatrix(e,t,n,r,i){var a=i===r-1,o=t.dimension(i);a?o.forEach(function(t,r){validateIndex(t),e[t]=n[r[0]]}):o.forEach(function(a,o){validateIndex(a),_setSubmatrix(e[a],t,n[o[0]],r,i+1)})}DenseMatrix$1.prototype.resize=function(e,t,n){if(!isCollection(e))throw TypeError(`Array or Matrix expected`);var r=e.valueOf().map(e=>Array.isArray(e)&&e.length===1?e[0]:e);return _resize$1(n?this.clone():this,r,t)};function _resize$1(e,t,n){if(t.length===0){for(var r=e._data;L(r);)r=r[0];return r}return e._size=t.slice(0),e._data=resize(e._data,e._size,n),e}e(_resize$1,`_resize`),DenseMatrix$1.prototype.reshape=function(e,t){var n=t?this.clone():this;return n._data=reshape(n._data,e),n._size=processSizesWildcard(e,n._size.reduce((e,t)=>e*t)),n};function _fit(e,t,n){for(var r=e._size.slice(0),i=!1;r.length<t.length;)r.push(0),i=!0;for(var a=0,o=t.length;a<o;a++)t[a]>r[a]&&(r[a]=t[a],i=!0);i&&_resize$1(e,r,n)}DenseMatrix$1.prototype.clone=function(){return new DenseMatrix$1({data:clone$2(this._data),size:clone$2(this._size),datatype:this._datatype})},DenseMatrix$1.prototype.size=function(){return this._size.slice(0)},DenseMatrix$1.prototype.map=function(e){var t=this,n=maxArgumentCount(e),r=function recurse(r,i){return L(r)?r.map(function(e,t){return recurse(e,i.concat(t))}):n===1?e(r):n===2?e(r,i):e(r,i,t)}(this._data,[]);return new DenseMatrix$1(r,this._datatype===void 0?void 0:getArrayDataType(r,typeOf))},DenseMatrix$1.prototype.forEach=function(e){var t=this;(function recurse(n,r){L(n)?n.forEach(function(e,t){recurse(e,r.concat(t))}):e(n,r,t)})(this._data,[])},DenseMatrix$1.prototype[Symbol.iterator]=function*(){yield*function*recurse(e,t){if(L(e))for(var n=0;n<e.length;n++)yield*recurse(e[n],t.concat(n));else yield{value:e,index:t}}(this._data,[])},DenseMatrix$1.prototype.rows=function(){var e=[];if(this.size().length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var t of this._data)e.push(new DenseMatrix$1([t],this._datatype));return e},DenseMatrix$1.prototype.columns=function(){var e=this,t=[],n=this.size();if(n.length!==2)throw TypeError(`Rows can only be returned for a 2D matrix.`);for(var r=this._data,i=function _loop$1(n){var i=r.map(e=>[e[n]]);t.push(new DenseMatrix$1(i,e._datatype))},a=0;a<n[1];a++)i(a);return t},DenseMatrix$1.prototype.toArray=function(){return clone$2(this._data)},DenseMatrix$1.prototype.valueOf=function(){return this._data},DenseMatrix$1.prototype.format=function(e){return format(this._data,e)},DenseMatrix$1.prototype.toString=function(){return format(this._data)},DenseMatrix$1.prototype.toJSON=function(){return{mathjs:`DenseMatrix`,data:this._data,size:this._size,datatype:this._datatype}},DenseMatrix$1.prototype.diagonal=function(e){if(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e))throw TypeError(`The parameter k must be an integer number`)}else e=0;for(var t=e>0?e:0,n=e<0?-e:0,r=this._size[0],i=this._size[1],a=Math.min(r-n,i-t),o=[],s=0;s<a;s++)o[s]=this._data[s+n][s+t];return new DenseMatrix$1({data:o,size:[a],datatype:this._datatype})},DenseMatrix$1.diagonal=function(e,t,n,r){if(!L(e))throw TypeError(`Array expected, size parameter`);if(e.length!==2)throw Error(`Only two dimensions matrix are supported`);if(e=e.map(function(e){if(isBigNumber(e)&&(e=e.toNumber()),!isNumber$1(e)||!isInteger(e)||e<1)throw Error(`Size values must be positive integers`);return e}),n){if(isBigNumber(n)&&(n=n.toNumber()),!isNumber$1(n)||!isInteger(n))throw TypeError(`The parameter k must be an integer number`)}else n=0;var i=n>0?n:0,a=n<0?-n:0,o=e[0],s=e[1],c=Math.min(o-a,s-i),l;if(L(t)){if(t.length!==c)throw Error(`Invalid value array length`);l=function _value$1(e){return t[e]}}else if(isMatrix(t)){var u=t.size();if(u.length!==1||u[0]!==c)throw Error(`Invalid matrix length`);l=function _value$1(e){return t.get([e])}}else l=function _value$1(){return t};r||=isBigNumber(l(0))?l(0).mul(0):0;var d=[];if(e.length>0){d=resize(d,e,r);for(var f=0;f<c;f++)d[f+a][f+i]=l(f)}return new DenseMatrix$1({data:d,size:[o,s]})},DenseMatrix$1.fromJSON=function(e){return new DenseMatrix$1(e)},DenseMatrix$1.prototype.swapRows=function(e,t){if(!isNumber$1(e)||!isInteger(e)||!isNumber$1(t)||!isInteger(t))throw Error(`Row index must be positive integers`);if(this._size.length!==2)throw Error(`Only two dimensional matrix is supported`);return validateIndex(e,this._size[0]),validateIndex(t,this._size[0]),DenseMatrix$1._swapRows(e,t,this._data),this},DenseMatrix$1._swapRows=function(e,t,n){var r=n[e];n[e]=n[t],n[t]=r};function preprocess(e){return isMatrix(e)?preprocess(e.valueOf()):L(e)?e.map(preprocess):e}return DenseMatrix$1},{isClass:!0});function deepMap(e,t,n){return e&&typeof e.map==`function`?e.map(function(e){return deepMap(e,t,n)}):t(e)}var nt=`isNumeric`,rt=factory(nt,[`typed`],e=>{var{typed:t}=e;return t(nt,{"number | BigNumber | Fraction | boolean":()=>!0,"Complex | Unit | string | null | undefined | Node":()=>!1,"Array | Matrix":t.referToSelf(e=>t=>deepMap(t,e))})}),it=`hasNumericValue`,at=factory(it,[`typed`,`isNumeric`],e=>{var{typed:t,isNumeric:n}=e;return t(it,{boolean:()=>!0,string:function string(e){return e.trim().length>0&&!isNaN(Number(e))},any:function any(e){return n(e)}})}),ot=Ne({BigNumber:Xe({config:Ee}),Complex:Qe({}),DenseMatrix:tt({Matrix:et({})}),Fraction:$e({})}),st=at({isNumeric:rt({typed:ot}),typed:ot});const 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)&&c(t)?adjustUnixTimestamp(t):shortTimePeriodIsMilliseconds(t)?n+t:n+t*I},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]=st(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:s}=e??{};return[t,n,r,o].some(l)?null:[t,n,r,i,a,o,...s??[]].filter(Boolean).join(`-`)},getRetryAfterWaitTime=(e,t=10,n=1)=>{let r=Date.now();return c(e)||u(e)?evaluateRetryAfterNumber(Number(e),r,t,n):isString$1(e)&&e!==``?evaluateRetryAfterString(e,r,t,n):n},evaluateRetryAfterNumber=(e,t,n=10,r=1)=>{if(e<n)return e;let i=adjustUnixTimestamp(e);if(i>t){let e=Math.floor((i-t)/I);return e>0&&e<n?e:r}return r},evaluateRetryAfterString=(e,t,n=10,r=1)=>{if(be.test(e)){let t=parseFloat(e);return t>0&&t<n?t:r}let i=new Date(e);if(Number.isNaN(i.getTime()))return r;let a=i.getTime();if(a>t){let e=Math.floor((a-t)/I);return e>0&&e<n?e:r}return r},retryErrorInterceptor=({axiosInstance:t,logger:n,requestConfig:r,context:a})=>e(async e=>{let{response:o,config:s}=e;if(s?.signal?.aborted)return Promise.reject(createAxiosError(`Request aborted`,s,`ERR_CANCELED`,o));let{status:c,retryAfter:l}=convertError(o,a,r,n);if(c===429&&p(s)){let r=getRetryAfterWaitTime(l);if(s._retryCount>=5)return n?.warning({category:`http-transport`,message:`Max retries exceeded for ${s?.url}. Aborting.`,context:{...a??{},retryAfterHeader:l,retryAfterAsNumber:r}}),Promise.reject(e);let c=s._retryCount??0,u={...s,_retryCount:c+1},d=l?r*I:i(u._retryCount);return n?.debug({category:`http-transport`,message:`Received 429 error from ${s?.url}`,context:{...a??{},retryAfterHeader:l,calculatedRetryAfter:d}}),await abortableDelay(d,s,o),t?.request(u)}return Promise.reject(e)},`retryErrorInterceptor`),convertError=(e,t,n,r)=>{let{provider:i}=t??{},{status:a,headers:o,data:s}=e??{},{retryafter:c}=superNormalizeHeaders(o??{});if(l(i)||l(e))return r?.warning({category:`http-transport`,message:`Invalid parameters for convertError`,context:{...t,responseIsMissing:l(e),providerIsMissing:l(i),status:e?.status??`undefined`,statusText:e?.statusText??`undefined`,retryafter:c??`undefined`}}),{status:a,retryAfter:c};let u=n?.rateLimits?.mappedRateLimitErrors;if(p(u)&&p(s))for(let e of u){let{errorStatus:t,errorMessagePath:n,errorMessage:r,retryAfterPath:i,retryAfterUnit:l,retryAfterValue:u}=e;if(t!==a)continue;let f=n??`message`,p=testMessage(d(s)?w({path:f,json:s})[0]:s,r);if(t===a&&p){let e=convertRetryAfter(u??extractRetryAfter(o,i),l);return{status:429,retryAfter:c??e}}}return{status:a,retryAfter:c}},testMessage=(e,t)=>t instanceof RegExp?t.test(e??``):e?.includes(t)??!1,extractRetryAfter=(e,t)=>p(t)&&p(e)?w({path:t,json:e})[0]:null,convertRetryAfter=(e,t=`seconds`)=>p(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)/I;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`)},ct=`rateLimitErrorInterceptor`,rateLimitErrorInterceptor=({axiosInstance:t,logger:n,requestConfig:r,context:a,concurrencyManager:o})=>e(async e=>{let{response:s,config:c}=e,u=c?.signal;if(l(a)||l(c))return n?.warning({category:`HttpClient`,message:`No context or config for this response - that doesn't seem right.`,context:{interceptor:ct,...c,httpsAgent:void 0,headers:void 0,hasContext:p(a),hasConfig:p(c)},code:F.InterceptorContextNotPresent}),Promise.reject(e);if(l(o))return n?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:ct,...c,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:p(o)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),Promise.reject(e);let{requestId:d,targetConcurrencyKey:f,leaseSubscription:m,setRemovalSubscription:h}=c?.requestMetadata??{};if(!(p(d)&&p(f)&&await o.releaseRequest(d,f))&&p(c?.requestMetadata)&&n?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{...a,interceptor:ct,requestId:d,targetConcurrencyKey:f,leaseSubscription:m,setRemovalSubscription:h},code:F.RateLimiterReleaseRequestFailed}),u?.aborted)return Promise.reject(createAxiosError(`Request aborted`,c,`ERR_CANCELED`,s));let{status:g,retryAfter:_}=convertError(s,a,r,n);if(g===429&&p(c)){let r=getRetryAfterWaitTime(_);if(c._retryCount>=5)return n?.warning({category:`HttpClient`,message:`Max retries exceeded for ${c.url}. Aborting.`,context:{...a??{},...c.requestMetadata??{},retryAfterHeader:_,retryAfterAsNumber:r}}),Promise.reject(e);let o=c?._retryCount??0,l={...c,_retryCount:o+1},u=_?r*I:i(l._retryCount);return n?.debug({category:`HttpClient`,message:`Received 429 error from ${c.url}`,context:{...a,retryAfterHeader:_,calculatedRetryAfter:u}}),await abortableDelay(u,c,s),t?.request(l)}return Promise.reject(e)},`rateLimitErrorInterceptor`),lt=`rateLimitResponseInterceptor`,rateLimitResponseInterceptor=({logger:t,context:n,concurrencyManager:r})=>e(async e=>{let i=e?.config,a=i?.signal;if(l(n))t?.warning({category:`HttpClient`,message:`No context for this response - that doesn't seem right.`,context:{interceptor:lt,...i,httpsAgent:void 0,headers:void 0}});else if(l(r))return t?.error({category:`HttpClient`,message:`ConcurrencyManager is not initialized`,context:{interceptor:lt,...i,httpsAgent:void 0,headers:void 0,concurrencyManagerInitialized:p(r)},code:F.RateLimitOrConcurrencyManagerNotInitialized}),e;else if(p(n.provider)&&p(n.accountSecureId)){let n=e?.headers;if(p(n)){let e=extractRateLimitHeaders(n);t?.debug({category:`HttpClient`,message:`Rate limit headers extracted`,context:{interceptor:lt,rateLimitHeaders:e}})}let{requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l}=i?.requestMetadata??{};if(await r.releaseRequest(o,s)||t?.error({category:`HttpClient`,message:`Failed to release request from concurrency manager`,context:{interceptor:lt,requestId:o,targetConcurrencyKey:s,leaseSubscription:c,setRemovalSubscription:l},code:F.RateLimiterReleaseRequestFailed}),a?.aborted)return Promise.reject(createAxiosError(`Request aborted`,i,`ERR_CANCELED`,e))}return e},`rateLimitResponseInterceptor`),validateRequestInterceptor=e=>(e.validateStatus??=e=>e>=200&&e<300,e),ut=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0}],dt=[{onFulfilled:null,onRejected:retryErrorInterceptor},{onFulfilled:null,onRejected:abortErrorInterceptor}],ft=[{onFulfilled:validateRequestInterceptor,onRejected:null,options:void 0},{onFulfilled:checkConcurrencyInterceptor,onRejected:null,options:void 0}],pt=[{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=p(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(ve.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(l(t))throw Error(`Singleton ${e.name} not prepared yet`);if(t.hasInitFailed?.())throw Error(`${e.name} initialization failed`);let n=t.getInstanceIfReady?.();if(p(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}};let mt=function(e){return e.HttpTransportInstanceCreateError=`HttpTransportInstanceCreateError`,e}({});const getTransportInstance=async({logger:e,redisClientConfig:t,context:n,requestConfig:r,httpsAgentConfig:i}={})=>{let a,{NODE_ENV:o}=process.env,s=n?.behaviours??[`CONCURRENCY`,`RETRY`];try{if(a=s.includes(`RETRY`)?createDefaultRetryInstance(e,n):createDefaultInstance(e,n),l(n?.service)||l(n?.organizationId)||o===`test`||l(t)||l(e))return a;let c=SingletonManager.getIfReady(RateLimitManager)??void 0,u=SingletonManager.getIfReady(ConcurrencyManager)??void 0,d=c?.isReady(),f=u?.isRedisConfigured(),m=[],h=[];if(s.includes(`CONCURRENCY`)){if(!f)throw Error(`Concurrency Manager cannot connect to Redis. Cannot create advanced transport instance.`);if(!d)throw Error(`RateLimitManager is not ready. Cannot create advanced transport instance.`);m.push(...ft),h.push(...pt)}let g=generateRequestKey(n);if(l(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:p(a)}}),a;let _=await ge.get(g);if(p(_))return _;let v={interceptors:{requestConfigs:m,responseConfigs:h},instanceConfig:{maxBodyLength:1/0},logger:e,context:n,requestConfig:r,httpsAgentConfig:i,concurrencyManager:u,rateLimitManager:c},y=HttpTransportFactory.createInstance(v);return e?.debug({category:`http-transport`,message:`Creating new Axios instance and caching it for key: [${g}]`,context:{...n}}),await ge.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:p(a)},error:t,code:mt.HttpTransportInstanceCreateError}),p(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:ut,responseConfigs:dt},instanceConfig:{maxBodyLength:1/0},logger:e,context:t};return HttpTransportFactory.createInstance(n)??createAxiosInstance()},createAxiosInstance=()=>y.create({maxBodyLength:1/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?o(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:o,context:s,traceId:c,payload:u,httpsAgent:d,httpAgent:f,requestConfig:m,httpsAgentConfig:h}){try{p(this.#r)&&l(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:s});if(y)return{...y,responseTime:new Date};let b=he.getInstance(),x=(p(c)?await b.get(c):null)?.signal,S=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:s,requestConfig:m,httpsAgentConfig:h})).request({headers:_,url:g,method:n,maxRedirects:i,responseType:a,data:v,httpsAgent:d,httpAgent:f,signal:x}),C={data:S.data,status:S.status,body:v,method:n,headers:this.#u(S.headers),requestUrl:t,responseType:S?.config?.responseType,responseTime:new Date};return await this.#c({url:g,payload:v,method:n,cacheTTL:o,context:s,response:C}),C}catch(e){let r=e;r.url=T(t),this.#n?.warning({category:this.name,message:`Request error [${n?.toUpperCase()} ${r.url}]: ${r.message}.`,error:r});let i=this.#g(r);throw p(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:d}){try{let f=this.#v(t,r),m=this.#l(e),h=this.#h(s,e),g=he.getInstance(),_=(p(o)?await g.get(o):null)?.signal,v=await(await this.#e({redisClientConfig:this.#r,logger:this.#n,context:a,requestConfig:u,httpsAgentConfig:d})).request({headers:m,url:f,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=T(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 p(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 f(e[`content-type`])?e[`content-type`]?.startsWith(`multipart/form-data`)??!1:!1}#p(e){return l(e)||typeof e!=`object`||!e?!1:`pipe`in e&&typeof e.pipe==`function`}#m(e){return Buffer.isBuffer(e)}#h(e,t){if(!(l(e)||d(e)&&Object.keys(e).length===0))return this.#f(t)||this.#p(e)||this.#m(e)?e:this.#d(t)?E.stringify(e):e}#g(e){if(b(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(l(t)||Object.keys(t).length===0)return e;let n={},r={},i={},a={};for(let[e,o]of Object.entries(t))if(this.#_(o)){let t=o.arrayFormat,s=o.value;t===`repeat`?r[e]=Array.isArray(s)?s:[s]:t===`brackets`?i[e]=Array.isArray(s)?s:[s]:t===`comma`?a[e]=Array.isArray(s)?s:[s]:n[e]=s}else n[e]=o;let o=[];Object.keys(n).length>0&&o.push(E.stringify(n)),Object.keys(r).length>0&&o.push(E.stringify(r,{arrayFormat:`repeat`})),Object.keys(i).length>0&&o.push(E.stringify(i,{arrayFormat:`brackets`})),Object.keys(a).length>0&&o.push(E.stringify(a,{arrayFormat:`comma`}));let s=o.join(`&`);return p(s)?`${e}?${s}`: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 ht=[`get`,`post`,`put`,`delete`,`patch`],gt={[A.rPush]:`
114
114
  local queueLength = redis.call('RPUSH', KEYS[1], ARGV[1])
115
115
 
116
116
  redis.call('PEXPIRE', KEYS[1], ARGV[2])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/transport",
3
- "version": "2.13.1",
3
+ "version": "2.14.0",
4
4
  "description": "",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.mjs",