@msafe/sui3-sdk 0.0.47 → 0.0.48

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
@@ -1,2 +1,2 @@
1
- "use strict";var Ji=Object.create;var Dt=Object.defineProperty;var Qi=Object.getOwnPropertyDescriptor;var Xi=Object.getOwnPropertyNames;var eo=Object.getPrototypeOf,to=Object.prototype.hasOwnProperty;var Nt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ro=(r,e)=>{for(var t in e)Dt(r,t,{get:e[t],enumerable:!0})},qn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xi(e))!to.call(r,s)&&s!==t&&Dt(r,s,{get:()=>e[s],enumerable:!(n=Qi(e,s))||n.enumerable});return r};var Ie=(r,e,t)=>(t=r!=null?Ji(eo(r)):{},qn(e||!r||!r.__esModule?Dt(t,"default",{value:r,enumerable:!0}):t,r)),no=r=>qn(Dt({},"__esModule",{value:!0}),r);var ea=Nt((Sm,Xs)=>{"use strict";Xs.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var ra=Nt((bm,ta)=>{"use strict";var cn=ea();ta.exports=(r,e={})=>{if(!cn(r)&&!Array.isArray(r))throw new TypeError("Expected a plain object or array");let{deep:t}=e,n=[],s=[],a=o=>{let c=n.indexOf(o);if(c!==-1)return s[c];let u=[];return n.push(o),s.push(u),u.push(...o.map(d=>Array.isArray(d)?a(d):cn(d)?i(d):d)),u},i=o=>{let c=n.indexOf(o);if(c!==-1)return s[c];let u={},d=Object.keys(o).sort(e.compare);n.push(o),s.push(u);for(let f of d){let g=o[f],m;t&&Array.isArray(g)?m=a(g):m=t&&cn(g)?i(g):g,Object.defineProperty(u,f,{...Object.getOwnPropertyDescriptor(o,f),value:m})}return u};return Array.isArray(r)?t?a(r):r.slice():i(r)}});var aa=Nt((Tm,sa)=>{"use strict";var Mc=Object.prototype.toString;sa.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var t=typeof e;if(t==="boolean")return"boolean";if(t==="string")return"string";if(t==="number")return"number";if(t==="symbol")return"symbol";if(t==="function")return Fc(e)?"generatorfunction":"function";if(Ac(e))return"array";if(Wc(e))return"buffer";if(_c(e))return"arguments";if(Nc(e))return"date";if(Dc(e))return"error";if(Pc(e))return"regexp";switch(na(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(Rc(e))return"generator";switch(t=Mc.call(e),t){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")};function na(r){return typeof r.constructor=="function"?r.constructor.name:null}function Ac(r){return Array.isArray?Array.isArray(r):r instanceof Array}function Dc(r){return r instanceof Error||typeof r.message=="string"&&r.constructor&&typeof r.constructor.stackTraceLimit=="number"}function Nc(r){return r instanceof Date?!0:typeof r.toDateString=="function"&&typeof r.getDate=="function"&&typeof r.setDate=="function"}function Pc(r){return r instanceof RegExp?!0:typeof r.flags=="string"&&typeof r.ignoreCase=="boolean"&&typeof r.multiline=="boolean"&&typeof r.global=="boolean"}function Fc(r,e){return na(r)==="GeneratorFunction"}function Rc(r){return typeof r.throw=="function"&&typeof r.return=="function"&&typeof r.next=="function"}function _c(r){try{if(typeof r.length=="number"&&typeof r.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function Wc(r){return r.constructor&&typeof r.constructor.isBuffer=="function"?r.constructor.isBuffer(r):!1}});var Qt=Nt((Im,ua)=>{"use strict";var jc=ra(),un=aa(),ia=(r,e)=>!e||un(e)!=="array"?!1:e.indexOf(r)>-1,Lc=(r,e)=>jc(r,{compare:e}),oa=(r,e)=>{let t=e&&e.compareFunction;return r.slice().sort(t)};function ca(r,e){let t=e&&e.compareFunction,n=Lc(r,t);return Object.keys(r).forEach(function(s){let a=n[s],i=un(a);if(i==="object"){(!e||!ia(s,e.ignoreObjectAtKeys))&&(n[s]=ca(a,e));return}i==="array"&&(!e||!ia(s,e.ignoreArrayAtKeys))&&(n[s]=oa(a,e))}),n}var St=(r,e)=>{let t=un(r);return St[t]?St[t](r,e):r};St.array=oa;St.object=ca;ua.exports=St});var nl={};ro(nl,{AddressBookSDK:()=>ke,COIN_TYPE_ARG_REGEX:()=>Cn,Coin:()=>Ct,CoinHelper:()=>Et,CreateHelper:()=>xe,DEV_API_URL:()=>Bi,DEV_SYNCING_URL:()=>qi,ENV_CONFIGS:()=>Vi,Formatter:()=>Q,HexToUint8Array:()=>ur,LOCAL_API_URL:()=>_n,LOCAL_SYNCING_URL:()=>Wn,MAINNET_RPC_URL:()=>Rn,MSafeAccount:()=>Se,MSafeClient:()=>br,MSafeEnv:()=>Li,MSafeGlobals:()=>At,PREV_API_URL:()=>Ui,PROD_API_URL:()=>Hi,SUI_COIN:()=>el,SignatureVerifier:()=>Mn,TESTNET_RPC_URL:()=>Sr,Uint8ArrayToHex:()=>Xu,addPrefix:()=>vn,getAllCoins:()=>rl,getMSafeConfig:()=>jn,getPublicKeyFromChain:()=>An,stringToBuffer:()=>cr});module.exports=no(nl);var z=require("@msafe/sui3-utils"),xe=class{constructor(e,t){this.globals=e;this.pkHelper=t}async getPublicKeyBatch(e){return this.pkHelper.getPublicKeyBatch(e)}async calculateMSafeAddress(e){let t=await this.reduceCreationInfoToRawConfig(e);return new z.MultiSigAccount(t).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,t){let n=z.PublicKeySerde.de(t);if(!(0,z.isSameAddress)(e,n.toSuiAddress()))throw new Error("Public key not match");this.pkHelper.addPublicKey(e,n)}async submitMSafeCreation(e){let t=await this.validateCreateInfo(e),n=z.SigningMessageHelper.createMSafeMessage(t),s=await this.globals.wallet.signPersonalMessage({messageStr:n});return await this.submitToBackend(e,s.signature),t}async reduceCreationInfoToRawConfig(e){let t=await this.getPublicKeyBatch(e.owners.map(n=>n.address));return t.forEach((n,s)=>{if(n===void 0)throw new Error(`Unknown public key for address: ${e.owners[s].address}`)}),{threshold:e.threshold,ownersWithWeight:e.owners.map((n,s)=>({publicKey:t[s],weight:n.weight})),creationNonce:e.creationNonce}}async submitToBackend(e,t){let n=await this.pkHelper.getPublicKeyBatch(e.owners.map(s=>s.address));await this.globals.backend.createMSafeAccount({owners:e.owners.map((s,a)=>({address:s.address,weight:s.weight,...z.PublicKeySerde.ser(n[a])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:t})}};var Tr=require("@msafe/sui3-utils");var Un=require("@msafe/sui3-utils"),ke=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let t=Un.SigningMessageHelper.updateAddressBookMessage(e),n=await this.globals.wallet.signPersonalMessage({messageStr:t});return this.globals.backend.updateAddressBook({updates:e,signature:n.signature})}async getMode(){return(await this.globals.backend.getAddressBookMode()).mode}async setMode(e){return this.globals.backend.setAddressBookMode({mode:e})}};var Pt=class{constructor(e){this.globals=e}async getMSafeByStatus(e,t){return this.globals.backend.getOwnedMSafeByStatus({status:e,pagination:t})}async updateMSafeStatus(e,t){return this.globals.backend.updateMSafeStatus({msafeAddress:e,status:t})}};var Na=require("@msafe/sui3-utils"),Ka=require("@mysten/sui.js/client"),J=Ie(require("axios"),1),we=require("@mysten/sui.js/utils"),qe=require("@mysten/sui.js/utils");var $=class extends Error{},Ft=class extends ${constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Rt=class extends ${constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},_t=class extends ${constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},j=class extends ${},Oe=class extends ${constructor(e){super(`Invalid unit ${e}`)}},x=class extends ${},L=class extends ${constructor(){super("Zone is an abstract class")}};var l="numeric",B="short",D="long",X={year:l,month:l,day:l},Ve={year:l,month:B,day:l},xr={year:l,month:B,day:l,weekday:B},Ge={year:l,month:D,day:l},ze={year:l,month:D,day:l,weekday:D},$e={hour:l,minute:l},Ze={hour:l,minute:l,second:l},Ke={hour:l,minute:l,second:l,timeZoneName:B},Ye={hour:l,minute:l,second:l,timeZoneName:D},Je={hour:l,minute:l,hourCycle:"h23"},Qe={hour:l,minute:l,second:l,hourCycle:"h23"},Xe={hour:l,minute:l,second:l,hourCycle:"h23",timeZoneName:B},et={hour:l,minute:l,second:l,hourCycle:"h23",timeZoneName:D},tt={year:l,month:l,day:l,hour:l,minute:l},rt={year:l,month:l,day:l,hour:l,minute:l,second:l},nt={year:l,month:B,day:l,hour:l,minute:l},st={year:l,month:B,day:l,hour:l,minute:l,second:l},kr={year:l,month:B,day:l,weekday:B,hour:l,minute:l},at={year:l,month:D,day:l,hour:l,minute:l,timeZoneName:B},it={year:l,month:D,day:l,hour:l,minute:l,second:l,timeZoneName:B},ot={year:l,month:D,day:l,weekday:D,hour:l,minute:l,timeZoneName:D},ct={year:l,month:D,day:l,weekday:D,hour:l,minute:l,second:l,timeZoneName:D};var A=class{get type(){throw new L}get name(){throw new L}get ianaName(){return this.name}get isUniversal(){throw new L}offsetName(e,t){throw new L}formatOffset(e,t){throw new L}offset(e){throw new L}equals(e){throw new L}get isValid(){throw new L}};var Or=null,ee=class r extends A{static get instance(){return Or===null&&(Or=new r),Or}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return jt(e,t,n)}formatOffset(e,t){return te(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var Bt={};function so(r){return Bt[r]||(Bt[r]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),Bt[r]}var ao={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function io(r,e){let t=r.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,s,a,i,o,c,u,d]=n;return[i,s,a,o,c,u,d]}function oo(r,e){let t=r.formatToParts(e),n=[];for(let s=0;s<t.length;s++){let{type:a,value:i}=t[s],o=ao[a];a==="era"?n[o]=i:h(o)||(n[o]=parseInt(i,10))}return n}var Lt={},M=class r extends A{static create(e){return Lt[e]||(Lt[e]=new r(e)),Lt[e]}static resetCache(){Lt={},Bt={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=r.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return jt(e,t,n,this.name)}formatOffset(e,t){return te(this.offset(e),t)}offset(e){let t=new Date(e);if(isNaN(t))return NaN;let n=so(this.name),[s,a,i,o,c,u,d]=n.formatToParts?oo(n,t):io(n,t);o==="BC"&&(s=-Math.abs(s)+1);let g=Ee({year:s,month:a,day:i,hour:c===24?0:c,minute:u,second:d,millisecond:0}),m=+t,k=m%1e3;return m-=k>=0?k:1e3+k,(g-m)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var Hn={};function co(r,e={}){let t=JSON.stringify([r,e]),n=Hn[t];return n||(n=new Intl.ListFormat(r,e),Hn[t]=n),n}var Er={};function Cr(r,e={}){let t=JSON.stringify([r,e]),n=Er[t];return n||(n=new Intl.DateTimeFormat(r,e),Er[t]=n),n}var vr={};function uo(r,e={}){let t=JSON.stringify([r,e]),n=vr[t];return n||(n=new Intl.NumberFormat(r,e),vr[t]=n),n}var Mr={};function lo(r,e={}){let{base:t,...n}=e,s=JSON.stringify([r,n]),a=Mr[s];return a||(a=new Intl.RelativeTimeFormat(r,e),Mr[s]=a),a}var ut=null;function mo(){return ut||(ut=new Intl.DateTimeFormat().resolvedOptions().locale,ut)}var Vn={};function ho(r){let e=Vn[r];if(!e){let t=new Intl.Locale(r);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,Vn[r]=e}return e}function fo(r){let e=r.indexOf("-x-");e!==-1&&(r=r.substring(0,e));let t=r.indexOf("-u-");if(t===-1)return[r];{let n,s;try{n=Cr(r).resolvedOptions(),s=r}catch{let c=r.substring(0,t);n=Cr(c).resolvedOptions(),s=c}let{numberingSystem:a,calendar:i}=n;return[s,a,i]}}function po(r,e,t){return(t||e)&&(r.includes("-u-")||(r+="-u"),t&&(r+=`-ca-${t}`),e&&(r+=`-nu-${e}`)),r}function go(r){let e=[];for(let t=1;t<=12;t++){let n=p.utc(2009,t,1);e.push(r(n))}return e}function yo(r){let e=[];for(let t=1;t<=7;t++){let n=p.utc(2016,11,13+t);e.push(r(n))}return e}function qt(r,e,t,n){let s=r.listingMode();return s==="error"?null:s==="en"?t(e):n(e)}function wo(r){return r.numberingSystem&&r.numberingSystem!=="latn"?!1:r.numberingSystem==="latn"||!r.locale||r.locale.startsWith("en")||new Intl.DateTimeFormat(r.intl).resolvedOptions().numberingSystem==="latn"}var Ar=class{constructor(e,t,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:s,floor:a,...i}=n;if(!t||Object.keys(i).length>0){let o={useGrouping:!1,...n};n.padTo>0&&(o.minimumIntegerDigits=n.padTo),this.inf=uo(e,o)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{let t=this.floor?Math.floor(e):Ce(e,3);return I(t,this.padTo)}}},Dr=class{constructor(e,t,n){this.opts=n,this.originalZone=void 0;let s;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let i=-1*(e.offset/60),o=i>=0?`Etc/GMT+${i}`:`Etc/GMT${i}`;e.offset!==0&&M.create(o).valid?(s=o,this.dt=e):(s="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,s=e.zone.name):(s="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let a={...this.opts};a.timeZone=a.timeZone||s,this.dtf=Cr(t,a)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:n}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Nr=class{constructor(e,t,n){this.opts={style:"long",...n},!t&&Ut()&&(this.rtf=lo(e,n))}format(e,t){return this.rtf?this.rtf.format(e,t):Gn(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},So={firstDay:1,minimalDays:4,weekend:[6,7]},b=class r{static fromOpts(e){return r.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,n,s,a=!1){let i=e||y.defaultLocale,o=i||(a?"en-US":mo()),c=t||y.defaultNumberingSystem,u=n||y.defaultOutputCalendar,d=lt(s)||y.defaultWeekSettings;return new r(o,c,u,d,i)}static resetCache(){ut=null,Er={},vr={},Mr={}}static fromObject({locale:e,numberingSystem:t,outputCalendar:n,weekSettings:s}={}){return r.create(e,t,n,s)}constructor(e,t,n,s,a){let[i,o,c]=fo(e);this.locale=i,this.numberingSystem=t||o||null,this.outputCalendar=n||c||null,this.weekSettings=s,this.intl=po(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=a,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=wo(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:r.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,lt(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return qt(this,e,Pr,()=>{let n=t?{month:e,day:"numeric"}:{month:e},s=t?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=go(a=>this.extract(a,n,"month"))),this.monthsCache[s][e]})}weekdays(e,t=!1){return qt(this,e,Fr,()=>{let n=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=t?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=yo(a=>this.extract(a,n,"weekday"))),this.weekdaysCache[s][e]})}meridiems(){return qt(this,void 0,()=>Rr,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[p.utc(2016,11,13,9),p.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return qt(this,e,_r,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[p.utc(-40,1,1),p.utc(2017,1,1)].map(n=>this.extract(n,t,"era"))),this.eraCache[e]})}extract(e,t,n){let s=this.dtFormatter(e,t),a=s.formatToParts(),i=a.find(o=>o.type.toLowerCase()===n);return i?i.value:null}numberFormatter(e={}){return new Ar(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new Dr(e,this.intl,t)}relFormatter(e={}){return new Nr(this.intl,this.isEnglish(),e)}listFormatter(e={}){return co(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Ht()?ho(this.locale):So}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};var jr=null,O=class r extends A{static get utcInstance(){return jr===null&&(jr=new r(0)),jr}static instance(e){return e===0?r.utcInstance:new r(e)}static parseSpecifier(e){if(e){let t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new r(de(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${te(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${te(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return te(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var ve=class extends A{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function q(r,e){let t;if(h(r)||r===null)return e;if(r instanceof A)return r;if(zn(r)){let n=r.toLowerCase();return n==="default"?e:n==="local"||n==="system"?ee.instance:n==="utc"||n==="gmt"?O.utcInstance:O.parseSpecifier(n)||M.create(r)}else return G(r)?O.instance(r):typeof r=="object"&&"offset"in r&&typeof r.offset=="function"?r:new ve(r)}var $n=()=>Date.now(),Zn="system",Kn=null,Yn=null,Jn=null,Qn=60,Xn,es=null,y=class{static get now(){return $n}static set now(e){$n=e}static set defaultZone(e){Zn=e}static get defaultZone(){return q(Zn,ee.instance)}static get defaultLocale(){return Kn}static set defaultLocale(e){Kn=e}static get defaultNumberingSystem(){return Yn}static set defaultNumberingSystem(e){Yn=e}static get defaultOutputCalendar(){return Jn}static set defaultOutputCalendar(e){Jn=e}static get defaultWeekSettings(){return es}static set defaultWeekSettings(e){es=lt(e)}static get twoDigitCutoffYear(){return Qn}static set twoDigitCutoffYear(e){Qn=e%100}static get throwOnInvalid(){return Xn}static set throwOnInvalid(e){Xn=e}static resetCaches(){b.resetCache(),M.resetCache()}};var E=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var ts=[0,31,59,90,120,151,181,212,243,273,304,334],rs=[0,31,60,91,121,152,182,213,244,274,305,335];function R(r,e){return new E("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${r}, which is invalid`)}function Vt(r,e,t){let n=new Date(Date.UTC(r,e-1,t));r<100&&r>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let s=n.getUTCDay();return s===0?7:s}function ns(r,e,t){return t+(he(r)?rs:ts)[e-1]}function ss(r,e){let t=he(r)?rs:ts,n=t.findIndex(a=>a<e),s=e-t[n];return{month:n+1,day:s}}function Gt(r,e){return(r-e+7)%7+1}function dt(r,e=4,t=1){let{year:n,month:s,day:a}=r,i=ns(n,s,a),o=Gt(Vt(n,s,a),t),c=Math.floor((i-o+14-e)/7),u;return c<1?(u=n-1,c=me(u,e,t)):c>me(n,e,t)?(u=n+1,c=1):u=n,{weekYear:u,weekNumber:c,weekday:o,...ht(r)}}function Lr(r,e=4,t=1){let{weekYear:n,weekNumber:s,weekday:a}=r,i=Gt(Vt(n,1,e),t),o=re(n),c=s*7+a-i-7+e,u;c<1?(u=n-1,c+=re(u)):c>o?(u=n+1,c-=re(n)):u=n;let{month:d,day:f}=ss(u,c);return{year:u,month:d,day:f,...ht(r)}}function zt(r){let{year:e,month:t,day:n}=r,s=ns(e,t,n);return{year:e,ordinal:s,...ht(r)}}function Br(r){let{year:e,ordinal:t}=r,{month:n,day:s}=ss(e,t);return{year:e,month:n,day:s,...ht(r)}}function qr(r,e){if(!h(r.localWeekday)||!h(r.localWeekNumber)||!h(r.localWeekYear)){if(!h(r.weekday)||!h(r.weekNumber)||!h(r.weekYear))throw new j("Cannot mix locale-based week fields with ISO-based week fields");return h(r.localWeekday)||(r.weekday=r.localWeekday),h(r.localWeekNumber)||(r.weekNumber=r.localWeekNumber),h(r.localWeekYear)||(r.weekYear=r.localWeekYear),delete r.localWeekday,delete r.localWeekNumber,delete r.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function as(r,e=4,t=1){let n=mt(r.weekYear),s=N(r.weekNumber,1,me(r.weekYear,e,t)),a=N(r.weekday,1,7);return n?s?a?!1:R("weekday",r.weekday):R("week",r.weekNumber):R("weekYear",r.weekYear)}function is(r){let e=mt(r.year),t=N(r.ordinal,1,re(r.year));return e?t?!1:R("ordinal",r.ordinal):R("year",r.year)}function Ur(r){let e=mt(r.year),t=N(r.month,1,12),n=N(r.day,1,Me(r.year,r.month));return e?t?n?!1:R("day",r.day):R("month",r.month):R("year",r.year)}function Hr(r){let{hour:e,minute:t,second:n,millisecond:s}=r,a=N(e,0,23)||e===24&&t===0&&n===0&&s===0,i=N(t,0,59),o=N(n,0,59),c=N(s,0,999);return a?i?o?c?!1:R("millisecond",s):R("second",n):R("minute",t):R("hour",e)}function h(r){return typeof r>"u"}function G(r){return typeof r=="number"}function mt(r){return typeof r=="number"&&r%1===0}function zn(r){return typeof r=="string"}function cs(r){return Object.prototype.toString.call(r)==="[object Date]"}function Ut(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Ht(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function us(r){return Array.isArray(r)?r:[r]}function Vr(r,e,t){if(r.length!==0)return r.reduce((n,s)=>{let a=[e(s),s];return n&&t(n[0],a[0])===n[0]?n:a},null)[1]}function ls(r,e){return e.reduce((t,n)=>(t[n]=r[n],t),{})}function ne(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function lt(r){if(r==null)return null;if(typeof r!="object")throw new x("Week settings must be an object");if(!N(r.firstDay,1,7)||!N(r.minimalDays,1,7)||!Array.isArray(r.weekend)||r.weekend.some(e=>!N(e,1,7)))throw new x("Invalid week settings");return{firstDay:r.firstDay,minimalDays:r.minimalDays,weekend:Array.from(r.weekend)}}function N(r,e,t){return mt(r)&&r>=e&&r<=t}function bo(r,e){return r-e*Math.floor(r/e)}function I(r,e=2){let t=r<0,n;return t?n="-"+(""+-r).padStart(e,"0"):n=(""+r).padStart(e,"0"),n}function Z(r){if(!(h(r)||r===null||r===""))return parseInt(r,10)}function se(r){if(!(h(r)||r===null||r===""))return parseFloat(r)}function ft(r){if(!(h(r)||r===null||r==="")){let e=parseFloat("0."+r)*1e3;return Math.floor(e)}}function Ce(r,e,t=!1){let n=10**e;return(t?Math.trunc:Math.round)(r*n)/n}function he(r){return r%4===0&&(r%100!==0||r%400===0)}function re(r){return he(r)?366:365}function Me(r,e){let t=bo(e-1,12)+1,n=r+(e-t)/12;return t===2?he(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function Ee(r){let e=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return r.year<100&&r.year>=0&&(e=new Date(e),e.setUTCFullYear(r.year,r.month-1,r.day)),+e}function os(r,e,t){return-Gt(Vt(r,1,e),t)+e-1}function me(r,e=4,t=1){let n=os(r,e,t),s=os(r+1,e,t);return(re(r)-n+s)/7}function pt(r){return r>99?r:r>y.twoDigitCutoffYear?1900+r:2e3+r}function jt(r,e,t,n=null){let s=new Date(r),a={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(a.timeZone=n);let i={timeZoneName:e,...a},o=new Intl.DateTimeFormat(t,i).formatToParts(s).find(c=>c.type.toLowerCase()==="timezonename");return o?o.value:null}function de(r,e){let t=parseInt(r,10);Number.isNaN(t)&&(t=0);let n=parseInt(e,10)||0,s=t<0||Object.is(t,-0)?-n:n;return t*60+s}function Gr(r){let e=Number(r);if(typeof r=="boolean"||r===""||Number.isNaN(e))throw new x(`Invalid unit value ${r}`);return e}function Ae(r,e){let t={};for(let n in r)if(ne(r,n)){let s=r[n];if(s==null)continue;t[e(n)]=Gr(s)}return t}function te(r,e){let t=Math.trunc(Math.abs(r/60)),n=Math.trunc(Math.abs(r%60)),s=r>=0?"+":"-";switch(e){case"short":return`${s}${I(t,2)}:${I(n,2)}`;case"narrow":return`${s}${t}${n>0?`:${n}`:""}`;case"techie":return`${s}${I(t,2)}${I(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function ht(r){return ls(r,["hour","minute","second","millisecond"])}var To=["January","February","March","April","May","June","July","August","September","October","November","December"],zr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Io=["J","F","M","A","M","J","J","A","S","O","N","D"];function Pr(r){switch(r){case"narrow":return[...Io];case"short":return[...zr];case"long":return[...To];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var $r=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Zr=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],xo=["M","T","W","T","F","S","S"];function Fr(r){switch(r){case"narrow":return[...xo];case"short":return[...Zr];case"long":return[...$r];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Rr=["AM","PM"],ko=["Before Christ","Anno Domini"],Oo=["BC","AD"],Eo=["B","A"];function _r(r){switch(r){case"narrow":return[...Eo];case"short":return[...Oo];case"long":return[...ko];default:return null}}function ds(r){return Rr[r.hour<12?0:1]}function ms(r,e){return Fr(e)[r.weekday-1]}function hs(r,e){return Pr(e)[r.month-1]}function fs(r,e){return _r(e)[r.year<0?0:1]}function Gn(r,e,t="always",n=!1){let s={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},a=["hours","minutes","seconds"].indexOf(r)===-1;if(t==="auto"&&a){let f=r==="days";switch(e){case 1:return f?"tomorrow":`next ${s[r][0]}`;case-1:return f?"yesterday":`last ${s[r][0]}`;case 0:return f?"today":`this ${s[r][0]}`;default:}}let i=Object.is(e,-0)||e<0,o=Math.abs(e),c=o===1,u=s[r],d=n?c?u[1]:u[2]||u[1]:c?s[r][0]:r;return i?`${o} ${d} ago`:`in ${o} ${d}`}function ps(r,e){let t="";for(let n of r)n.literal?t+=n.val:t+=e(n.val);return t}var Co={D:X,DD:Ve,DDD:Ge,DDDD:ze,t:$e,tt:Ze,ttt:Ke,tttt:Ye,T:Je,TT:Qe,TTT:Xe,TTTT:et,f:tt,ff:nt,fff:at,ffff:ot,F:rt,FF:st,FFF:it,FFFF:ct},C=class r{static create(e,t={}){return new r(e,t)}static parseFormat(e){let t=null,n="",s=!1,a=[];for(let i=0;i<e.length;i++){let o=e.charAt(i);o==="'"?(n.length>0&&a.push({literal:s||/^\s+$/.test(n),val:n}),t=null,n="",s=!s):s||o===t?n+=o:(n.length>0&&a.push({literal:/^\s+$/.test(n),val:n}),n=o,t=o)}return n.length>0&&a.push({literal:s||/^\s+$/.test(n),val:n}),a}static macroTokenToFormatOpts(e){return Co[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0){if(this.opts.forceSimple)return I(e,t);let n={...this.opts};return t>0&&(n.padTo=t),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,t){let n=this.loc.listingMode()==="en",s=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",a=(m,k)=>this.loc.extract(e,m,k),i=m=>e.isOffsetFixed&&e.offset===0&&m.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,m.format):"",o=()=>n?ds(e):a({hour:"numeric",hourCycle:"h12"},"dayperiod"),c=(m,k)=>n?hs(e,m):a(k?{month:m}:{month:m,day:"numeric"},"month"),u=(m,k)=>n?ms(e,m):a(k?{weekday:m}:{weekday:m,month:"long",day:"numeric"},"weekday"),d=m=>{let k=r.macroTokenToFormatOpts(m);return k?this.formatWithSystemDefault(e,k):m},f=m=>n?fs(e,m):a({era:m},"era"),g=m=>{switch(m){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return i({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return i({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return i({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return o();case"d":return s?a({day:"numeric"},"day"):this.num(e.day);case"dd":return s?a({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return u("short",!0);case"cccc":return u("long",!0);case"ccccc":return u("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return u("short",!1);case"EEEE":return u("long",!1);case"EEEEE":return u("narrow",!1);case"L":return s?a({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return s?a({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return c("short",!0);case"LLLL":return c("long",!0);case"LLLLL":return c("narrow",!0);case"M":return s?a({month:"numeric"},"month"):this.num(e.month);case"MM":return s?a({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return c("short",!1);case"MMMM":return c("long",!1);case"MMMMM":return c("narrow",!1);case"y":return s?a({year:"numeric"},"year"):this.num(e.year);case"yy":return s?a({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return s?a({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return s?a({year:"numeric"},"year"):this.num(e.year,6);case"G":return f("short");case"GG":return f("long");case"GGGGG":return f("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return d(m)}};return ps(r.parseFormat(t),g)}formatDurationFromString(e,t){let n=c=>{switch(c[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},s=c=>u=>{let d=n(u);return d?this.num(c.get(d),u.length):u},a=r.parseFormat(t),i=a.reduce((c,{literal:u,val:d})=>u?c:c.concat(d),[]),o=e.shiftTo(...i.map(n).filter(c=>c));return ps(a,s(o))}};var ys=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Ne(...r){let e=r.reduce((t,n)=>t+n.source,"");return RegExp(`^${e}$`)}function Pe(...r){return e=>r.reduce(([t,n,s],a)=>{let[i,o,c]=a(e,s);return[{...t,...i},o||n,c]},[{},null,1]).slice(0,2)}function Fe(r,...e){if(r==null)return[null,null];for(let[t,n]of e){let s=t.exec(r);if(s)return n(s)}return[null,null]}function ws(...r){return(e,t)=>{let n={},s;for(s=0;s<r.length;s++)n[r[s]]=Z(e[t+s]);return[n,null,t+s]}}var Ss=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,vo=`(?:${Ss.source}?(?:\\[(${ys.source})\\])?)?`,Kr=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,bs=RegExp(`${Kr.source}${vo}`),Yr=RegExp(`(?:T${bs.source})?`),Mo=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Ao=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Do=/(\d{4})-?(\d{3})/,No=ws("weekYear","weekNumber","weekDay"),Po=ws("year","ordinal"),Fo=/(\d{4})-(\d\d)-(\d\d)/,Ts=RegExp(`${Kr.source} ?(?:${Ss.source}|(${ys.source}))?`),Ro=RegExp(`(?: ${Ts.source})?`);function De(r,e,t){let n=r[e];return h(n)?t:Z(n)}function _o(r,e){return[{year:De(r,e),month:De(r,e+1,1),day:De(r,e+2,1)},null,e+3]}function Re(r,e){return[{hours:De(r,e,0),minutes:De(r,e+1,0),seconds:De(r,e+2,0),milliseconds:ft(r[e+3])},null,e+4]}function gt(r,e){let t=!r[e]&&!r[e+1],n=de(r[e+1],r[e+2]),s=t?null:O.instance(n);return[{},s,e+3]}function yt(r,e){let t=r[e]?M.create(r[e]):null;return[{},t,e+1]}var Wo=RegExp(`^T?${Kr.source}$`),jo=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Lo(r){let[e,t,n,s,a,i,o,c,u]=r,d=e[0]==="-",f=c&&c[0]==="-",g=(m,k=!1)=>m!==void 0&&(k||m&&d)?-m:m;return[{years:g(se(t)),months:g(se(n)),weeks:g(se(s)),days:g(se(a)),hours:g(se(i)),minutes:g(se(o)),seconds:g(se(c),c==="-0"),milliseconds:g(ft(u),f)}]}var Bo={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function Jr(r,e,t,n,s,a,i){let o={year:e.length===2?pt(Z(e)):Z(e),month:zr.indexOf(t)+1,day:Z(n),hour:Z(s),minute:Z(a)};return i&&(o.second=Z(i)),r&&(o.weekday=r.length>3?$r.indexOf(r)+1:Zr.indexOf(r)+1),o}var qo=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Uo(r){let[,e,t,n,s,a,i,o,c,u,d,f]=r,g=Jr(e,s,n,t,a,i,o),m;return c?m=Bo[c]:u?m=0:m=de(d,f),[g,new O(m)]}function Ho(r){return r.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var Vo=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Go=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,zo=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function gs(r){let[,e,t,n,s,a,i,o]=r;return[Jr(e,s,n,t,a,i,o),O.utcInstance]}function $o(r){let[,e,t,n,s,a,i,o]=r;return[Jr(e,o,t,n,s,a,i),O.utcInstance]}var Zo=Ne(Mo,Yr),Ko=Ne(Ao,Yr),Yo=Ne(Do,Yr),Jo=Ne(bs),Is=Pe(_o,Re,gt,yt),Qo=Pe(No,Re,gt,yt),Xo=Pe(Po,Re,gt,yt),ec=Pe(Re,gt,yt);function xs(r){return Fe(r,[Zo,Is],[Ko,Qo],[Yo,Xo],[Jo,ec])}function ks(r){return Fe(Ho(r),[qo,Uo])}function Os(r){return Fe(r,[Vo,gs],[Go,gs],[zo,$o])}function Es(r){return Fe(r,[jo,Lo])}var tc=Pe(Re);function Cs(r){return Fe(r,[Wo,tc])}var rc=Ne(Fo,Ro),nc=Ne(Ts),sc=Pe(Re,gt,yt);function vs(r){return Fe(r,[rc,Is],[nc,sc])}var Ms="Invalid Duration",Ds={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},ac={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...Ds},_=146097/400,_e=146097/4800,ic={years:{quarters:4,months:12,weeks:_/7,days:_,hours:_*24,minutes:_*24*60,seconds:_*24*60*60,milliseconds:_*24*60*60*1e3},quarters:{months:3,weeks:_/28,days:_/4,hours:_*24/4,minutes:_*24*60/4,seconds:_*24*60*60/4,milliseconds:_*24*60*60*1e3/4},months:{weeks:_e/7,days:_e,hours:_e*24,minutes:_e*24*60,seconds:_e*24*60*60,milliseconds:_e*24*60*60*1e3},...Ds},fe=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],oc=fe.slice(0).reverse();function ae(r,e,t=!1){let n={values:t?e.values:{...r.values,...e.values||{}},loc:r.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||r.conversionAccuracy,matrix:e.matrix||r.matrix};return new T(n)}function Ns(r,e){let t=e.milliseconds??0;for(let n of oc.slice(1))e[n]&&(t+=e[n]*r[n].milliseconds);return t}function As(r,e){let t=Ns(r,e)<0?-1:1;fe.reduceRight((n,s)=>{if(h(e[s]))return n;if(n){let a=e[n]*t,i=r[s][n],o=Math.floor(a/i);e[s]+=o*t,e[n]-=o*i*t}return s},null),fe.reduce((n,s)=>{if(h(e[s]))return n;if(n){let a=e[n]%1;e[n]-=a,e[s]+=a*r[n][s]}return s},null)}function cc(r){let e={};for(let[t,n]of Object.entries(r))n!==0&&(e[t]=n);return e}var T=class r{constructor(e){let t=e.conversionAccuracy==="longterm"||!1,n=t?ic:ac;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||b.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,t){return r.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new x(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new r({values:Ae(e,r.normalizeUnit),loc:b.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(G(e))return r.fromMillis(e);if(r.isDuration(e))return e;if(typeof e=="object")return r.fromObject(e);throw new x(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){let[n]=Es(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){let[n]=Cs(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new x("need to specify a reason the Duration is invalid");let n=e instanceof E?e:new E(e,t);if(y.throwOnInvalid)throw new _t(n);return new r({invalid:n})}static normalizeUnit(e){let t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new Oe(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){let n={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?C.create(this.loc,n).formatDurationFromString(this,e):Ms}toHuman(e={}){if(!this.isValid)return Ms;let t=fe.map(n=>{let s=this.values[n];return h(s)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(s)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(t)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Ce(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},p.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Ns(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e),n={};for(let s of fe)(ne(t.values,s)||ne(this.values,s))&&(n[s]=t.get(s)+this.get(s));return ae(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let n of Object.keys(this.values))t[n]=Gr(e(this.values[n],n));return ae(this,{values:t},!0)}get(e){return this[r.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let t={...this.values,...Ae(e,r.normalizeUnit)};return ae(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:n,matrix:s}={}){let i={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:s,conversionAccuracy:n};return ae(this,i)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return As(this.matrix,e),ae(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=cc(this.normalize().shiftToAll().toObject());return ae(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(i=>r.normalizeUnit(i));let t={},n={},s=this.toObject(),a;for(let i of fe)if(e.indexOf(i)>=0){a=i;let o=0;for(let u in n)o+=this.matrix[u][i]*n[u],n[u]=0;G(s[i])&&(o+=s[i]);let c=Math.trunc(o);t[i]=c,n[i]=(o*1e3-c*1e3)/1e3}else G(s[i])&&(n[i]=s[i]);for(let i in n)n[i]!==0&&(t[a]+=i===a?n[i]:n[i]/this.matrix[a][i]);return As(this.matrix,t),ae(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return ae(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(n,s){return n===void 0||n===0?s===void 0||s===0:n===s}for(let n of fe)if(!t(this.values[n],e.values[n]))return!1;return!0}};var We="Invalid Interval";function uc(r,e){return!r||!r.isValid?K.invalid("missing or invalid start"):!e||!e.isValid?K.invalid("missing or invalid end"):e<r?K.invalid("end before start",`The end of an interval must be after its start, but you had start=${r.toISO()} and end=${e.toISO()}`):null}var K=class r{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new x("need to specify a reason the Interval is invalid");let n=e instanceof E?e:new E(e,t);if(y.throwOnInvalid)throw new Rt(n);return new r({invalid:n})}static fromDateTimes(e,t){let n=je(e),s=je(t),a=uc(n,s);return a??new r({start:n,end:s})}static after(e,t){let n=T.fromDurationLike(t),s=je(e);return r.fromDateTimes(s,s.plus(n))}static before(e,t){let n=T.fromDurationLike(t),s=je(e);return r.fromDateTimes(s.minus(n),s)}static fromISO(e,t){let[n,s]=(e||"").split("/",2);if(n&&s){let a,i;try{a=p.fromISO(n,t),i=a.isValid}catch{i=!1}let o,c;try{o=p.fromISO(s,t),c=o.isValid}catch{c=!1}if(i&&c)return r.fromDateTimes(a,o);if(i){let u=T.fromISO(s,t);if(u.isValid)return r.after(a,u)}else if(c){let u=T.fromISO(n,t);if(u.isValid)return r.before(o,u)}}return r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",t){if(!this.isValid)return NaN;let n=this.start.startOf(e,t),s;return t?.useLocaleWeeks?s=this.end.reconfigure({locale:n.locale}):s=this.end,s=s.startOf(e,t),Math.floor(s.diff(n,e).get(e))+(s.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?r.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];let t=e.map(je).filter(i=>this.contains(i)).sort((i,o)=>i.toMillis()-o.toMillis()),n=[],{s}=this,a=0;for(;s<this.e;){let i=t[a]||this.e,o=+i>+this.e?this.e:i;n.push(r.fromDateTimes(s,o)),s=o,a+=1}return n}splitBy(e){let t=T.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s:n}=this,s=1,a,i=[];for(;n<this.e;){let o=this.start.plus(t.mapUnits(c=>c*s));a=+o>+this.e?this.e:o,i.push(r.fromDateTimes(n,a)),n=a,s+=1}return i}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let t=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return t>=n?null:r.fromDateTimes(t,n)}union(e){if(!this.isValid)return this;let t=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return r.fromDateTimes(t,n)}static merge(e){let[t,n]=e.sort((s,a)=>s.s-a.s).reduce(([s,a],i)=>a?a.overlaps(i)||a.abutsStart(i)?[s,a.union(i)]:[s.concat([a]),i]:[s,i],[[],null]);return n&&t.push(n),t}static xor(e){let t=null,n=0,s=[],a=e.map(c=>[{time:c.s,type:"s"},{time:c.e,type:"e"}]),i=Array.prototype.concat(...a),o=i.sort((c,u)=>c.time-u.time);for(let c of o)n+=c.type==="s"?1:-1,n===1?t=c.time:(t&&+t!=+c.time&&s.push(r.fromDateTimes(t,c.time)),t=null);return r.merge(s)}difference(...e){return r.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:We}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=X,t={}){return this.isValid?C.create(this.s.loc.clone(t),e).formatInterval(this):We}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:We}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:We}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:We}toFormat(e,{separator:t=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:We}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):T.invalid(this.invalidReason)}mapEndpoints(e){return r.fromDateTimes(e(this.s),e(this.e))}};var Y=class{static hasDST(e=y.defaultZone){let t=p.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return M.isValidZone(e)}static normalizeZone(e){return q(e,y.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||b.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||b.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||b.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null,outputCalendar:a="gregory"}={}){return(s||b.create(t,n,a)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null,outputCalendar:a="gregory"}={}){return(s||b.create(t,n,a)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null}={}){return(s||b.create(t,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null}={}){return(s||b.create(t,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return b.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return b.create(t,null,"gregory").eras(e)}static features(){return{relative:Ut(),localeWeek:Ht()}}};function Ps(r,e){let t=s=>s.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=t(e)-t(r);return Math.floor(T.fromMillis(n).as("days"))}function lc(r,e,t){let n=[["years",(c,u)=>u.year-c.year],["quarters",(c,u)=>u.quarter-c.quarter+(u.year-c.year)*4],["months",(c,u)=>u.month-c.month+(u.year-c.year)*12],["weeks",(c,u)=>{let d=Ps(c,u);return(d-d%7)/7}],["days",Ps]],s={},a=r,i,o;for(let[c,u]of n)t.indexOf(c)>=0&&(i=c,s[c]=u(r,e),o=a.plus(s),o>e?(s[c]--,r=a.plus(s),r>e&&(o=r,s[c]--,r=a.plus(s))):r=o);return[r,s,o,i]}function Fs(r,e,t,n){let[s,a,i,o]=lc(r,e,t),c=e-s,u=t.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);u.length===0&&(i<e&&(i=s.plus({[o]:1})),i!==s&&(a[o]=(a[o]||0)+c/(i-s)));let d=T.fromObject(a,n);return u.length>0?T.fromMillis(c,n).shiftTo(...u).plus(d):d}var Qr={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Rs={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},dc=Qr.hanidec.replace(/[\[|\]]/g,"").split("");function _s(r){let e=parseInt(r,10);if(isNaN(e)){e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(r[t].search(Qr.hanidec)!==-1)e+=dc.indexOf(r[t]);else for(let s in Rs){let[a,i]=Rs[s];n>=a&&n<=i&&(e+=n-a)}}return parseInt(e,10)}else return e}function W({numberingSystem:r},e=""){return new RegExp(`${Qr[r||"latn"]}${e}`)}var mc="missing Intl.DateTimeFormat.formatToParts support";function w(r,e=t=>t){return{regex:r,deser:([t])=>e(_s(t))}}var hc="\xA0",Ls=`[ ${hc}]`,Bs=new RegExp(Ls,"g");function fc(r){return r.replace(/\./g,"\\.?").replace(Bs,Ls)}function Ws(r){return r.replace(/\./g,"").replace(Bs," ").toLowerCase()}function U(r,e){return r===null?null:{regex:RegExp(r.map(fc).join("|")),deser:([t])=>r.findIndex(n=>Ws(t)===Ws(n))+e}}function js(r,e){return{regex:r,deser:([,t,n])=>de(t,n),groups:e}}function $t(r){return{regex:r,deser:([e])=>e}}function pc(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function gc(r,e){let t=W(e),n=W(e,"{2}"),s=W(e,"{3}"),a=W(e,"{4}"),i=W(e,"{6}"),o=W(e,"{1,2}"),c=W(e,"{1,3}"),u=W(e,"{1,6}"),d=W(e,"{1,9}"),f=W(e,"{2,4}"),g=W(e,"{4,6}"),m=V=>({regex:RegExp(pc(V.val)),deser:([Te])=>Te,literal:!0}),be=(V=>{if(r.literal)return m(V);switch(V.val){case"G":return U(e.eras("short"),0);case"GG":return U(e.eras("long"),0);case"y":return w(u);case"yy":return w(f,pt);case"yyyy":return w(a);case"yyyyy":return w(g);case"yyyyyy":return w(i);case"M":return w(o);case"MM":return w(n);case"MMM":return U(e.months("short",!0),1);case"MMMM":return U(e.months("long",!0),1);case"L":return w(o);case"LL":return w(n);case"LLL":return U(e.months("short",!1),1);case"LLLL":return U(e.months("long",!1),1);case"d":return w(o);case"dd":return w(n);case"o":return w(c);case"ooo":return w(s);case"HH":return w(n);case"H":return w(o);case"hh":return w(n);case"h":return w(o);case"mm":return w(n);case"m":return w(o);case"q":return w(o);case"qq":return w(n);case"s":return w(o);case"ss":return w(n);case"S":return w(c);case"SSS":return w(s);case"u":return $t(d);case"uu":return $t(o);case"uuu":return w(t);case"a":return U(e.meridiems(),0);case"kkkk":return w(a);case"kk":return w(f,pt);case"W":return w(o);case"WW":return w(n);case"E":case"c":return w(t);case"EEE":return U(e.weekdays("short",!1),1);case"EEEE":return U(e.weekdays("long",!1),1);case"ccc":return U(e.weekdays("short",!0),1);case"cccc":return U(e.weekdays("long",!0),1);case"Z":case"ZZ":return js(new RegExp(`([+-]${o.source})(?::(${n.source}))?`),2);case"ZZZ":return js(new RegExp(`([+-]${o.source})(${n.source})?`),2);case"z":return $t(/[a-z_+-/]{1,256}?/i);case" ":return $t(/[^\S\n\r]/);default:return m(V)}})(r)||{invalidReason:mc};return be.token=r,be}var yc={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function wc(r,e,t){let{type:n,value:s}=r;if(n==="literal"){let c=/^\s+$/.test(s);return{literal:!c,val:c?" ":s}}let a=e[n],i=n;n==="hour"&&(e.hour12!=null?i=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?i="hour12":i="hour24":i=t.hour12?"hour12":"hour24");let o=yc[i];if(typeof o=="object"&&(o=o[a]),o)return{literal:!1,val:o}}function Sc(r){return[`^${r.map(t=>t.regex).reduce((t,n)=>`${t}(${n.source})`,"")}$`,r]}function bc(r,e,t){let n=r.match(e);if(n){let s={},a=1;for(let i in t)if(ne(t,i)){let o=t[i],c=o.groups?o.groups+1:1;!o.literal&&o.token&&(s[o.token.val[0]]=o.deser(n.slice(a,a+c))),a+=c}return[n,s]}else return[n,{}]}function Tc(r){let e=a=>{switch(a){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},t=null,n;return h(r.z)||(t=M.create(r.z)),h(r.Z)||(t||(t=new O(r.Z)),n=r.Z),h(r.q)||(r.M=(r.q-1)*3+1),h(r.h)||(r.h<12&&r.a===1?r.h+=12:r.h===12&&r.a===0&&(r.h=0)),r.G===0&&r.y&&(r.y=-r.y),h(r.u)||(r.S=ft(r.u)),[Object.keys(r).reduce((a,i)=>{let o=e(i);return o&&(a[o]=r[i]),a},{}),t,n]}var Xr=null;function Ic(){return Xr||(Xr=p.fromMillis(1555555555555)),Xr}function xc(r,e){if(r.literal)return r;let t=C.macroTokenToFormatOpts(r.val),n=rn(t,e);return n==null||n.includes(void 0)?r:n}function en(r,e){return Array.prototype.concat(...r.map(t=>xc(t,e)))}function tn(r,e,t){let n=en(C.parseFormat(t),r),s=n.map(i=>gc(i,r)),a=s.find(i=>i.invalidReason);if(a)return{input:e,tokens:n,invalidReason:a.invalidReason};{let[i,o]=Sc(s),c=RegExp(i,"i"),[u,d]=bc(e,c,o),[f,g,m]=d?Tc(d):[null,null,void 0];if(ne(d,"a")&&ne(d,"H"))throw new j("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:c,rawMatches:u,matches:d,result:f,zone:g,specificOffset:m}}}function qs(r,e,t){let{result:n,zone:s,specificOffset:a,invalidReason:i}=tn(r,e,t);return[n,s,a,i]}function rn(r,e){if(!r)return null;let n=C.create(e,r).dtFormatter(Ic()),s=n.formatToParts(),a=n.resolvedOptions();return s.map(i=>wc(i,r,a))}var nn="Invalid DateTime",Us=864e13;function Zt(r){return new E("unsupported zone",`the zone "${r.name}" is not supported`)}function sn(r){return r.weekData===null&&(r.weekData=dt(r.c)),r.weekData}function an(r){return r.localWeekData===null&&(r.localWeekData=dt(r.c,r.loc.getMinDaysInFirstWeek(),r.loc.getStartOfWeek())),r.localWeekData}function pe(r,e){let t={ts:r.ts,zone:r.zone,c:r.c,o:r.o,loc:r.loc,invalid:r.invalid};return new p({...t,...e,old:t})}function Ks(r,e,t){let n=r-e*60*1e3,s=t.offset(n);if(e===s)return[n,e];n-=(s-e)*60*1e3;let a=t.offset(n);return s===a?[n,s]:[r-Math.min(s,a)*60*1e3,Math.max(s,a)]}function Kt(r,e){r+=e*60*1e3;let t=new Date(r);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function Jt(r,e,t){return Ks(Ee(r),e,t)}function Hs(r,e){let t=r.o,n=r.c.year+Math.trunc(e.years),s=r.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,a={...r.c,year:n,month:s,day:Math.min(r.c.day,Me(n,s))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},i=T.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),o=Ee(a),[c,u]=Ks(o,t,r.zone);return i!==0&&(c+=i,u=r.zone.offset(c)),{ts:c,o:u}}function wt(r,e,t,n,s,a){let{setZone:i,zone:o}=t;if(r&&Object.keys(r).length!==0||e){let c=e||o,u=p.fromObject(r,{...t,zone:c,specificOffset:a});return i?u:u.setZone(o)}else return p.invalid(new E("unparsable",`the input "${s}" can't be parsed as ${n}`))}function Yt(r,e,t=!0){return r.isValid?C.create(b.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(r,e):null}function on(r,e){let t=r.c.year>9999||r.c.year<0,n="";return t&&r.c.year>=0&&(n+="+"),n+=I(r.c.year,t?6:4),e?(n+="-",n+=I(r.c.month),n+="-",n+=I(r.c.day)):(n+=I(r.c.month),n+=I(r.c.day)),n}function Vs(r,e,t,n,s,a){let i=I(r.c.hour);return e?(i+=":",i+=I(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(i+=":")):i+=I(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(i+=I(r.c.second),(r.c.millisecond!==0||!n)&&(i+=".",i+=I(r.c.millisecond,3))),s&&(r.isOffsetFixed&&r.offset===0&&!a?i+="Z":r.o<0?(i+="-",i+=I(Math.trunc(-r.o/60)),i+=":",i+=I(Math.trunc(-r.o%60))):(i+="+",i+=I(Math.trunc(r.o/60)),i+=":",i+=I(Math.trunc(r.o%60)))),a&&(i+="["+r.zone.ianaName+"]"),i}var Ys={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},kc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Oc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Js=["year","month","day","hour","minute","second","millisecond"],Ec=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Cc=["year","ordinal","hour","minute","second","millisecond"];function vc(r){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[r.toLowerCase()];if(!e)throw new Oe(r);return e}function Gs(r){switch(r.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return vc(r)}}function zs(r,e){let t=q(e.zone,y.defaultZone),n=b.fromObject(e),s=y.now(),a,i;if(h(r.year))a=s;else{for(let u of Js)h(r[u])&&(r[u]=Ys[u]);let o=Ur(r)||Hr(r);if(o)return p.invalid(o);let c=t.offset(s);[a,i]=Jt(r,c,t)}return new p({ts:a,zone:t,loc:n,o:i})}function $s(r,e,t){let n=h(t.round)?!0:t.round,s=(i,o)=>(i=Ce(i,n||t.calendary?0:2,!0),e.loc.clone(t).relFormatter(t).format(i,o)),a=i=>t.calendary?e.hasSame(r,i)?0:e.startOf(i).diff(r.startOf(i),i).get(i):e.diff(r,i).get(i);if(t.unit)return s(a(t.unit),t.unit);for(let i of t.units){let o=a(i);if(Math.abs(o)>=1)return s(o,i)}return s(r>e?-0:0,t.units[t.units.length-1])}function Zs(r){let e={},t;return r.length>0&&typeof r[r.length-1]=="object"?(e=r[r.length-1],t=Array.from(r).slice(0,r.length-1)):t=Array.from(r),[e,t]}var p=class r{constructor(e){let t=e.zone||y.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new E("invalid input"):null)||(t.isValid?null:Zt(t));this.ts=h(e.ts)?y.now():e.ts;let s=null,a=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[s,a]=[e.old.c,e.old.o];else{let o=t.offset(this.ts);s=Kt(this.ts,o),n=Number.isNaN(s.year)?new E("invalid input"):null,s=n?null:s,a=n?null:o}this._zone=t,this.loc=e.loc||b.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=s,this.o=a,this.isLuxonDateTime=!0}static now(){return new r({})}static local(){let[e,t]=Zs(arguments),[n,s,a,i,o,c,u]=t;return zs({year:n,month:s,day:a,hour:i,minute:o,second:c,millisecond:u},e)}static utc(){let[e,t]=Zs(arguments),[n,s,a,i,o,c,u]=t;return e.zone=O.utcInstance,zs({year:n,month:s,day:a,hour:i,minute:o,second:c,millisecond:u},e)}static fromJSDate(e,t={}){let n=cs(e)?e.valueOf():NaN;if(Number.isNaN(n))return r.invalid("invalid input");let s=q(t.zone,y.defaultZone);return s.isValid?new r({ts:n,zone:s,loc:b.fromObject(t)}):r.invalid(Zt(s))}static fromMillis(e,t={}){if(G(e))return e<-Us||e>Us?r.invalid("Timestamp out of range"):new r({ts:e,zone:q(t.zone,y.defaultZone),loc:b.fromObject(t)});throw new x(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(G(e))return new r({ts:e*1e3,zone:q(t.zone,y.defaultZone),loc:b.fromObject(t)});throw new x("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};let n=q(t.zone,y.defaultZone);if(!n.isValid)return r.invalid(Zt(n));let s=b.fromObject(t),a=Ae(e,Gs),{minDaysInFirstWeek:i,startOfWeek:o}=qr(a,s),c=y.now(),u=h(t.specificOffset)?n.offset(c):t.specificOffset,d=!h(a.ordinal),f=!h(a.year),g=!h(a.month)||!h(a.day),m=f||g,k=a.weekYear||a.weekNumber;if((m||d)&&k)throw new j("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(g&&d)throw new j("Can't mix ordinal dates with month/day");let be=k||a.weekday&&!m,V,Te,Ue=Kt(c,u);be?(V=Ec,Te=kc,Ue=dt(Ue,i,o)):d?(V=Cc,Te=Oc,Ue=zt(Ue)):(V=Js,Te=Ys);let Ln=!1;for(let He of V){let Yi=a[He];h(Yi)?Ln?a[He]=Te[He]:a[He]=Ue[He]:Ln=!0}let zi=be?as(a,i,o):d?is(a):Ur(a),Bn=zi||Hr(a);if(Bn)return r.invalid(Bn);let $i=be?Lr(a,i,o):d?Br(a):a,[Zi,Ki]=Jt($i,u,n),Ir=new r({ts:Zi,zone:n,o:Ki,loc:s});return a.weekday&&m&&e.weekday!==Ir.weekday?r.invalid("mismatched weekday",`you can't specify both a weekday of ${a.weekday} and a date of ${Ir.toISO()}`):Ir}static fromISO(e,t={}){let[n,s]=xs(e);return wt(n,s,t,"ISO 8601",e)}static fromRFC2822(e,t={}){let[n,s]=ks(e);return wt(n,s,t,"RFC 2822",e)}static fromHTTP(e,t={}){let[n,s]=Os(e);return wt(n,s,t,"HTTP",t)}static fromFormat(e,t,n={}){if(h(e)||h(t))throw new x("fromFormat requires an input string and a format");let{locale:s=null,numberingSystem:a=null}=n,i=b.fromOpts({locale:s,numberingSystem:a,defaultToEN:!0}),[o,c,u,d]=qs(i,e,t);return d?r.invalid(d):wt(o,c,n,`format ${t}`,e,u)}static fromString(e,t,n={}){return r.fromFormat(e,t,n)}static fromSQL(e,t={}){let[n,s]=vs(e);return wt(n,s,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new x("need to specify a reason the DateTime is invalid");let n=e instanceof E?e:new E(e,t);if(y.throwOnInvalid)throw new Ft(n);return new r({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let n=rn(e,b.fromObject(t));return n?n.map(s=>s?s.val:null).join(""):null}static expandFormat(e,t={}){return en(C.parseFormat(e),b.fromObject(t)).map(s=>s.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?sn(this).weekYear:NaN}get weekNumber(){return this.isValid?sn(this).weekNumber:NaN}get weekday(){return this.isValid?sn(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?an(this).weekday:NaN}get localWeekNumber(){return this.isValid?an(this).weekNumber:NaN}get localWeekYear(){return this.isValid?an(this).weekYear:NaN}get ordinal(){return this.isValid?zt(this.c).ordinal:NaN}get monthShort(){return this.isValid?Y.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Y.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Y.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Y.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,t=6e4,n=Ee(this.c),s=this.zone.offset(n-e),a=this.zone.offset(n+e),i=this.zone.offset(n-s*t),o=this.zone.offset(n-a*t);if(i===o)return[this];let c=n-i*t,u=n-o*t,d=Kt(c,i),f=Kt(u,o);return d.hour===f.hour&&d.minute===f.minute&&d.second===f.second&&d.millisecond===f.millisecond?[pe(this,{ts:c}),pe(this,{ts:u})]:[this]}get isInLeapYear(){return he(this.year)}get daysInMonth(){return Me(this.year,this.month)}get daysInYear(){return this.isValid?re(this.year):NaN}get weeksInWeekYear(){return this.isValid?me(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?me(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:n,calendar:s}=C.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:n,outputCalendar:s}}toUTC(e=0,t={}){return this.setZone(O.instance(e),t)}toLocal(){return this.setZone(y.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:n=!1}={}){if(e=q(e,y.defaultZone),e.equals(this.zone))return this;if(e.isValid){let s=this.ts;if(t||n){let a=e.offset(this.ts),i=this.toObject();[s]=Jt(i,a,e)}return pe(this,{ts:s,zone:e})}else return r.invalid(Zt(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:n}={}){let s=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:n});return pe(this,{loc:s})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=Ae(e,Gs),{minDaysInFirstWeek:n,startOfWeek:s}=qr(t,this.loc),a=!h(t.weekYear)||!h(t.weekNumber)||!h(t.weekday),i=!h(t.ordinal),o=!h(t.year),c=!h(t.month)||!h(t.day),u=o||c,d=t.weekYear||t.weekNumber;if((u||i)&&d)throw new j("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&i)throw new j("Can't mix ordinal dates with month/day");let f;a?f=Lr({...dt(this.c,n,s),...t},n,s):h(t.ordinal)?(f={...this.toObject(),...t},h(t.day)&&(f.day=Math.min(Me(f.year,f.month),f.day))):f=Br({...zt(this.c),...t});let[g,m]=Jt(f,this.o,this.zone);return pe(this,{ts:g,o:m})}plus(e){if(!this.isValid)return this;let t=T.fromDurationLike(e);return pe(this,Hs(this,t))}minus(e){if(!this.isValid)return this;let t=T.fromDurationLike(e).negate();return pe(this,Hs(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;let n={},s=T.normalizeUnit(e);switch(s){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break;case"milliseconds":break}if(s==="weeks")if(t){let a=this.loc.getStartOfWeek(),{weekday:i}=this;i<a&&(n.weekNumber=this.weekNumber-1),n.weekday=a}else n.weekday=1;if(s==="quarters"){let a=Math.ceil(this.month/3);n.month=(a-1)*3+1}return this.set(n)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?C.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):nn}toLocaleString(e=X,t={}){return this.isValid?C.create(this.loc.clone(t),e).formatDateTime(this):nn}toLocaleParts(e={}){return this.isValid?C.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:n=!1,includeOffset:s=!0,extendedZone:a=!1}={}){if(!this.isValid)return null;let i=e==="extended",o=on(this,i);return o+="T",o+=Vs(this,i,t,n,s,a),o}toISODate({format:e="extended"}={}){return this.isValid?on(this,e==="extended"):null}toISOWeekDate(){return Yt(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:n=!0,includePrefix:s=!1,extendedZone:a=!1,format:i="extended"}={}){return this.isValid?(s?"T":"")+Vs(this,i==="extended",t,e,n,a):null}toRFC2822(){return Yt(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Yt(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?on(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:n=!0}={}){let s="HH:mm:ss.SSS";return(t||e)&&(n&&(s+=" "),t?s+="z":e&&(s+="ZZ")),Yt(this,s,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():nn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",n={}){if(!this.isValid||!e.isValid)return T.invalid("created by diffing an invalid DateTime");let s={locale:this.locale,numberingSystem:this.numberingSystem,...n},a=us(t).map(T.normalizeUnit),i=e.valueOf()>this.valueOf(),o=i?this:e,c=i?e:this,u=Fs(o,c,a,s);return i?u.negate():u}diffNow(e="milliseconds",t={}){return this.diff(r.now(),e,t)}until(e){return this.isValid?K.fromDateTimes(this,e):this}hasSame(e,t,n){if(!this.isValid)return!1;let s=e.valueOf(),a=this.setZone(e.zone,{keepLocalTime:!0});return a.startOf(t,n)<=s&&s<=a.endOf(t,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let t=e.base||r.fromObject({},{zone:this.zone}),n=e.padding?this<t?-e.padding:e.padding:0,s=["years","months","days","hours","minutes","seconds"],a=e.unit;return Array.isArray(e.unit)&&(s=e.unit,a=void 0),$s(t,this.plus(n),{...e,numeric:"always",units:s,unit:a})}toRelativeCalendar(e={}){return this.isValid?$s(e.base||r.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(r.isDateTime))throw new x("min requires all arguments be DateTimes");return Vr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(r.isDateTime))throw new x("max requires all arguments be DateTimes");return Vr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,n={}){let{locale:s=null,numberingSystem:a=null}=n,i=b.fromOpts({locale:s,numberingSystem:a,defaultToEN:!0});return tn(i,e,t)}static fromStringExplain(e,t,n={}){return r.fromFormatExplain(e,t,n)}static get DATE_SHORT(){return X}static get DATE_MED(){return Ve}static get DATE_MED_WITH_WEEKDAY(){return xr}static get DATE_FULL(){return Ge}static get DATE_HUGE(){return ze}static get TIME_SIMPLE(){return $e}static get TIME_WITH_SECONDS(){return Ze}static get TIME_WITH_SHORT_OFFSET(){return Ke}static get TIME_WITH_LONG_OFFSET(){return Ye}static get TIME_24_SIMPLE(){return Je}static get TIME_24_WITH_SECONDS(){return Qe}static get TIME_24_WITH_SHORT_OFFSET(){return Xe}static get TIME_24_WITH_LONG_OFFSET(){return et}static get DATETIME_SHORT(){return tt}static get DATETIME_SHORT_WITH_SECONDS(){return rt}static get DATETIME_MED(){return nt}static get DATETIME_MED_WITH_SECONDS(){return st}static get DATETIME_MED_WITH_WEEKDAY(){return kr}static get DATETIME_FULL(){return at}static get DATETIME_FULL_WITH_SECONDS(){return it}static get DATETIME_HUGE(){return ot}static get DATETIME_HUGE_WITH_SECONDS(){return ct}};function je(r){if(p.isDateTime(r))return r;if(r&&r.valueOf&&G(r.valueOf()))return p.fromJSDate(r);if(r&&typeof r=="object")return p.fromObject(r);throw new x(`Unknown datetime argument: ${r}, of type ${typeof r}`)}var bt=require("@mysten/sui.js/transactions"),hn=require("@mysten/sui.js/transactions"),It=require("@mysten/sui.js/utils"),fn=require("buffer"),Xa=require("@mysten/sui.js/utils"),In=require("@mysten/sui.js/bcs"),xt=require("@mysten/sui.js/utils");var Qs=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var yn=require("@mysten/sui.js/transactions"),ue=require("@mysten/sui.js/utils");var Tt=require("@mysten/sui.js/transactions"),kt=require("@mysten/sui.js/utils");var pi=Ie(Qt(),1),gi=require("@msafe/sui3-utils"),yi=require("@msafe/sui3-utils"),wi=require("@msafe/sui3-utils"),Tn=require("@mysten/sui.js/bcs"),ce=require("@mysten/sui.js/utils"),bi=require("@msafe/sui3-utils"),Be=require("@msafe/sui3-utils"),Ti=require("@msafe/sui3-utils"),Ii=Ie(Qt(),1),ki=require("@msafe/sui3-utils"),Ei=require("@msafe/sui3-utils"),Ci=require("@mysten/sui.js/transactions"),sr=require("@msafe/sui3-utils"),Mi=require("@mysten/sui.js/transactions"),ar=require("@mysten/sui.js/utils"),vm=Ie(Qt(),1),Bc=Object.defineProperty,Da=(r,e)=>{for(var t in e)Bc(r,t,{get:e[t],enumerable:!0})},Pa={};Da(Pa,{contractId:()=>_a,default:()=>qc,feeObjId:()=>La,roleObjId:()=>Wa,status:()=>Ra,transaction:()=>Fa,upgradeCapObjId:()=>Ba,vaultObjId:()=>ja});var Fa="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Ra="success",_a="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Wa="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",ja="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",La="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Ba="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",qc={transaction:Fa,status:Ra,contractId:_a,roleObjId:Wa,vaultObjId:ja,feeObjId:La,upgradeCapObjId:Ba},qa={};Da(qa,{contractId:()=>Va,default:()=>Uc,feeObjId:()=>$a,roleObjId:()=>Ga,status:()=>Ha,transaction:()=>Ua,upgradeCapObjId:()=>Za,vaultObjId:()=>za});var Ua="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Ha="success",Va="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Ga="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",za="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",$a="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Za="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Uc={transaction:Ua,status:Ha,contractId:Va,roleObjId:Ga,vaultObjId:za,feeObjId:$a,upgradeCapObjId:Za},Hc="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Vc="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Gc="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",zc="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",$c="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Zc="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Kc="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Yc="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",la=Pa,da=qa,Jc=new Map([["dev",{env:"dev",rpc:{url:Hc},backend:{url:$c},contract:la}],["stg",{env:"stg",rpc:{url:Vc},backend:{url:Zc},contract:la}],["prev",{env:"prev",rpc:{url:Gc},backend:{url:Kc},contract:da}],["prod",{env:"prod",rpc:{url:zc},backend:{url:Yc},contract:da}]]);function Qc(r,e){let t=Jc.get(r);if(!t)throw new Error(`Env not supported: ${r}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}var F=class extends Error{mpayErrorCode;context;constructor(r,e,t={}){let{cause:n,context:s}=t;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=r,this.context=s}},Xc=class extends F{constructor(){super(11,"Backend is not specified")}},eu=class extends F{constructor(){super(1,"Wallet not connected")}},ln=class extends F{constructor(r,e){super(10,r,{context:e})}},tu=class ye{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof J.AxiosError)throw new ln(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new ln(e.data.code)}throw new ln(e.status.toString())}async getIncomingStreams(e,t){let n=await J.default.post(`${this.apiURL}/stream`,{recipient:e,...t});return ye.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await J.default.post(`${this.apiURL}/stream`,{sender:e,...t});return ye.parseResponseData(n)}async getStreamHistory(e){let t=await J.default.post(`${this.apiURL}/stream-events`,e),n=ye.parseResponseData(t);return n.data.forEach(s=>{let a=s;return a.data.type==="create_stream"?a.data.balance=BigInt(a.data.balance):a.data.type==="cancel_stream"?a.data.withdrawAmount=BigInt(a.data.withdrawAmount):a.data.type==="claim"||a.data.type==="auto_claim"?a.data.claimAmount=BigInt(a.data.claimAmount):a.data.type==="set_auto_claim"&&(a.data.enabled=!!a.data.enabled),a.createdAt=new Date(a.createdAt),a}),n}async getAllCoinTypes(e){let t=await J.default.post(`${this.apiURL}/stream-info`,{address:e});return ye.parseResponseData(t)}async getAllRecipients(e,t){let n=await J.default.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return ye.parseResponseData(n)}async getAllSenders(e,t){let n=await J.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return ye.parseResponseData(n)}},Ya=class Ja{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Ka.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new tu(e.backend.url))}static new(e,t){let n=Qc(e,t);return new Ja(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Xc;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new eu;return this.signer}async walletAddress(){return this.wallet.address()}},ma=50n,dn=10000n,ru=25n,ha=100000000n,ge=class{constructor(r){this.object=r}moveArg(r){return r.object(this.object)}},fa=class{constructor(r){this.objects=r}moveArgs(r){return r.makeMoveVec({objects:this.objects.map(e=>r.object(e))})}},tr=class Qa{constructor(e){return this.result=e,new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,n){if(n in t)return Reflect.get(t,n);let s=i=>new Qa(t.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield s(i),i++};if(typeof n=="symbol")return;let a=parseInt(n,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}moveArg(){return this.result}},pa=class extends F{constructor(r,e){super(3,r,{context:e})}},nu=class{constructor(r){this.results=r}callResult(r){return this.results.results[r]}returnValue(r,e){return r.returnValues[e]}getValue(r=0,e=0){let t=this.callResult(r);return this.returnValue(t,e)}getAddress(r=0,e=0){let[t,n]=this.getValue(r,e);if(n!=="address")throw new pa("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return(0,Xa.normalizeSuiAddress)(fn.Buffer.from(t).toString("hex"))}getU64(r=0,e=0){let[t,n]=this.getValue(r,e);if(n!=="u64")throw new pa("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return fn.Buffer.from(t).readBigInt64LE()}},P=class extends F{constructor(r,e,t){super(2,`Invalid input: ${r}`,{context:{fieldKey:e,fieldValue:t}})}},ei={groupId:"string",name:"string"},su=64;function au(r){return ti(r),In.bcs.ser(ei,r).toString("base64")}function pn(r){let e=In.bcs.de(ei,r,"base64");return ti(e),e}function ti(r){if(!ga(r.name))throw new P("Invalid metadata: Name contains unknown character");if(!ga(r.groupId))throw new P("Invalid metadata: Group ID contains unknown character");if(r.name.length>su)throw new P("Invalid metadata: Name exceed max length 64")}function ga(r){return/^[\x00-\x7F]+$/.test(r)}function ri(r,e){return(0,xt.normalizeStructTag)(r)===(0,xt.normalizeStructTag)(e)}function Le(r,e){return(0,xt.normalizeStructTag)(r)===(0,xt.normalizeStructTag)(e)}var ni="txn.gas";function iu(){return Qs()}var gn=class si{constructor(e,t,n){this.globals=e,this.feeContract=t,this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:au({name:e.name,groupId:iu()}),coinType:(0,It.normalizeStructTag)(e.coinType),recipients:e.recipients.map(t=>({address:t.address,cliffAmount:t.cliffAmount,amountPerEpoch:t.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let t=new hn.TransactionBlock,n=this.calculateFeesInternal(e),s=this.getCreateStreamCoinRequests(e,n),a=await this.wallet.requestCoins(s),i=await this.addMergeCoins(t,a[0]),o;s.length>1?o=await this.addMergeCoins(t,a[1]):o=i;for(let c=0;c<e.recipients.length;c++){let u=e.recipients[c],d=this.amountForRecipient(u,e.numberEpoch),f=this.getStreamFeeLocal(d),[g]=t.splitCoins(i,[t.pure(d+f,"u64")]),[m]=t.splitCoins(o,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new tr(g),flatFeeCoin:new tr(m),metadata:e.metadata,recipient:u.address,timeStart:e.startTime,cliff:u.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:u.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=si.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:ma,denominator:dn},claimFeePercent:{numerator:ru,denominator:dn},flatFeePerStream:ha}}async addMergeCoins(e,t){let n;return t.mergedCoins&&t.mergedCoins.length?(e.mergeCoins(e.object(t.primaryCoin),t.mergedCoins.map(s=>e.object(s))),n=e.object(t.primaryCoin)):t.primaryCoin===ni?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return ri(n,It.SUI_TYPE_ARG)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:It.SUI_TYPE_ARG,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((n,s)=>{let a=this.amountForRecipient(s,e.numberEpoch),i=this.getStreamFeeLocal(a);return{totalAmount:n.totalAmount+a,streamFeeAmount:n.streamFeeAmount+i}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return ha}getStreamFeeLocal(e){return e*ma/dn}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new hn.TransactionBlock,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new nu(n).getU64()}get wallet(){return this.globals.wallet}},ou="0x0000000000000000000000000000000000000000000000000000000000000006",ai=class{constructor(r,e,t){this.moduleName=r,this.config=e,this.globals=t}addContractCall(r,e){let t=`${this.config.contractId}::${this.moduleName}::${e.method}`;return r.add(yn.Transactions.MoveCall({target:t,arguments:e.arguments.map(n=>n instanceof fa?n.moveArgs(r):n instanceof ge?n.moveArg(r):n instanceof tr?n.moveArg():r.pure(n)),typeArguments:e.typeArgs})),r}addTransactionBlock(r,e,t=[],n=[]){r.add(yn.Transactions.MoveCall({target:e,arguments:t.map(s=>s instanceof fa?s.moveArgs(r):s instanceof ge?s.moveArg(r):s instanceof tr?s.moveArg():r.pure(s)),typeArguments:n}))}makeObject(r){return typeof r=="string"?new ge(r):r}vaultObject(){return new ge(this.config.vaultObjId)}roleObject(){return new ge(this.config.roleObjId)}feeObject(){return new ge(this.config.feeObjId)}clockObject(){return new ge(ou)}},ii=class ie extends ai{constructor(e,t){super(ie.ModuleName,e,t),this.config=e,this.globals=t}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:ie.MethodName.set_streaming_fee,arguments:[n,s,t],typeArgs:[]})}setStreamingFlatFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:ie.MethodName.set_streaming_flat_fee,arguments:[n,s,t],typeArgs:[]})}setClaimFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:ie.MethodName.set_claim_fee,arguments:[n,s,t],typeArgs:[]})}streamingFee(e,t){let n=this.feeObject();return this.addContractCall(e,{method:ie.MethodName.streaming_fee,arguments:[n,t],typeArgs:[]})}claimFee(e,t){return this.addContractCall(e,{method:ie.MethodName.claim_fee,arguments:[this.feeObject(),t],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:ie.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},nr=class v extends ai{constructor(e,t){super(v.ModuleName,e,t),this.config=e,this.globals=t}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,t){let n=this.feeObject(),s=this.vaultObject(),a=this.makeObject(t.paymentCoin),i=this.makeObject(t.flatFeeCoin),o=this.clockObject();return this.addContractCall(e,{method:v.MethodName.create_stream,arguments:[n,s,a,i,t.metadata,t.recipient,t.timeStart,t.cliff,t.epochInterval,t.numEpoch,t.amountPerEpoch,t.cancelable,o],typeArgs:[t.coinType]})}setAutoClaim(e,t){let n=this.makeObject(t.streamId);return this.addContractCall(e,{method:v.MethodName.set_auto_claim,arguments:[n,t.enabled],typeArgs:[t.coinType]})}cancelStream(e,t){let n=this.makeObject(t.streamId),s=this.clockObject();return this.addContractCall(e,{method:v.MethodName.cancel_stream,arguments:[n,s],typeArgs:[t.coinType]})}claimStream(e,t){let n=this.makeObject(t.streamId),s=this.clockObject();return this.addContractCall(e,{method:v.MethodName.claim_stream,arguments:[n,s],typeArgs:[t.coinType]})}claimStreamByProxy(e,t){let n=this.makeObject(t.streamId),s=this.vaultObject(),a=this.feeObject(),i=this.clockObject();return this.addContractCall(e,{method:v.MethodName.claim_stream_by_proxy,arguments:[n,s,a,i],typeArgs:[t.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.claim_stream_by_proxy}`}},oi=class{constructor(r){this.globals=r;let e=r.envConfig.contract;this.feeContract=new ii(e,r),this.streamContract=new nr(e,r)}feeContract;streamContract;async createStreams(r){let e=gn.convertCreateStreamInfoToInternal(r);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new gn(this.globals,this.feeContract,this.streamContract)}setAutoClaim(r,e,t){let n=new bt.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:r,enabled:e,coinType:t})}claimStream(r,e){let t=new bt.TransactionBlock;return this.streamContract.claimStream(t,{streamId:r,coinType:e})}claimStreamByProxy(r,e){let t=new bt.TransactionBlock;return this.streamContract.claimStreamByProxy(t,{streamId:r,coinType:e})}cancelStream(r,e){let t=new bt.TransactionBlock;return this.streamContract.cancelStream(t,{streamId:r,coinType:e}),t}},cu=class extends F{constructor(r,e){super(12,`Transaction failed: ${e}`,{context:{status:r,msg:e}})}},uu=1e3,lu=class{constructor(r){this.globals=r,this.coinMetaHelper=new du(r.suiClient),this.createStreamHelper=new oi(r).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(r){if(r.effects?.status.status!=="success")throw new cu(r.effects?.status.status,r.effects?.status.error);return r.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(r){return this.createStreamHelper.calculateCreateStreamFees(r)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(r){if(r.steps===0n)throw new P("Invalid stream steps: 0");let e=r.cliff?r.cliff:{numerator:0n,denominator:100n},t=r.totalAmount*e.numerator/e.denominator,n=(r.totalAmount-t)/r.steps,s={realTotalAmount:n*r.steps+t,cliffAmount:t,amountPerStep:n};return this.validateStreamAmount(s,r.totalAmount),s}calculateTimelineByInterval(r){if(r.steps===0n)throw new P("Invalid stream steps: 0");let e=r.timeStart.plus(r.interval.toMillis()*Number(r.steps)),t={timeStart:r.timeStart,timeEnd:e,interval:r.interval,steps:r.steps};return this.validateTimeline(t),t}calculateTimelineByTotalDuration(r){if(r.steps===0n)throw new P("Invalid stream steps: 0");let e=BigInt(r.total.toMillis())/r.steps,t=r.timeStart.plus(T.fromMillis(Number(e*r.steps))),n={timeStart:r.timeStart,timeEnd:t,interval:T.fromMillis(Number(e)),steps:r.steps};return this.validateTimeline(n),n}async getBalance(r,e){let t=await this.globals.suiClient.getBalance({owner:r,coinType:e}),n=await this.getCoinMeta(e);return{...t,coinType:(0,qe.normalizeStructTag)(t.coinType),coinMeta:n}}async getAllBalance(r){let e=await this.globals.suiClient.getAllBalances({owner:r}),t=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,s)=>({...n,coinType:(0,qe.normalizeStructTag)(n.coinType),coinMeta:t[s]}))}async getCoinMeta(r){return this.coinMetaHelper.getCoinMeta(r)}async simulateTransactionBlock(r){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:r,sender:await this.globals.wallet.address()})}validateStreamAmount(r,e){if(r.amountPerStep===0n)throw new P("Stream amount too small","totalAmount",e);if(r.cliffAmount>r.realTotalAmount)throw new P("Invalid cliff settings")}validateTimeline(r){if(r.interval.toMillis()<uu)throw new P("Interval shall be at least 1 second","interval",r.interval)}},du=class{constructor(r){this.suiClient=r,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(r){let e=(0,qe.normalizeStructTag)(r||qe.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let t=await this.queryCoinMeta(e);return t&&this.coinMetaReg.set(e,t),t}async queryCoinMeta(r){return await this.suiClient.getCoinMetadata({coinType:r})||void 0}},mu=class extends F{constructor(){super(7,"Connected wallet is not creator")}},ya=class extends F{constructor(){super(8,"Connected wallet is not recipient")}},wa=class extends F{constructor(r,e){super(6,r,{context:e})}},H=class extends F{constructor(r,e={}){super(0,r,e)}},hu=class extends F{constructor(r){super(5,"Stream not found",{context:{streamId:r}})}},fu=(1n<<64n)-1n,rr=1e3;function Sa(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/rr);return p.fromMillis(t*rr)}function ba(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/rr);return T.fromMillis(t*rr)}var xn=class oe{constructor(e,t,n){this.globals=e,this.streamId=t,this.rawData=n,this.streamContract=new nr(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let n=await oe.fetchStreamData(e,t);return new oe(e,t,n)}static fromObjectData(e,t,n){let s=oe.parseRawStreamData(t,n);return new oe(e,t,s)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await oe.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new H("Object Id does not align");this.rawData=oe.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new mu;let e=new Tt.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new ya;let e=new Tt.TransactionBlock;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new ya;let t=new Tt.TransactionBlock;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new Tt.TransactionBlock;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,kt.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return ba(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return pn(e).groupId}get name(){let{metadata:e}=this.rawData.config;return pn(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Sa(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return ba(t)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:Sa((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===fu?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=p.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let n=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,t){let n=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return oe.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new hu(e):new wa(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data.content;if(n.dataType!=="moveObject")throw new wa("Unexpected object type",{gotType:n.dataType});let{typeParams:s}=(0,kt.parseStructTag)(n.type),a=(0,kt.normalizeStructTag)(s[0]),i=n.fields,o=i.config.fields,c=i.status.fields;return{coinType:a,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(o.amount_per_epoch),cancelable:o.cancelable,cliff:BigInt(o.cliff),creator:o.creator,epochInterval:BigInt(o.epoch_interval),metadata:o.metadata,recipient:o.recipient,timeStart:BigInt(o.time_start),totalEpoch:BigInt(o.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}},mn=class extends F{constructor(r,e){super(9,`Invalid stream group: ${r}`,{context:e})}};async function pu(r){let e=[];for(;await r.hasNext();){let t=await r.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var gu=class{constructor(r){this.requester=r,this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},ci=class{constructor(r){this.requester=r,this.pager=new gu(r),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}},yu=25;async function Ta(r,e,t){let n=new ui(e),s=new li(r,n,t);return await pu(s)}var ui=class{constructor(r){this.ids=r,this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},li=class extends ci{constructor(r,e,t){super(new wu(r,e,t)),this.suiClient=r,this.idIter=e,this.options=t}},wu=class{constructor(r,e,t){this.suiClient=r,this.stringIter=e,this.options=t,this.filter=t?.filter,this.pageSize=t?.pageSize||yu,this.objectOptions=t?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let r=[];for(;r.length<this.pageSize&&await this.stringIter.hasNext();){let n=await this.stringIter.next();n&&r.push(n)}let e=await this.suiClient.multiGetObjects({ids:r,options:this.objectOptions}),t;if(this.filter){let{filter:n}=this;t=e.filter(s=>n?.(s))}else t=e;return{data:t,hasNext:await this.stringIter.hasNext()}}},Su=class Xt{constructor(e,t){if(this.globals=e,this.streams=t,t.length===0)throw new mn("stream size 0");let n=t.map(s=>s.groupId);if(new Set(n).size!==1)throw new P("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let n=await Ta(e.suiClient,t);return n.forEach(s=>{if(!s)throw new H("stream group object data undefined")}),Xt.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let s=await Xt.parseGroupStreams(e,t,n);return new Xt(e,s)}static checkStreamGroup(e){let t=e.map(a=>a.groupCommonInfo),n=t[0],s=!0;return t.forEach(a=>{bu(n,a)||(s=!1)}),s}async refresh(){let e=await Ta(this.globals.suiClient,this.streams.map(t=>t.streamId));this.streams.forEach((t,n)=>{t.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,t)=>e+t.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,t)=>e+t.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,t)=>t.nextReleaseAmount===null?e:e+t.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,t)=>e+t.totalAmount,0n),streamed:this.streams.reduce((e,t)=>e+t.streamedAmount,0n),claimed:this.streams.reduce((e,t)=>e+t.claimedAmount,0n),claimable:this.streams.reduce((e,t)=>e+t.claimable,0n),canceled:this.streams.reduce((e,t)=>e+t.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,t,n){let s=n.map((a,i)=>xn.fromObjectData(e,t[i],a)).filter(a=>!!a);if(new Set(s.map(a=>a.groupId)).size!==1)throw new mn("Not same group ID");if(!this.checkStreamGroup(s))throw new mn("Not same stream settings");return s}};function bu(r,e){return r.name===e.name&&r.groupId===e.groupId&&r.creator===e.creator&&r.start.toMillis()===e.start.toMillis()&&r.interval.toMillis()===e.interval.toMillis()&&r.steps===e.steps&&r.cancelable===e.cancelable}var Ia=class wn{constructor(e,t){this.it=e,this.pageSize=t}static async newIncoming(e){let t=await xa.newIncoming(e);return new wn(t,e.pageSize)}static async newOutgoing(e){let t=await xa.newOutgoing(e);return new wn(t,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},xa=class Sn{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await ka.newIncomingQuery(e);return new Sn(t)}static async newOutgoing(e){let t=await ka.newOutgoingQuery(e);return new Sn(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new H("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new H("No more results");return e}},ka=class bn{constructor(e,t,n,s){this.globals=e,this.recipient=t,this.groupRefs=n,this.query=s,this.current=0;let a=new ui(n.flat().map(i=>i.streamId));this.objectIter=new li(e.suiClient,a)}current=0;objectIter;static async newIncomingQuery(e){let t=Ou(e.query),n=await e.globals.walletAddress(),s=(await e.globals.backend.getIncomingStreams(n,t)).filter(i=>(0,ue.normalizeSuiAddress)(i.recipient)===(0,ue.normalizeSuiAddress)(n)),a=Oa(s);return new bn(e.globals,n,a,e.query)}static async newOutgoingQuery(e){let t=Eu(e.query),n=await e.globals.walletAddress(),s=await e.globals.backend.getOutgoingStreams(n,t),a=Oa(s);return new bn(e.globals,n,a,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let t=await xu(this.globals,e[0].streamId,this.objectIter);return this.current++,di(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await ku(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Iu(t,this.query)?t:this.doNextRequest()}throw new H("Stream group with no stream")}};function Oa(r){let e=new Map;return r.forEach(t=>{let n=e.get(t.groupId);n?(n.push(t),e.set(t.groupId,n)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,n)=>p.fromISO(n[0].createDate).toMillis()-p.fromISO(t[0].createDate).toMillis())}function di(r,e){if(e===void 0)return!0;let t=Tu(r,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?r.progress.claimable!==0n:r.progress.claimable===0n;return t&&n}return t}function Tu(r,e){return e===void 0?!0:Array.isArray(e)?e.includes(r.progress.status):r.progress.status===e}function Iu(r,e){if(!e)return!0;let t=!1;return r.streams.forEach(n=>{di(n,e)&&(t=!0)}),t}async function xu(r,e,t){let n=await mi(t,e);return xn.fromObjectData(r,e,n)}async function ku(r,e,t){let n=[];for(;n.length<e.length;){let s=await mi(t,e[n.length]);n.push(s)}return Su.newFromObjectResponse(r,e,n)}async function mi(r,e){if(!await r.hasNext())throw new H("object iterator has been consumed");let t=await r.next();if(!t||t.error||t.data===void 0||t.data===null)throw new H("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new H("stream id not aligned");return t}function Ou(r){return{status:kn(r?.status),coinType:hi(r?.coinType),sender:fi(r?.sender)}}function Eu(r){return{status:kn(r?.status),coinType:hi(r?.coinType),recipient:fi(r?.recipient)}}function kn(r){return r===void 0||r.length===0?"all":Array.isArray(r)?r.reduce((e,t)=>{let n=kn(t);return!e||e===n?n:"all"},void 0):Cu(r)}function Cu(r){switch(r){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new P("Unknown stream filtered status")}}function hi(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>(0,ue.normalizeStructTag)(e)):void 0:(0,ue.normalizeStructTag)(r)}function fi(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>(0,ue.normalizeSuiAddress)(e)):void 0:(0,ue.normalizeSuiAddress)(r)}var vu=class extends F{constructor(r,e,t){super(4,`Not enough balance: ${r}`,{context:{coinType:r,requestAmount:e,gotAmount:t}}),this.coinType=r,this.requestAmount=e,this.gotAmount=t}},Mu=25;async function Au(r,e,t,n="0x2::sui::SUI",s=Mu){let a=new Du(r,e,n,s),i=BigInt(0),o=[];for(;await a.hasNext()&&i<t;){let c=await a.next();c&&(o.push(c),i+=BigInt(c.balance))}if(i<t)throw new vu(n,t,i);return o}var Du=class extends ci{constructor(r,e,t,n){super(new Nu(r,e,t,n)),this.suiClient=r,this.owner=e,this.coinType=t,this.reqPageSize=n}},Nu=class{constructor(r,e,t,n){if(this.suiClient=r,this.owner=e,this.coinType=t,this.reqPageSize=n,n<=0)throw new H("Invalid reqPageSize")}nextCursor;async doNextRequest(){let r=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=r.nextCursor,{data:r.data,hasNext:r.hasNextPage}}},Pu=class{constructor(r){this.msafe=r}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(r){return this.msafe.requestCoins(r)}},Fu=class{constructor(r){this.account=r}async address(){return this.account.address}},Ru=class{constructor(r,e){this.singleWallet=r,this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(r){return Promise.all(r.map(e=>this.requestCoin(e)))}async requestCoin(r){if(ri(r.coinType,we.SUI_TYPE_ARG))return{primaryCoin:ni};if(r.amount<=0)throw new P("Invalid coin request","coinAmount",r.amount);let e=await Au(this.suiClient,await this.address(),r.amount,r.coinType);if(e.length===0)throw new H("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(t=>t.coinObjectId)}}},_u=class{globals;helper;constructor(r,e){this.globals=Ya.new(r,e),this.helper=new lu(this.globals)}connectSingleWallet(r){let e=new Ru(r,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(r){let e=new Pu(r);this.globals.connectWallet(e)}async createStream(r){return this.builder().createStreams(r)}async getStream(r){return xn.new(this.globals,r)}async getIncomingStreams(r,e=10){return Ia.newIncoming({globals:this.globals,query:r,pageSize:e})}async getOutgoingStreams(r,e=10){return Ia.newOutgoing({globals:this.globals,query:r,pageSize:e})}async getCoinTypesForStreamFilter(){let r=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(r)).map(e=>(0,we.normalizeStructTag)(e))}async getRecipientsForStreamFilter(r){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,r)).map(t=>(0,we.normalizeSuiAddress)(t))}async getCreatorsForStreamFilter(r){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,r)).map(t=>(0,we.normalizeSuiAddress)(t))}get wallet(){return this.globals.wallet}builder(){return new oi(this.globals)}},Wu=class{constructor(r){this.data=r}serialize(){return JSON.stringify((0,pi.default)(this.data))}},Ot=class extends Wu{application="mpay";getClient(r,e){let t=new _u(r==="sui:mainnet"?"prod":"dev");return t.connectSingleWallet(new Fu(e)),t}},Ea=class extends Ot{constructor(r){super(r),this.data=r}txType=Na.TransactionType.Stream;txSubType="Cancel";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).cancel()}},Ca=class extends Ot{constructor(r){super(r),this.data=r}txType=gi.TransactionType.Stream;txSubType="ClaimByProxy";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).claimByProxy()}},va=class extends Ot{constructor(r){super(r),this.data=r}txType=yi.TransactionType.Stream;txSubType="Claim";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).claim()}},Ma=class extends Ot{constructor(r){super(r),this.data=r}txType=wi.TransactionType.Stream;txSubType="CreateStream";async build(r){let{network:e,account:t}=r;return this.getClient(e,t).createStream(this.data)}},Si=class er{constructor(e,t){this.moveCall=e,this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return er.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return er.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,ce.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return er.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Tn.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,ce.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,ce.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,ce.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,ce.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Tn.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,ce.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},ju=class{constructor(r,e){this.globals=r,this.txb=e}decode(){let r=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(r);return{type:"CreateStream",info:r,fees:e}}decodeCreateStreamInfo(){let r=this.createStreamTransactions().map(e=>this.getCreationInfoFromMoveCall(e));return this.aggregateGroupStreamInfo(r)}createStreamTransactions(){let r=this.transactions.filter(e=>e.kind==="MoveCall"&&Le(e.target,this.contract.createStreamTarget));if(r.length===0)throw new H("No create stream transactions");return r.map(e=>new Si(e,this.txb))}getCreationInfoFromMoveCall(r){let e=r.decodeInputString(4),{name:t,groupId:n}=pn(e),s=r.decodeInputAddress(5),a=r.decodeInputU64(6),i=r.decodeInputU64(7),o=r.decodeInputU64(8),c=r.decodeInputU64(9),u=r.decodeInputU64(10),d=r.decodeInputBool(11),f=r.typeArg(0);return{name:t,groupId:n,recipient:s,timeStart:a,cliff:i,epochInterval:o,totalEpoch:c,amountPerEpoch:u,cancelable:d,coinType:f}}aggregateGroupStreamInfo(r){if(new Set(r.map(t=>JSON.stringify({name:t.name,groupId:t.groupId,timeStart:String(t.timeStart),epochInterval:String(t.epochInterval),totalEpoch:String(t.totalEpoch),cancelable:t.cancelable,coinType:t.coinType}))).size!==1)throw new P("Stream group not have common info");let e=r.map(t=>({address:t.recipient,amountPerStep:t.amountPerEpoch,cliffAmount:t.cliff}));return{name:r[0].name,coinType:r[0].coinType,recipients:e,interval:r[0].epochInterval,steps:r[0].totalEpoch,startTimeMs:r[0].timeStart,cancelable:r[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(r=>r.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new nr(this.globals.envConfig.contract,this.globals)}get feeContract(){return new ii(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new gn(this.globals,this.feeContract,this.contract)}getInputArg(r){if(r.kind!=="Input")throw new Error("not input type");return"value"in r?r:this.txb.blockData.inputs[r.index]}},Lu=class{constructor(r,e){this.globals=r,this.txb=e,this.contract=new nr(r.envConfig.contract,r)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction()}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(r=>r.kind==="MoveCall"&&Le(r.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Le(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Le(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Le(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Le(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new ju(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let r=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:r,enabled:e}}decodeClaimTransaction(){return{type:"Claim",streamId:this.helper.decodeSharedObjectId(0)}}decodeClaimByProxyTransaction(){return{type:"ClaimByProxy",streamId:this.helper.decodeSharedObjectId(0)}}decodeCancelStreamTransaction(){return{type:"Cancel",streamId:this.helper.decodeSharedObjectId(0)}}get helper(){let r=this.transactions[0];return new Si(r,this.txb)}},Aa=class extends Ot{constructor(r){super(r),this.data=r}txType=bi.TransactionType.Stream;txSubType="SetAutoClaim";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},Bu=class{application="mpay";async deserialize(r){let{chain:e,transactionBlock:t}=r,n=Ya.new(e==="sui:mainnet"?"prod":"dev"),s=new Lu(n,t).decode(),a;switch(s.type){case"CreateStream":a=new Ma(s.info);break;case"SetAutoClaim":a=new Aa({streamId:s.streamId,enabled:s.enabled});break;case"Claim":a=new va({streamId:s.streamId});break;case"ClaimByProxy":a=new Ca({streamId:s.streamId});break;case"Cancel":a=new Ea({streamId:s.streamId});break;default:throw new Error(`Unknown transaction type: ${s}`)}return{txType:a.txType,txSubType:a.txSubType,intentionData:a.data}}async build(r){let{intentionData:e}=r,t;switch(r.txSubType){case"CreateStream":t=new Ma(e);break;case"Claim":t=new va(e);break;case"ClaimByProxy":t=new Ca(e);break;case"SetAutoClaim":t=new Aa(e);break;case"Cancel":t=new Ea(e);break;default:throw new Error("not implemented")}return t.build({...r})}},On=class{constructor(r){this.data=r}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,Ii.default)(this.data))}},qu=class xi extends On{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e;return(0,Ti.buildCoinTransferTxb)(t,this.data,n.address)}static fromData(e){return new xi(e)}},Uu=class Oi extends On{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e;return(0,ki.buildObjectTransferTxb)(t,this.data,n.address)}static fromData(e){return new Oi(e)}},Hu=class vi extends On{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:t}=e,n=Ci.TransactionBlock.from(this.data.content);if(!(0,Ei.isSameAddress)(n.blockData.sender,t.address))throw new Error("Invalid sender address");return n}static fromData(e){return new vi(e)}},Vu=class{application;constructor(){this.application=Be.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(r){let{suiClient:e,account:t}=r,n;switch(r.txSubType){case Be.TransactionSubTypes.assets.coin.send:n=qu.fromData(r.intentionData);break;case Be.TransactionSubTypes.assets.object.send:n=Uu.fromData(r.intentionData);break;case Be.TransactionSubTypes.others.plain:n=Hu.fromData(r.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:t})}},Gu=class{apps;constructor(r){this.apps=new Map(r.map(e=>[e.application,e]))}getAppHelper(r){let e=this.apps.get(r);if(!e)throw new Error(`${r} not registered`);return e}},zu="msafe-plain-tx",$u=sr.TransactionSubTypes.others.plain,Zu=class{application;constructor(){this.application=zu}async deserialize(r){let{transactionBlock:e,suiClient:t}=r,n=await e.build({client:t});return{txType:sr.TransactionType.Other,txSubType:$u,intentionData:{content:(0,ar.toHEX)(n)}}}async build(r){let{suiClient:e,account:t}=r,n=Mi.TransactionBlock.from((0,ar.fromHEX)(r.intentionData.content)),s=await e.devInspectTransactionBlock({transactionBlock:n,sender:t.address});if(s.effects.status.status!=="success")throw new Error(s.effects.status.error);return n}},ir=new Gu([new Vu,new Bu,new Zu]);var S=require("@msafe/sui3-utils"),Fn=require("@mysten/sui.js/transactions"),hr=require("@mysten/sui.js/utils");var Ai=require("@mysten/sui.js/transactions"),Ku=1000n,Yu=120n,Ju=100n,Qu={multiplier:{numerator:Yu,denominator:Ju}};var or=class{constructor(e){this.globals=e}async simulate(e,t=Qu){let n=this.copyTransactionBlock(e.txb),{suiClient:s}=this.globals,a=await this.getGasPrice(t);n.setGasPrice(a);let i=await s.devInspectTransactionBlock({transactionBlock:n,sender:e.sender}),{gasUsed:o}=i.effects,c=this.toGasBudget(o,a),u=i.effects.status.status==="success",d;return u||(d=i.effects.status.error),{success:u,gasPrice:a,gasObject:i.effects.gasObject.reference,gasUsed:o,gasBudget:c,simulationError:d}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let t=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(t,e)}toGasBudget(e,t){let{computationCost:n,storageCost:s}=e,a=Ku*t,i=BigInt(n)+a,o=i+BigInt(s);return o>i?o:i}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,t){if(this.isFixedValue(t))return t.fixedVal;if(this.isMultiplier(t)){let{multiplier:n}=t;return e*n.numerator/n.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ai.TransactionBlock.from(e.serialize())}};var En=require("buffer");function cr(r){return En.Buffer.from(r,"utf-8")}function Xu(r){return`0x${Array.prototype.map.call(r,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ur(r){return Uint8Array.from(En.Buffer.from(r.startsWith("0x")?r.slice(2):r,"hex"))}var dr=require("@mysten/sui.js/verify");var le=require("@mysten/sui.js/utils");var lr=require("@mysten/sui.js/utils"),Et=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let t=(0,lr.normalizeStructTag)(e);if(this._coinMetaReg.has(t))return this._coinMetaReg.get(t);let n=await this.queryCoinMeta(t);return n&&this._coinMetaReg.set(t,n),n}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Cn=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,Ct=class r{static isCoin(e){return e?(0,lr.normalizeStructTag)(e).match(Cn)!=null:!1}static getCoinType(e){let[,t]=(0,lr.normalizeStructTag)(e).match(Cn)??[];return t||null}static getBalance(e){if(!r.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:t}=e.content?.fields;if(t!==void 0)return BigInt(t)}};var Q=class{static normalizeSuiAddress(e){return(0,le.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,le.normalizeStructTag)(e)}static isSuiAddressEqual(e,t){return(0,le.normalizeSuiAddress)(e)===(0,le.normalizeSuiAddress)(t)}static isSuiStructEqual(e,t){return(0,le.normalizeStructTag)(e)===(0,le.normalizeStructTag)(t)}static isCoinObjectType(e){return Ct.isCoin(e)}};function vn(r,e){return r.startsWith(e)?r:e+r}var Mn=class r{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,dr.verifyTransactionBlock)(e.message,e.signature):(0,dr.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let t=cr(e.messageStr);return this.getPublicKeyFromSignature({message:t,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let t=await r.getPublicKeyFromSignature(e);return Q.isSuiAddressEqual(t.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let t=cr(e.messageStr);return this.verifySignature({message:t,messageType:"Personal",signature:e.signature,targetAddress:e.targetAddress})}static async verifyTransactionSignature(e){return this.verifySignature({messageType:"TransactionBlock",message:e.payload,signature:e.signature,targetAddress:e.targetAddress})}};var Di=require("@msafe/sui3-utils"),Ni=require("@mysten/sui.js/cryptography"),Pi=require("@mysten/sui.js/multisig");var el="0x2::sui::SUI";async function An(r,e){let t;try{t=await r.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(t.data.length===0||!t.data[0].transaction?.txSignatures)return;let s=t.data[0].transaction?.txSignatures;for(let a=0;a!==s.length;a++){let i=s[a],o=tl(i,e);if(o)return o}}function tl(r,e){let t=(0,Ni.parseSerializedSignature)(r);switch(t.signatureScheme){case"MultiSig":{let n=new Pi.MultiSigPublicKey(t.multisig.multisig_pk).toSuiAddress();if(Q.isSuiAddressEqual(n,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(Q.isSuiAddressEqual(t.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let n=Di.PublicKeySerde.de({publicKeyEncoded:t.publicKey,schema:t.signatureScheme});return Q.isSuiAddressEqual(n.toSuiAddress(),e)?n:void 0}default:throw new Error("Unknown schema")}}async function rl(r){let e=!0,t,n=[];for(;e;){let s=await r.suiClient.getCoins({owner:r.owner,coinType:r.coinType,cursor:t});n.push(...s.data),e=s.hasNextPage,t=s.nextCursor}return n}var Fi=25;async function Ri(r){let e=[];for(;await r.hasNext();){let t=await r.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var Dn=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},mr=class{constructor(e){this.requester=e;this.pager=new Dn(e),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};async function _i(r,e,t){let n=new Nn(r,e,t);return await Ri(n)}var Nn=class extends mr{constructor(t,n,s){super(new Pn(t,n,s));this.provider=t;this.owner=n;this.options=s}},Pn=class{constructor(e,t,n){this.provider=e;this.owner=t;this.options=n;this.nextCursor=null,this.filter=n?.filter,this.pageSize=n?.pageSize||Fi,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}nextCursor;filter;pageSize;objectOptions;async doNextRequest(){let e=await this.provider.getOwnedObjects({owner:this.owner,options:this.objectOptions,cursor:this.nextCursor,limit:this.pageSize});this.nextCursor=e.nextCursor;let t;if(this.filter){let{filter:n}=this;t=e.data.filter(s=>n?.(s))}else t=e.data;return{data:t.map(n=>n.data).filter(n=>n),hasNext:e.hasNextPage}}};var Se=class r{constructor(e,t){this.globals=e;this.info=t;this.multiSig=new S.MultiSigAccount({threshold:t.threshold,ownersWithWeight:t.owners,creationNonce:t.creationNonce}),this.coinHelper=new Et(this.suiClient),this.simulator=new or(e)}multiSig;coinHelper;simulator;static async New(e,t){let n=await e.backend.getMSafeAccountInfo(t);if(new r(e,n).address!==t)throw new Error("Invalid msafe config with address")}async ownedCoins(){let e=await this.suiClient.getAllBalances({owner:this.address});return Promise.all(e.map(async t=>{let n=await this.coinHelper.getCoinMeta(t.coinType),s=t.lockedBalance.number?BigInt(t.totalBalance)-BigInt(t.lockedBalance.number):BigInt(t.totalBalance);return{type:(0,hr.normalizeStructTag)(t.coinType),balance:BigInt(s),metadata:n}}))}async ownedObjects(e){let t={filter:n=>!n?.data?.type?.startsWith("0x2::coin::Coin"),...e};return _i(this.suiClient,this.address,t)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let t=e.pending,n=e.reject;return{application:t.application,txType:t.txType,txSubType:t.txSubType,createdAt:t.createdAt,creator:t.creator,digest:t.digest,intention:t.intention,sequenceNumber:t.sequenceNumber,payload:t.payload,votes:t.votes,approvalWeight:this.calculateWeightFromVotes(t.votes),msafeAddress:t.msafeAddress,rejectDigest:n?.digest??"",rejectPayload:n?.payload??"",rejectVotes:n?.votes??[],rejectWeight:this.calculateWeightFromVotes(n?.votes??[])}}async historyTransaction(e){return this.backend.getHistoryTransactions({msafeAddress:this.address,...e})}async futureIntentions(e){return this.backend.getFutureIntentions({msafeAddress:this.address,...e})}async currentSequenceNumber(){return this.backend.getCurrentSequenceNumber(this.address)}async nextSequenceNumber(){return this.backend.getNextSequenceNumber(this.address)}async simulateIntention(e){let t=ir.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async proposeIntention(e){let t=S.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),n=await this.wallet.signPersonalMessage({messageStr:t});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:n.signature})}async proposeIntentionAndBuildVote(e){let t=ir.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});n.setGasPrice(e.gasPrice),n.setGasBudget(e.gasBudget),n.setSender(this.address);let s=await n.build({client:this.globals.suiClient}),a=await n.getDigest({client:this.globals.suiClient}),i=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,hr.toHEX)(s),digest:a,msafeAddress:this.address,signature:i.signature})}async simulateCoinTransferIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Assets,txSubType:S.TransactionSubTypes.assets.coin.send,sequenceNumber:t,intention:e})}async proposeCoinTransferIntention(e){let t=await this.nextSequenceNumber();return this.proposeIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Assets,txSubType:S.TransactionSubTypes.assets.coin.send,sequenceNumber:t,intention:e})}async simulateObjectTransferIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Assets,txSubType:S.TransactionSubTypes.assets.object.send,sequenceNumber:t,intention:e})}async proposeObjectTransferIntention(e){let t=await this.nextSequenceNumber();return this.proposeIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Assets,txSubType:S.TransactionSubTypes.assets.object.send,sequenceNumber:t,intention:e})}async simulatePlainPayloadIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Other,txSubType:S.TransactionSubTypes.others.plain,sequenceNumber:t,intention:e})}async proposePlainPayloadIntention(e){let t=await this.nextSequenceNumber(),n=Fn.TransactionBlock.from(e.payload);if(!n.blockData.sender||!(0,S.isSameAddress)(n.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Other,txSubType:S.TransactionSubTypes.others.plain,sequenceNumber:t,intention:e})}async voteForTransaction(e,t){let n=ur(t),s=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:s.signature})}async proposePendingTransaction(e){let t=new Fn.TransactionBlock,n=await t.build({client:this.suiClient}),s=await t.getDigest({client:this.suiClient}),a=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:s,signature:a.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let t=e.payload,n=(0,S.buildRejectTxb)(this.address,t);return this.simulator.simulate({txb:n,sender:this.address})}async rejectCurrentTx(e){let t=await this.pendingTransaction();if(!t||t.rejectDigest!=="")throw new Error("Already rejected");let n=t.payload,s=(0,S.buildRejectTxb)(this.address,n),a=await s.getDigest({client:this.suiClient}),i=await s.build({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:a,signature:o.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),t=ir.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,t=!1){let n=t?e.rejectVotes:e.votes,s=t?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(n)<this.info.threshold)throw new Error("Not enough signature");let a=[],i=new Map(n.map(c=>[c.userAddress,c.signature]));for(let c=0;c<this.info.owners.length;c++){let u=this.info.owners[c],d=i.get(u.address);d&&a.push(d)}let o=this.multiSig.combinePartialSignatures(a);return this.suiClient.executeTransactionBlock({transactionBlock:ur(s),signature:o,options:{showEffects:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(t=>t.userAddress))}calculateWeight(e){let t=0;for(let n=0;n<e.length;n++){let s=this.info.owners.find(a=>(0,S.isSameAddress)(a.address,e[n]));s&&(t+=s.weight)}return t}get address(){return this.multiSig.address}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}async userAddress(){return this.globals.wallet.address()}get suiClient(){return this.globals.suiClient}};var Wi=require("@msafe/sui3-utils"),ji=require("@mysten/sui.js/utils");var fr=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let t=this.knownPublicKeys.get(e);if(t)return t;let n=await this._getPublicKey(e);return n&&this.knownPublicKeys.set(e,n),n}async getPublicKeyBatch(e){let t=new Array(e.length).fill(void 0);for(let a=0;a<e.length;a++){let i=e[a];t[a]=this.knownPublicKeys.get(i)}let n=t.map((a,i)=>a===void 0?i:-1).filter(a=>a!==-1);if(n.length===0)return t;let s=await this.globals.backend.getPublicKeyBatch(n.map(a=>e[a]));for(let a=0;a<n.length;a++){let i=n[a];t[i]=s[a]}for(let a=0;a<t.length;a++)t[a]===void 0&&(t[a]=await this.getPublicKeyFromChain(e[a]));for(let a=0;a<e.length;a++)t[a]&&this.knownPublicKeys.set(e[a],t[a]);return t}addPublicKey(e,t){if(!(0,Wi.isSameAddress)(e,t.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,ji.normalizeSuiAddress)(e),t)}async _getPublicKey(e){let t=await this.getPublicKeyFromBackend(e);if(t)return t;let n=await this.getPublicKeyFromChain(e);if(n)return n}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return An(this.globals.suiClient,e)}};var pr=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Gi=require("@mysten/sui.js/client");var Mt=require("@msafe/sui3-utils"),vt=Ie(require("axios"),1),wr=Ie(require("json-bigint"),1);var gr=class r{constructor(e){this.apiURL=e}_token;async authSign(e){let t=await this.post("/auth/login",e);return this._token=t.data.accessToken,this._token}async verifyToken(e){try{return(await this.get("/auth",{headers:this.headers(e)})).status===200}catch{return!1}}setJWTToken(e){this._token=e}async getPublicKey(e){return(await this.getPublicKeyBatch([e]))[0]}async getPublicKeyBatch(e){let t={userAddressList:e};return(await this.get("/user/public-keys",{params:t,headers:this.headers()})).data?.map(s=>s?Mt.PublicKeySerde.de(s):void 0)}async getMSafeAccountInfo(e){let t={msafeAddress:e},n=await this.get("/msafe",{params:t,headers:this.headers()});return r.toMSafeConfig(n.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let t={status:e.status??Mt.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},n=await this.get("/msafe/owned",{params:t,headers:this.headers()});return{data:n.data.data.map(r.toMSafeConfig),meta:n.data.meta}}async updateMSafeStatus(e){let t=e;await this.post("/msafe/status",t,{headers:this.headers()})}async getPendingTransactions(e){return(await this.get("/transaction/pending",{params:e,headers:this.headers()})).data}async getHistoryTransactions(e){return(await this.get("/transaction/history",{params:e,headers:this.headers()})).data}async getFutureIntentions(e){return(await this.get("/transaction/intention",{params:e,headers:this.headers()})).data}async getNextIntention(e){return(await this.get("/transaction/intention/next",{params:e,headers:this.headers()})).data}async getCurrentSequenceNumber(e){return(await this.get("/transaction/sn/current",{params:{msafeAddress:e},headers:this.headers()})).data}async getNextSequenceNumber(e){return(await this.get("/transaction/sn/next",{params:{msafeAddress:e},headers:this.headers()})).data}async createMSafeAccount(e){await this.post("/msafe/create",e,{headers:this.headers()})}async proposeIntention(e){await this.post("/transaction/intention",e,{headers:this.headers()})}async proposePendingTransaction(e){}async rejectCurrentTx(e){await this.post("/transaction/pending/reject",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async voteForTransaction(e){await this.post("/transaction/pending/vote",e,{headers:this.headers()})}async buildNextIntentionAndAddToPending(e){await this.post("/transaction/pending/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async proposeIntentionAndBuildVote(e){await this.post("/transaction/intention/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async skipNextFailedIntention(e){await this.post("/transaction/pending/skip",e,{headers:this.headers()})}async getAddressBookEntries(e){return(await this.get("/address-book",{headers:this.headers(),params:e})).data}async updateAddressBook(e){await this.post("/address-book",e,{headers:this.headers()})}async getAddressBookMode(){return(await this.get("/address-book/mode",{headers:this.headers()})).data}async setAddressBookMode(e){await this.post("/address-book/mode",{mode:e.mode},{headers:this.headers()})}async submitReport(e){await this.post("/report",e)}async getDashboard(e){return(await this.get("/dashboard",{params:e,headers:this.headers()})).data}headers(e){return{Authorization:`Bearer ${e||this._token}`}}static toMSafeConfig(e){return{...e,owners:e.owners.map(t=>({address:t.address,weight:t.weight,publicKey:Mt.PublicKeySerde.de({publicKeyEncoded:t.publicKeyEncoded,schema:t.schema})}))}}async get(e,t){let n=this.getFullUrl(e);try{return await vt.default.get(n,t)}catch(s){throw yr.fromError(s)??s}}async post(e,t,n){let s=this.getFullUrl(e);try{return await vt.default.post(s,t,{...n,transformRequest:this.getTransformRequest()})}catch(a){throw yr.fromError(a)??a}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${vn(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:t}=vt.default.defaults;return t?t instanceof Array?e=t:e=[t]:e=[],[n=>wr.parse(wr.stringify(n)),...e]}},yr=class r extends Error{constructor(t){super();this.e=t;Error.captureStackTrace(this,this.constructor)}name;static fromError(t){if(vt.default.isAxiosError(t)&&t?.response?.data&&"message"in t.response.data)return new r(t)}get status(){return this.e.response?.status??void 0}get message(){return`${this.respMessage()??"Unknown resp"}`}respMessage(){if(this.e.response?.data)return(this.e.response?.data).message??void 0}get endpoint(){return this.e.config?.url??""}toString(){return this.message}};var Li=(a=>(a.local="local",a.unit="unit",a.dev="dev",a.prev="prev",a.prod="prod",a))(Li||{}),Sr="https://fullnode.testnet.sui.io",Rn="https://fullnode.mainnet.sui.io",_n="http://127.0.0.1:3000",Wn="http://127.0.0.1:3001",Bi="https://sui-dev.m-safe.link",qi="http://13.56.226.148:81",Ui="https://sui-preview.m-safe.link",Hi="https://sui.m-safe.link",Vi=new Map([["unit",{suiClient:{url:Sr},backend:{url:_n},syncingURL:Wn,network:"sui:testnet"}],["local",{suiClient:{url:Sr},backend:{url:_n},syncingURL:Wn,network:"sui:testnet"}],["dev",{suiClient:{url:Sr},backend:{url:Bi},syncingURL:qi,network:"sui:testnet"}],["prev",{suiClient:{url:Rn},backend:{url:Ui},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:Rn},backend:{url:Hi},syncingURL:"",network:"sui:mainnet"}]]);function jn(r,e){let t=Vi.get(r);if(!t)throw new Error("Unknown environment");return e?.suiClient?.url&&(t.suiClient.url=e.suiClient.url),e?.backend?.url&&(t.backend.url=e.backend.url),t}var At=class r{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,t){let n=jn(e,t),s=new Gi.SuiClient(n.suiClient),a=new gr(n.backend.url);return new r({backend:a,suiClient:s,config:n})}connectWallet(e){this._wallet=e}get wallet(){if(!this._wallet)throw new Error("wallet not connected");return this._wallet}set wallet(e){this._wallet=e}};var br=class r{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,t){let n=await At.New(e,t);return new r(n)}async connectWallet(e){if(e.jwtToken&&await this.backend.verifyToken(e.jwtToken))return this.globals.wallet=e.wallet,this.backend.setJWTToken(e.jwtToken),e.jwtToken;let t=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(t),t}async authSign(e){let t=Tr.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),n=await e.signPersonalMessage({messageStr:t});return this.backend.authSign({address:await e.address(),message:t,signature:n.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:Tr.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new Se(this.globals,e)}async getMSafeAccountFromAddress(e){let t=await this.backend.getMSafeAccountInfo(e);return new Se(this.globals,t)}get creationHelper(){return this._creationHelper||(this._creationHelper=new xe(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new fr(this.globals)),this._publicKeyHelper}get config(){return this.globals.config}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}get AddressBook(){return new ke(this.globals)}get Invitation(){return new Pt(this.globals)}get Report(){return new pr(this.globals)}async walletAddress(){return this.wallet.address()}};
1
+ "use strict";var Ji=Object.create;var Dt=Object.defineProperty;var Qi=Object.getOwnPropertyDescriptor;var Xi=Object.getOwnPropertyNames;var eo=Object.getPrototypeOf,to=Object.prototype.hasOwnProperty;var Nt=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ro=(r,e)=>{for(var t in e)Dt(r,t,{get:e[t],enumerable:!0})},qn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xi(e))!to.call(r,s)&&s!==t&&Dt(r,s,{get:()=>e[s],enumerable:!(n=Qi(e,s))||n.enumerable});return r};var Ie=(r,e,t)=>(t=r!=null?Ji(eo(r)):{},qn(e||!r||!r.__esModule?Dt(t,"default",{value:r,enumerable:!0}):t,r)),no=r=>qn(Dt({},"__esModule",{value:!0}),r);var ea=Nt((Sm,Xs)=>{"use strict";Xs.exports=r=>{if(Object.prototype.toString.call(r)!=="[object Object]")return!1;let e=Object.getPrototypeOf(r);return e===null||e===Object.prototype}});var ra=Nt((bm,ta)=>{"use strict";var cn=ea();ta.exports=(r,e={})=>{if(!cn(r)&&!Array.isArray(r))throw new TypeError("Expected a plain object or array");let{deep:t}=e,n=[],s=[],a=o=>{let c=n.indexOf(o);if(c!==-1)return s[c];let u=[];return n.push(o),s.push(u),u.push(...o.map(d=>Array.isArray(d)?a(d):cn(d)?i(d):d)),u},i=o=>{let c=n.indexOf(o);if(c!==-1)return s[c];let u={},d=Object.keys(o).sort(e.compare);n.push(o),s.push(u);for(let f of d){let g=o[f],m;t&&Array.isArray(g)?m=a(g):m=t&&cn(g)?i(g):g,Object.defineProperty(u,f,{...Object.getOwnPropertyDescriptor(o,f),value:m})}return u};return Array.isArray(r)?t?a(r):r.slice():i(r)}});var aa=Nt((Tm,sa)=>{"use strict";var Mc=Object.prototype.toString;sa.exports=function(e){if(e===void 0)return"undefined";if(e===null)return"null";var t=typeof e;if(t==="boolean")return"boolean";if(t==="string")return"string";if(t==="number")return"number";if(t==="symbol")return"symbol";if(t==="function")return Fc(e)?"generatorfunction":"function";if(Ac(e))return"array";if(Wc(e))return"buffer";if(_c(e))return"arguments";if(Nc(e))return"date";if(Dc(e))return"error";if(Pc(e))return"regexp";switch(na(e)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(Rc(e))return"generator";switch(t=Mc.call(e),t){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return t.slice(8,-1).toLowerCase().replace(/\s/g,"")};function na(r){return typeof r.constructor=="function"?r.constructor.name:null}function Ac(r){return Array.isArray?Array.isArray(r):r instanceof Array}function Dc(r){return r instanceof Error||typeof r.message=="string"&&r.constructor&&typeof r.constructor.stackTraceLimit=="number"}function Nc(r){return r instanceof Date?!0:typeof r.toDateString=="function"&&typeof r.getDate=="function"&&typeof r.setDate=="function"}function Pc(r){return r instanceof RegExp?!0:typeof r.flags=="string"&&typeof r.ignoreCase=="boolean"&&typeof r.multiline=="boolean"&&typeof r.global=="boolean"}function Fc(r,e){return na(r)==="GeneratorFunction"}function Rc(r){return typeof r.throw=="function"&&typeof r.return=="function"&&typeof r.next=="function"}function _c(r){try{if(typeof r.length=="number"&&typeof r.callee=="function")return!0}catch(e){if(e.message.indexOf("callee")!==-1)return!0}return!1}function Wc(r){return r.constructor&&typeof r.constructor.isBuffer=="function"?r.constructor.isBuffer(r):!1}});var Qt=Nt((Im,ua)=>{"use strict";var jc=ra(),un=aa(),ia=(r,e)=>!e||un(e)!=="array"?!1:e.indexOf(r)>-1,Lc=(r,e)=>jc(r,{compare:e}),oa=(r,e)=>{let t=e&&e.compareFunction;return r.slice().sort(t)};function ca(r,e){let t=e&&e.compareFunction,n=Lc(r,t);return Object.keys(r).forEach(function(s){let a=n[s],i=un(a);if(i==="object"){(!e||!ia(s,e.ignoreObjectAtKeys))&&(n[s]=ca(a,e));return}i==="array"&&(!e||!ia(s,e.ignoreArrayAtKeys))&&(n[s]=oa(a,e))}),n}var St=(r,e)=>{let t=un(r);return St[t]?St[t](r,e):r};St.array=oa;St.object=ca;ua.exports=St});var nl={};ro(nl,{AddressBookSDK:()=>ke,COIN_TYPE_ARG_REGEX:()=>Cn,Coin:()=>Ct,CoinHelper:()=>Et,CreateHelper:()=>xe,DEV_API_URL:()=>Bi,DEV_SYNCING_URL:()=>qi,ENV_CONFIGS:()=>Vi,Formatter:()=>Q,HexToUint8Array:()=>ur,LOCAL_API_URL:()=>_n,LOCAL_SYNCING_URL:()=>Wn,MAINNET_RPC_URL:()=>Rn,MSafeAccount:()=>Se,MSafeClient:()=>br,MSafeEnv:()=>Li,MSafeGlobals:()=>At,PREV_API_URL:()=>Ui,PROD_API_URL:()=>Hi,SUI_COIN:()=>el,SignatureVerifier:()=>Mn,TESTNET_RPC_URL:()=>Sr,Uint8ArrayToHex:()=>Xu,addPrefix:()=>vn,getAllCoins:()=>rl,getMSafeConfig:()=>jn,getPublicKeyFromChain:()=>An,stringToBuffer:()=>cr});module.exports=no(nl);var z=require("@msafe/sui3-utils"),xe=class{constructor(e,t){this.globals=e;this.pkHelper=t}async getPublicKeyBatch(e){return this.pkHelper.getPublicKeyBatch(e)}async calculateMSafeAddress(e){let t=await this.reduceCreationInfoToRawConfig(e);return new z.MultiSigAccount(t).address}async validateCreateInfo(e){return this.calculateMSafeAddress(e)}addPublicKey(e,t){let n=z.PublicKeySerde.de(t);if(!(0,z.isSameAddress)(e,n.toSuiAddress()))throw new Error("Public key not match");this.pkHelper.addPublicKey(e,n)}async submitMSafeCreation(e){let t=await this.validateCreateInfo(e),n=z.SigningMessageHelper.createMSafeMessage(t),s=await this.globals.wallet.signPersonalMessage({messageStr:n});return await this.submitToBackend(e,s.signature),t}async reduceCreationInfoToRawConfig(e){let t=await this.getPublicKeyBatch(e.owners.map(n=>n.address));return t.forEach((n,s)=>{if(n===void 0)throw new Error(`Unknown public key for address: ${e.owners[s].address}`)}),{threshold:e.threshold,ownersWithWeight:e.owners.map((n,s)=>({publicKey:t[s],weight:n.weight})),creationNonce:e.creationNonce}}async submitToBackend(e,t){let n=await this.pkHelper.getPublicKeyBatch(e.owners.map(s=>s.address));await this.globals.backend.createMSafeAccount({owners:e.owners.map((s,a)=>({address:s.address,weight:s.weight,...z.PublicKeySerde.ser(n[a])})),threshold:e.threshold,name:e.name,description:e.description,creationNonce:e.creationNonce,signature:t})}};var Tr=require("@msafe/sui3-utils");var Un=require("@msafe/sui3-utils"),ke=class{constructor(e){this.globals=e}async getEntries(e){return this.globals.backend.getAddressBookEntries(e)}async update(e){let t=Un.SigningMessageHelper.updateAddressBookMessage(e),n=await this.globals.wallet.signPersonalMessage({messageStr:t});return this.globals.backend.updateAddressBook({updates:e,signature:n.signature})}async getMode(){return(await this.globals.backend.getAddressBookMode()).mode}async setMode(e){return this.globals.backend.setAddressBookMode({mode:e})}};var Pt=class{constructor(e){this.globals=e}async getMSafeByStatus(e,t){return this.globals.backend.getOwnedMSafeByStatus({status:e,pagination:t})}async updateMSafeStatus(e,t){return this.globals.backend.updateMSafeStatus({msafeAddress:e,status:t})}};var Na=require("@msafe/sui3-utils"),Ka=require("@mysten/sui.js/client"),J=Ie(require("axios"),1),we=require("@mysten/sui.js/utils"),qe=require("@mysten/sui.js/utils");var $=class extends Error{},Ft=class extends ${constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Rt=class extends ${constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},_t=class extends ${constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},j=class extends ${},Oe=class extends ${constructor(e){super(`Invalid unit ${e}`)}},x=class extends ${},L=class extends ${constructor(){super("Zone is an abstract class")}};var l="numeric",B="short",D="long",X={year:l,month:l,day:l},Ve={year:l,month:B,day:l},xr={year:l,month:B,day:l,weekday:B},Ge={year:l,month:D,day:l},ze={year:l,month:D,day:l,weekday:D},$e={hour:l,minute:l},Ze={hour:l,minute:l,second:l},Ke={hour:l,minute:l,second:l,timeZoneName:B},Ye={hour:l,minute:l,second:l,timeZoneName:D},Je={hour:l,minute:l,hourCycle:"h23"},Qe={hour:l,minute:l,second:l,hourCycle:"h23"},Xe={hour:l,minute:l,second:l,hourCycle:"h23",timeZoneName:B},et={hour:l,minute:l,second:l,hourCycle:"h23",timeZoneName:D},tt={year:l,month:l,day:l,hour:l,minute:l},rt={year:l,month:l,day:l,hour:l,minute:l,second:l},nt={year:l,month:B,day:l,hour:l,minute:l},st={year:l,month:B,day:l,hour:l,minute:l,second:l},kr={year:l,month:B,day:l,weekday:B,hour:l,minute:l},at={year:l,month:D,day:l,hour:l,minute:l,timeZoneName:B},it={year:l,month:D,day:l,hour:l,minute:l,second:l,timeZoneName:B},ot={year:l,month:D,day:l,weekday:D,hour:l,minute:l,timeZoneName:D},ct={year:l,month:D,day:l,weekday:D,hour:l,minute:l,second:l,timeZoneName:D};var A=class{get type(){throw new L}get name(){throw new L}get ianaName(){return this.name}get isUniversal(){throw new L}offsetName(e,t){throw new L}formatOffset(e,t){throw new L}offset(e){throw new L}equals(e){throw new L}get isValid(){throw new L}};var Or=null,ee=class r extends A{static get instance(){return Or===null&&(Or=new r),Or}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return jt(e,t,n)}formatOffset(e,t){return te(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var Bt={};function so(r){return Bt[r]||(Bt[r]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:r,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),Bt[r]}var ao={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function io(r,e){let t=r.format(e).replace(/\u200E/g,""),n=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,s,a,i,o,c,u,d]=n;return[i,s,a,o,c,u,d]}function oo(r,e){let t=r.formatToParts(e),n=[];for(let s=0;s<t.length;s++){let{type:a,value:i}=t[s],o=ao[a];a==="era"?n[o]=i:h(o)||(n[o]=parseInt(i,10))}return n}var Lt={},M=class r extends A{static create(e){return Lt[e]||(Lt[e]=new r(e)),Lt[e]}static resetCache(){Lt={},Bt={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=r.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:t,locale:n}){return jt(e,t,n,this.name)}formatOffset(e,t){return te(this.offset(e),t)}offset(e){let t=new Date(e);if(isNaN(t))return NaN;let n=so(this.name),[s,a,i,o,c,u,d]=n.formatToParts?oo(n,t):io(n,t);o==="BC"&&(s=-Math.abs(s)+1);let g=Ee({year:s,month:a,day:i,hour:c===24?0:c,minute:u,second:d,millisecond:0}),m=+t,k=m%1e3;return m-=k>=0?k:1e3+k,(g-m)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var Hn={};function co(r,e={}){let t=JSON.stringify([r,e]),n=Hn[t];return n||(n=new Intl.ListFormat(r,e),Hn[t]=n),n}var Er={};function Cr(r,e={}){let t=JSON.stringify([r,e]),n=Er[t];return n||(n=new Intl.DateTimeFormat(r,e),Er[t]=n),n}var vr={};function uo(r,e={}){let t=JSON.stringify([r,e]),n=vr[t];return n||(n=new Intl.NumberFormat(r,e),vr[t]=n),n}var Mr={};function lo(r,e={}){let{base:t,...n}=e,s=JSON.stringify([r,n]),a=Mr[s];return a||(a=new Intl.RelativeTimeFormat(r,e),Mr[s]=a),a}var ut=null;function mo(){return ut||(ut=new Intl.DateTimeFormat().resolvedOptions().locale,ut)}var Vn={};function ho(r){let e=Vn[r];if(!e){let t=new Intl.Locale(r);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,Vn[r]=e}return e}function fo(r){let e=r.indexOf("-x-");e!==-1&&(r=r.substring(0,e));let t=r.indexOf("-u-");if(t===-1)return[r];{let n,s;try{n=Cr(r).resolvedOptions(),s=r}catch{let c=r.substring(0,t);n=Cr(c).resolvedOptions(),s=c}let{numberingSystem:a,calendar:i}=n;return[s,a,i]}}function po(r,e,t){return(t||e)&&(r.includes("-u-")||(r+="-u"),t&&(r+=`-ca-${t}`),e&&(r+=`-nu-${e}`)),r}function go(r){let e=[];for(let t=1;t<=12;t++){let n=p.utc(2009,t,1);e.push(r(n))}return e}function yo(r){let e=[];for(let t=1;t<=7;t++){let n=p.utc(2016,11,13+t);e.push(r(n))}return e}function qt(r,e,t,n){let s=r.listingMode();return s==="error"?null:s==="en"?t(e):n(e)}function wo(r){return r.numberingSystem&&r.numberingSystem!=="latn"?!1:r.numberingSystem==="latn"||!r.locale||r.locale.startsWith("en")||new Intl.DateTimeFormat(r.intl).resolvedOptions().numberingSystem==="latn"}var Ar=class{constructor(e,t,n){this.padTo=n.padTo||0,this.floor=n.floor||!1;let{padTo:s,floor:a,...i}=n;if(!t||Object.keys(i).length>0){let o={useGrouping:!1,...n};n.padTo>0&&(o.minimumIntegerDigits=n.padTo),this.inf=uo(e,o)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{let t=this.floor?Math.floor(e):Ce(e,3);return I(t,this.padTo)}}},Dr=class{constructor(e,t,n){this.opts=n,this.originalZone=void 0;let s;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let i=-1*(e.offset/60),o=i>=0?`Etc/GMT+${i}`:`Etc/GMT${i}`;e.offset!==0&&M.create(o).valid?(s=o,this.dt=e):(s="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,s=e.zone.name):(s="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let a={...this.opts};a.timeZone=a.timeZone||s,this.dtf=Cr(t,a)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){let n=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:n}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},Nr=class{constructor(e,t,n){this.opts={style:"long",...n},!t&&Ut()&&(this.rtf=lo(e,n))}format(e,t){return this.rtf?this.rtf.format(e,t):Gn(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},So={firstDay:1,minimalDays:4,weekend:[6,7]},b=class r{static fromOpts(e){return r.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,n,s,a=!1){let i=e||y.defaultLocale,o=i||(a?"en-US":mo()),c=t||y.defaultNumberingSystem,u=n||y.defaultOutputCalendar,d=lt(s)||y.defaultWeekSettings;return new r(o,c,u,d,i)}static resetCache(){ut=null,Er={},vr={},Mr={}}static fromObject({locale:e,numberingSystem:t,outputCalendar:n,weekSettings:s}={}){return r.create(e,t,n,s)}constructor(e,t,n,s,a){let[i,o,c]=fo(e);this.locale=i,this.numberingSystem=t||o||null,this.outputCalendar=n||c||null,this.weekSettings=s,this.intl=po(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=a,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=wo(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:r.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,lt(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return qt(this,e,Pr,()=>{let n=t?{month:e,day:"numeric"}:{month:e},s=t?"format":"standalone";return this.monthsCache[s][e]||(this.monthsCache[s][e]=go(a=>this.extract(a,n,"month"))),this.monthsCache[s][e]})}weekdays(e,t=!1){return qt(this,e,Fr,()=>{let n=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},s=t?"format":"standalone";return this.weekdaysCache[s][e]||(this.weekdaysCache[s][e]=yo(a=>this.extract(a,n,"weekday"))),this.weekdaysCache[s][e]})}meridiems(){return qt(this,void 0,()=>Rr,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[p.utc(2016,11,13,9),p.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return qt(this,e,_r,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[p.utc(-40,1,1),p.utc(2017,1,1)].map(n=>this.extract(n,t,"era"))),this.eraCache[e]})}extract(e,t,n){let s=this.dtFormatter(e,t),a=s.formatToParts(),i=a.find(o=>o.type.toLowerCase()===n);return i?i.value:null}numberFormatter(e={}){return new Ar(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new Dr(e,this.intl,t)}relFormatter(e={}){return new Nr(this.intl,this.isEnglish(),e)}listFormatter(e={}){return co(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Ht()?ho(this.locale):So}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}};var jr=null,O=class r extends A{static get utcInstance(){return jr===null&&(jr=new r(0)),jr}static instance(e){return e===0?r.utcInstance:new r(e)}static parseSpecifier(e){if(e){let t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new r(de(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${te(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${te(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return te(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var ve=class extends A{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function q(r,e){let t;if(h(r)||r===null)return e;if(r instanceof A)return r;if(zn(r)){let n=r.toLowerCase();return n==="default"?e:n==="local"||n==="system"?ee.instance:n==="utc"||n==="gmt"?O.utcInstance:O.parseSpecifier(n)||M.create(r)}else return G(r)?O.instance(r):typeof r=="object"&&"offset"in r&&typeof r.offset=="function"?r:new ve(r)}var $n=()=>Date.now(),Zn="system",Kn=null,Yn=null,Jn=null,Qn=60,Xn,es=null,y=class{static get now(){return $n}static set now(e){$n=e}static set defaultZone(e){Zn=e}static get defaultZone(){return q(Zn,ee.instance)}static get defaultLocale(){return Kn}static set defaultLocale(e){Kn=e}static get defaultNumberingSystem(){return Yn}static set defaultNumberingSystem(e){Yn=e}static get defaultOutputCalendar(){return Jn}static set defaultOutputCalendar(e){Jn=e}static get defaultWeekSettings(){return es}static set defaultWeekSettings(e){es=lt(e)}static get twoDigitCutoffYear(){return Qn}static set twoDigitCutoffYear(e){Qn=e%100}static get throwOnInvalid(){return Xn}static set throwOnInvalid(e){Xn=e}static resetCaches(){b.resetCache(),M.resetCache()}};var E=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var ts=[0,31,59,90,120,151,181,212,243,273,304,334],rs=[0,31,60,91,121,152,182,213,244,274,305,335];function R(r,e){return new E("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${r}, which is invalid`)}function Vt(r,e,t){let n=new Date(Date.UTC(r,e-1,t));r<100&&r>=0&&n.setUTCFullYear(n.getUTCFullYear()-1900);let s=n.getUTCDay();return s===0?7:s}function ns(r,e,t){return t+(he(r)?rs:ts)[e-1]}function ss(r,e){let t=he(r)?rs:ts,n=t.findIndex(a=>a<e),s=e-t[n];return{month:n+1,day:s}}function Gt(r,e){return(r-e+7)%7+1}function dt(r,e=4,t=1){let{year:n,month:s,day:a}=r,i=ns(n,s,a),o=Gt(Vt(n,s,a),t),c=Math.floor((i-o+14-e)/7),u;return c<1?(u=n-1,c=me(u,e,t)):c>me(n,e,t)?(u=n+1,c=1):u=n,{weekYear:u,weekNumber:c,weekday:o,...ht(r)}}function Lr(r,e=4,t=1){let{weekYear:n,weekNumber:s,weekday:a}=r,i=Gt(Vt(n,1,e),t),o=re(n),c=s*7+a-i-7+e,u;c<1?(u=n-1,c+=re(u)):c>o?(u=n+1,c-=re(n)):u=n;let{month:d,day:f}=ss(u,c);return{year:u,month:d,day:f,...ht(r)}}function zt(r){let{year:e,month:t,day:n}=r,s=ns(e,t,n);return{year:e,ordinal:s,...ht(r)}}function Br(r){let{year:e,ordinal:t}=r,{month:n,day:s}=ss(e,t);return{year:e,month:n,day:s,...ht(r)}}function qr(r,e){if(!h(r.localWeekday)||!h(r.localWeekNumber)||!h(r.localWeekYear)){if(!h(r.weekday)||!h(r.weekNumber)||!h(r.weekYear))throw new j("Cannot mix locale-based week fields with ISO-based week fields");return h(r.localWeekday)||(r.weekday=r.localWeekday),h(r.localWeekNumber)||(r.weekNumber=r.localWeekNumber),h(r.localWeekYear)||(r.weekYear=r.localWeekYear),delete r.localWeekday,delete r.localWeekNumber,delete r.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function as(r,e=4,t=1){let n=mt(r.weekYear),s=N(r.weekNumber,1,me(r.weekYear,e,t)),a=N(r.weekday,1,7);return n?s?a?!1:R("weekday",r.weekday):R("week",r.weekNumber):R("weekYear",r.weekYear)}function is(r){let e=mt(r.year),t=N(r.ordinal,1,re(r.year));return e?t?!1:R("ordinal",r.ordinal):R("year",r.year)}function Ur(r){let e=mt(r.year),t=N(r.month,1,12),n=N(r.day,1,Me(r.year,r.month));return e?t?n?!1:R("day",r.day):R("month",r.month):R("year",r.year)}function Hr(r){let{hour:e,minute:t,second:n,millisecond:s}=r,a=N(e,0,23)||e===24&&t===0&&n===0&&s===0,i=N(t,0,59),o=N(n,0,59),c=N(s,0,999);return a?i?o?c?!1:R("millisecond",s):R("second",n):R("minute",t):R("hour",e)}function h(r){return typeof r>"u"}function G(r){return typeof r=="number"}function mt(r){return typeof r=="number"&&r%1===0}function zn(r){return typeof r=="string"}function cs(r){return Object.prototype.toString.call(r)==="[object Date]"}function Ut(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Ht(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function us(r){return Array.isArray(r)?r:[r]}function Vr(r,e,t){if(r.length!==0)return r.reduce((n,s)=>{let a=[e(s),s];return n&&t(n[0],a[0])===n[0]?n:a},null)[1]}function ls(r,e){return e.reduce((t,n)=>(t[n]=r[n],t),{})}function ne(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function lt(r){if(r==null)return null;if(typeof r!="object")throw new x("Week settings must be an object");if(!N(r.firstDay,1,7)||!N(r.minimalDays,1,7)||!Array.isArray(r.weekend)||r.weekend.some(e=>!N(e,1,7)))throw new x("Invalid week settings");return{firstDay:r.firstDay,minimalDays:r.minimalDays,weekend:Array.from(r.weekend)}}function N(r,e,t){return mt(r)&&r>=e&&r<=t}function bo(r,e){return r-e*Math.floor(r/e)}function I(r,e=2){let t=r<0,n;return t?n="-"+(""+-r).padStart(e,"0"):n=(""+r).padStart(e,"0"),n}function Z(r){if(!(h(r)||r===null||r===""))return parseInt(r,10)}function se(r){if(!(h(r)||r===null||r===""))return parseFloat(r)}function ft(r){if(!(h(r)||r===null||r==="")){let e=parseFloat("0."+r)*1e3;return Math.floor(e)}}function Ce(r,e,t=!1){let n=10**e;return(t?Math.trunc:Math.round)(r*n)/n}function he(r){return r%4===0&&(r%100!==0||r%400===0)}function re(r){return he(r)?366:365}function Me(r,e){let t=bo(e-1,12)+1,n=r+(e-t)/12;return t===2?he(n)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function Ee(r){let e=Date.UTC(r.year,r.month-1,r.day,r.hour,r.minute,r.second,r.millisecond);return r.year<100&&r.year>=0&&(e=new Date(e),e.setUTCFullYear(r.year,r.month-1,r.day)),+e}function os(r,e,t){return-Gt(Vt(r,1,e),t)+e-1}function me(r,e=4,t=1){let n=os(r,e,t),s=os(r+1,e,t);return(re(r)-n+s)/7}function pt(r){return r>99?r:r>y.twoDigitCutoffYear?1900+r:2e3+r}function jt(r,e,t,n=null){let s=new Date(r),a={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};n&&(a.timeZone=n);let i={timeZoneName:e,...a},o=new Intl.DateTimeFormat(t,i).formatToParts(s).find(c=>c.type.toLowerCase()==="timezonename");return o?o.value:null}function de(r,e){let t=parseInt(r,10);Number.isNaN(t)&&(t=0);let n=parseInt(e,10)||0,s=t<0||Object.is(t,-0)?-n:n;return t*60+s}function Gr(r){let e=Number(r);if(typeof r=="boolean"||r===""||Number.isNaN(e))throw new x(`Invalid unit value ${r}`);return e}function Ae(r,e){let t={};for(let n in r)if(ne(r,n)){let s=r[n];if(s==null)continue;t[e(n)]=Gr(s)}return t}function te(r,e){let t=Math.trunc(Math.abs(r/60)),n=Math.trunc(Math.abs(r%60)),s=r>=0?"+":"-";switch(e){case"short":return`${s}${I(t,2)}:${I(n,2)}`;case"narrow":return`${s}${t}${n>0?`:${n}`:""}`;case"techie":return`${s}${I(t,2)}${I(n,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function ht(r){return ls(r,["hour","minute","second","millisecond"])}var To=["January","February","March","April","May","June","July","August","September","October","November","December"],zr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Io=["J","F","M","A","M","J","J","A","S","O","N","D"];function Pr(r){switch(r){case"narrow":return[...Io];case"short":return[...zr];case"long":return[...To];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var $r=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Zr=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],xo=["M","T","W","T","F","S","S"];function Fr(r){switch(r){case"narrow":return[...xo];case"short":return[...Zr];case"long":return[...$r];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var Rr=["AM","PM"],ko=["Before Christ","Anno Domini"],Oo=["BC","AD"],Eo=["B","A"];function _r(r){switch(r){case"narrow":return[...Eo];case"short":return[...Oo];case"long":return[...ko];default:return null}}function ds(r){return Rr[r.hour<12?0:1]}function ms(r,e){return Fr(e)[r.weekday-1]}function hs(r,e){return Pr(e)[r.month-1]}function fs(r,e){return _r(e)[r.year<0?0:1]}function Gn(r,e,t="always",n=!1){let s={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},a=["hours","minutes","seconds"].indexOf(r)===-1;if(t==="auto"&&a){let f=r==="days";switch(e){case 1:return f?"tomorrow":`next ${s[r][0]}`;case-1:return f?"yesterday":`last ${s[r][0]}`;case 0:return f?"today":`this ${s[r][0]}`;default:}}let i=Object.is(e,-0)||e<0,o=Math.abs(e),c=o===1,u=s[r],d=n?c?u[1]:u[2]||u[1]:c?s[r][0]:r;return i?`${o} ${d} ago`:`in ${o} ${d}`}function ps(r,e){let t="";for(let n of r)n.literal?t+=n.val:t+=e(n.val);return t}var Co={D:X,DD:Ve,DDD:Ge,DDDD:ze,t:$e,tt:Ze,ttt:Ke,tttt:Ye,T:Je,TT:Qe,TTT:Xe,TTTT:et,f:tt,ff:nt,fff:at,ffff:ot,F:rt,FF:st,FFF:it,FFFF:ct},C=class r{static create(e,t={}){return new r(e,t)}static parseFormat(e){let t=null,n="",s=!1,a=[];for(let i=0;i<e.length;i++){let o=e.charAt(i);o==="'"?(n.length>0&&a.push({literal:s||/^\s+$/.test(n),val:n}),t=null,n="",s=!s):s||o===t?n+=o:(n.length>0&&a.push({literal:/^\s+$/.test(n),val:n}),n=o,t=o)}return n.length>0&&a.push({literal:s||/^\s+$/.test(n),val:n}),a}static macroTokenToFormatOpts(e){return Co[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0){if(this.opts.forceSimple)return I(e,t);let n={...this.opts};return t>0&&(n.padTo=t),this.loc.numberFormatter(n).format(e)}formatDateTimeFromString(e,t){let n=this.loc.listingMode()==="en",s=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",a=(m,k)=>this.loc.extract(e,m,k),i=m=>e.isOffsetFixed&&e.offset===0&&m.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,m.format):"",o=()=>n?ds(e):a({hour:"numeric",hourCycle:"h12"},"dayperiod"),c=(m,k)=>n?hs(e,m):a(k?{month:m}:{month:m,day:"numeric"},"month"),u=(m,k)=>n?ms(e,m):a(k?{weekday:m}:{weekday:m,month:"long",day:"numeric"},"weekday"),d=m=>{let k=r.macroTokenToFormatOpts(m);return k?this.formatWithSystemDefault(e,k):m},f=m=>n?fs(e,m):a({era:m},"era"),g=m=>{switch(m){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return i({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return i({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return i({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return o();case"d":return s?a({day:"numeric"},"day"):this.num(e.day);case"dd":return s?a({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return u("short",!0);case"cccc":return u("long",!0);case"ccccc":return u("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return u("short",!1);case"EEEE":return u("long",!1);case"EEEEE":return u("narrow",!1);case"L":return s?a({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return s?a({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return c("short",!0);case"LLLL":return c("long",!0);case"LLLLL":return c("narrow",!0);case"M":return s?a({month:"numeric"},"month"):this.num(e.month);case"MM":return s?a({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return c("short",!1);case"MMMM":return c("long",!1);case"MMMMM":return c("narrow",!1);case"y":return s?a({year:"numeric"},"year"):this.num(e.year);case"yy":return s?a({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return s?a({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return s?a({year:"numeric"},"year"):this.num(e.year,6);case"G":return f("short");case"GG":return f("long");case"GGGGG":return f("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return d(m)}};return ps(r.parseFormat(t),g)}formatDurationFromString(e,t){let n=c=>{switch(c[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},s=c=>u=>{let d=n(u);return d?this.num(c.get(d),u.length):u},a=r.parseFormat(t),i=a.reduce((c,{literal:u,val:d})=>u?c:c.concat(d),[]),o=e.shiftTo(...i.map(n).filter(c=>c));return ps(a,s(o))}};var ys=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Ne(...r){let e=r.reduce((t,n)=>t+n.source,"");return RegExp(`^${e}$`)}function Pe(...r){return e=>r.reduce(([t,n,s],a)=>{let[i,o,c]=a(e,s);return[{...t,...i},o||n,c]},[{},null,1]).slice(0,2)}function Fe(r,...e){if(r==null)return[null,null];for(let[t,n]of e){let s=t.exec(r);if(s)return n(s)}return[null,null]}function ws(...r){return(e,t)=>{let n={},s;for(s=0;s<r.length;s++)n[r[s]]=Z(e[t+s]);return[n,null,t+s]}}var Ss=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,vo=`(?:${Ss.source}?(?:\\[(${ys.source})\\])?)?`,Kr=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,bs=RegExp(`${Kr.source}${vo}`),Yr=RegExp(`(?:T${bs.source})?`),Mo=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Ao=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Do=/(\d{4})-?(\d{3})/,No=ws("weekYear","weekNumber","weekDay"),Po=ws("year","ordinal"),Fo=/(\d{4})-(\d\d)-(\d\d)/,Ts=RegExp(`${Kr.source} ?(?:${Ss.source}|(${ys.source}))?`),Ro=RegExp(`(?: ${Ts.source})?`);function De(r,e,t){let n=r[e];return h(n)?t:Z(n)}function _o(r,e){return[{year:De(r,e),month:De(r,e+1,1),day:De(r,e+2,1)},null,e+3]}function Re(r,e){return[{hours:De(r,e,0),minutes:De(r,e+1,0),seconds:De(r,e+2,0),milliseconds:ft(r[e+3])},null,e+4]}function gt(r,e){let t=!r[e]&&!r[e+1],n=de(r[e+1],r[e+2]),s=t?null:O.instance(n);return[{},s,e+3]}function yt(r,e){let t=r[e]?M.create(r[e]):null;return[{},t,e+1]}var Wo=RegExp(`^T?${Kr.source}$`),jo=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Lo(r){let[e,t,n,s,a,i,o,c,u]=r,d=e[0]==="-",f=c&&c[0]==="-",g=(m,k=!1)=>m!==void 0&&(k||m&&d)?-m:m;return[{years:g(se(t)),months:g(se(n)),weeks:g(se(s)),days:g(se(a)),hours:g(se(i)),minutes:g(se(o)),seconds:g(se(c),c==="-0"),milliseconds:g(ft(u),f)}]}var Bo={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function Jr(r,e,t,n,s,a,i){let o={year:e.length===2?pt(Z(e)):Z(e),month:zr.indexOf(t)+1,day:Z(n),hour:Z(s),minute:Z(a)};return i&&(o.second=Z(i)),r&&(o.weekday=r.length>3?$r.indexOf(r)+1:Zr.indexOf(r)+1),o}var qo=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Uo(r){let[,e,t,n,s,a,i,o,c,u,d,f]=r,g=Jr(e,s,n,t,a,i,o),m;return c?m=Bo[c]:u?m=0:m=de(d,f),[g,new O(m)]}function Ho(r){return r.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var Vo=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Go=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,zo=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function gs(r){let[,e,t,n,s,a,i,o]=r;return[Jr(e,s,n,t,a,i,o),O.utcInstance]}function $o(r){let[,e,t,n,s,a,i,o]=r;return[Jr(e,o,t,n,s,a,i),O.utcInstance]}var Zo=Ne(Mo,Yr),Ko=Ne(Ao,Yr),Yo=Ne(Do,Yr),Jo=Ne(bs),Is=Pe(_o,Re,gt,yt),Qo=Pe(No,Re,gt,yt),Xo=Pe(Po,Re,gt,yt),ec=Pe(Re,gt,yt);function xs(r){return Fe(r,[Zo,Is],[Ko,Qo],[Yo,Xo],[Jo,ec])}function ks(r){return Fe(Ho(r),[qo,Uo])}function Os(r){return Fe(r,[Vo,gs],[Go,gs],[zo,$o])}function Es(r){return Fe(r,[jo,Lo])}var tc=Pe(Re);function Cs(r){return Fe(r,[Wo,tc])}var rc=Ne(Fo,Ro),nc=Ne(Ts),sc=Pe(Re,gt,yt);function vs(r){return Fe(r,[rc,Is],[nc,sc])}var Ms="Invalid Duration",Ds={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},ac={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...Ds},_=146097/400,_e=146097/4800,ic={years:{quarters:4,months:12,weeks:_/7,days:_,hours:_*24,minutes:_*24*60,seconds:_*24*60*60,milliseconds:_*24*60*60*1e3},quarters:{months:3,weeks:_/28,days:_/4,hours:_*24/4,minutes:_*24*60/4,seconds:_*24*60*60/4,milliseconds:_*24*60*60*1e3/4},months:{weeks:_e/7,days:_e,hours:_e*24,minutes:_e*24*60,seconds:_e*24*60*60,milliseconds:_e*24*60*60*1e3},...Ds},fe=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],oc=fe.slice(0).reverse();function ae(r,e,t=!1){let n={values:t?e.values:{...r.values,...e.values||{}},loc:r.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||r.conversionAccuracy,matrix:e.matrix||r.matrix};return new T(n)}function Ns(r,e){let t=e.milliseconds??0;for(let n of oc.slice(1))e[n]&&(t+=e[n]*r[n].milliseconds);return t}function As(r,e){let t=Ns(r,e)<0?-1:1;fe.reduceRight((n,s)=>{if(h(e[s]))return n;if(n){let a=e[n]*t,i=r[s][n],o=Math.floor(a/i);e[s]+=o*t,e[n]-=o*i*t}return s},null),fe.reduce((n,s)=>{if(h(e[s]))return n;if(n){let a=e[n]%1;e[n]-=a,e[s]+=a*r[n][s]}return s},null)}function cc(r){let e={};for(let[t,n]of Object.entries(r))n!==0&&(e[t]=n);return e}var T=class r{constructor(e){let t=e.conversionAccuracy==="longterm"||!1,n=t?ic:ac;e.matrix&&(n=e.matrix),this.values=e.values,this.loc=e.loc||b.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=n,this.isLuxonDuration=!0}static fromMillis(e,t){return r.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new x(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new r({values:Ae(e,r.normalizeUnit),loc:b.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(G(e))return r.fromMillis(e);if(r.isDuration(e))return e;if(typeof e=="object")return r.fromObject(e);throw new x(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){let[n]=Es(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){let[n]=Cs(e);return n?r.fromObject(n,t):r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new x("need to specify a reason the Duration is invalid");let n=e instanceof E?e:new E(e,t);if(y.throwOnInvalid)throw new _t(n);return new r({invalid:n})}static normalizeUnit(e){let t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new Oe(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){let n={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?C.create(this.loc,n).formatDurationFromString(this,e):Ms}toHuman(e={}){if(!this.isValid)return Ms;let t=fe.map(n=>{let s=this.values[n];return h(s)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:n.slice(0,-1)}).format(s)}).filter(n=>n);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(t)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Ce(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},p.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Ns(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e),n={};for(let s of fe)(ne(t.values,s)||ne(this.values,s))&&(n[s]=t.get(s)+this.get(s));return ae(this,{values:n},!0)}minus(e){if(!this.isValid)return this;let t=r.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let n of Object.keys(this.values))t[n]=Gr(e(this.values[n],n));return ae(this,{values:t},!0)}get(e){return this[r.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let t={...this.values,...Ae(e,r.normalizeUnit)};return ae(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:n,matrix:s}={}){let i={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:s,conversionAccuracy:n};return ae(this,i)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return As(this.matrix,e),ae(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=cc(this.normalize().shiftToAll().toObject());return ae(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(i=>r.normalizeUnit(i));let t={},n={},s=this.toObject(),a;for(let i of fe)if(e.indexOf(i)>=0){a=i;let o=0;for(let u in n)o+=this.matrix[u][i]*n[u],n[u]=0;G(s[i])&&(o+=s[i]);let c=Math.trunc(o);t[i]=c,n[i]=(o*1e3-c*1e3)/1e3}else G(s[i])&&(n[i]=s[i]);for(let i in n)n[i]!==0&&(t[a]+=i===a?n[i]:n[i]/this.matrix[a][i]);return As(this.matrix,t),ae(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return ae(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(n,s){return n===void 0||n===0?s===void 0||s===0:n===s}for(let n of fe)if(!t(this.values[n],e.values[n]))return!1;return!0}};var We="Invalid Interval";function uc(r,e){return!r||!r.isValid?K.invalid("missing or invalid start"):!e||!e.isValid?K.invalid("missing or invalid end"):e<r?K.invalid("end before start",`The end of an interval must be after its start, but you had start=${r.toISO()} and end=${e.toISO()}`):null}var K=class r{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,t=null){if(!e)throw new x("need to specify a reason the Interval is invalid");let n=e instanceof E?e:new E(e,t);if(y.throwOnInvalid)throw new Rt(n);return new r({invalid:n})}static fromDateTimes(e,t){let n=je(e),s=je(t),a=uc(n,s);return a??new r({start:n,end:s})}static after(e,t){let n=T.fromDurationLike(t),s=je(e);return r.fromDateTimes(s,s.plus(n))}static before(e,t){let n=T.fromDurationLike(t),s=je(e);return r.fromDateTimes(s.minus(n),s)}static fromISO(e,t){let[n,s]=(e||"").split("/",2);if(n&&s){let a,i;try{a=p.fromISO(n,t),i=a.isValid}catch{i=!1}let o,c;try{o=p.fromISO(s,t),c=o.isValid}catch{c=!1}if(i&&c)return r.fromDateTimes(a,o);if(i){let u=T.fromISO(s,t);if(u.isValid)return r.after(a,u)}else if(c){let u=T.fromISO(n,t);if(u.isValid)return r.before(o,u)}}return r.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",t){if(!this.isValid)return NaN;let n=this.start.startOf(e,t),s;return t?.useLocaleWeeks?s=this.end.reconfigure({locale:n.locale}):s=this.end,s=s.startOf(e,t),Math.floor(s.diff(n,e).get(e))+(s.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?r.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];let t=e.map(je).filter(i=>this.contains(i)).sort((i,o)=>i.toMillis()-o.toMillis()),n=[],{s}=this,a=0;for(;s<this.e;){let i=t[a]||this.e,o=+i>+this.e?this.e:i;n.push(r.fromDateTimes(s,o)),s=o,a+=1}return n}splitBy(e){let t=T.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s:n}=this,s=1,a,i=[];for(;n<this.e;){let o=this.start.plus(t.mapUnits(c=>c*s));a=+o>+this.e?this.e:o,i.push(r.fromDateTimes(n,a)),n=a,s+=1}return i}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let t=this.s>e.s?this.s:e.s,n=this.e<e.e?this.e:e.e;return t>=n?null:r.fromDateTimes(t,n)}union(e){if(!this.isValid)return this;let t=this.s<e.s?this.s:e.s,n=this.e>e.e?this.e:e.e;return r.fromDateTimes(t,n)}static merge(e){let[t,n]=e.sort((s,a)=>s.s-a.s).reduce(([s,a],i)=>a?a.overlaps(i)||a.abutsStart(i)?[s,a.union(i)]:[s.concat([a]),i]:[s,i],[[],null]);return n&&t.push(n),t}static xor(e){let t=null,n=0,s=[],a=e.map(c=>[{time:c.s,type:"s"},{time:c.e,type:"e"}]),i=Array.prototype.concat(...a),o=i.sort((c,u)=>c.time-u.time);for(let c of o)n+=c.type==="s"?1:-1,n===1?t=c.time:(t&&+t!=+c.time&&s.push(r.fromDateTimes(t,c.time)),t=null);return r.merge(s)}difference(...e){return r.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:We}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=X,t={}){return this.isValid?C.create(this.s.loc.clone(t),e).formatInterval(this):We}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:We}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:We}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:We}toFormat(e,{separator:t=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:We}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):T.invalid(this.invalidReason)}mapEndpoints(e){return r.fromDateTimes(e(this.s),e(this.e))}};var Y=class{static hasDST(e=y.defaultZone){let t=p.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return M.isValidZone(e)}static normalizeZone(e){return q(e,y.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||b.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||b.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||b.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null,outputCalendar:a="gregory"}={}){return(s||b.create(t,n,a)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null,outputCalendar:a="gregory"}={}){return(s||b.create(t,n,a)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null}={}){return(s||b.create(t,n,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:n=null,locObj:s=null}={}){return(s||b.create(t,n,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return b.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return b.create(t,null,"gregory").eras(e)}static features(){return{relative:Ut(),localeWeek:Ht()}}};function Ps(r,e){let t=s=>s.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),n=t(e)-t(r);return Math.floor(T.fromMillis(n).as("days"))}function lc(r,e,t){let n=[["years",(c,u)=>u.year-c.year],["quarters",(c,u)=>u.quarter-c.quarter+(u.year-c.year)*4],["months",(c,u)=>u.month-c.month+(u.year-c.year)*12],["weeks",(c,u)=>{let d=Ps(c,u);return(d-d%7)/7}],["days",Ps]],s={},a=r,i,o;for(let[c,u]of n)t.indexOf(c)>=0&&(i=c,s[c]=u(r,e),o=a.plus(s),o>e?(s[c]--,r=a.plus(s),r>e&&(o=r,s[c]--,r=a.plus(s))):r=o);return[r,s,o,i]}function Fs(r,e,t,n){let[s,a,i,o]=lc(r,e,t),c=e-s,u=t.filter(f=>["hours","minutes","seconds","milliseconds"].indexOf(f)>=0);u.length===0&&(i<e&&(i=s.plus({[o]:1})),i!==s&&(a[o]=(a[o]||0)+c/(i-s)));let d=T.fromObject(a,n);return u.length>0?T.fromMillis(c,n).shiftTo(...u).plus(d):d}var Qr={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Rs={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},dc=Qr.hanidec.replace(/[\[|\]]/g,"").split("");function _s(r){let e=parseInt(r,10);if(isNaN(e)){e="";for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);if(r[t].search(Qr.hanidec)!==-1)e+=dc.indexOf(r[t]);else for(let s in Rs){let[a,i]=Rs[s];n>=a&&n<=i&&(e+=n-a)}}return parseInt(e,10)}else return e}function W({numberingSystem:r},e=""){return new RegExp(`${Qr[r||"latn"]}${e}`)}var mc="missing Intl.DateTimeFormat.formatToParts support";function w(r,e=t=>t){return{regex:r,deser:([t])=>e(_s(t))}}var hc="\xA0",Ls=`[ ${hc}]`,Bs=new RegExp(Ls,"g");function fc(r){return r.replace(/\./g,"\\.?").replace(Bs,Ls)}function Ws(r){return r.replace(/\./g,"").replace(Bs," ").toLowerCase()}function U(r,e){return r===null?null:{regex:RegExp(r.map(fc).join("|")),deser:([t])=>r.findIndex(n=>Ws(t)===Ws(n))+e}}function js(r,e){return{regex:r,deser:([,t,n])=>de(t,n),groups:e}}function $t(r){return{regex:r,deser:([e])=>e}}function pc(r){return r.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function gc(r,e){let t=W(e),n=W(e,"{2}"),s=W(e,"{3}"),a=W(e,"{4}"),i=W(e,"{6}"),o=W(e,"{1,2}"),c=W(e,"{1,3}"),u=W(e,"{1,6}"),d=W(e,"{1,9}"),f=W(e,"{2,4}"),g=W(e,"{4,6}"),m=V=>({regex:RegExp(pc(V.val)),deser:([Te])=>Te,literal:!0}),be=(V=>{if(r.literal)return m(V);switch(V.val){case"G":return U(e.eras("short"),0);case"GG":return U(e.eras("long"),0);case"y":return w(u);case"yy":return w(f,pt);case"yyyy":return w(a);case"yyyyy":return w(g);case"yyyyyy":return w(i);case"M":return w(o);case"MM":return w(n);case"MMM":return U(e.months("short",!0),1);case"MMMM":return U(e.months("long",!0),1);case"L":return w(o);case"LL":return w(n);case"LLL":return U(e.months("short",!1),1);case"LLLL":return U(e.months("long",!1),1);case"d":return w(o);case"dd":return w(n);case"o":return w(c);case"ooo":return w(s);case"HH":return w(n);case"H":return w(o);case"hh":return w(n);case"h":return w(o);case"mm":return w(n);case"m":return w(o);case"q":return w(o);case"qq":return w(n);case"s":return w(o);case"ss":return w(n);case"S":return w(c);case"SSS":return w(s);case"u":return $t(d);case"uu":return $t(o);case"uuu":return w(t);case"a":return U(e.meridiems(),0);case"kkkk":return w(a);case"kk":return w(f,pt);case"W":return w(o);case"WW":return w(n);case"E":case"c":return w(t);case"EEE":return U(e.weekdays("short",!1),1);case"EEEE":return U(e.weekdays("long",!1),1);case"ccc":return U(e.weekdays("short",!0),1);case"cccc":return U(e.weekdays("long",!0),1);case"Z":case"ZZ":return js(new RegExp(`([+-]${o.source})(?::(${n.source}))?`),2);case"ZZZ":return js(new RegExp(`([+-]${o.source})(${n.source})?`),2);case"z":return $t(/[a-z_+-/]{1,256}?/i);case" ":return $t(/[^\S\n\r]/);default:return m(V)}})(r)||{invalidReason:mc};return be.token=r,be}var yc={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function wc(r,e,t){let{type:n,value:s}=r;if(n==="literal"){let c=/^\s+$/.test(s);return{literal:!c,val:c?" ":s}}let a=e[n],i=n;n==="hour"&&(e.hour12!=null?i=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?i="hour12":i="hour24":i=t.hour12?"hour12":"hour24");let o=yc[i];if(typeof o=="object"&&(o=o[a]),o)return{literal:!1,val:o}}function Sc(r){return[`^${r.map(t=>t.regex).reduce((t,n)=>`${t}(${n.source})`,"")}$`,r]}function bc(r,e,t){let n=r.match(e);if(n){let s={},a=1;for(let i in t)if(ne(t,i)){let o=t[i],c=o.groups?o.groups+1:1;!o.literal&&o.token&&(s[o.token.val[0]]=o.deser(n.slice(a,a+c))),a+=c}return[n,s]}else return[n,{}]}function Tc(r){let e=a=>{switch(a){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},t=null,n;return h(r.z)||(t=M.create(r.z)),h(r.Z)||(t||(t=new O(r.Z)),n=r.Z),h(r.q)||(r.M=(r.q-1)*3+1),h(r.h)||(r.h<12&&r.a===1?r.h+=12:r.h===12&&r.a===0&&(r.h=0)),r.G===0&&r.y&&(r.y=-r.y),h(r.u)||(r.S=ft(r.u)),[Object.keys(r).reduce((a,i)=>{let o=e(i);return o&&(a[o]=r[i]),a},{}),t,n]}var Xr=null;function Ic(){return Xr||(Xr=p.fromMillis(1555555555555)),Xr}function xc(r,e){if(r.literal)return r;let t=C.macroTokenToFormatOpts(r.val),n=rn(t,e);return n==null||n.includes(void 0)?r:n}function en(r,e){return Array.prototype.concat(...r.map(t=>xc(t,e)))}function tn(r,e,t){let n=en(C.parseFormat(t),r),s=n.map(i=>gc(i,r)),a=s.find(i=>i.invalidReason);if(a)return{input:e,tokens:n,invalidReason:a.invalidReason};{let[i,o]=Sc(s),c=RegExp(i,"i"),[u,d]=bc(e,c,o),[f,g,m]=d?Tc(d):[null,null,void 0];if(ne(d,"a")&&ne(d,"H"))throw new j("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:n,regex:c,rawMatches:u,matches:d,result:f,zone:g,specificOffset:m}}}function qs(r,e,t){let{result:n,zone:s,specificOffset:a,invalidReason:i}=tn(r,e,t);return[n,s,a,i]}function rn(r,e){if(!r)return null;let n=C.create(e,r).dtFormatter(Ic()),s=n.formatToParts(),a=n.resolvedOptions();return s.map(i=>wc(i,r,a))}var nn="Invalid DateTime",Us=864e13;function Zt(r){return new E("unsupported zone",`the zone "${r.name}" is not supported`)}function sn(r){return r.weekData===null&&(r.weekData=dt(r.c)),r.weekData}function an(r){return r.localWeekData===null&&(r.localWeekData=dt(r.c,r.loc.getMinDaysInFirstWeek(),r.loc.getStartOfWeek())),r.localWeekData}function pe(r,e){let t={ts:r.ts,zone:r.zone,c:r.c,o:r.o,loc:r.loc,invalid:r.invalid};return new p({...t,...e,old:t})}function Ks(r,e,t){let n=r-e*60*1e3,s=t.offset(n);if(e===s)return[n,e];n-=(s-e)*60*1e3;let a=t.offset(n);return s===a?[n,s]:[r-Math.min(s,a)*60*1e3,Math.max(s,a)]}function Kt(r,e){r+=e*60*1e3;let t=new Date(r);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function Jt(r,e,t){return Ks(Ee(r),e,t)}function Hs(r,e){let t=r.o,n=r.c.year+Math.trunc(e.years),s=r.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,a={...r.c,year:n,month:s,day:Math.min(r.c.day,Me(n,s))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},i=T.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),o=Ee(a),[c,u]=Ks(o,t,r.zone);return i!==0&&(c+=i,u=r.zone.offset(c)),{ts:c,o:u}}function wt(r,e,t,n,s,a){let{setZone:i,zone:o}=t;if(r&&Object.keys(r).length!==0||e){let c=e||o,u=p.fromObject(r,{...t,zone:c,specificOffset:a});return i?u:u.setZone(o)}else return p.invalid(new E("unparsable",`the input "${s}" can't be parsed as ${n}`))}function Yt(r,e,t=!0){return r.isValid?C.create(b.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(r,e):null}function on(r,e){let t=r.c.year>9999||r.c.year<0,n="";return t&&r.c.year>=0&&(n+="+"),n+=I(r.c.year,t?6:4),e?(n+="-",n+=I(r.c.month),n+="-",n+=I(r.c.day)):(n+=I(r.c.month),n+=I(r.c.day)),n}function Vs(r,e,t,n,s,a){let i=I(r.c.hour);return e?(i+=":",i+=I(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(i+=":")):i+=I(r.c.minute),(r.c.millisecond!==0||r.c.second!==0||!t)&&(i+=I(r.c.second),(r.c.millisecond!==0||!n)&&(i+=".",i+=I(r.c.millisecond,3))),s&&(r.isOffsetFixed&&r.offset===0&&!a?i+="Z":r.o<0?(i+="-",i+=I(Math.trunc(-r.o/60)),i+=":",i+=I(Math.trunc(-r.o%60))):(i+="+",i+=I(Math.trunc(r.o/60)),i+=":",i+=I(Math.trunc(r.o%60)))),a&&(i+="["+r.zone.ianaName+"]"),i}var Ys={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},kc={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Oc={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Js=["year","month","day","hour","minute","second","millisecond"],Ec=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Cc=["year","ordinal","hour","minute","second","millisecond"];function vc(r){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[r.toLowerCase()];if(!e)throw new Oe(r);return e}function Gs(r){switch(r.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return vc(r)}}function zs(r,e){let t=q(e.zone,y.defaultZone),n=b.fromObject(e),s=y.now(),a,i;if(h(r.year))a=s;else{for(let u of Js)h(r[u])&&(r[u]=Ys[u]);let o=Ur(r)||Hr(r);if(o)return p.invalid(o);let c=t.offset(s);[a,i]=Jt(r,c,t)}return new p({ts:a,zone:t,loc:n,o:i})}function $s(r,e,t){let n=h(t.round)?!0:t.round,s=(i,o)=>(i=Ce(i,n||t.calendary?0:2,!0),e.loc.clone(t).relFormatter(t).format(i,o)),a=i=>t.calendary?e.hasSame(r,i)?0:e.startOf(i).diff(r.startOf(i),i).get(i):e.diff(r,i).get(i);if(t.unit)return s(a(t.unit),t.unit);for(let i of t.units){let o=a(i);if(Math.abs(o)>=1)return s(o,i)}return s(r>e?-0:0,t.units[t.units.length-1])}function Zs(r){let e={},t;return r.length>0&&typeof r[r.length-1]=="object"?(e=r[r.length-1],t=Array.from(r).slice(0,r.length-1)):t=Array.from(r),[e,t]}var p=class r{constructor(e){let t=e.zone||y.defaultZone,n=e.invalid||(Number.isNaN(e.ts)?new E("invalid input"):null)||(t.isValid?null:Zt(t));this.ts=h(e.ts)?y.now():e.ts;let s=null,a=null;if(!n)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[s,a]=[e.old.c,e.old.o];else{let o=t.offset(this.ts);s=Kt(this.ts,o),n=Number.isNaN(s.year)?new E("invalid input"):null,s=n?null:s,a=n?null:o}this._zone=t,this.loc=e.loc||b.create(),this.invalid=n,this.weekData=null,this.localWeekData=null,this.c=s,this.o=a,this.isLuxonDateTime=!0}static now(){return new r({})}static local(){let[e,t]=Zs(arguments),[n,s,a,i,o,c,u]=t;return zs({year:n,month:s,day:a,hour:i,minute:o,second:c,millisecond:u},e)}static utc(){let[e,t]=Zs(arguments),[n,s,a,i,o,c,u]=t;return e.zone=O.utcInstance,zs({year:n,month:s,day:a,hour:i,minute:o,second:c,millisecond:u},e)}static fromJSDate(e,t={}){let n=cs(e)?e.valueOf():NaN;if(Number.isNaN(n))return r.invalid("invalid input");let s=q(t.zone,y.defaultZone);return s.isValid?new r({ts:n,zone:s,loc:b.fromObject(t)}):r.invalid(Zt(s))}static fromMillis(e,t={}){if(G(e))return e<-Us||e>Us?r.invalid("Timestamp out of range"):new r({ts:e,zone:q(t.zone,y.defaultZone),loc:b.fromObject(t)});throw new x(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(G(e))return new r({ts:e*1e3,zone:q(t.zone,y.defaultZone),loc:b.fromObject(t)});throw new x("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};let n=q(t.zone,y.defaultZone);if(!n.isValid)return r.invalid(Zt(n));let s=b.fromObject(t),a=Ae(e,Gs),{minDaysInFirstWeek:i,startOfWeek:o}=qr(a,s),c=y.now(),u=h(t.specificOffset)?n.offset(c):t.specificOffset,d=!h(a.ordinal),f=!h(a.year),g=!h(a.month)||!h(a.day),m=f||g,k=a.weekYear||a.weekNumber;if((m||d)&&k)throw new j("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(g&&d)throw new j("Can't mix ordinal dates with month/day");let be=k||a.weekday&&!m,V,Te,Ue=Kt(c,u);be?(V=Ec,Te=kc,Ue=dt(Ue,i,o)):d?(V=Cc,Te=Oc,Ue=zt(Ue)):(V=Js,Te=Ys);let Ln=!1;for(let He of V){let Yi=a[He];h(Yi)?Ln?a[He]=Te[He]:a[He]=Ue[He]:Ln=!0}let zi=be?as(a,i,o):d?is(a):Ur(a),Bn=zi||Hr(a);if(Bn)return r.invalid(Bn);let $i=be?Lr(a,i,o):d?Br(a):a,[Zi,Ki]=Jt($i,u,n),Ir=new r({ts:Zi,zone:n,o:Ki,loc:s});return a.weekday&&m&&e.weekday!==Ir.weekday?r.invalid("mismatched weekday",`you can't specify both a weekday of ${a.weekday} and a date of ${Ir.toISO()}`):Ir}static fromISO(e,t={}){let[n,s]=xs(e);return wt(n,s,t,"ISO 8601",e)}static fromRFC2822(e,t={}){let[n,s]=ks(e);return wt(n,s,t,"RFC 2822",e)}static fromHTTP(e,t={}){let[n,s]=Os(e);return wt(n,s,t,"HTTP",t)}static fromFormat(e,t,n={}){if(h(e)||h(t))throw new x("fromFormat requires an input string and a format");let{locale:s=null,numberingSystem:a=null}=n,i=b.fromOpts({locale:s,numberingSystem:a,defaultToEN:!0}),[o,c,u,d]=qs(i,e,t);return d?r.invalid(d):wt(o,c,n,`format ${t}`,e,u)}static fromString(e,t,n={}){return r.fromFormat(e,t,n)}static fromSQL(e,t={}){let[n,s]=vs(e);return wt(n,s,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new x("need to specify a reason the DateTime is invalid");let n=e instanceof E?e:new E(e,t);if(y.throwOnInvalid)throw new Ft(n);return new r({invalid:n})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let n=rn(e,b.fromObject(t));return n?n.map(s=>s?s.val:null).join(""):null}static expandFormat(e,t={}){return en(C.parseFormat(e),b.fromObject(t)).map(s=>s.val).join("")}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?sn(this).weekYear:NaN}get weekNumber(){return this.isValid?sn(this).weekNumber:NaN}get weekday(){return this.isValid?sn(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?an(this).weekday:NaN}get localWeekNumber(){return this.isValid?an(this).weekNumber:NaN}get localWeekYear(){return this.isValid?an(this).weekYear:NaN}get ordinal(){return this.isValid?zt(this.c).ordinal:NaN}get monthShort(){return this.isValid?Y.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Y.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Y.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Y.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,t=6e4,n=Ee(this.c),s=this.zone.offset(n-e),a=this.zone.offset(n+e),i=this.zone.offset(n-s*t),o=this.zone.offset(n-a*t);if(i===o)return[this];let c=n-i*t,u=n-o*t,d=Kt(c,i),f=Kt(u,o);return d.hour===f.hour&&d.minute===f.minute&&d.second===f.second&&d.millisecond===f.millisecond?[pe(this,{ts:c}),pe(this,{ts:u})]:[this]}get isInLeapYear(){return he(this.year)}get daysInMonth(){return Me(this.year,this.month)}get daysInYear(){return this.isValid?re(this.year):NaN}get weeksInWeekYear(){return this.isValid?me(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?me(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:n,calendar:s}=C.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:n,outputCalendar:s}}toUTC(e=0,t={}){return this.setZone(O.instance(e),t)}toLocal(){return this.setZone(y.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:n=!1}={}){if(e=q(e,y.defaultZone),e.equals(this.zone))return this;if(e.isValid){let s=this.ts;if(t||n){let a=e.offset(this.ts),i=this.toObject();[s]=Jt(i,a,e)}return pe(this,{ts:s,zone:e})}else return r.invalid(Zt(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:n}={}){let s=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:n});return pe(this,{loc:s})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=Ae(e,Gs),{minDaysInFirstWeek:n,startOfWeek:s}=qr(t,this.loc),a=!h(t.weekYear)||!h(t.weekNumber)||!h(t.weekday),i=!h(t.ordinal),o=!h(t.year),c=!h(t.month)||!h(t.day),u=o||c,d=t.weekYear||t.weekNumber;if((u||i)&&d)throw new j("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(c&&i)throw new j("Can't mix ordinal dates with month/day");let f;a?f=Lr({...dt(this.c,n,s),...t},n,s):h(t.ordinal)?(f={...this.toObject(),...t},h(t.day)&&(f.day=Math.min(Me(f.year,f.month),f.day))):f=Br({...zt(this.c),...t});let[g,m]=Jt(f,this.o,this.zone);return pe(this,{ts:g,o:m})}plus(e){if(!this.isValid)return this;let t=T.fromDurationLike(e);return pe(this,Hs(this,t))}minus(e){if(!this.isValid)return this;let t=T.fromDurationLike(e).negate();return pe(this,Hs(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;let n={},s=T.normalizeUnit(e);switch(s){case"years":n.month=1;case"quarters":case"months":n.day=1;case"weeks":case"days":n.hour=0;case"hours":n.minute=0;case"minutes":n.second=0;case"seconds":n.millisecond=0;break;case"milliseconds":break}if(s==="weeks")if(t){let a=this.loc.getStartOfWeek(),{weekday:i}=this;i<a&&(n.weekNumber=this.weekNumber-1),n.weekday=a}else n.weekday=1;if(s==="quarters"){let a=Math.ceil(this.month/3);n.month=(a-1)*3+1}return this.set(n)}endOf(e,t){return this.isValid?this.plus({[e]:1}).startOf(e,t).minus(1):this}toFormat(e,t={}){return this.isValid?C.create(this.loc.redefaultToEN(t)).formatDateTimeFromString(this,e):nn}toLocaleString(e=X,t={}){return this.isValid?C.create(this.loc.clone(t),e).formatDateTime(this):nn}toLocaleParts(e={}){return this.isValid?C.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:t=!1,suppressMilliseconds:n=!1,includeOffset:s=!0,extendedZone:a=!1}={}){if(!this.isValid)return null;let i=e==="extended",o=on(this,i);return o+="T",o+=Vs(this,i,t,n,s,a),o}toISODate({format:e="extended"}={}){return this.isValid?on(this,e==="extended"):null}toISOWeekDate(){return Yt(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:t=!1,includeOffset:n=!0,includePrefix:s=!1,extendedZone:a=!1,format:i="extended"}={}){return this.isValid?(s?"T":"")+Vs(this,i==="extended",t,e,n,a):null}toRFC2822(){return Yt(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Yt(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?on(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:t=!1,includeOffsetSpace:n=!0}={}){let s="HH:mm:ss.SSS";return(t||e)&&(n&&(s+=" "),t?s+="z":e&&(s+="ZZ")),Yt(this,s,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():nn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let t={...this.c};return e.includeConfig&&(t.outputCalendar=this.outputCalendar,t.numberingSystem=this.loc.numberingSystem,t.locale=this.loc.locale),t}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,t="milliseconds",n={}){if(!this.isValid||!e.isValid)return T.invalid("created by diffing an invalid DateTime");let s={locale:this.locale,numberingSystem:this.numberingSystem,...n},a=us(t).map(T.normalizeUnit),i=e.valueOf()>this.valueOf(),o=i?this:e,c=i?e:this,u=Fs(o,c,a,s);return i?u.negate():u}diffNow(e="milliseconds",t={}){return this.diff(r.now(),e,t)}until(e){return this.isValid?K.fromDateTimes(this,e):this}hasSame(e,t,n){if(!this.isValid)return!1;let s=e.valueOf(),a=this.setZone(e.zone,{keepLocalTime:!0});return a.startOf(t,n)<=s&&s<=a.endOf(t,n)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let t=e.base||r.fromObject({},{zone:this.zone}),n=e.padding?this<t?-e.padding:e.padding:0,s=["years","months","days","hours","minutes","seconds"],a=e.unit;return Array.isArray(e.unit)&&(s=e.unit,a=void 0),$s(t,this.plus(n),{...e,numeric:"always",units:s,unit:a})}toRelativeCalendar(e={}){return this.isValid?$s(e.base||r.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(r.isDateTime))throw new x("min requires all arguments be DateTimes");return Vr(e,t=>t.valueOf(),Math.min)}static max(...e){if(!e.every(r.isDateTime))throw new x("max requires all arguments be DateTimes");return Vr(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,n={}){let{locale:s=null,numberingSystem:a=null}=n,i=b.fromOpts({locale:s,numberingSystem:a,defaultToEN:!0});return tn(i,e,t)}static fromStringExplain(e,t,n={}){return r.fromFormatExplain(e,t,n)}static get DATE_SHORT(){return X}static get DATE_MED(){return Ve}static get DATE_MED_WITH_WEEKDAY(){return xr}static get DATE_FULL(){return Ge}static get DATE_HUGE(){return ze}static get TIME_SIMPLE(){return $e}static get TIME_WITH_SECONDS(){return Ze}static get TIME_WITH_SHORT_OFFSET(){return Ke}static get TIME_WITH_LONG_OFFSET(){return Ye}static get TIME_24_SIMPLE(){return Je}static get TIME_24_WITH_SECONDS(){return Qe}static get TIME_24_WITH_SHORT_OFFSET(){return Xe}static get TIME_24_WITH_LONG_OFFSET(){return et}static get DATETIME_SHORT(){return tt}static get DATETIME_SHORT_WITH_SECONDS(){return rt}static get DATETIME_MED(){return nt}static get DATETIME_MED_WITH_SECONDS(){return st}static get DATETIME_MED_WITH_WEEKDAY(){return kr}static get DATETIME_FULL(){return at}static get DATETIME_FULL_WITH_SECONDS(){return it}static get DATETIME_HUGE(){return ot}static get DATETIME_HUGE_WITH_SECONDS(){return ct}};function je(r){if(p.isDateTime(r))return r;if(r&&r.valueOf&&G(r.valueOf()))return p.fromJSDate(r);if(r&&typeof r=="object")return p.fromObject(r);throw new x(`Unknown datetime argument: ${r}, of type ${typeof r}`)}var bt=require("@mysten/sui.js/transactions"),hn=require("@mysten/sui.js/transactions"),It=require("@mysten/sui.js/utils"),fn=require("buffer"),Xa=require("@mysten/sui.js/utils"),In=require("@mysten/sui.js/bcs"),xt=require("@mysten/sui.js/utils");var Qs=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>(t&=63,t<36?e+=t.toString(36):t<62?e+=(t-26).toString(36).toUpperCase():t>62?e+="-":e+="_",e),"");var yn=require("@mysten/sui.js/transactions"),ue=require("@mysten/sui.js/utils");var Tt=require("@mysten/sui.js/transactions"),kt=require("@mysten/sui.js/utils");var pi=Ie(Qt(),1),gi=require("@msafe/sui3-utils"),yi=require("@msafe/sui3-utils"),wi=require("@msafe/sui3-utils"),Tn=require("@mysten/sui.js/bcs"),ce=require("@mysten/sui.js/utils"),bi=require("@msafe/sui3-utils"),Be=require("@msafe/sui3-utils"),Ti=require("@msafe/sui3-utils"),Ii=Ie(Qt(),1),ki=require("@msafe/sui3-utils"),Ei=require("@msafe/sui3-utils"),Ci=require("@mysten/sui.js/transactions"),sr=require("@msafe/sui3-utils"),Mi=require("@mysten/sui.js/transactions"),ar=require("@mysten/sui.js/utils"),vm=Ie(Qt(),1),Bc=Object.defineProperty,Da=(r,e)=>{for(var t in e)Bc(r,t,{get:e[t],enumerable:!0})},Pa={};Da(Pa,{contractId:()=>_a,default:()=>qc,feeObjId:()=>La,roleObjId:()=>Wa,status:()=>Ra,transaction:()=>Fa,upgradeCapObjId:()=>Ba,vaultObjId:()=>ja});var Fa="DiBZq4UmVVYiRL6ZJmFKYoHcxtxqrhsCXSkFyT7wUr3j",Ra="success",_a="0x81c960dc653975fbd0072deca8afb92d322898c911622898ba1b2e3ad0c4bd8d",Wa="0xc6ec0bdee0bb59a72077e9acd2f42457043cf47080b3d3fad4d39abf28bba63a",ja="0xbc4021387fbac149119fd24e92be9e58f745774292f3a2a12e2ac6daf5363e1d",La="0x4178f63970fe2daeb256dc5730ad172e82b3e8eb45f31b33e0daae72cd35e1e1",Ba="0xe1e9aa7d222d151bfe6dd83358b0d7fdcb11260f710800cfaf7ccc1b1e245115",qc={transaction:Fa,status:Ra,contractId:_a,roleObjId:Wa,vaultObjId:ja,feeObjId:La,upgradeCapObjId:Ba},qa={};Da(qa,{contractId:()=>Va,default:()=>Uc,feeObjId:()=>$a,roleObjId:()=>Ga,status:()=>Ha,transaction:()=>Ua,upgradeCapObjId:()=>Za,vaultObjId:()=>za});var Ua="855FNDV8o8Z3fWULPnQo9qdhLJpsg7wZrkCpNyfw9KfB",Ha="success",Va="0xc357c3985e8fb875d6b37141497af660779aa1bab0ec489b2213efd74067d1fa",Ga="0x5ab49bdf9fd1413e328ef242b3f8d83dde791b38a0b627bfc87fb25c010d34f1",za="0xb483558770d8eb26007f193b75db40f0a45f2e36863a687625885d4de6993378",$a="0x48453fc4d7cde3fe35aad89e5dfb496608a6a55ea529a1c0274681a808627f94",Za="0x34279779a0d0d36bd5044b04830d607fa1b0ecf316548c8ac3a44151e4f1a42a",Uc={transaction:Ua,status:Ha,contractId:Va,roleObjId:Ga,vaultObjId:za,feeObjId:$a,upgradeCapObjId:Za},Hc="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Vc="https://sui-testnet.blockvision.org/v1/2Sgk89ivT64MnKdcGzjmyjY2ndD",Gc="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",zc="https://sui-mainnet.blockvision.org/v1/2Sgk7NPvqkd7mESYkxF01yX15l7",$c="https://bc3p6l5unl.execute-api.us-west-1.amazonaws.com/prod",Zc="https://rolsbkota7.execute-api.us-west-1.amazonaws.com/prod",Kc="https://6p6mkx33ne.execute-api.us-west-1.amazonaws.com/prod",Yc="https://xrae3mrjv5.execute-api.us-west-1.amazonaws.com/prod",la=Pa,da=qa,Jc=new Map([["dev",{env:"dev",rpc:{url:Hc},backend:{url:$c},contract:la}],["stg",{env:"stg",rpc:{url:Vc},backend:{url:Zc},contract:la}],["prev",{env:"prev",rpc:{url:Gc},backend:{url:Kc},contract:da}],["prod",{env:"prod",rpc:{url:zc},backend:{url:Yc},contract:da}]]);function Qc(r,e){let t=Jc.get(r);if(!t)throw new Error(`Env not supported: ${r}`);return e&&e.rpc&&(t.rpc=e.rpc),e&&e.backend&&(t.backend=e.backend),e&&e.contract&&(t.contract=e.contract),t}var F=class extends Error{mpayErrorCode;context;constructor(r,e,t={}){let{cause:n,context:s}=t;n?super(`[MPay] ${e}: ${n}`):super(`[MPay] ${e}`),this.mpayErrorCode=r,this.context=s}},Xc=class extends F{constructor(){super(11,"Backend is not specified")}},eu=class extends F{constructor(){super(1,"Wallet not connected")}},ln=class extends F{constructor(r,e){super(10,r,{context:e})}},tu=class ye{constructor(e){this.apiURL=e}static parseResponseData(e){if(e instanceof J.AxiosError)throw new ln(e.response?.statusText);if(e.status===200){if(e.data.success)return e.data.data;throw new ln(e.data.code)}throw new ln(e.status.toString())}async getIncomingStreams(e,t){let n=await J.default.post(`${this.apiURL}/stream`,{recipient:e,...t});return ye.parseResponseData(n)}async getOutgoingStreams(e,t){let n=await J.default.post(`${this.apiURL}/stream`,{sender:e,...t});return ye.parseResponseData(n)}async getStreamHistory(e){let t=await J.default.post(`${this.apiURL}/stream-events`,e),n=ye.parseResponseData(t);return n.data.forEach(s=>{let a=s;return a.data.type==="create_stream"?a.data.balance=BigInt(a.data.balance):a.data.type==="cancel_stream"?a.data.withdrawAmount=BigInt(a.data.withdrawAmount):a.data.type==="claim"||a.data.type==="auto_claim"?a.data.claimAmount=BigInt(a.data.claimAmount):a.data.type==="set_auto_claim"&&(a.data.enabled=!!a.data.enabled),a.createdAt=new Date(a.createdAt),a}),n}async getAllCoinTypes(e){let t=await J.default.post(`${this.apiURL}/stream-info`,{address:e});return ye.parseResponseData(t)}async getAllRecipients(e,t){let n=await J.default.post(`${this.apiURL}/stream-info`,{sender:e,status:t});return ye.parseResponseData(n)}async getAllSenders(e,t){let n=await J.default.post(`${this.apiURL}/stream-info`,{recipient:e,status:t});return ye.parseResponseData(n)}},Ya=class Ja{signer;suiClient;envConfig;_backend;constructor(e){this.envConfig=e,this.suiClient=new Ka.SuiClient({url:e.rpc.url}),e.backend&&(this._backend=new tu(e.backend.url))}static new(e,t){let n=Qc(e,t);return new Ja(n)}get walletType(){return this.wallet?this.wallet.type:"disconnected"}get backend(){if(!this._backend)throw new Xc;return this._backend}set backend(e){this._backend=e}connectWallet(e){this.signer=e}disconnect(){this.signer=void 0}get wallet(){if(!this.signer)throw new eu;return this.signer}async walletAddress(){return this.wallet.address()}},ma=50n,dn=10000n,ru=25n,ha=100000000n,ge=class{constructor(r){this.object=r}moveArg(r){return r.object(this.object)}},fa=class{constructor(r){this.objects=r}moveArgs(r){return r.makeMoveVec({objects:this.objects.map(e=>r.object(e))})}},tr=class Qa{constructor(e){return this.result=e,new Proxy(this,{set(){throw new Error("The transaction result is a proxy, and does not support setting properties directly")},get(t,n){if(n in t)return Reflect.get(t,n);let s=i=>new Qa(t.result[i]);if(n===Symbol.iterator)return function*(){let i=0;for(;;)yield s(i),i++};if(typeof n=="symbol")return;let a=parseInt(n,10);if(!(Number.isNaN(a)||a<0))return s(a)}})}moveArg(){return this.result}},pa=class extends F{constructor(r,e){super(3,r,{context:e})}},nu=class{constructor(r){this.results=r}callResult(r){return this.results.results[r]}returnValue(r,e){return r.returnValues[e]}getValue(r=0,e=0){let t=this.callResult(r);return this.returnValue(t,e)}getAddress(r=0,e=0){let[t,n]=this.getValue(r,e);if(n!=="address")throw new pa("Invalid contract return type.",{ctx:{expectType:"address",gotType:n}});return(0,Xa.normalizeSuiAddress)(fn.Buffer.from(t).toString("hex"))}getU64(r=0,e=0){let[t,n]=this.getValue(r,e);if(n!=="u64")throw new pa("Invalid contract return type.",{ctx:{expectType:"u64",gotType:n}});return fn.Buffer.from(t).readBigInt64LE()}},P=class extends F{constructor(r,e,t){super(2,`Invalid input: ${r}`,{context:{fieldKey:e,fieldValue:t}})}},ei={groupId:"string",name:"string"},su=64;function au(r){return ti(r),In.bcs.ser(ei,r).toString("base64")}function pn(r){let e=In.bcs.de(ei,r,"base64");return ti(e),e}function ti(r){if(!ga(r.name))throw new P("Invalid metadata: Name contains unknown character");if(!ga(r.groupId))throw new P("Invalid metadata: Group ID contains unknown character");if(r.name.length>su)throw new P("Invalid metadata: Name exceed max length 64")}function ga(r){return/^[\x00-\x7F]+$/.test(r)}function ri(r,e){return(0,xt.normalizeStructTag)(r)===(0,xt.normalizeStructTag)(e)}function Le(r,e){return(0,xt.normalizeStructTag)(r)===(0,xt.normalizeStructTag)(e)}var ni="txn.gas";function iu(){return Qs()}var gn=class si{constructor(e,t,n){this.globals=e,this.feeContract=t,this.streamContract=n}static convertCreateStreamInfoToInternal(e){return{metadata:au({name:e.name,groupId:iu()}),coinType:(0,It.normalizeStructTag)(e.coinType),recipients:e.recipients.map(t=>({address:t.address,cliffAmount:t.cliffAmount,amountPerEpoch:t.amountPerStep})),epochInterval:e.interval,numberEpoch:e.steps,startTime:e.startTimeMs,cancelable:e.cancelable}}async buildCreateStreamTransactionBlock(e){let t=new hn.TransactionBlock,n=this.calculateFeesInternal(e),s=this.getCreateStreamCoinRequests(e,n),a=await this.wallet.requestCoins(s),i=await this.addMergeCoins(t,a[0]),o;s.length>1?o=await this.addMergeCoins(t,a[1]):o=i;for(let c=0;c<e.recipients.length;c++){let u=e.recipients[c],d=this.amountForRecipient(u,e.numberEpoch),f=this.getStreamFeeLocal(d),[g]=t.splitCoins(i,[t.pure(d+f,"u64")]),[m]=t.splitCoins(o,[t.pure(this.flatSuiFee,"u64")]);this.streamContract.createStream(t,{paymentCoin:new tr(g),flatFeeCoin:new tr(m),metadata:e.metadata,recipient:u.address,timeStart:e.startTime,cliff:u.cliffAmount,epochInterval:e.epochInterval,numEpoch:e.numberEpoch,amountPerEpoch:u.amountPerEpoch,cancelable:e.cancelable,coinType:e.coinType})}return t}calculateCreateStreamFees(e){let t=si.convertCreateStreamInfoToInternal(e);return this.calculateFeesInternal(t)}feeParams(){return{createFeePercent:{numerator:ma,denominator:dn},claimFeePercent:{numerator:ru,denominator:dn},flatFeePerStream:ha}}async addMergeCoins(e,t){let n;return t.mergedCoins&&t.mergedCoins.length?(e.mergeCoins(e.object(t.primaryCoin),t.mergedCoins.map(s=>e.object(s))),n=e.object(t.primaryCoin)):t.primaryCoin===ni?n=e.gas:n=e.object(t.primaryCoin),n}getCreateStreamCoinRequests(e,t){let n=e.coinType;return ri(n,It.SUI_TYPE_ARG)?[{coinType:n,amount:t.totalAmount+t.streamFeeAmount+t.flatFeeAmount}]:[{coinType:n,amount:t.totalAmount+t.streamFeeAmount},{coinType:It.SUI_TYPE_ARG,amount:t.flatFeeAmount}]}calculateFeesInternal(e){let t=e.recipients.reduce((n,s)=>{let a=this.amountForRecipient(s,e.numberEpoch),i=this.getStreamFeeLocal(a);return{totalAmount:n.totalAmount+a,streamFeeAmount:n.streamFeeAmount+i}},{totalAmount:0n,streamFeeAmount:0n});return{flatFeeAmount:BigInt(e.recipients.length)*this.flatSuiFee,...t}}amountForRecipient(e,t){return BigInt(e.amountPerEpoch)*BigInt(t)+BigInt(e.cliffAmount)}get flatSuiFee(){return ha}getStreamFeeLocal(e){return e*ma/dn}async getStreamFeeRemote(e){let t=this.feeContract.streamingFee(new hn.TransactionBlock,e),n=await this.globals.suiClient.devInspectTransactionBlock({sender:await this.globals.walletAddress(),transactionBlock:t});return new nu(n).getU64()}get wallet(){return this.globals.wallet}},ou="0x0000000000000000000000000000000000000000000000000000000000000006",ai=class{constructor(r,e,t){this.moduleName=r,this.config=e,this.globals=t}addContractCall(r,e){let t=`${this.config.contractId}::${this.moduleName}::${e.method}`;return r.add(yn.Transactions.MoveCall({target:t,arguments:e.arguments.map(n=>n instanceof fa?n.moveArgs(r):n instanceof ge?n.moveArg(r):n instanceof tr?n.moveArg():r.pure(n)),typeArguments:e.typeArgs})),r}addTransactionBlock(r,e,t=[],n=[]){r.add(yn.Transactions.MoveCall({target:e,arguments:t.map(s=>s instanceof fa?s.moveArgs(r):s instanceof ge?s.moveArg(r):s instanceof tr?s.moveArg():r.pure(s)),typeArguments:n}))}makeObject(r){return typeof r=="string"?new ge(r):r}vaultObject(){return new ge(this.config.vaultObjId)}roleObject(){return new ge(this.config.roleObjId)}feeObject(){return new ge(this.config.feeObjId)}clockObject(){return new ge(ou)}},ii=class ie extends ai{constructor(e,t){super(ie.ModuleName,e,t),this.config=e,this.globals=t}static ModuleName="fee_module";static MethodName={set_streaming_fee:"set_streaming_fee",set_claim_fee:"set_claim_fee",set_streaming_flat_fee:"set_streaming_flat_fee",streaming_flat_fee:"streaming_flat_fee",streaming_fee:"streaming_fee",claim_fee:"claim_fee",fee_denominator:"fee_denominator"};setStreamingFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:ie.MethodName.set_streaming_fee,arguments:[n,s,t],typeArgs:[]})}setStreamingFlatFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:ie.MethodName.set_streaming_flat_fee,arguments:[n,s,t],typeArgs:[]})}setClaimFee(e,t){let n=this.roleObject(),s=this.feeObject();return this.addContractCall(e,{method:ie.MethodName.set_claim_fee,arguments:[n,s,t],typeArgs:[]})}streamingFee(e,t){let n=this.feeObject();return this.addContractCall(e,{method:ie.MethodName.streaming_fee,arguments:[n,t],typeArgs:[]})}claimFee(e,t){return this.addContractCall(e,{method:ie.MethodName.claim_fee,arguments:[this.feeObject(),t],typeArgs:[]})}feeDenominator(e){return this.addContractCall(e,{method:ie.MethodName.fee_denominator,arguments:[this.feeObject()],typeArgs:[]})}},nr=class v extends ai{constructor(e,t){super(v.ModuleName,e,t),this.config=e,this.globals=t}static ModuleName="stream";static MethodName={create_stream:"create_stream",set_auto_claim:"set_auto_claim",cancel_stream:"cancel_stream",claim_stream:"claim_stream",claim_stream_by_proxy:"claim_stream_by_proxy",stream_current_epoch:"stream_current_epoch",now_milli_seconds:"now_milli_seconds"};createStream(e,t){let n=this.feeObject(),s=this.vaultObject(),a=this.makeObject(t.paymentCoin),i=this.makeObject(t.flatFeeCoin),o=this.clockObject();return this.addContractCall(e,{method:v.MethodName.create_stream,arguments:[n,s,a,i,t.metadata,t.recipient,t.timeStart,t.cliff,t.epochInterval,t.numEpoch,t.amountPerEpoch,t.cancelable,o],typeArgs:[t.coinType]})}setAutoClaim(e,t){let n=this.makeObject(t.streamId);return this.addContractCall(e,{method:v.MethodName.set_auto_claim,arguments:[n,t.enabled],typeArgs:[t.coinType]})}cancelStream(e,t){let n=this.makeObject(t.streamId),s=this.clockObject();return this.addContractCall(e,{method:v.MethodName.cancel_stream,arguments:[n,s],typeArgs:[t.coinType]})}claimStream(e,t){let n=this.makeObject(t.streamId),s=this.clockObject();return this.addContractCall(e,{method:v.MethodName.claim_stream,arguments:[n,s],typeArgs:[t.coinType]})}claimStreamByProxy(e,t){let n=this.makeObject(t.streamId),s=this.vaultObject(),a=this.feeObject(),i=this.clockObject();return this.addContractCall(e,{method:v.MethodName.claim_stream_by_proxy,arguments:[n,s,a,i],typeArgs:[t.coinType]})}get createStreamTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.create_stream}`}get setAutoClaimTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.set_auto_claim}`}get cancelStreamTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.cancel_stream}`}get claimStreamTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.claim_stream}`}get claimStreamByProxyTarget(){return`${this.config.contractId}::${v.ModuleName}::${v.MethodName.claim_stream_by_proxy}`}},oi=class{constructor(r){this.globals=r;let e=r.envConfig.contract;this.feeContract=new ii(e,r),this.streamContract=new nr(e,r)}feeContract;streamContract;async createStreams(r){let e=gn.convertCreateStreamInfoToInternal(r);return this.createStreamHelper().buildCreateStreamTransactionBlock(e)}createStreamHelper(){return new gn(this.globals,this.feeContract,this.streamContract)}setAutoClaim(r,e,t){let n=new bt.TransactionBlock;return this.streamContract.setAutoClaim(n,{streamId:r,enabled:e,coinType:t})}claimStream(r,e){let t=new bt.TransactionBlock;return this.streamContract.claimStream(t,{streamId:r,coinType:e})}claimStreamByProxy(r,e){let t=new bt.TransactionBlock;return this.streamContract.claimStreamByProxy(t,{streamId:r,coinType:e})}cancelStream(r,e){let t=new bt.TransactionBlock;return this.streamContract.cancelStream(t,{streamId:r,coinType:e}),t}},cu=class extends F{constructor(r,e){super(12,`Transaction failed: ${e}`,{context:{status:r,msg:e}})}},uu=1e3,lu=class{constructor(r){this.globals=r,this.coinMetaHelper=new du(r.suiClient),this.createStreamHelper=new oi(r).createStreamHelper()}coinMetaHelper;createStreamHelper;getStreamIdsFromCreateStreamResponse(r){if(r.effects?.status.status!=="success")throw new cu(r.effects?.status.status,r.effects?.status.error);return r.objectChanges.filter(e=>e.type==="created"&&e.objectType.startsWith(`${this.globals.envConfig.contract.contractId}::stream::Stream`)).map(e=>e.objectId)}calculateCreateStreamFees(r){return this.createStreamHelper.calculateCreateStreamFees(r)}feeParams(){return this.createStreamHelper.feeParams()}calculateStreamAmount(r){if(r.steps===0n)throw new P("Invalid stream steps: 0");let e=r.cliff?r.cliff:{numerator:0n,denominator:100n},t=r.totalAmount*e.numerator/e.denominator,n=(r.totalAmount-t)/r.steps,s={realTotalAmount:n*r.steps+t,cliffAmount:t,amountPerStep:n};return this.validateStreamAmount(s,r.totalAmount),s}calculateTimelineByInterval(r){if(r.steps===0n)throw new P("Invalid stream steps: 0");let e=r.timeStart.plus(r.interval.toMillis()*Number(r.steps)),t={timeStart:r.timeStart,timeEnd:e,interval:r.interval,steps:r.steps};return this.validateTimeline(t),t}calculateTimelineByTotalDuration(r){if(r.steps===0n)throw new P("Invalid stream steps: 0");let e=BigInt(r.total.toMillis())/r.steps,t=r.timeStart.plus(T.fromMillis(Number(e*r.steps))),n={timeStart:r.timeStart,timeEnd:t,interval:T.fromMillis(Number(e)),steps:r.steps};return this.validateTimeline(n),n}async getBalance(r,e){let t=await this.globals.suiClient.getBalance({owner:r,coinType:e}),n=await this.getCoinMeta(e);return{...t,coinType:(0,qe.normalizeStructTag)(t.coinType),coinMeta:n}}async getAllBalance(r){let e=await this.globals.suiClient.getAllBalances({owner:r}),t=await Promise.all(e.map(n=>this.getCoinMeta(n.coinType)));return e.map((n,s)=>({...n,coinType:(0,qe.normalizeStructTag)(n.coinType),coinMeta:t[s]}))}async getCoinMeta(r){return this.coinMetaHelper.getCoinMeta(r)}async simulateTransactionBlock(r){return this.globals.suiClient.devInspectTransactionBlock({transactionBlock:r,sender:await this.globals.wallet.address()})}validateStreamAmount(r,e){if(r.amountPerStep===0n)throw new P("Stream amount too small","totalAmount",e);if(r.cliffAmount>r.realTotalAmount)throw new P("Invalid cliff settings")}validateTimeline(r){if(r.interval.toMillis()<uu)throw new P("Interval shall be at least 1 second","interval",r.interval)}},du=class{constructor(r){this.suiClient=r,this.coinMetaReg=new Map}coinMetaReg;async getCoinMeta(r){let e=(0,qe.normalizeStructTag)(r||qe.SUI_TYPE_ARG);if(this.coinMetaReg.has(e))return this.coinMetaReg.get(e);let t=await this.queryCoinMeta(e);return t&&this.coinMetaReg.set(e,t),t}async queryCoinMeta(r){return await this.suiClient.getCoinMetadata({coinType:r})||void 0}},mu=class extends F{constructor(){super(7,"Connected wallet is not creator")}},ya=class extends F{constructor(){super(8,"Connected wallet is not recipient")}},wa=class extends F{constructor(r,e){super(6,r,{context:e})}},H=class extends F{constructor(r,e={}){super(0,r,e)}},hu=class extends F{constructor(r){super(5,"Stream not found",{context:{streamId:r}})}},fu=(1n<<64n)-1n,rr=1e3;function Sa(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/rr);return p.fromMillis(t*rr)}function ba(r){let e;typeof r=="number"?e=r:typeof r=="bigint"?e=Number(r):e=r.toMillis();let t=Math.round(e/rr);return T.fromMillis(t*rr)}var xn=class oe{constructor(e,t,n){this.globals=e,this.streamId=t,this.rawData=n,this.streamContract=new nr(e.envConfig.contract,e)}streamContract;type="Stream";static async new(e,t){let n=await oe.fetchStreamData(e,t);return new oe(e,t,n)}static fromObjectData(e,t,n){let s=oe.parseRawStreamData(t,n);return new oe(e,t,s)}get info(){return{name:this.name,creator:this.creator,coinType:this.coinType,totalAmount:this.totalAmount,start:this.timeStart,end:this.timeEnd,cancelable:this.cancelable,cliffAmount:this.cliff,duration:this.duration,interval:this.interval,steps:this.totalSteps,nextReleaseDate:this.nextReleaseDate,nextReleaseAmount:this.nextReleaseAmount,groupId:this.groupId,streamId:this.streamId,recipient:this.recipient,progress:this.progress,autoClaim:this.autoClaim}}get groupCommonInfo(){return{name:this.name,groupId:this.groupId,creator:this.creator,start:this.timeStart,interval:this.interval,steps:this.totalSteps,cancelable:this.cancelable}}async refresh(){this.rawData=await oe.fetchStreamData(this.globals,this.streamId)}refreshWithData(e){if(e.data?.objectId!==this.streamId)throw new H("Object Id does not align");this.rawData=oe.parseRawStreamData(this.streamId,e)}async historyEvents(e){return this.globals.backend.getStreamHistory({streamId:this.streamId,pagination:e})}async cancel(){if(await this.globals.walletAddress()!==this.creator)throw new mu;let e=new Tt.TransactionBlock;return this.streamContract.cancelStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async claim(){if(await this.globals.walletAddress()!==this.recipient)throw new ya;let e=new Tt.TransactionBlock;return this.streamContract.claimStream(e,{streamId:this.streamId,coinType:this.coinType}),e}async setAutoClaim(e){if(await this.globals.walletAddress()!==this.recipient)throw new ya;let t=new Tt.TransactionBlock;return this.streamContract.setAutoClaim(t,{streamId:this.streamId,coinType:this.coinType,enabled:e}),t}async claimByProxy(){let e=new Tt.TransactionBlock;return this.streamContract.claimStreamByProxy(e,{streamId:this.streamId,coinType:this.coinType}),e}get wallet(){return this.globals.wallet}get client(){return this.globals.suiClient}get coinType(){return(0,kt.normalizeStructTag)(this.rawData.coinType)}get progress(){return{status:this.streamStatus,total:this.totalAmount,streamed:this.streamedAmount,claimed:this.claimedAmount,claimable:this.claimable,canceled:this.canceledAmount}}get balance(){return this.rawData.balance}get autoClaim(){return this.rawData.autoClaim}get amountPerEpoch(){return this.rawData.config.amountPerEpoch}get cancelable(){return this.rawData.config.cancelable}get cliff(){return this.rawData.config.cliff}get creator(){return this.rawData.config.creator}get interval(){return ba(this.rawData.config.epochInterval)}get groupId(){let{metadata:e}=this.rawData.config;return pn(e).groupId}get name(){let{metadata:e}=this.rawData.config;return pn(e).name}get recipient(){return this.rawData.config.recipient}get timeStart(){return Sa(this.rawData.config.timeStart)}get duration(){let e=this.rawData.config,t=e.epochInterval*e.totalEpoch;return ba(t)}get timeEnd(){return this.timeStart.plus(this.duration)}get totalSteps(){return this.rawData.config.totalEpoch}get claimable(){return this.streamedAmount-this.claimedAmount}get nextReleaseDate(){return this.currentEpoch===-1n?this.timeStart:this.currentEpoch>=this.totalSteps||this.isCanceled?null:Sa((this.currentEpoch+1n)*this.rawData.config.epochInterval+this.rawData.config.timeStart)}get nextReleaseAmount(){return this.currentEpoch===-1n?this.cliff:this.currentEpoch>=this.totalSteps||this.isCanceled?null:this.amountPerEpoch}get streamStatus(){let e=this.rawData.status.status;return e===16?"CANCELED":e===17?"SETTLED":e===1?"COMPLETED":this.currentEpoch>=this.totalSteps?"STREAMED":"STREAMING"}get streamedAmount(){return this.currentEpoch===-1n?0n:this.isCanceled?this.rawData.status.epochCanceled*this.amountPerEpoch+this.cliff:this.currentEpoch*this.amountPerEpoch+this.cliff}get claimedAmount(){return this.rawData.status.epochClaimed===fu?0n:this.rawData.status.epochClaimed*this.amountPerEpoch+this.cliff}get currentEpoch(){let e=p.now().toMillis(),t=this.timeStart.toMillis();if(e<t)return-1n;let n=Math.floor((e-t)/Number(this.rawData.config.epochInterval));return BigInt(n)>Number(this.rawData.config.totalEpoch)?this.rawData.config.totalEpoch:BigInt(n)}get totalAmount(){let e=this.rawData.config;return e.amountPerEpoch*e.totalEpoch+e.cliff}get isCanceled(){let e=this.rawData.status.status;return e===16||e===17}get canceledAmount(){return this.isCanceled?this.totalAmount-this.streamedAmount:0n}static async fetchStreamData(e,t){let n=await e.suiClient.getObject({id:t,options:{showContent:!0,showType:!0}});return oe.parseRawStreamData(t,n)}static parseRawStreamData(e,t){if(t.error)throw t.error.code==="notExists"?new hu(e):new wa(`get stream data: ${t.error.code}`,{streamId:e,...t.error});let n=t.data.content;if(n.dataType!=="moveObject")throw new wa("Unexpected object type",{gotType:n.dataType});let{typeParams:s}=(0,kt.parseStructTag)(n.type),a=(0,kt.normalizeStructTag)(s[0]),i=n.fields,o=i.config.fields,c=i.status.fields;return{coinType:a,autoClaim:i.auto_claim,balance:BigInt(i.balance.fields.balance),config:{amountPerEpoch:BigInt(o.amount_per_epoch),cancelable:o.cancelable,cliff:BigInt(o.cliff),creator:o.creator,epochInterval:BigInt(o.epoch_interval),metadata:o.metadata,recipient:o.recipient,timeStart:BigInt(o.time_start),totalEpoch:BigInt(o.total_epoch)},status:{status:c.status,epochCanceled:BigInt(c.epoch_canceled),epochClaimed:BigInt(c.epoch_claimed)}}}},mn=class extends F{constructor(r,e){super(9,`Invalid stream group: ${r}`,{context:e})}};async function pu(r){let e=[];for(;await r.hasNext();){let t=await r.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var gu=class{constructor(r){this.requester=r,this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},ci=class{constructor(r){this.requester=r,this.pager=new gu(r),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}},yu=25;async function Ta(r,e,t){let n=new ui(e),s=new li(r,n,t);return await pu(s)}var ui=class{constructor(r){this.ids=r,this.cursor=-1}cursor;async hasNext(){return this.cursor<this.ids.length-1}async next(){if(this.cursor+=1,this.cursor>=this.ids.length)throw new Error("invalid iterator implementation");return this.ids[this.cursor]}},li=class extends ci{constructor(r,e,t){super(new wu(r,e,t)),this.suiClient=r,this.idIter=e,this.options=t}},wu=class{constructor(r,e,t){this.suiClient=r,this.stringIter=e,this.options=t,this.filter=t?.filter,this.pageSize=t?.pageSize||yu,this.objectOptions=t?.objectOptions||{showType:!0,showContent:!0}}filter;pageSize;objectOptions;async doNextRequest(){let r=[];for(;r.length<this.pageSize&&await this.stringIter.hasNext();){let n=await this.stringIter.next();n&&r.push(n)}let e=await this.suiClient.multiGetObjects({ids:r,options:this.objectOptions}),t;if(this.filter){let{filter:n}=this;t=e.filter(s=>n?.(s))}else t=e;return{data:t,hasNext:await this.stringIter.hasNext()}}},Su=class Xt{constructor(e,t){if(this.globals=e,this.streams=t,t.length===0)throw new mn("stream size 0");let n=t.map(s=>s.groupId);if(new Set(n).size!==1)throw new P("Stream does not have same group ID")}type="StreamGroup";static async new(e,t){let n=await Ta(e.suiClient,t);return n.forEach(s=>{if(!s)throw new H("stream group object data undefined")}),Xt.newFromObjectResponse(e,t,n)}static async newFromObjectResponse(e,t,n){let s=await Xt.parseGroupStreams(e,t,n);return new Xt(e,s)}static checkStreamGroup(e){let t=e.map(a=>a.groupCommonInfo),n=t[0],s=!0;return t.forEach(a=>{bu(n,a)||(s=!1)}),s}async refresh(){let e=await Ta(this.globals.suiClient,this.streams.map(t=>t.streamId));this.streams.forEach((t,n)=>{t.refreshWithData(e[n])})}get groupId(){return this.streams[0].groupId}get creator(){return this.streams[0].creator}get info(){return{groupId:this.groupId,streamIds:this.streams.map(e=>e.streamId),progress:this.progress,name:this.streams[0].name,creator:this.creator,coinType:this.streams[0].coinType,totalAmount:this.streams.reduce((e,t)=>e+t.totalAmount,0n),start:this.streams[0].timeStart,end:this.streams[0].timeEnd,cancelable:this.streams[0].cancelable,cliffAmount:this.streams.reduce((e,t)=>e+t.cliff,0n),duration:this.streams[0].duration,interval:this.streams[0].interval,steps:this.streams[0].totalSteps,nextReleaseAmount:this.streams.reduce((e,t)=>t.nextReleaseAmount===null?e:e+t.nextReleaseAmount,0n),nextReleaseDate:this.streams[0].nextReleaseDate}}get progress(){return{total:this.streams.reduce((e,t)=>e+t.totalAmount,0n),streamed:this.streams.reduce((e,t)=>e+t.streamedAmount,0n),claimed:this.streams.reduce((e,t)=>e+t.claimedAmount,0n),claimable:this.streams.reduce((e,t)=>e+t.claimable,0n),canceled:this.streams.reduce((e,t)=>e+t.canceledAmount,0n)}}async historyEvents(e){return this.globals.backend.getStreamHistory({groupId:this.groupId,pagination:e})}static async parseGroupStreams(e,t,n){let s=n.map((a,i)=>xn.fromObjectData(e,t[i],a)).filter(a=>!!a);if(new Set(s.map(a=>a.groupId)).size!==1)throw new mn("Not same group ID");if(!this.checkStreamGroup(s))throw new mn("Not same stream settings");return s}};function bu(r,e){return r.name===e.name&&r.groupId===e.groupId&&r.creator===e.creator&&r.start.toMillis()===e.start.toMillis()&&r.interval.toMillis()===e.interval.toMillis()&&r.steps===e.steps&&r.cancelable===e.cancelable}var Ia=class wn{constructor(e,t){this.it=e,this.pageSize=t}static async newIncoming(e){let t=await xa.newIncoming(e);return new wn(t,e.pageSize)}static async newOutgoing(e){let t=await xa.newOutgoing(e);return new wn(t,e.pageSize)}async hasNext(){return this.it.hasNext()}async next(){let e=[];for(;e.length<this.pageSize&&await this.it.hasNext();)e.push(await this.it.next());return e}},xa=class Sn{constructor(e){this.requester=e}cachedNext;static async newIncoming(e){let t=await ka.newIncomingQuery(e);return new Sn(t)}static async newOutgoing(e){let t=await ka.newOutgoingQuery(e);return new Sn(t)}async hasNext(){return this.cachedNext===void 0&&(this.cachedNext=await this.requester.doNextRequest()),this.cachedNext!==null}async next(){if(this.cachedNext===void 0){let t=await this.requester.doNextRequest();if(t===null)throw new H("No more results");return t}let e=this.cachedNext;if(this.cachedNext=void 0,e===null)throw new H("No more results");return e}},ka=class bn{constructor(e,t,n,s){this.globals=e,this.recipient=t,this.groupRefs=n,this.query=s,this.current=0;let a=new ui(n.flat().map(i=>i.streamId));this.objectIter=new li(e.suiClient,a)}current=0;objectIter;static async newIncomingQuery(e){let t=Ou(e.query),n=await e.globals.walletAddress(),s=(await e.globals.backend.getIncomingStreams(n,t)).filter(i=>(0,ue.normalizeSuiAddress)(i.recipient)===(0,ue.normalizeSuiAddress)(n)),a=Oa(s);return new bn(e.globals,n,a,e.query)}static async newOutgoingQuery(e){let t=Eu(e.query),n=await e.globals.walletAddress(),s=await e.globals.backend.getOutgoingStreams(n,t),a=Oa(s);return new bn(e.globals,n,a,e.query)}async doNextRequest(){if(this.current>=this.groupRefs.length)return null;let e=this.groupRefs[this.current];if(e.length===1){let t=await xu(this.globals,e[0].streamId,this.objectIter);return this.current++,di(t,this.query)?t:this.doNextRequest()}if(e.length>1){let t=await ku(this.globals,e.map(n=>n.streamId),this.objectIter);return this.current++,Iu(t,this.query)?t:this.doNextRequest()}throw new H("Stream group with no stream")}};function Oa(r){let e=new Map;return r.forEach(t=>{let n=e.get(t.groupId);n?(n.push(t),e.set(t.groupId,n)):e.set(t.groupId,[t])}),Array.from(e.values()).sort((t,n)=>p.fromISO(n[0].createDate).toMillis()-p.fromISO(t[0].createDate).toMillis())}function di(r,e){if(e===void 0)return!0;let t=Tu(r,e.status);if(e&&"claimable"in e&&e.claimable!==void 0){let n=e.claimable?r.progress.claimable!==0n:r.progress.claimable===0n;return t&&n}return t}function Tu(r,e){return e===void 0?!0:Array.isArray(e)?e.includes(r.progress.status):r.progress.status===e}function Iu(r,e){if(!e)return!0;let t=!1;return r.streams.forEach(n=>{di(n,e)&&(t=!0)}),t}async function xu(r,e,t){let n=await mi(t,e);return xn.fromObjectData(r,e,n)}async function ku(r,e,t){let n=[];for(;n.length<e.length;){let s=await mi(t,e[n.length]);n.push(s)}return Su.newFromObjectResponse(r,e,n)}async function mi(r,e){if(!await r.hasNext())throw new H("object iterator has been consumed");let t=await r.next();if(!t||t.error||t.data===void 0||t.data===null)throw new H("object iterator undefined response",{cause:t?.error});if(t?.data?.objectId!==e)throw new H("stream id not aligned");return t}function Ou(r){return{status:kn(r?.status),coinType:hi(r?.coinType),sender:fi(r?.sender)}}function Eu(r){return{status:kn(r?.status),coinType:hi(r?.coinType),recipient:fi(r?.recipient)}}function kn(r){return r===void 0||r.length===0?"all":Array.isArray(r)?r.reduce((e,t)=>{let n=kn(t);return!e||e===n?n:"all"},void 0):Cu(r)}function Cu(r){switch(r){case"STREAMING":case"STREAMED":case"CANCELED":return"active";case"COMPLETED":case"SETTLED":return"inactive";default:throw new P("Unknown stream filtered status")}}function hi(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>(0,ue.normalizeStructTag)(e)):void 0:(0,ue.normalizeStructTag)(r)}function fi(r){if(r)return Array.isArray(r)?r.length!==0?r.map(e=>(0,ue.normalizeSuiAddress)(e)):void 0:(0,ue.normalizeSuiAddress)(r)}var vu=class extends F{constructor(r,e,t){super(4,`Not enough balance: ${r}`,{context:{coinType:r,requestAmount:e,gotAmount:t}}),this.coinType=r,this.requestAmount=e,this.gotAmount=t}},Mu=25;async function Au(r,e,t,n="0x2::sui::SUI",s=Mu){let a=new Du(r,e,n,s),i=BigInt(0),o=[];for(;await a.hasNext()&&i<t;){let c=await a.next();c&&(o.push(c),i+=BigInt(c.balance))}if(i<t)throw new vu(n,t,i);return o}var Du=class extends ci{constructor(r,e,t,n){super(new Nu(r,e,t,n)),this.suiClient=r,this.owner=e,this.coinType=t,this.reqPageSize=n}},Nu=class{constructor(r,e,t,n){if(this.suiClient=r,this.owner=e,this.coinType=t,this.reqPageSize=n,n<=0)throw new H("Invalid reqPageSize")}nextCursor;async doNextRequest(){let r=await this.suiClient.getCoins({owner:this.owner,coinType:this.coinType,cursor:this.nextCursor,limit:this.reqPageSize});return this.nextCursor=r.nextCursor,{data:r.data,hasNext:r.hasNextPage}}},Pu=class{constructor(r){this.msafe=r}get type(){return"msafe"}async address(){return this.msafe.address()}async requestCoins(r){return this.msafe.requestCoins(r)}},Fu=class{constructor(r){this.account=r}async address(){return this.account.address}},Ru=class{constructor(r,e){this.singleWallet=r,this.suiClient=e}get type(){return"single"}async address(){return this.singleWallet.address()}async requestCoins(r){return Promise.all(r.map(e=>this.requestCoin(e)))}async requestCoin(r){if(ri(r.coinType,we.SUI_TYPE_ARG))return{primaryCoin:ni};if(r.amount<=0)throw new P("Invalid coin request","coinAmount",r.amount);let e=await Au(this.suiClient,await this.address(),r.amount,r.coinType);if(e.length===0)throw new H("no coins available");return{primaryCoin:e[0].coinObjectId,mergedCoins:e.slice(1).map(t=>t.coinObjectId)}}},_u=class{globals;helper;constructor(r,e){this.globals=Ya.new(r,e),this.helper=new lu(this.globals)}connectSingleWallet(r){let e=new Ru(r,this.globals.suiClient);this.globals.connectWallet(e)}connectMSafeAccount(r){let e=new Pu(r);this.globals.connectWallet(e)}async createStream(r){return this.builder().createStreams(r)}async getStream(r){return xn.new(this.globals,r)}async getIncomingStreams(r,e=10){return Ia.newIncoming({globals:this.globals,query:r,pageSize:e})}async getOutgoingStreams(r,e=10){return Ia.newOutgoing({globals:this.globals,query:r,pageSize:e})}async getCoinTypesForStreamFilter(){let r=await this.wallet.address();return(await this.globals.backend.getAllCoinTypes(r)).map(e=>(0,we.normalizeStructTag)(e))}async getRecipientsForStreamFilter(r){let e=await this.wallet.address();return(await this.globals.backend.getAllRecipients(e,r)).map(t=>(0,we.normalizeSuiAddress)(t))}async getCreatorsForStreamFilter(r){let e=await this.wallet.address();return(await this.globals.backend.getAllSenders(e,r)).map(t=>(0,we.normalizeSuiAddress)(t))}get wallet(){return this.globals.wallet}builder(){return new oi(this.globals)}},Wu=class{constructor(r){this.data=r}serialize(){return JSON.stringify((0,pi.default)(this.data))}},Ot=class extends Wu{application="mpay";getClient(r,e){let t=new _u(r==="sui:mainnet"?"prod":"dev");return t.connectSingleWallet(new Fu(e)),t}},Ea=class extends Ot{constructor(r){super(r),this.data=r}txType=Na.TransactionType.Stream;txSubType="Cancel";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).cancel()}},Ca=class extends Ot{constructor(r){super(r),this.data=r}txType=gi.TransactionType.Stream;txSubType="ClaimByProxy";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).claimByProxy()}},va=class extends Ot{constructor(r){super(r),this.data=r}txType=yi.TransactionType.Stream;txSubType="Claim";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).claim()}},Ma=class extends Ot{constructor(r){super(r),this.data=r}txType=wi.TransactionType.Stream;txSubType="CreateStream";async build(r){let{network:e,account:t}=r;return this.getClient(e,t).createStream(this.data)}},Si=class er{constructor(e,t){this.moveCall=e,this.txb=t}decodeSharedObjectId(e){let t=this.getInputParam(e);return er.getSharedObjectId(t)}decodeOwnedObjectId(e){let t=this.getInputParam(e);return er.getOwnedObjectId(t)}decodeInputU64(e){let t=this.decodePureArg(e,"u64");return BigInt(t)}decodeInputAddress(e){let t=this.decodePureArg(e,"address");return(0,ce.normalizeSuiAddress)(t)}decodeInputString(e){return this.decodePureArg(e,"string")}decodeInputBool(e){return this.decodePureArg(e,"bool")}decodePureArg(e,t){let n=this.getInputParam(e);return er.getPureInputValue(n,t)}getInputParam(e){let t=this.moveCall.arguments[e];if(t.kind!=="Input")throw new Error("not input type");return this.txb.blockData.inputs[t.index]}static getPureInputValue(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value=="object"&&"Pure"in e.value){let n=e.value.Pure;return Tn.bcs.de(t,new Uint8Array(n))}return e.value}static getOwnedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value=="object"){if(!("Object"in e.value)||!("ImmOrOwned"in e.value.Object))throw new Error("not ImmOrOwned");return(0,ce.normalizeSuiAddress)(e.value.Object.ImmOrOwned.objectId)}return(0,ce.normalizeSuiAddress)(e.value)}static getSharedObjectId(e){if(e.type!=="object")throw new Error(`not object argument: ${JSON.stringify(e)}`);if(typeof e.value!="object")return(0,ce.normalizeSuiAddress)(e.value);if(!("Object"in e.value)||!("Shared"in e.value.Object))throw new Error("not Shared");return(0,ce.normalizeSuiAddress)(e.value.Object.Shared.objectId)}static getPureInput(e,t){if(e.type!=="pure")throw new Error("not pure argument");if(typeof e.value!="object")return e.value;if(!("Pure"in e.value))throw new Error("Pure not in value");let n=e.value.Pure;return Tn.bcs.de(t,new Uint8Array(n))}typeArg(e){return(0,ce.normalizeStructTag)(this.moveCall.typeArguments[e])}txArg(e){return this.moveCall.arguments[e]}},ju=class{constructor(r,e){this.globals=r,this.txb=e}decode(){let r=this.decodeCreateStreamInfo(),e=this.createStreamHelper().calculateCreateStreamFees(r);return{type:"CreateStream",info:r,fees:e}}decodeCreateStreamInfo(){let r=this.createStreamTransactions().map(e=>this.getCreationInfoFromMoveCall(e));return this.aggregateGroupStreamInfo(r)}createStreamTransactions(){let r=this.transactions.filter(e=>e.kind==="MoveCall"&&Le(e.target,this.contract.createStreamTarget));if(r.length===0)throw new H("No create stream transactions");return r.map(e=>new Si(e,this.txb))}getCreationInfoFromMoveCall(r){let e=r.decodeInputString(4),{name:t,groupId:n}=pn(e),s=r.decodeInputAddress(5),a=r.decodeInputU64(6),i=r.decodeInputU64(7),o=r.decodeInputU64(8),c=r.decodeInputU64(9),u=r.decodeInputU64(10),d=r.decodeInputBool(11),f=r.typeArg(0);return{name:t,groupId:n,recipient:s,timeStart:a,cliff:i,epochInterval:o,totalEpoch:c,amountPerEpoch:u,cancelable:d,coinType:f}}aggregateGroupStreamInfo(r){if(new Set(r.map(t=>JSON.stringify({name:t.name,groupId:t.groupId,timeStart:String(t.timeStart),epochInterval:String(t.epochInterval),totalEpoch:String(t.totalEpoch),cancelable:t.cancelable,coinType:t.coinType}))).size!==1)throw new P("Stream group not have common info");let e=r.map(t=>({address:t.recipient,amountPerStep:t.amountPerEpoch,cliffAmount:t.cliff}));return{name:r[0].name,coinType:r[0].coinType,recipients:e,interval:r[0].epochInterval,steps:r[0].totalEpoch,startTimeMs:r[0].timeStart,cancelable:r[0].cancelable}}mergeCoinTransactions(){return this.transactions.filter(r=>r.kind==="MergeCoins")}get transactions(){return this.txb.blockData.transactions}get contract(){return new nr(this.globals.envConfig.contract,this.globals)}get feeContract(){return new ii(this.globals.envConfig.contract,this.globals)}createStreamHelper(){return new gn(this.globals,this.feeContract,this.contract)}getInputArg(r){if(r.kind!=="Input")throw new Error("not input type");return"value"in r?r:this.txb.blockData.inputs[r.index]}},Lu=class{constructor(r,e){this.globals=r,this.txb=e,this.contract=new nr(r.envConfig.contract,r)}contract;decode(){if(this.isCreateStreamTransaction())return this.decodeCreateStreamTransaction();if(this.isClaimByProxyTransaction())return this.decodeClaimByProxyTransaction();if(this.isSetAutoClaimTransaction())return this.decodeSetAutoClaimTransaction();if(this.isCancelStreamTransaction())return this.decodeCancelStreamTransaction();if(this.isClaimStreamTransaction())return this.decodeClaimTransaction()}get transactions(){return this.txb.blockData.transactions}isCreateStreamTransaction(){return this.transactions.findIndex(r=>r.kind==="MoveCall"&&Le(r.target,this.contract.createStreamTarget))!==-1}isSetAutoClaimTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Le(this.transactions[0].target,this.contract.setAutoClaimTarget)}isCancelStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Le(this.transactions[0].target,this.contract.cancelStreamTarget)}isClaimStreamTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Le(this.transactions[0].target,this.contract.claimStreamTarget)}isClaimByProxyTransaction(){return this.transactions.length===1&&this.transactions[0].kind==="MoveCall"&&Le(this.transactions[0].target,this.contract.claimStreamByProxyTarget)}decodeCreateStreamTransaction(){return new ju(this.globals,this.txb).decode()}decodeSetAutoClaimTransaction(){let r=this.helper.decodeSharedObjectId(0),e=this.helper.decodeInputBool(1);return{type:"SetAutoClaim",streamId:r,enabled:e}}decodeClaimTransaction(){return{type:"Claim",streamId:this.helper.decodeSharedObjectId(0)}}decodeClaimByProxyTransaction(){return{type:"ClaimByProxy",streamId:this.helper.decodeSharedObjectId(0)}}decodeCancelStreamTransaction(){return{type:"Cancel",streamId:this.helper.decodeSharedObjectId(0)}}get helper(){let r=this.transactions[0];return new Si(r,this.txb)}},Aa=class extends Ot{constructor(r){super(r),this.data=r}txType=bi.TransactionType.Stream;txSubType="SetAutoClaim";async build(r){let{network:e,account:t}=r;return(await this.getClient(e,t).getStream(this.data.streamId)).setAutoClaim(this.data.enabled)}},Bu=class{application="mpay";async deserialize(r){let{chain:e,transactionBlock:t}=r,n=Ya.new(e==="sui:mainnet"?"prod":"dev"),s=new Lu(n,t).decode(),a;switch(s.type){case"CreateStream":a=new Ma(s.info);break;case"SetAutoClaim":a=new Aa({streamId:s.streamId,enabled:s.enabled});break;case"Claim":a=new va({streamId:s.streamId});break;case"ClaimByProxy":a=new Ca({streamId:s.streamId});break;case"Cancel":a=new Ea({streamId:s.streamId});break;default:throw new Error(`Unknown transaction type: ${s}`)}return{txType:a.txType,txSubType:a.txSubType,intentionData:a.data}}async build(r){let{intentionData:e}=r,t;switch(r.txSubType){case"CreateStream":t=new Ma(e);break;case"Claim":t=new va(e);break;case"ClaimByProxy":t=new Ca(e);break;case"SetAutoClaim":t=new Aa(e);break;case"Cancel":t=new Ea(e);break;default:throw new Error("not implemented")}return t.build({...r})}},On=class{constructor(r){this.data=r}get application(){return"msafe-core"}serialize(){return JSON.stringify((0,Ii.default)(this.data))}},qu=class xi extends On{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e;return(0,Ti.buildCoinTransferTxb)(t,this.data,n.address)}static fromData(e){return new xi(e)}},Uu=class Oi extends On{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{suiClient:t,account:n}=e;return(0,ki.buildObjectTransferTxb)(t,this.data,n.address)}static fromData(e){return new Oi(e)}},Hu=class vi extends On{constructor(e){super(e),this.data=e}txType;txSubType;async build(e){let{account:t}=e,n=Ci.TransactionBlock.from(this.data.content);if(!(0,Ei.isSameAddress)(n.blockData.sender,t.address))throw new Error("Invalid sender address");return n}static fromData(e){return new vi(e)}},Vu=class{application;constructor(){this.application=Be.TransactionDefaultApplication}deserialize(){throw new Error("MSafe core transaction intention should be build from API")}async build(r){let{suiClient:e,account:t}=r,n;switch(r.txSubType){case Be.TransactionSubTypes.assets.coin.send:n=qu.fromData(r.intentionData);break;case Be.TransactionSubTypes.assets.object.send:n=Uu.fromData(r.intentionData);break;case Be.TransactionSubTypes.others.plain:n=Hu.fromData(r.intentionData);break;default:throw new Error("not implemented")}return n.build({suiClient:e,account:t})}},Gu=class{apps;constructor(r){this.apps=new Map(r.map(e=>[e.application,e]))}getAppHelper(r){let e=this.apps.get(r);if(!e)throw new Error(`${r} not registered`);return e}},zu="msafe-plain-tx",$u=sr.TransactionSubTypes.others.plain,Zu=class{application;constructor(){this.application=zu}async deserialize(r){let{transactionBlock:e,suiClient:t}=r,n=await e.build({client:t});return{txType:sr.TransactionType.Other,txSubType:$u,intentionData:{content:(0,ar.toHEX)(n)}}}async build(r){let{suiClient:e,account:t}=r,n=Mi.TransactionBlock.from((0,ar.fromHEX)(r.intentionData.content)),s=await e.devInspectTransactionBlock({transactionBlock:n,sender:t.address});if(s.effects.status.status!=="success")throw new Error(s.effects.status.error);return n}},ir=new Gu([new Vu,new Bu,new Zu]);var S=require("@msafe/sui3-utils"),Fn=require("@mysten/sui.js/transactions"),hr=require("@mysten/sui.js/utils");var Ai=require("@mysten/sui.js/transactions"),Ku=1000n,Yu=120n,Ju=100n,Qu={multiplier:{numerator:Yu,denominator:Ju}};var or=class{constructor(e){this.globals=e}async simulate(e,t=Qu){let n=this.copyTransactionBlock(e.txb),{suiClient:s}=this.globals,a=await this.getGasPrice(t);n.setGasPrice(a);let i=await s.devInspectTransactionBlock({transactionBlock:n,sender:e.sender}),{gasUsed:o}=i.effects,c=this.toGasBudget(o,a),u=i.effects.status.status==="success",d;return u||(d=i.effects.status.error),{success:u,gasPrice:a,gasObject:i.effects.gasObject.reference,gasUsed:o,gasBudget:c,simulationError:d}}async getGasPrice(e){if(this.isFixedValue(e))return e.fixedVal;let t=await this.globals.suiClient.getReferenceGasPrice();return this.applyGasOption(t,e)}toGasBudget(e,t){let{computationCost:n,storageCost:s}=e,a=Ku*t,i=BigInt(n)+a,o=i+BigInt(s);return o>i?o:i}isFixedValue(e){return"fixedVal"in e}isMultiplier(e){return"multiplier"in e}applyGasOption(e,t){if(this.isFixedValue(t))return t.fixedVal;if(this.isMultiplier(t)){let{multiplier:n}=t;return e*n.numerator/n.denominator}throw new Error("Sanity: Unknown gas price option")}copyTransactionBlock(e){return Ai.TransactionBlock.from(e.serialize())}};var En=require("buffer");function cr(r){return En.Buffer.from(r,"utf-8")}function Xu(r){return`0x${Array.prototype.map.call(r,e=>`0${e.toString(16)}`.slice(-2)).join("")}`}function ur(r){return Uint8Array.from(En.Buffer.from(r.startsWith("0x")?r.slice(2):r,"hex"))}var dr=require("@mysten/sui.js/verify");var le=require("@mysten/sui.js/utils");var lr=require("@mysten/sui.js/utils"),Et=class{_client;_coinMetaReg;constructor(e){this._client=e,this._coinMetaReg=new Map}async getCoinMeta(e){let t=(0,lr.normalizeStructTag)(e);if(this._coinMetaReg.has(t))return this._coinMetaReg.get(t);let n=await this.queryCoinMeta(t);return n&&this._coinMetaReg.set(t,n),n}async queryCoinMeta(e){return await this._client.getCoinMetadata({coinType:e})||void 0}},Cn=/^0x0000000000000000000000000000000000000000000000000000000000000002::coin::Coin<(.+)>$/,Ct=class r{static isCoin(e){return e?(0,lr.normalizeStructTag)(e).match(Cn)!=null:!1}static getCoinType(e){let[,t]=(0,lr.normalizeStructTag)(e).match(Cn)??[];return t||null}static getBalance(e){if(!r.isCoin(e.type)||e.content?.dataType!=="moveObject")return;let{balance:t}=e.content?.fields;if(t!==void 0)return BigInt(t)}};var Q=class{static normalizeSuiAddress(e){return(0,le.normalizeSuiAddress)(e)}static normalizeStructTag(e){return(0,le.normalizeStructTag)(e)}static isSuiAddressEqual(e,t){return(0,le.normalizeSuiAddress)(e)===(0,le.normalizeSuiAddress)(t)}static isSuiStructEqual(e,t){return(0,le.normalizeStructTag)(e)===(0,le.normalizeStructTag)(t)}static isCoinObjectType(e){return Ct.isCoin(e)}};function vn(r,e){return r.startsWith(e)?r:e+r}var Mn=class r{static async getPublicKeyFromSignature(e){return e.messageType==="TransactionBlock"?(0,dr.verifyTransactionBlock)(e.message,e.signature):(0,dr.verifyPersonalMessage)(e.message,e.signature)}static async getPublicKeyFromPersonalSignature(e){let t=cr(e.messageStr);return this.getPublicKeyFromSignature({message:t,messageType:"Personal",signature:e.signature})}static async verifySignature(e){let t=await r.getPublicKeyFromSignature(e);return Q.isSuiAddressEqual(t.toSuiAddress(),e.targetAddress)}static async verifyPersonalSignature(e){let t=cr(e.messageStr);return this.verifySignature({message:t,messageType:"Personal",signature:e.signature,targetAddress:e.targetAddress})}static async verifyTransactionSignature(e){return this.verifySignature({messageType:"TransactionBlock",message:e.payload,signature:e.signature,targetAddress:e.targetAddress})}};var Di=require("@msafe/sui3-utils"),Ni=require("@mysten/sui.js/cryptography"),Pi=require("@mysten/sui.js/multisig");var el="0x2::sui::SUI";async function An(r,e){let t;try{t=await r.queryTransactionBlocks({filter:{FromAddress:e},options:{showInput:!0},limit:2})}catch{return}if(t.data.length===0||!t.data[0].transaction?.txSignatures)return;let s=t.data[0].transaction?.txSignatures;for(let a=0;a!==s.length;a++){let i=s[a],o=tl(i,e);if(o)return o}}function tl(r,e){let t=(0,Ni.parseSerializedSignature)(r);switch(t.signatureScheme){case"MultiSig":{let n=new Pi.MultiSigPublicKey(t.multisig.multisig_pk).toSuiAddress();if(Q.isSuiAddressEqual(n,e))throw new Error("multi-sig wallet cannot be owner");return}case"ZkLogin":{if(Q.isSuiAddressEqual(t.zkLogin.address,e))throw new Error("ZkLogin wallet cannot be owner");return}case"ED25519":case"Secp256k1":case"Secp256r1":{let n=Di.PublicKeySerde.de({publicKeyEncoded:t.publicKey,schema:t.signatureScheme});return Q.isSuiAddressEqual(n.toSuiAddress(),e)?n:void 0}default:throw new Error("Unknown schema")}}async function rl(r){let e=!0,t,n=[];for(;e;){let s=await r.suiClient.getCoins({owner:r.owner,coinType:r.coinType,cursor:t});n.push(...s.data),e=s.hasNextPage,t=s.nextCursor}return n}var Fi=25;async function Ri(r){let e=[];for(;await r.hasNext();){let t=await r.next();e.push(t)}return e&&Array.isArray(e[0])?e.flat(1):e}var Dn=class{constructor(e){this.requester=e;this.curPage=void 0,this.init=!0}curPage;init;async hasNext(){if(this.init)return this.curPage||(this.curPage=await this.requester.doNextRequest()),!!this.curPage.data?.length||this.curPage.hasNext;if(!this.curPage)throw new Error("invalid implementation of iterator");return this.curPage.hasNext}async next(){return this.init?(this.init=!1,this.curPage||(this.curPage=await this.requester.doNextRequest()),this.curPage.data):(this.curPage=await this.requester.doNextRequest(),this.curPage.data)}},mr=class{constructor(e){this.requester=e;this.pager=new Dn(e),this.curData=[],this.cursor=0}cursor;pager;curData;async hasNext(){return this.cursor<this.curData.length-1?!0:this.pager.hasNext()}async next(){for(this.cursor+=1;this.cursor>=this.curData.length;)if(await this.pager.hasNext())this.curData=await this.pager.next(),this.cursor=0;else throw new Error("not more data");return this.curData[this.cursor]}};async function _i(r,e,t){let n=new Nn(r,e,t);return await Ri(n)}var Nn=class extends mr{constructor(t,n,s){super(new Pn(t,n,s));this.provider=t;this.owner=n;this.options=s}},Pn=class{constructor(e,t,n){this.provider=e;this.owner=t;this.options=n;this.nextCursor=null,this.filter=n?.filter,this.pageSize=n?.pageSize||Fi,this.objectOptions=n?.objectOptions||{showType:!0,showContent:!0}}nextCursor;filter;pageSize;objectOptions;async doNextRequest(){let e=await this.provider.getOwnedObjects({owner:this.owner,options:this.objectOptions,cursor:this.nextCursor,limit:this.pageSize});this.nextCursor=e.nextCursor;let t;if(this.filter){let{filter:n}=this;t=e.data.filter(s=>n?.(s))}else t=e.data;return{data:t.map(n=>n.data).filter(n=>n),hasNext:e.hasNextPage}}};var Se=class r{constructor(e,t){this.globals=e;this.info=t;this.multiSig=new S.MultiSigAccount({threshold:t.threshold,ownersWithWeight:t.owners,creationNonce:t.creationNonce}),this.coinHelper=new Et(this.suiClient),this.simulator=new or(e)}multiSig;coinHelper;simulator;static async New(e,t){let n=await e.backend.getMSafeAccountInfo(t);if(new r(e,n).address!==t)throw new Error("Invalid msafe config with address")}async ownedCoins(){let e=await this.suiClient.getAllBalances({owner:this.address});return Promise.all(e.map(async t=>{let n=await this.coinHelper.getCoinMeta(t.coinType),s=t.lockedBalance.number?BigInt(t.totalBalance)-BigInt(t.lockedBalance.number):BigInt(t.totalBalance);return{type:(0,hr.normalizeStructTag)(t.coinType),balance:BigInt(s),metadata:n}}))}async ownedObjects(e){let t={filter:n=>!n?.data?.type?.startsWith("0x2::coin::Coin"),...e};return _i(this.suiClient,this.address,t)}async pendingTransaction(){let e=await this.backend.getPendingTransactions({msafeAddress:this.address});if(!e.pending)return;let t=e.pending,n=e.reject;return{application:t.application,txType:t.txType,txSubType:t.txSubType,createdAt:t.createdAt,creator:t.creator,digest:t.digest,intention:t.intention,sequenceNumber:t.sequenceNumber,payload:t.payload,votes:t.votes,approvalWeight:this.calculateWeightFromVotes(t.votes),msafeAddress:t.msafeAddress,rejectDigest:n?.digest??"",rejectPayload:n?.payload??"",rejectVotes:n?.votes??[],rejectWeight:this.calculateWeightFromVotes(n?.votes??[])}}async historyTransaction(e){return this.backend.getHistoryTransactions({msafeAddress:this.address,...e})}async futureIntentions(e){return this.backend.getFutureIntentions({msafeAddress:this.address,...e})}async currentSequenceNumber(){return this.backend.getCurrentSequenceNumber(this.address)}async nextSequenceNumber(){return this.backend.getNextSequenceNumber(this.address)}async simulateIntention(e){let t=ir.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async proposeIntention(e){let t=S.SigningMessageHelper.proposeIntentionMessage({msafeAddress:this.address,intention:e.intention,sn:e.sequenceNumber}),n=await this.wallet.signPersonalMessage({messageStr:t});return this.backend.proposeIntention({...e,msafeAddress:this.address,signature:n.signature})}async proposeIntentionAndBuildVote(e){let t=ir.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});n.setGasPrice(e.gasPrice),n.setGasBudget(e.gasBudget),n.setSender(this.address);let s=await n.build({client:this.globals.suiClient}),a=await n.getDigest({client:this.globals.suiClient}),i=await this.wallet.signTransactionBlock({transactionBlock:s});return this.backend.proposeIntentionAndBuildVote({...e,payload:(0,hr.toHEX)(s),digest:a,msafeAddress:this.address,signature:i.signature})}async simulateCoinTransferIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Assets,txSubType:S.TransactionSubTypes.assets.coin.send,sequenceNumber:t,intention:e})}async proposeCoinTransferIntention(e){let t=await this.nextSequenceNumber();return this.proposeIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Assets,txSubType:S.TransactionSubTypes.assets.coin.send,sequenceNumber:t,intention:e})}async simulateObjectTransferIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Assets,txSubType:S.TransactionSubTypes.assets.object.send,sequenceNumber:t,intention:e})}async proposeObjectTransferIntention(e){let t=await this.nextSequenceNumber();return this.proposeIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Assets,txSubType:S.TransactionSubTypes.assets.object.send,sequenceNumber:t,intention:e})}async simulatePlainPayloadIntention(e){let t=await this.nextSequenceNumber();return this.simulateIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Other,txSubType:S.TransactionSubTypes.others.plain,sequenceNumber:t,intention:e})}async proposePlainPayloadIntention(e){let t=await this.nextSequenceNumber(),n=Fn.TransactionBlock.from(e.payload);if(!n.blockData.sender||!(0,S.isSameAddress)(n.blockData.sender,this.address))throw new Error("Transaction sender is not same as the multisig address");return this.proposeIntention({application:S.TransactionDefaultApplication,txType:S.TransactionType.Other,txSubType:S.TransactionSubTypes.others.plain,sequenceNumber:t,intention:e})}async voteForTransaction(e,t){let n=ur(t),s=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.voteForTransaction({msafeAddress:this.address,digest:e,signature:s.signature})}async proposePendingTransaction(e){let t=new Fn.TransactionBlock,n=await t.build({client:this.suiClient}),s=await t.getDigest({client:this.suiClient}),a=await this.wallet.signTransactionBlock({transactionBlock:n});return this.backend.proposePendingTransaction({msafeAddress:this.address,userAddress:await this.userAddress(),intention:e,digest:s,signature:a.signature})}async simulateRejectTx(){let e=await this.pendingTransaction();if(!e||e.rejectDigest!=="")throw new Error("Already rejected");let t=e.payload,n=(0,S.buildRejectTxb)(this.address,t);return this.simulator.simulate({txb:n,sender:this.address})}async rejectCurrentTx(e){let t=await this.pendingTransaction();if(!t||t.rejectDigest!=="")throw new Error("Already rejected");let n=t.payload,s=(0,S.buildRejectTxb)(this.address,n),a=await s.getDigest({client:this.suiClient}),i=await s.build({client:this.suiClient}),o=await this.wallet.signTransactionBlock({transactionBlock:i});return this.backend.rejectCurrentTx({msafeAddress:this.address,digest:a,signature:o.signature,...e})}async simulateBuildTransaction(){let e=await this.backend.getNextIntention({msafeAddress:this.address}),t=ir.getAppHelper(e.application);if(!t)throw new Error(`Can't find app helper for application ${e.application}`);let n=await t.build({network:this.globals.config.network,intentionData:e.intention,txType:e.txType,txSubType:e.txSubType,suiClient:this.globals.suiClient,account:{address:this.address}});return this.simulator.simulate({txb:n,sender:this.address})}async buildNextIntentionAndAddToPending(e){return this.backend.buildNextIntentionAndAddToPending({msafeAddress:this.address,forceBuild:e.forceBuild,gasPrice:e.gasPrice,gasBudget:e.gasBudget})}async skipNextFailedIntention(){return this.backend.skipNextFailedIntention({msafeAddress:this.address})}async executePendingTx(e,t=!1){let n=t?e.rejectVotes:e.votes,s=t?e.rejectPayload:e.payload;if(this.calculateWeightFromVotes(n)<this.info.threshold)throw new Error("Not enough signature");let a=[],i=new Map(n.map(c=>[c.userAddress,c.signature]));for(let c=0;c<this.info.owners.length;c++){let u=this.info.owners[c],d=i.get(u.address);d&&a.push(d)}let o=this.multiSig.combinePartialSignatures(a);return this.suiClient.executeTransactionBlock({transactionBlock:ur(s),signature:o,options:{showEffects:!0,showEvents:!0}})}async dashboard(){return this.backend.getDashboard({msafeAddress:this.address})}calculateWeightFromVotes(e){return this.calculateWeight(e.map(t=>t.userAddress))}calculateWeight(e){let t=0;for(let n=0;n<e.length;n++){let s=this.info.owners.find(a=>(0,S.isSameAddress)(a.address,e[n]));s&&(t+=s.weight)}return t}get address(){return this.multiSig.address}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}async userAddress(){return this.globals.wallet.address()}get suiClient(){return this.globals.suiClient}};var Wi=require("@msafe/sui3-utils"),ji=require("@mysten/sui.js/utils");var fr=class{constructor(e){this.globals=e;this.knownPublicKeys=new Map}knownPublicKeys;async getPublicKey(e){let t=this.knownPublicKeys.get(e);if(t)return t;let n=await this._getPublicKey(e);return n&&this.knownPublicKeys.set(e,n),n}async getPublicKeyBatch(e){let t=new Array(e.length).fill(void 0);for(let a=0;a<e.length;a++){let i=e[a];t[a]=this.knownPublicKeys.get(i)}let n=t.map((a,i)=>a===void 0?i:-1).filter(a=>a!==-1);if(n.length===0)return t;let s=await this.globals.backend.getPublicKeyBatch(n.map(a=>e[a]));for(let a=0;a<n.length;a++){let i=n[a];t[i]=s[a]}for(let a=0;a<t.length;a++)t[a]===void 0&&(t[a]=await this.getPublicKeyFromChain(e[a]));for(let a=0;a<e.length;a++)t[a]&&this.knownPublicKeys.set(e[a],t[a]);return t}addPublicKey(e,t){if(!(0,Wi.isSameAddress)(e,t.toSuiAddress()))throw new Error("Invalid public key");this.knownPublicKeys.set((0,ji.normalizeSuiAddress)(e),t)}async _getPublicKey(e){let t=await this.getPublicKeyFromBackend(e);if(t)return t;let n=await this.getPublicKeyFromChain(e);if(n)return n}async getPublicKeyFromBackend(e){try{return await this.globals.backend.getPublicKey(e)}catch{return}}async getPublicKeyFromChain(e){return An(this.globals.suiClient,e)}};var pr=class{constructor(e){this.globals=e}async create(e){return this.globals.backend.submitReport(e)}};var Gi=require("@mysten/sui.js/client");var Mt=require("@msafe/sui3-utils"),vt=Ie(require("axios"),1),wr=Ie(require("json-bigint"),1);var gr=class r{constructor(e){this.apiURL=e}_token;async authSign(e){let t=await this.post("/auth/login",e);return this._token=t.data.accessToken,this._token}async verifyToken(e){try{return(await this.get("/auth",{headers:this.headers(e)})).status===200}catch{return!1}}setJWTToken(e){this._token=e}async getPublicKey(e){return(await this.getPublicKeyBatch([e]))[0]}async getPublicKeyBatch(e){let t={userAddressList:e};return(await this.get("/user/public-keys",{params:t,headers:this.headers()})).data?.map(s=>s?Mt.PublicKeySerde.de(s):void 0)}async getMSafeAccountInfo(e){let t={msafeAddress:e},n=await this.get("/msafe",{params:t,headers:this.headers()});return r.toMSafeConfig(n.data)}async getUserInfo(){return(await this.get("/user",{headers:this.headers()})).data}async getOwnedMSafeByStatus(e){let t={status:e.status??Mt.UserMSafeStatus.active,...e.pagination?{page:e.pagination.page.toString(),limit:e.pagination.limit.toString()}:{}},n=await this.get("/msafe/owned",{params:t,headers:this.headers()});return{data:n.data.data.map(r.toMSafeConfig),meta:n.data.meta}}async updateMSafeStatus(e){let t=e;await this.post("/msafe/status",t,{headers:this.headers()})}async getPendingTransactions(e){return(await this.get("/transaction/pending",{params:e,headers:this.headers()})).data}async getHistoryTransactions(e){return(await this.get("/transaction/history",{params:e,headers:this.headers()})).data}async getFutureIntentions(e){return(await this.get("/transaction/intention",{params:e,headers:this.headers()})).data}async getNextIntention(e){return(await this.get("/transaction/intention/next",{params:e,headers:this.headers()})).data}async getCurrentSequenceNumber(e){return(await this.get("/transaction/sn/current",{params:{msafeAddress:e},headers:this.headers()})).data}async getNextSequenceNumber(e){return(await this.get("/transaction/sn/next",{params:{msafeAddress:e},headers:this.headers()})).data}async createMSafeAccount(e){await this.post("/msafe/create",e,{headers:this.headers()})}async proposeIntention(e){await this.post("/transaction/intention",e,{headers:this.headers()})}async proposePendingTransaction(e){}async rejectCurrentTx(e){await this.post("/transaction/pending/reject",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async voteForTransaction(e){await this.post("/transaction/pending/vote",e,{headers:this.headers()})}async buildNextIntentionAndAddToPending(e){await this.post("/transaction/pending/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async proposeIntentionAndBuildVote(e){await this.post("/transaction/intention/build",{...e,gasPrice:e.gasPrice.toString(),gasBudget:e.gasBudget.toString()},{headers:this.headers()})}async skipNextFailedIntention(e){await this.post("/transaction/pending/skip",e,{headers:this.headers()})}async getAddressBookEntries(e){return(await this.get("/address-book",{headers:this.headers(),params:e})).data}async updateAddressBook(e){await this.post("/address-book",e,{headers:this.headers()})}async getAddressBookMode(){return(await this.get("/address-book/mode",{headers:this.headers()})).data}async setAddressBookMode(e){await this.post("/address-book/mode",{mode:e.mode},{headers:this.headers()})}async submitReport(e){await this.post("/report",e)}async getDashboard(e){return(await this.get("/dashboard",{params:e,headers:this.headers()})).data}headers(e){return{Authorization:`Bearer ${e||this._token}`}}static toMSafeConfig(e){return{...e,owners:e.owners.map(t=>({address:t.address,weight:t.weight,publicKey:Mt.PublicKeySerde.de({publicKeyEncoded:t.publicKeyEncoded,schema:t.schema})}))}}async get(e,t){let n=this.getFullUrl(e);try{return await vt.default.get(n,t)}catch(s){throw yr.fromError(s)??s}}async post(e,t,n){let s=this.getFullUrl(e);try{return await vt.default.post(s,t,{...n,transformRequest:this.getTransformRequest()})}catch(a){throw yr.fromError(a)??a}}getFullUrl(e){return e.startsWith(this.apiURL)?e:`${this.apiURL}${vn(e,"/")}`}getTransformRequest(){let e=[],{transformRequest:t}=vt.default.defaults;return t?t instanceof Array?e=t:e=[t]:e=[],[n=>wr.parse(wr.stringify(n)),...e]}},yr=class r extends Error{constructor(t){super();this.e=t;Error.captureStackTrace(this,this.constructor)}name;static fromError(t){if(vt.default.isAxiosError(t)&&t?.response?.data&&"message"in t.response.data)return new r(t)}get status(){return this.e.response?.status??void 0}get message(){return`${this.respMessage()??"Unknown resp"}`}respMessage(){if(this.e.response?.data)return(this.e.response?.data).message??void 0}get endpoint(){return this.e.config?.url??""}toString(){return this.message}};var Li=(a=>(a.local="local",a.unit="unit",a.dev="dev",a.prev="prev",a.prod="prod",a))(Li||{}),Sr="https://fullnode.testnet.sui.io",Rn="https://fullnode.mainnet.sui.io",_n="http://127.0.0.1:3000",Wn="http://127.0.0.1:3001",Bi="https://sui-dev.m-safe.link",qi="http://13.56.226.148:81",Ui="https://sui-preview.m-safe.link",Hi="https://sui.m-safe.link",Vi=new Map([["unit",{suiClient:{url:Sr},backend:{url:_n},syncingURL:Wn,network:"sui:testnet"}],["local",{suiClient:{url:Sr},backend:{url:_n},syncingURL:Wn,network:"sui:testnet"}],["dev",{suiClient:{url:Sr},backend:{url:Bi},syncingURL:qi,network:"sui:testnet"}],["prev",{suiClient:{url:Rn},backend:{url:Ui},syncingURL:"",network:"sui:mainnet"}],["prod",{suiClient:{url:Rn},backend:{url:Hi},syncingURL:"",network:"sui:mainnet"}]]);function jn(r,e){let t=Vi.get(r);if(!t)throw new Error("Unknown environment");return e?.suiClient?.url&&(t.suiClient.url=e.suiClient.url),e?.backend?.url&&(t.backend.url=e.backend.url),t}var At=class r{backend;suiClient;config;_wallet;constructor(e){this.backend=e.backend,this.suiClient=e.suiClient,this.config=e.config}static async New(e,t){let n=jn(e,t),s=new Gi.SuiClient(n.suiClient),a=new gr(n.backend.url);return new r({backend:a,suiClient:s,config:n})}connectWallet(e){this._wallet=e}get wallet(){if(!this._wallet)throw new Error("wallet not connected");return this._wallet}set wallet(e){this._wallet=e}};var br=class r{constructor(e){this.globals=e}_creationHelper;_publicKeyHelper;static async New(e,t){let n=await At.New(e,t);return new r(n)}async connectWallet(e){if(e.jwtToken&&await this.backend.verifyToken(e.jwtToken))return this.globals.wallet=e.wallet,this.backend.setJWTToken(e.jwtToken),e.jwtToken;let t=await this.authSign(e.wallet);return this.globals.wallet=e.wallet,this.backend.setJWTToken(t),t}async authSign(e){let t=Tr.SigningMessageHelper.loginMessageWithTimestamp(new Date().toUTCString()),n=await e.signPersonalMessage({messageStr:t});return this.backend.authSign({address:await e.address(),message:t,signature:n.signature,walletType:e.walletType})}async userInfo(){return this.globals.backend.getUserInfo()}async ownedMSafe(e){return this.globals.backend.getOwnedMSafeByStatus({status:Tr.UserMSafeStatus.active,pagination:e})}async createAccount(e){return this.creationHelper.submitMSafeCreation(e)}getMSafeAccount(e){return new Se(this.globals,e)}async getMSafeAccountFromAddress(e){let t=await this.backend.getMSafeAccountInfo(e);return new Se(this.globals,t)}get creationHelper(){return this._creationHelper||(this._creationHelper=new xe(this.globals,this.publicKeyHelper)),this._creationHelper}get publicKeyHelper(){return this._publicKeyHelper||(this._publicKeyHelper=new fr(this.globals)),this._publicKeyHelper}get config(){return this.globals.config}get backend(){return this.globals.backend}get wallet(){return this.globals.wallet}get AddressBook(){return new ke(this.globals)}get Invitation(){return new Pt(this.globals)}get Report(){return new pr(this.globals)}async walletAddress(){return this.wallet.address()}};
2
2
  //# sourceMappingURL=index.cjs.map