@junobuild/core-standalone 5.2.2 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var hf=Object.defineProperty;var mf=(e,t)=>{for(var r in t)hf(e,r,{get:t[r],enumerable:!0})};var sl;(function(e){e[e.SysFatal=1]="SysFatal",e[e.SysTransient=2]="SysTransient",e[e.DestinationInvalid=3]="DestinationInvalid",e[e.CanisterReject=4]="CanisterReject",e[e.CanisterError=5]="CanisterError"})(sl||(sl={}));var Pr;(function(e){e.Replied="replied",e.Rejected="rejected"})(Pr||(Pr={}));function al(e){return e!=null&&"reject_code"in e}function cl(e){return e!=null&&"certificate"in e}var Si="abcdefghijklmnopqrstuvwxyz234567",Qn=Object.create(null);for(let e=0;e<Si.length;e++)Qn[Si[e]]=e;Qn[0]=Qn.o;Qn[1]=Qn.i;function ll(e){let t=0,r=0,n="";function o(i){return t<0?r|=i>>-t:r=i<<t&248,t>3?(t-=8,1):(t<4&&(n+=Si[r>>3],t+=5),0)}for(let i=0;i<e.length;)i+=o(e[i]);return n+(t<0?Si[r>>3]:"")}function ul(e){let t=0,r=0,n=new Uint8Array(e.length*4/3|0),o=0;function i(s){let a=Qn[s.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(s)}`);a<<=3,r|=a>>>t,t+=5,t>=8&&(n[o++]=r,t-=8,t>0?r=a<<5-t&255:r=0)}for(let s of e)i(s);return n.slice(0,o)}var _f=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function dl(e){let t=-1;for(let r=0;r<e.length;r++){let o=(e[r]^t)&255;t=_f[o]^t>>>8}return(t^-1)>>>0}var Cn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Lt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ha(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function fe(e,...t){if(!Lt(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ma(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function fl(e,t){fe(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Fn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Fi(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Rt(e,t){return e<<32-t|e>>>t}var hl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",yf=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function j(e){if(fe(e),hl)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=yf[e[r]];return t}var lr={_0:48,_9:57,A:65,F:70,a:97,f:102};function pl(e){if(e>=lr._0&&e<=lr._9)return e-lr._0;if(e>=lr.A&&e<=lr.F)return e-(lr.A-10);if(e>=lr.a&&e<=lr.f)return e-(lr.a-10)}function Ee(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(hl)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=pl(e.charCodeAt(i)),a=pl(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function G(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function _a(e){return typeof e=="string"&&(e=G(e)),fe(e),e}function K(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];fe(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}var Ci=class{};function Vi(e){let t=n=>e().update(_a(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function eo(e=32){if(Cn&&typeof Cn.getRandomValues=="function")return Cn.getRandomValues(new Uint8Array(e));if(Cn&&typeof Cn.randomBytes=="function")return Uint8Array.from(Cn.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function gf(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,u=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+u,a,n)}function ml(e,t,r){return e&t^~e&r}function _l(e,t,r){return e&t^e&r^t&r}var Bo=class extends Ci{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Fi(this.buffer)}update(t){ma(this),t=_a(t),fe(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Fi(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){ma(this),fl(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,Fn(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let d=s;d<o;d++)r[d]=0;gf(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=Fi(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=c/4,p=this.get();if(u>p.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<u;d++)a.setUint32(4*d,p[d],i)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},ur=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),dr=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var Ce=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Pi=BigInt(4294967295),yl=BigInt(32);function xf(e,t=!1){return t?{h:Number(e&Pi),l:Number(e>>yl&Pi)}:{h:Number(e>>yl&Pi)|0,l:Number(e&Pi)|0}}function gl(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=xf(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var ya=(e,t,r)=>e>>>r,ga=(e,t,r)=>e<<32-r|t>>>r,Vn=(e,t,r)=>e>>>r|t<<32-r,Pn=(e,t,r)=>e<<32-r|t>>>r,Do=(e,t,r)=>e<<64-r|t>>>r-32,Uo=(e,t,r)=>e>>>r-32|t<<64-r;function qt(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var xl=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),bl=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,wl=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),Tl=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,Nl=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),Ol=(e,t,r,n,o,i)=>t+r+n+o+i+(e/2**32|0)|0;var wf=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Br=new Uint32Array(64),Bi=class extends Bo{constructor(t=32){super(64,t,8,!1),this.A=ur[0]|0,this.B=ur[1]|0,this.C=ur[2]|0,this.D=ur[3]|0,this.E=ur[4]|0,this.F=ur[5]|0,this.G=ur[6]|0,this.H=ur[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let d=0;d<16;d++,r+=4)Br[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){let l=Br[d-15],f=Br[d-2],h=Rt(l,7)^Rt(l,18)^l>>>3,_=Rt(f,17)^Rt(f,19)^f>>>10;Br[d]=_+Br[d-7]+h+Br[d-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:u,H:p}=this;for(let d=0;d<64;d++){let l=Rt(a,6)^Rt(a,11)^Rt(a,25),f=p+l+ml(a,c,u)+wf[d]+Br[d]|0,_=(Rt(n,2)^Rt(n,13)^Rt(n,22))+_l(n,o,i)|0;p=u,u=c,c=a,a=s+f|0,s=i,i=o,o=n,n=f+_|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,p=p+this.H|0,this.set(n,o,i,s,a,c,u,p)}roundClean(){Fn(Br)}destroy(){this.set(0,0,0,0,0,0,0,0),Fn(this.buffer)}},xa=class extends Bi{constructor(){super(28),this.A=dr[0]|0,this.B=dr[1]|0,this.C=dr[2]|0,this.D=dr[3]|0,this.E=dr[4]|0,this.F=dr[5]|0,this.G=dr[6]|0,this.H=dr[7]|0}},El=gl(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Tf=El[0],Nf=El[1],Dr=new Uint32Array(80),Ur=new Uint32Array(80),ba=class extends Bo{constructor(t=64){super(128,t,16,!1),this.Ah=Ce[0]|0,this.Al=Ce[1]|0,this.Bh=Ce[2]|0,this.Bl=Ce[3]|0,this.Ch=Ce[4]|0,this.Cl=Ce[5]|0,this.Dh=Ce[6]|0,this.Dl=Ce[7]|0,this.Eh=Ce[8]|0,this.El=Ce[9]|0,this.Fh=Ce[10]|0,this.Fl=Ce[11]|0,this.Gh=Ce[12]|0,this.Gl=Ce[13]|0,this.Hh=Ce[14]|0,this.Hl=Ce[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:u,El:p,Fh:d,Fl:l,Gh:f,Gl:h,Hh:_,Hl:g}=this;return[t,r,n,o,i,s,a,c,u,p,d,l,f,h,_,g]}set(t,r,n,o,i,s,a,c,u,p,d,l,f,h,_,g){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=p|0,this.Fh=d|0,this.Fl=l|0,this.Gh=f|0,this.Gl=h|0,this.Hh=_|0,this.Hl=g|0}process(t,r){for(let y=0;y<16;y++,r+=4)Dr[y]=t.getUint32(r),Ur[y]=t.getUint32(r+=4);for(let y=16;y<80;y++){let T=Dr[y-15]|0,O=Ur[y-15]|0,R=Vn(T,O,1)^Vn(T,O,8)^ya(T,O,7),E=Pn(T,O,1)^Pn(T,O,8)^ga(T,O,7),I=Dr[y-2]|0,w=Ur[y-2]|0,v=Vn(I,w,19)^Do(I,w,61)^ya(I,w,6),V=Pn(I,w,19)^Uo(I,w,61)^ga(I,w,6),S=wl(E,V,Ur[y-7],Ur[y-16]),x=Tl(S,R,v,Dr[y-7],Dr[y-16]);Dr[y]=x|0,Ur[y]=S|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:u,Dl:p,Eh:d,El:l,Fh:f,Fl:h,Gh:_,Gl:g,Hh:m,Hl:b}=this;for(let y=0;y<80;y++){let T=Vn(d,l,14)^Vn(d,l,18)^Do(d,l,41),O=Pn(d,l,14)^Pn(d,l,18)^Uo(d,l,41),R=d&f^~d&_,E=l&h^~l&g,I=Nl(b,O,E,Nf[y],Ur[y]),w=Ol(I,m,T,R,Tf[y],Dr[y]),v=I|0,V=Vn(n,o,28)^Do(n,o,34)^Do(n,o,39),S=Pn(n,o,28)^Uo(n,o,34)^Uo(n,o,39),x=n&i^n&a^i&a,N=o&s^o&c^s&c;m=_|0,b=g|0,_=f|0,g=h|0,f=d|0,h=l|0,{h:d,l}=qt(u|0,p|0,w|0,v|0),u=a|0,p=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let F=xl(v,S,N);n=bl(F,w,V,x),o=F|0}({h:n,l:o}=qt(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=qt(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=qt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:p}=qt(this.Dh|0,this.Dl|0,u|0,p|0),{h:d,l}=qt(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=qt(this.Fh|0,this.Fl|0,f|0,h|0),{h:_,l:g}=qt(this.Gh|0,this.Gl|0,_|0,g|0),{h:m,l:b}=qt(this.Hh|0,this.Hl|0,m|0,b|0),this.set(n,o,i,s,a,c,u,p,d,l,f,h,_,g,m,b)}roundClean(){Fn(Dr,Ur)}destroy(){Fn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Ve=Vi(()=>new Bi),Rl=Vi(()=>new xa),vl=Vi(()=>new ba);var Di="__principal__",Of=2,Il=4,Ef="aaaaa-aa",k=class e{static anonymous(){return new this(new Uint8Array([Il]))}static managementCanister(){return this.fromText(Ef)}static selfAuthenticating(t){let r=Rl(t);return new this(new Uint8Array([...r,Of]))}static from(t){if(typeof t=="string")return e.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new e(t);if(e.isPrincipal(t))return new e(t._arr);throw new Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(t){return new this(Ee(t))}static fromText(t){let r=t;if(t.includes(Di)){let s=JSON.parse(t);Di in s&&(r=s[Di])}let n=r.toLowerCase().replace(/-/g,""),o=ul(n);o=o.slice(4,o.length);let i=new this(o);if(i.toText()!==r)throw new Error(`Principal "${i.toText()}" does not have a valid checksum (original value "${r}" may not be a valid Principal ID).`);return i}static fromUint8Array(t){return new this(t)}static isPrincipal(t){return t instanceof e||typeof t=="object"&&t!==null&&"_isPrincipal"in t&&t._isPrincipal===!0&&"_arr"in t&&t._arr instanceof Uint8Array}constructor(t){this._arr=t,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===Il}toUint8Array(){return this._arr}toHex(){return j(this._arr).toUpperCase()}toText(){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,dl(this._arr));let n=new Uint8Array(t),o=new Uint8Array([...n,...this._arr]),s=ll(o).match(/.{1,5}/g);if(!s)throw new Error;return s.join("-")}toString(){return this.toText()}toJSON(){return{[Di]:this.toText()}}compareTo(t){for(let r=0;r<Math.min(this._arr.length,t._arr.length);r++){if(this._arr[r]<t._arr[r])return"lt";if(this._arr[r]>t._arr[r])return"gt"}return this._arr.length<t._arr.length?"lt":this._arr.length>t._arr.length?"gt":"eq"}ltEq(t){let r=this.compareTo(t);return r=="lt"||r=="eq"}gtEq(t){let r=this.compareTo(t);return r=="gt"||r=="eq"}};var pr;(function(e){e.Trust="Trust",e.Protocol="Protocol",e.Reject="Reject",e.Transport="Transport",e.External="External",e.Limit="Limit",e.Input="Input",e.Unknown="Unknown"})(pr||(pr={}));var $=class{constructor(t=!1){this.isCertified=t}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`
1
+ var Mf=Object.defineProperty;var jf=(e,t)=>{for(var r in t)Mf(e,r,{get:t[r],enumerable:!0})};var Kf=class extends Error{},jo=(e,t)=>{if(e==null)throw new Kf(t)};var mr=e=>new Uint8Array(e),Li=e=>Array.from(e);var Fl=({a:e,b:t})=>e.length===t.length&&e.every((r,n)=>r===t[n]);var Kr=e=>{let t=[];for(let r=0;r<e.length;r+=32768)t.push(String.fromCharCode(...e.subarray(r,r+32768)));return btoa(t.join(""))},Bl=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0));var U=e=>e==null,J=e=>!U(e),_r=e=>J(e)&&e!=="",pt=e=>!_r(e),se=e=>J(e)?[e]:[],me=e=>e?.[0];var ki="abcdefghijklmnopqrstuvwxyz234567",ao=Object.create(null);for(let e=0;e<ki.length;e++)ao[ki[e]]=e;ao[0]=ao.o;ao[1]=ao.i;function $f(e){let t=0,r=0,n="";function o(i){return t<0?r|=i>>-t:r=i<<t&248,t>3?(t-=8,1):(t<4&&(n+=ki[r>>3],t+=5),0)}for(let i=0;i<e.length;)i+=o(e[i]);return n+(t<0?ki[r>>3]:"")}function Hf(e){let t=0,r=0,n=new Uint8Array(e.length*4/3|0),o=0;function i(s){let a=ao[s.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(s)}`);a<<=3,r|=a>>>t,t+=5,t>=8&&(n[o++]=r,t-=8,t>0?r=a<<5-t&255:r=0)}for(let s of e)i(s);return n.slice(0,o)}var Gf=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function Jf(e){let t=-1;for(let r=0;r<e.length;r++){let n=(e[r]^t)&255;t=Gf[n]^t>>>8}return(t^-1)>>>0}function Wf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function qi(e,...t){if(!Wf(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Cl(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function zf(e,t){qi(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Ua(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Da(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Mt(e,t){return e<<32-t|e>>>t}var Dl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Yf=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Zf(e){if(qi(e),Dl)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Yf[e[r]];return t}var hr={_0:48,_9:57,A:65,F:70,a:97,f:102};function Vl(e){if(e>=hr._0&&e<=hr._9)return e-hr._0;if(e>=hr.A&&e<=hr.F)return e-(hr.A-10);if(e>=hr.a&&e<=hr.f)return e-(hr.a-10)}function Xf(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Dl)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=Vl(e.charCodeAt(i)),a=Vl(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function Qf(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Ul(e){return typeof e=="string"&&(e=Qf(e)),qi(e),e}var eh=class{};function th(e){let t=n=>e().update(Ul(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function rh(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+l,a,n)}function nh(e,t,r){return e&t^~e&r}function oh(e,t,r){return e&t^e&r^t&r}var ih=class extends eh{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Da(this.buffer)}update(e){Cl(this),e=Ul(e),qi(e);let{view:t,buffer:r,blockLen:n}=this,o=e.length;for(let i=0;i<o;){let s=Math.min(n-this.pos,o-i);if(s===n){let a=Da(e);for(;n<=o-i;i+=n)this.process(a,i);continue}r.set(e.subarray(i,i+s),this.pos),this.pos+=s,i+=s,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Cl(this),zf(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:o}=this,{pos:i}=this;t[i++]=128,Ua(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(r,0),i=0);for(let d=i;d<n;d++)t[d]=0;rh(r,n-8,BigInt(this.length*8),o),this.process(r,0);let s=Da(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=a/4,l=this.get();if(c>l.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,l[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:o,destroyed:i,pos:s}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=s,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},qr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Mr=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),sh=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),jr=new Uint32Array(64),ah=class extends ih{constructor(e=32){super(64,e,8,!1),this.A=qr[0]|0,this.B=qr[1]|0,this.C=qr[2]|0,this.D=qr[3]|0,this.E=qr[4]|0,this.F=qr[5]|0,this.G=qr[6]|0,this.H=qr[7]|0}get(){let{A:e,B:t,C:r,D:n,E:o,F:i,G:s,H:a}=this;return[e,t,r,n,o,i,s,a]}set(e,t,r,n,o,i,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)jr[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let p=jr[d-15],u=jr[d-2],f=Mt(p,7)^Mt(p,18)^p>>>3,h=Mt(u,17)^Mt(u,19)^u>>>10;jr[d]=h+jr[d-7]+f+jr[d-16]|0}let{A:r,B:n,C:o,D:i,E:s,F:a,G:c,H:l}=this;for(let d=0;d<64;d++){let p=Mt(s,6)^Mt(s,11)^Mt(s,25),u=l+p+nh(s,a,c)+sh[d]+jr[d]|0,f=(Mt(r,2)^Mt(r,13)^Mt(r,22))+oh(r,n,o)|0;l=c,c=a,a=s,s=i+u|0,i=o,o=n,n=r,r=u+f|0}r=r+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(r,n,o,i,s,a,c,l)}roundClean(){Ua(jr)}destroy(){this.set(0,0,0,0,0,0,0,0),Ua(this.buffer)}},ch=class extends ah{constructor(){super(28),this.A=Mr[0]|0,this.B=Mr[1]|0,this.C=Mr[2]|0,this.D=Mr[3]|0,this.E=Mr[4]|0,this.F=Mr[5]|0,this.G=Mr[6]|0,this.H=Mr[7]|0}},lh=th(()=>new ch),Ui="__principal__",uh=2,Pl=4,dh="aaaaa-aa",ka=class so{static anonymous(){return new this(new Uint8Array([Pl]))}static managementCanister(){return this.fromText(dh)}static selfAuthenticating(t){let r=lh(t);return new this(new Uint8Array([...r,uh]))}static from(t){if(typeof t=="string")return so.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new so(t);if(so.isPrincipal(t))return new so(t._arr);throw new Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(t){return new this(Xf(t))}static fromText(t){let r=t;if(t.includes(Ui)){let s=JSON.parse(t);Ui in s&&(r=s[Ui])}let n=r.toLowerCase().replace(/-/g,""),o=Hf(n);o=o.slice(4,o.length);let i=new this(o);if(i.toText()!==r)throw new Error(`Principal "${i.toText()}" does not have a valid checksum (original value "${r}" may not be a valid Principal ID).`);return i}static fromUint8Array(t){return new this(t)}static isPrincipal(t){return t instanceof so||typeof t=="object"&&t!==null&&"_isPrincipal"in t&&t._isPrincipal===!0&&"_arr"in t&&t._arr instanceof Uint8Array}constructor(t){this._arr=t,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===Pl}toUint8Array(){return this._arr}toHex(){return Zf(this._arr).toUpperCase()}toText(){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,Jf(this._arr));let r=new Uint8Array(t),n=new Uint8Array([...r,...this._arr]),o=$f(n).match(/.{1,5}/g);if(!o)throw new Error;return o.join("-")}toString(){return this.toText()}toJSON(){return{[Ui]:this.toText()}}compareTo(t){for(let r=0;r<Math.min(this._arr.length,t._arr.length);r++){if(this._arr[r]<t._arr[r])return"lt";if(this._arr[r]>t._arr[r])return"gt"}return this._arr.length<t._arr.length?"lt":this._arr.length>t._arr.length?"gt":"eq"}ltEq(t){let r=this.compareTo(t);return r=="lt"||r=="eq"}gtEq(t){let r=this.compareTo(t);return r=="gt"||r=="eq"}},La="__bigint__",qa="__principal__",Ma="__uint8array__",ph=(e,t)=>typeof t=="bigint"?{[La]:`${t}`}:J(t)&&ka.isPrincipal(t)?{[qa]:ka.from(t).toText()}:J(t)&&t instanceof Uint8Array?{[Ma]:Array.from(t)}:t,fh=(e,t)=>{let r=n=>t[n];return J(t)&&typeof t=="object"&&La in t?BigInt(r(La)):J(t)&&typeof t=="object"&&qa in t?ka.fromText(r(qa)):J(t)&&typeof t=="object"&&Ma in t?Uint8Array.from(r(Ma)):t},kl=async e=>{let t=new Blob([JSON.stringify(e,ph)],{type:"application/json; charset=utf-8"});return new Uint8Array(await t.arrayBuffer())},Mi=async e=>{let t=new Blob([e instanceof Uint8Array?e:new Uint8Array(e)],{type:"application/json; charset=utf-8"});return JSON.parse(await t.text(),fh)},ji=()=>typeof window<"u";var Ll;(function(e){e[e.SysFatal=1]="SysFatal",e[e.SysTransient=2]="SysTransient",e[e.DestinationInvalid=3]="DestinationInvalid",e[e.CanisterReject=4]="CanisterReject",e[e.CanisterError=5]="CanisterError"})(Ll||(Ll={}));var $r;(function(e){e.Replied="replied",e.Rejected="rejected"})($r||($r={}));function ql(e){return e!=null&&"reject_code"in e}function Ml(e){return e!=null&&"certificate"in e}var Ki="abcdefghijklmnopqrstuvwxyz234567",co=Object.create(null);for(let e=0;e<Ki.length;e++)co[Ki[e]]=e;co[0]=co.o;co[1]=co.i;function jl(e){let t=0,r=0,n="";function o(i){return t<0?r|=i>>-t:r=i<<t&248,t>3?(t-=8,1):(t<4&&(n+=Ki[r>>3],t+=5),0)}for(let i=0;i<e.length;)i+=o(e[i]);return n+(t<0?Ki[r>>3]:"")}function Kl(e){let t=0,r=0,n=new Uint8Array(e.length*4/3|0),o=0;function i(s){let a=co[s.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(s)}`);a<<=3,r|=a>>>t,t+=5,t>=8&&(n[o++]=r,t-=8,t>0?r=a<<5-t&255:r=0)}for(let s of e)i(s);return n.slice(0,o)}var hh=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function $l(e){let t=-1;for(let r=0;r<e.length;r++){let o=(e[r]^t)&255;t=hh[o]^t>>>8}return(t^-1)>>>0}var Un=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function jt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function ja(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function fe(e,...t){if(!jt(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Ka(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Gl(e,t){fe(e);let r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function kn(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Hi(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Rt(e,t){return e<<32-t|e>>>t}var Jl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",mh=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function j(e){if(fe(e),Jl)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=mh[e[r]];return t}var yr={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hl(e){if(e>=yr._0&&e<=yr._9)return e-yr._0;if(e>=yr.A&&e<=yr.F)return e-(yr.A-10);if(e>=yr.a&&e<=yr.f)return e-(yr.a-10)}function Ee(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(Jl)return Uint8Array.fromHex(e);let t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(r);for(let o=0,i=0;o<r;o++,i+=2){let s=Hl(e.charCodeAt(i)),a=Hl(e.charCodeAt(i+1));if(s===void 0||a===void 0){let c=e[i]+e[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}n[o]=s*16+a}return n}function G(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function $a(e){return typeof e=="string"&&(e=G(e)),fe(e),e}function $(...e){let t=0;for(let n=0;n<e.length;n++){let o=e[n];fe(o),t+=o.length}let r=new Uint8Array(t);for(let n=0,o=0;n<e.length;n++){let i=e[n];r.set(i,o),o+=i.length}return r}var $i=class{};function Gi(e){let t=n=>e().update($a(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function lo(e=32){if(Un&&typeof Un.getRandomValues=="function")return Un.getRandomValues(new Uint8Array(e));if(Un&&typeof Un.randomBytes=="function")return Uint8Array.from(Un.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function _h(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);let o=BigInt(32),i=BigInt(4294967295),s=Number(r>>o&i),a=Number(r&i),c=n?4:0,l=n?0:4;e.setUint32(t+c,s,n),e.setUint32(t+l,a,n)}function Wl(e,t,r){return e&t^~e&r}function zl(e,t,r){return e&t^e&r^t&r}var Ko=class extends $i{constructor(t,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(t),this.view=Hi(this.buffer)}update(t){Ka(this),t=$a(t),fe(t);let{view:r,buffer:n,blockLen:o}=this,i=t.length;for(let s=0;s<i;){let a=Math.min(o-this.pos,i-s);if(a===o){let c=Hi(t);for(;o<=i-s;s+=o)this.process(c,s);continue}n.set(t.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Ka(this),Gl(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,kn(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let p=s;p<o;p++)r[p]=0;_h(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=Hi(t),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,d[p],i)}digest(){let{buffer:t,outputLen:r}=this;this.digestInto(t);let n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:i,destroyed:s,pos:a}=this;return t.destroyed=s,t.finished=i,t.length=o,t.pos=a,o%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}},gr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xr=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var Ae=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var Ji=BigInt(4294967295),Yl=BigInt(32);function yh(e,t=!1){return t?{h:Number(e&Ji),l:Number(e>>Yl&Ji)}:{h:Number(e>>Yl&Ji)|0,l:Number(e&Ji)|0}}function Zl(e,t=!1){let r=e.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let i=0;i<r;i++){let{h:s,l:a}=yh(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var Ha=(e,t,r)=>e>>>r,Ga=(e,t,r)=>e<<32-r|t>>>r,Ln=(e,t,r)=>e>>>r|t<<32-r,qn=(e,t,r)=>e<<32-r|t>>>r,$o=(e,t,r)=>e<<64-r|t>>>r-32,Ho=(e,t,r)=>e>>>r-32|t<<64-r;function Kt(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var Xl=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Ql=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,eu=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),tu=(e,t,r,n,o)=>t+r+n+o+(e/2**32|0)|0,ru=(e,t,r,n,o)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(o>>>0),nu=(e,t,r,n,o,i)=>t+r+n+o+i+(e/2**32|0)|0;var xh=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Hr=new Uint32Array(64),Wi=class extends Ko{constructor(t=32){super(64,t,8,!1),this.A=gr[0]|0,this.B=gr[1]|0,this.C=gr[2]|0,this.D=gr[3]|0,this.E=gr[4]|0,this.F=gr[5]|0,this.G=gr[6]|0,this.H=gr[7]|0}get(){let{A:t,B:r,C:n,D:o,E:i,F:s,G:a,H:c}=this;return[t,r,n,o,i,s,a,c]}set(t,r,n,o,i,s,a,c){this.A=t|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=i|0,this.F=s|0,this.G=a|0,this.H=c|0}process(t,r){for(let p=0;p<16;p++,r+=4)Hr[p]=t.getUint32(r,!1);for(let p=16;p<64;p++){let u=Hr[p-15],f=Hr[p-2],h=Rt(u,7)^Rt(u,18)^u>>>3,_=Rt(f,17)^Rt(f,19)^f>>>10;Hr[p]=_+Hr[p-7]+h+Hr[p-16]|0}let{A:n,B:o,C:i,D:s,E:a,F:c,G:l,H:d}=this;for(let p=0;p<64;p++){let u=Rt(a,6)^Rt(a,11)^Rt(a,25),f=d+u+Wl(a,c,l)+xh[p]+Hr[p]|0,_=(Rt(n,2)^Rt(n,13)^Rt(n,22))+zl(n,o,i)|0;d=l,l=c,c=a,a=s+f|0,s=i,i=o,o=n,n=f+_|0}n=n+this.A|0,o=o+this.B|0,i=i+this.C|0,s=s+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(n,o,i,s,a,c,l,d)}roundClean(){kn(Hr)}destroy(){this.set(0,0,0,0,0,0,0,0),kn(this.buffer)}},Ja=class extends Wi{constructor(){super(28),this.A=xr[0]|0,this.B=xr[1]|0,this.C=xr[2]|0,this.D=xr[3]|0,this.E=xr[4]|0,this.F=xr[5]|0,this.G=xr[6]|0,this.H=xr[7]|0}},ou=Zl(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),bh=ou[0],wh=ou[1],Gr=new Uint32Array(80),Jr=new Uint32Array(80),Wa=class extends Ko{constructor(t=64){super(128,t,16,!1),this.Ah=Ae[0]|0,this.Al=Ae[1]|0,this.Bh=Ae[2]|0,this.Bl=Ae[3]|0,this.Ch=Ae[4]|0,this.Cl=Ae[5]|0,this.Dh=Ae[6]|0,this.Dl=Ae[7]|0,this.Eh=Ae[8]|0,this.El=Ae[9]|0,this.Fh=Ae[10]|0,this.Fl=Ae[11]|0,this.Gh=Ae[12]|0,this.Gl=Ae[13]|0,this.Hh=Ae[14]|0,this.Hl=Ae[15]|0}get(){let{Ah:t,Al:r,Bh:n,Bl:o,Ch:i,Cl:s,Dh:a,Dl:c,Eh:l,El:d,Fh:p,Fl:u,Gh:f,Gl:h,Hh:_,Hl:y}=this;return[t,r,n,o,i,s,a,c,l,d,p,u,f,h,_,y]}set(t,r,n,o,i,s,a,c,l,d,p,u,f,h,_,y){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=i|0,this.Cl=s|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=d|0,this.Fh=p|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=_|0,this.Hl=y|0}process(t,r){for(let g=0;g<16;g++,r+=4)Gr[g]=t.getUint32(r),Jr[g]=t.getUint32(r+=4);for(let g=16;g<80;g++){let T=Gr[g-15]|0,O=Jr[g-15]|0,v=Ln(T,O,1)^Ln(T,O,8)^Ha(T,O,7),E=qn(T,O,1)^qn(T,O,8)^Ga(T,O,7),C=Gr[g-2]|0,w=Jr[g-2]|0,I=Ln(C,w,19)^$o(C,w,61)^Ha(C,w,6),P=qn(C,w,19)^Ho(C,w,61)^Ga(C,w,6),A=eu(E,P,Jr[g-7],Jr[g-16]),x=tu(A,v,I,Gr[g-7],Gr[g-16]);Gr[g]=x|0,Jr[g]=A|0}let{Ah:n,Al:o,Bh:i,Bl:s,Ch:a,Cl:c,Dh:l,Dl:d,Eh:p,El:u,Fh:f,Fl:h,Gh:_,Gl:y,Hh:m,Hl:b}=this;for(let g=0;g<80;g++){let T=Ln(p,u,14)^Ln(p,u,18)^$o(p,u,41),O=qn(p,u,14)^qn(p,u,18)^Ho(p,u,41),v=p&f^~p&_,E=u&h^~u&y,C=ru(b,O,E,wh[g],Jr[g]),w=nu(C,m,T,v,bh[g],Gr[g]),I=C|0,P=Ln(n,o,28)^$o(n,o,34)^$o(n,o,39),A=qn(n,o,28)^Ho(n,o,34)^Ho(n,o,39),x=n&i^n&a^i&a,N=o&s^o&c^s&c;m=_|0,b=y|0,_=f|0,y=h|0,f=p|0,h=u|0,{h:p,l:u}=Kt(l|0,d|0,w|0,I|0),l=a|0,d=c|0,a=i|0,c=s|0,i=n|0,s=o|0;let S=Xl(I,A,N);n=Ql(S,w,P,x),o=S|0}({h:n,l:o}=Kt(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Kt(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Kt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:d}=Kt(this.Dh|0,this.Dl|0,l|0,d|0),{h:p,l:u}=Kt(this.Eh|0,this.El|0,p|0,u|0),{h:f,l:h}=Kt(this.Fh|0,this.Fl|0,f|0,h|0),{h:_,l:y}=Kt(this.Gh|0,this.Gl|0,_|0,y|0),{h:m,l:b}=Kt(this.Hh|0,this.Hl|0,m|0,b|0),this.set(n,o,i,s,a,c,l,d,p,u,f,h,_,y,m,b)}roundClean(){kn(Gr,Jr)}destroy(){kn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Ve=Gi(()=>new Wi),iu=Gi(()=>new Ja),su=Gi(()=>new Wa);var zi="__principal__",Th=2,au=4,Nh="aaaaa-aa",q=class e{static anonymous(){return new this(new Uint8Array([au]))}static managementCanister(){return this.fromText(Nh)}static selfAuthenticating(t){let r=iu(t);return new this(new Uint8Array([...r,Th]))}static from(t){if(typeof t=="string")return e.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new e(t);if(e.isPrincipal(t))return new e(t._arr);throw new Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(t){return new this(Ee(t))}static fromText(t){let r=t;if(t.includes(zi)){let s=JSON.parse(t);zi in s&&(r=s[zi])}let n=r.toLowerCase().replace(/-/g,""),o=Kl(n);o=o.slice(4,o.length);let i=new this(o);if(i.toText()!==r)throw new Error(`Principal "${i.toText()}" does not have a valid checksum (original value "${r}" may not be a valid Principal ID).`);return i}static fromUint8Array(t){return new this(t)}static isPrincipal(t){return t instanceof e||typeof t=="object"&&t!==null&&"_isPrincipal"in t&&t._isPrincipal===!0&&"_arr"in t&&t._arr instanceof Uint8Array}constructor(t){this._arr=t,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===au}toUint8Array(){return this._arr}toHex(){return j(this._arr).toUpperCase()}toText(){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,$l(this._arr));let n=new Uint8Array(t),o=new Uint8Array([...n,...this._arr]),s=jl(o).match(/.{1,5}/g);if(!s)throw new Error;return s.join("-")}toString(){return this.toText()}toJSON(){return{[zi]:this.toText()}}compareTo(t){for(let r=0;r<Math.min(this._arr.length,t._arr.length);r++){if(this._arr[r]<t._arr[r])return"lt";if(this._arr[r]>t._arr[r])return"gt"}return this._arr.length<t._arr.length?"lt":this._arr.length>t._arr.length?"gt":"eq"}ltEq(t){let r=this.compareTo(t);return r=="lt"||r=="eq"}gtEq(t){let r=this.compareTo(t);return r=="gt"||r=="eq"}};var br;(function(e){e.Trust="Trust",e.Protocol="Protocol",e.Reject="Reject",e.Transport="Transport",e.External="External",e.Limit="Limit",e.Input="Input",e.Unknown="Unknown"})(br||(br={}));var Yi;(function(e){e.Normal="normal",e.Verbose="verbose"})(Yi||(Yi={}));var Oh=new Set(["arg","certificate","nonce"]);function za(e){return(t,r)=>r instanceof Uint8Array?e===Yi.Normal&&Oh.has(t)?`<${r.length} bytes, set ErrorCode.verbosity = ErrorVerbosity.Verbose to display>`:`hex(${r.length}):${j(r)}`:r}var K=class e{static{this.verbosity=Yi.Normal}constructor(t=!1){this.isCertified=t}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`
2
2
  Request context:
3
3
  Request ID (hex): ${this.requestContext.requestId?j(this.requestContext.requestId):"undefined"}
4
4
  Sender pubkey (hex): ${j(this.requestContext.senderPubKey)}
@@ -6,52 +6,59 @@ Request context:
6
6
  Ingress expiry: ${this.requestContext.ingressExpiry.toString()}`),this.callContext&&(t+=`
7
7
  Call context:
8
8
  Canister ID: ${this.callContext.canisterId.toText()}
9
- Method name: ${this.callContext.methodName}
10
- HTTP details: ${JSON.stringify(this.callContext.httpDetails,null,2)}`),t}},ot=class e extends Error{get code(){return this.cause.code}set code(t){this.cause.code=t}get kind(){return this.cause.kind}set kind(t){this.cause.kind=t}get isCertified(){return this.code.isCertified}constructor(t,r){super(t.toString()),this.name="AgentError",this.cause={code:t,kind:r},Object.setPrototypeOf(this,e.prototype)}hasCode(t){return this.code instanceof t}toString(){return`${this.name} (${this.kind}): ${this.message}`}},fr=class extends ot{static fromCode(t){return new this(t)}},Me=class e extends fr{constructor(t){super(t,pr.Trust),this.name="TrustError",Object.setPrototypeOf(this,e.prototype)}},ee=class e extends fr{constructor(t){super(t,pr.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,e.prototype)}},kr=class e extends fr{constructor(t){super(t,pr.Reject),this.name="RejectError",Object.setPrototypeOf(this,e.prototype)}},ko=class e extends fr{constructor(t){super(t,pr.Transport),this.name="TransportError",Object.setPrototypeOf(this,e.prototype)}},me=class e extends fr{constructor(t){super(t,pr.External),this.name="ExternalError",Object.setPrototypeOf(this,e.prototype)}};var Y=class e extends fr{constructor(t){super(t,pr.Input),this.name="InputError",Object.setPrototypeOf(this,e.prototype)}},ae=class e extends fr{constructor(t){super(t,pr.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,e.prototype)}},vt=class e extends ${constructor(t,r){super(),this.reason=t,this.error=r,this.name="CertificateVerificationErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=this.reason;return this.error&&(t+=`: ${Go(this.error)}`),`Certificate verification error: "${t}"`}},hr=class e extends ${constructor(t,r,n,o,i){super(),this.maxAgeInMinutes=t,this.certificateTime=r,this.currentTime=n,this.timeDiffMsecs=o,this.ageType=i,this.name="CertificateTimeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`}},Ui=class e extends ${constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Certificate has too many delegations"}},Bn=class e extends ${constructor(t,r){super(),this.canisterId=t,this.subnetId=r,this.name="CertificateNotAuthorizedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`}},ki=class e extends ${constructor(t){super(),this.subnetId=t,this.name="CertificateNotAuthorizedForSubnetErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate is not authorized for subnet ${this.subnetId.toText()}`}},It=class e extends ${constructor(t,r){super(),this.message=t,this.lookupStatus=r,this.name="LookupErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}},Li=class e extends ${constructor(t){super(),this.message=t,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},qi=class e extends ${constructor(t){super(),this.message=t,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},to=class e extends ${constructor(t,r){super(),this.expectedLength=t,this.actualLength=r,this.name="DerKeyLengthMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}},Mi=class e extends ${constructor(t,r){super(),this.expectedPrefix=t,this.actualPrefix=r,this.name="DerPrefixMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${j(this.expectedPrefix)}, but got ${j(this.actualPrefix)}`}},ji=class e extends ${constructor(t,r){super(),this.expectedLength=t,this.actualLength=r,this.name="DerDecodeLengthMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}},At=class e extends ${constructor(t){super(),this.error=t,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},Lo=class e extends ${constructor(t){super(),this.error=t,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},Ki=class e extends ${constructor(t,r){super(),this.error=t,this.input=r,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${Go(this.error)}, input: ${j(this.input)}`}},Hi=class e extends ${constructor(t,r){super(),this.error=t,this.value=r,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${Go(this.error)}, input: ${this.value}`}};var Dn=class e extends ${constructor(t,r,n){super(),this.message=t,this.requestId=r,this.status=n,this.name="TimeoutWaitingForResponseErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`${this.message}
9
+ Method name: ${this.callContext.methodName}`,"httpDetails"in this.callContext&&(t+=`
10
+ HTTP details: ${JSON.stringify(this.callContext.httpDetails,za(e.verbosity),2)}`)),t}},st=class e extends Error{get code(){return this.cause.code}set code(t){this.cause.code=t}get kind(){return this.cause.kind}set kind(t){this.cause.kind=t}get isCertified(){return this.code.isCertified}constructor(t,r){super(t.toString()),this.name="AgentError",this.cause={code:t,kind:r},Object.setPrototypeOf(this,e.prototype)}hasCode(t){return this.code instanceof t}toString(){return`${this.name} (${this.kind}): ${this.message}`}},wr=class extends st{static fromCode(t){return new this(t)}},Ye=class e extends wr{constructor(t){super(t,br.Trust),this.name="TrustError",Object.setPrototypeOf(this,e.prototype)}},re=class e extends wr{constructor(t){super(t,br.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,e.prototype)}},vt=class e extends wr{constructor(t){super(t,br.Reject),this.name="RejectError",Object.setPrototypeOf(this,e.prototype)}},Go=class e extends wr{constructor(t){super(t,br.Transport),this.name="TransportError",Object.setPrototypeOf(this,e.prototype)}},Pe=class e extends wr{constructor(t){super(t,br.External),this.name="ExternalError",Object.setPrototypeOf(this,e.prototype)}};var z=class e extends wr{constructor(t){super(t,br.Input),this.name="InputError",Object.setPrototypeOf(this,e.prototype)}},ae=class e extends wr{constructor(t){super(t,br.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,e.prototype)}},It=class e extends K{constructor(t,r){super(),this.reason=t,this.error=r,this.name="CertificateVerificationErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=this.reason;return this.error&&(t+=`: ${Qo(this.error)}`),`Certificate verification error: "${t}"`}},Tr=class e extends K{constructor(t,r,n,o,i){super(),this.maxAgeInMinutes=t,this.certificateTime=r,this.currentTime=n,this.timeDiffMsecs=o,this.ageType=i,this.name="CertificateTimeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`}},Zi=class e extends K{constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Certificate has too many delegations"}},Mn=class e extends K{constructor(t,r){super(),this.canisterId=t,this.subnetId=r,this.name="CertificateNotAuthorizedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`}},Xi=class e extends K{constructor(t){super(),this.subnetId=t,this.name="CertificateNotAuthorizedForSubnetErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The certificate is not authorized for subnet ${this.subnetId.toText()}`}},At=class e extends K{constructor(t,r){super(),this.message=t,this.lookupStatus=r,this.name="LookupErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}},Qi=class e extends K{constructor(t){super(),this.message=t,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},es=class e extends K{constructor(t){super(),this.message=t,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},uo=class e extends K{constructor(t,r){super(),this.expectedLength=t,this.actualLength=r,this.name="DerKeyLengthMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}},ts=class e extends K{constructor(t,r){super(),this.expectedPrefix=t,this.actualPrefix=r,this.name="DerPrefixMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${j(this.expectedPrefix)}, but got ${j(this.actualPrefix)}`}},rs=class e extends K{constructor(t,r){super(),this.expectedLength=t,this.actualLength=r,this.name="DerDecodeLengthMismatchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}},St=class e extends K{constructor(t){super(),this.error=t,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},Jo=class e extends K{constructor(t){super(),this.error=t,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},ns=class e extends K{constructor(t,r){super(),this.error=t,this.input=r,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${Qo(this.error)}, input: ${j(this.input)}`}},os=class e extends K{constructor(t,r){super(),this.error=t,this.value=r,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${Qo(this.error)}, input: ${this.value}`}};var jn=class e extends K{constructor(t,r,n){super(),this.message=t,this.requestId=r,this.status=n,this.name="TimeoutWaitingForResponseErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`${this.message}
11
11
  `;return this.requestId&&(t+=` Request ID: ${j(this.requestId)}
12
12
  `),this.status&&(t+=` Request status: ${this.status}
13
- `),t}},Gi=class e extends ${constructor(t,r,n){super(),this.maxIngressExpiryInMinutes=t,this.requestId=r,this.retryTimes=n,this.name="CertificateOutdatedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?
13
+ `),t}},is=class e extends K{constructor(t,r,n){super(),this.maxIngressExpiryInMinutes=t,this.requestId=r,this.retryTimes=n,this.name="CertificateOutdatedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?
14
14
  Request ID: ${j(this.requestId)}
15
- `;return this.retryTimes!==void 0&&(t+=` Retried ${this.retryTimes} times.`),t}},ro=class e extends ${constructor(t,r,n,o){super(!0),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="CertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
15
+ `;return this.retryTimes!==void 0&&(t+=` Retried ${this.retryTimes} times.`),t}},ss=class e extends K{constructor(t,r,n,o){super(!0),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="CertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
16
16
  Request ID: ${j(this.requestId)}
17
17
  Reject code: ${this.rejectCode}
18
18
  Reject text: ${this.rejectMessage}
19
19
  Error code: ${this.rejectErrorCode}
20
- `}},$i=class e extends ${constructor(t,r,n,o,i){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.signatures=i,this.name="UncertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
20
+ `}},as=class e extends K{constructor(t,r,n,o,i){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.signatures=i,this.name="UncertifiedRejectErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
21
21
  Request ID: ${j(this.requestId)}
22
22
  Reject code: ${this.rejectCode}
23
23
  Reject text: ${this.rejectMessage}
24
24
  Error code: ${this.rejectErrorCode}
25
- `}},Ji=class e extends ${constructor(t,r,n,o){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="UncertifiedRejectUpdateErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
25
+ `}},cs=class e extends K{constructor(t,r,n,o){super(),this.requestId=t,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="UncertifiedRejectUpdateErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`The replica returned a rejection error:
26
26
  Request ID: ${j(this.requestId)}
27
27
  Reject code: ${this.rejectCode}
28
28
  Reject text: ${this.rejectMessage}
29
29
  Error code: ${this.rejectErrorCode}
30
- `}},Wi=class e extends ${constructor(t){super(),this.requestId=t,this.name="RequestStatusDoneNoReplyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Call was marked as done but we never saw the reply:
30
+ `}},ls=class e extends K{constructor(t){super(),this.requestId=t,this.name="RequestStatusDoneNoReplyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Call was marked as done but we never saw the reply:
31
31
  Request ID: ${j(this.requestId)}
32
- `}},lt=class e extends ${constructor(t){super(),this.shouldFetchRootKey=t,this.name="MissingRootKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.shouldFetchRootKey===void 0?"Agent is missing root key":`Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`}},zi=class e extends ${constructor(t){super(),this.value=t,this.name="HashValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}},no=class e extends ${constructor(t){super(),this.error=t,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.error}},Lr=class e extends ${constructor(){super(),this.name="IdentityInvalidErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"This identity has expired due this application's security policy. Please refresh your authentication."}},Mt=class e extends ${constructor(t,r){super(),this.message=t,this.providedIngressExpiryInMinutes=r,this.name="IngressExpiryInvalidErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}},Yi=class e extends ${constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}},Zi=class e extends ${constructor(t){super(),this.error=t,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},Xi=class e extends ${constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}},Qi=class e extends ${constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}},es=class e extends ${constructor(t){super(),this.nodeId=t,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},Re=class e extends ${constructor(t){super(),this.error=t,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${Go(this.error)}`}},qr=class e extends ${constructor(t){super(),this.error=t,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},qo=class e extends ${constructor(t,r,n,o){super(),this.status=t,this.statusText=r,this.headers=n,this.bodyText=o,this.name="HttpErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`HTTP request failed:
32
+ `}},Ct=class e extends K{constructor(t){super(),this.shouldFetchRootKey=t,this.name="MissingRootKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.shouldFetchRootKey===void 0?"Agent is missing root key":`Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`}},us=class e extends K{constructor(t){super(),this.value=t,this.name="HashValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}},Wr=class e extends K{constructor(){super(),this.name="IdentityInvalidErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"This identity has expired due this application's security policy. Please refresh your authentication."}},$t=class e extends K{constructor(t,r){super(),this.message=t,this.providedIngressExpiryInMinutes=r,this.name="IngressExpiryInvalidErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}},ds=class e extends K{constructor(){super(),this.name="MissingFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"No fetch implementation available. Provide a `fetch` function in HttpAgentOptions or ensure `globalThis.fetch` is defined."}},ps=class e extends K{constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}},fs=class e extends K{constructor(t,r){super(),this.signatureCount=t,this.maxExpected=r,this.name="ExcessiveSignaturesErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contains ${this.signatureCount} signatures, which exceeds the subnet size of ${this.maxExpected}. This suggests a malformed or malicious response.`}},hs=class e extends K{constructor(t){super(),this.error=t,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}};var ms=class e extends K{constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}},_s=class e extends K{constructor(t){super(),this.nodeId=t,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},Se=class e extends K{constructor(t){super(),this.error=t,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${Qo(this.error)}`}},ys=class e extends K{constructor(t,r,n,o){super(),this.status=t,this.requestId=r,this.response=n,this.rawCertificate=o,this.name="UnexpectedV4StatusErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=(r,n)=>n instanceof Uint8Array?`hex(${n.length}):${j(n)}`:n;return`Unexpected request status in v4 sync response: "${this.status}"
33
+ Request ID (hex): ${j(this.requestId)}
34
+ Response: ${JSON.stringify(this.response,t,2)}`}},zr=class e extends K{constructor(t){super(),this.error=t,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},Wo=class e extends K{constructor(t,r,n,o){super(),this.status=t,this.statusText=r,this.headers=n,this.bodyText=o,this.name="HttpErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){let t=`HTTP request failed:
33
35
  Status: ${this.status} (${this.statusText})
34
- Headers: ${JSON.stringify(this.headers)}
36
+ Headers: ${JSON.stringify(this.headers,za(K.verbosity))}
35
37
  `;return this.bodyText&&(t+=` Body: ${this.bodyText}
36
- `),t}},Mo=class e extends ${constructor(){super(),this.name="HttpV4ApiNotSupportedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"HTTP request failed: v4 API is not supported"}},jo=class e extends ${constructor(t){super(),this.error=t,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${Go(this.error)}`}},Ko=class e extends ${constructor(t){super(),this.receivedCanisterId=t,this.name="MissingCanisterIdErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Canister ID is required, but received ${typeof this.receivedCanisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`}},ts=class e extends ${constructor(t){super(),this.request=t,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},Ho=class e extends ${constructor(t){super(),this.error=t,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function Go(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e)}catch{return String(e)}}var ut=new Error("unreachable");var qn={};mf(qn,{Bool:()=>Ul,BoolClass:()=>ss,ConstructType:()=>Ht,Empty:()=>Bl,EmptyClass:()=>Jo,FixedIntClass:()=>yr,FixedNatClass:()=>Kt,Float32:()=>jl,Float64:()=>Kl,FloatClass:()=>Yo,Func:()=>iu,FuncClass:()=>Ln,Int:()=>ql,Int16:()=>Gl,Int32:()=>$l,Int64:()=>Jl,Int8:()=>Hl,IntClass:()=>Wo,Nat:()=>Ml,Nat16:()=>zl,Nat32:()=>Yl,Nat64:()=>Zl,Nat8:()=>Wl,NatClass:()=>zo,Null:()=>kl,NullClass:()=>Un,Opt:()=>tu,OptClass:()=>Kr,PrimitiveType:()=>Xe,Principal:()=>Xl,PrincipalClass:()=>ls,Rec:()=>ou,RecClass:()=>dt,Record:()=>ru,RecordClass:()=>kn,Reserved:()=>Dl,ReservedClass:()=>Gt,Service:()=>su,ServiceClass:()=>co,Text:()=>Ll,TextClass:()=>as,Tuple:()=>Ql,TupleClass:()=>cs,Type:()=>io,Unknown:()=>Sf,UnknownClass:()=>is,Variant:()=>nu,VariantClass:()=>ao,Vec:()=>eu,VecClass:()=>so,Visitor:()=>Ra,decode:()=>Af,encode:()=>If,resetSubtypeCache:()=>va,subtype:()=>Aa});function Z(...e){let t=new Uint8Array(e.reduce((n,o)=>n+o.byteLength,0)),r=0;for(let n of e)t.set(n,r),r+=n.byteLength;return t}var St=class{save(){return this._view}restore(t){if(!(t instanceof Uint8Array))throw new Error("Checkpoint must be a Uint8Array");this._view=t}constructor(t,r=t?.byteLength||0){if(t&&!(t instanceof Uint8Array))try{t=jt(t)}catch{throw new Error("Buffer must be a Uint8Array")}if(r<0||!Number.isInteger(r))throw new Error("Length must be a non-negative integer");if(t&&r>t.byteLength)throw new Error("Length cannot exceed buffer length");this._buffer=t||new Uint8Array(0),this._view=new Uint8Array(this._buffer.buffer,0,r)}get buffer(){return this._view.slice()}get byteLength(){return this._view.byteLength}read(t){let r=this._view.subarray(0,t);return this._view=this._view.subarray(t),r.slice()}readUint8(){if(this._view.byteLength===0)return;let t=this._view[0];return this._view=this._view.subarray(1),t}write(t){if(!(t instanceof Uint8Array))throw new Error("Buffer must be a Uint8Array");let r=this._view.byteLength;this._view.byteOffset+this._view.byteLength+t.byteLength>=this._buffer.byteLength?this.alloc(t.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+t.byteLength),this._view.set(t,r)}get end(){return this._view.byteLength===0}alloc(t){if(t<=0||!Number.isInteger(t))throw new Error("Amount must be a positive integer");let r=new Uint8Array((this._buffer.byteLength+t)*1.2|0),n=new Uint8Array(r.buffer,0,this._view.byteLength+t);n.set(this._view),this._buffer=r,this._view=n}};function jt(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?jt(e.buffer):new Uint8Array(e)}function oo(e,t){if(e.byteLength!==t.byteLength)return e.byteLength-t.byteLength;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return e[r]-t[r];return 0}function Al(e,t){return oo(e,t)===0}function Sl(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Rf(e){let r=new TextEncoder().encode(e),n=0;for(let o of r)n=(n*223+o)%2**32;return n}function je(e){if(/^_\d+_$/.test(e)||/^_0x[0-9a-fA-F]+_$/.test(e)){let t=+e.slice(1,-1);if(Number.isSafeInteger(t)&&t>=0&&t<2**32)return t}return Rf(e)}function wa(e){let t=BigInt(e);if(e<=0)throw new RangeError("Input must be positive");return t.toString(2).length-1}function rs(e){let t=BigInt(e);if(e<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<t}function Cl(){throw new Error("unexpected end of buffer")}function jr(e,t){return e.byteLength<t&&Cl(),e.read(t)}function Mr(e){let t=e.readUint8();return t===void 0&&Cl(),t}function ie(e){if(typeof e=="number"&&(e=BigInt(e)),e<BigInt(0))throw new Error("Cannot leb encode negative values.");let t=(e===BigInt(0)?0:wa(e))+1,r=new St(new Uint8Array(t),0);for(;;){let n=Number(e&BigInt(127));if(e/=BigInt(128),e===BigInt(0)){r.write(new Uint8Array([n]));break}else r.write(new Uint8Array([n|128]))}return r.buffer}function _e(e){let t=BigInt(1),r=BigInt(0),n;do n=Mr(e),r+=BigInt(n&127).valueOf()*t,t*=BigInt(128);while(n>=128);return r}function ye(e){typeof e=="number"&&(e=BigInt(e));let t=e<BigInt(0);t&&(e=-e-BigInt(1));let r=(e===BigInt(0)?0:wa(e))+1,n=new St(new Uint8Array(r),0);for(;;){let i=o(e);if(e/=BigInt(128),t&&e===BigInt(0)&&(i&64)!==0||!t&&e===BigInt(0)&&(i&64)===0){n.write(new Uint8Array([i]));break}else n.write(new Uint8Array([i|128]))}function o(i){let s=i%BigInt(128);return Number(t?BigInt(128)-s-BigInt(1):s)}return n.buffer}function mr(e){let t=new Uint8Array(e.buffer),r=0;for(;r<t.byteLength;r++)if(t[r]<128){if((t[r]&64)===0)return _e(e);break}let n=new Uint8Array(jr(e,r+1)),o=BigInt(0);for(let i=n.byteLength-1;i>=0;i--)o=o*BigInt(128)+BigInt(128-(n[i]&127)-1);return-o-BigInt(1)}function Fl(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return Ta(e,t)}function Ta(e,t){e=BigInt(e);let r=new St(new Uint8Array(Math.min(1,t)),0),n=0,o=BigInt(256),i=BigInt(0),s=Number(e%o);for(r.write(new Uint8Array([s]));++n<t;)e<0&&i===BigInt(0)&&s!==0&&(i=BigInt(1)),s=Number((e/o-i)%BigInt(256)),r.write(new Uint8Array([s])),o*=BigInt(256);return r.buffer}function Na(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=BigInt(Mr(e)),n=BigInt(1),o=0;for(;++o<t;){n*=BigInt(256);let i=BigInt(Mr(e));r=r+n*i}return r}function Vl(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=Na(e,t),n=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return r>=n&&(r-=n*BigInt(2)),r}var Q;(function(e){e[e.Null=-1]="Null",e[e.Bool=-2]="Bool",e[e.Nat=-3]="Nat",e[e.Int=-4]="Int",e[e.Float32=-13]="Float32",e[e.Float64=-14]="Float64",e[e.Text=-15]="Text",e[e.Reserved=-16]="Reserved",e[e.Empty=-17]="Empty",e[e.Opt=-18]="Opt",e[e.Vector=-19]="Vector",e[e.Record=-20]="Record",e[e.Variant=-21]="Variant",e[e.Func=-22]="Func",e[e.Service=-23]="Service",e[e.Principal=-24]="Principal"})(Q||(Q={}));var ns="DIDL",vf=new TextEncoder().encode(ns),Pl=400;function $o(e,t,r){return e.map((n,o)=>r(n,t[o]))}var Ea=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(t){return this._idx.has(t.name)}add(t,r){let n=this._typs.length;this._idx.set(t.name,n),this._idxRefCount.set(n,1),this._typs.push(r)}merge(t,r){let n=this._idx.get(t.name),o=this._idx.get(r);if(n===void 0)throw new Error("Missing type index for "+t);if(o===void 0)throw new Error("Missing type index for "+r);this._typs[n]=this._typs[o];let i=this._getIdxRefCount(n),s=this._getIdxRefCount(o);this._idxRefCount.set(n,i+s),this._idx.set(r,n),this._idxRefCount.set(o,0),this._compactFromEnd()}_getIdxRefCount(t){return this._idxRefCount.get(t)||0}_compactFromEnd(){for(;this._typs.length>0;){let t=this._typs.length-1;if(this._getIdxRefCount(t)>0)break;this._typs.pop(),this._idxRefCount.delete(t)}}encode(){let t=ie(this._typs.length),r=Z(...this._typs);return Z(t,r)}indexOf(t){if(!this._idx.has(t))throw new Error("Missing type index for "+t);return ye(this._idx.get(t)||0)}},Ra=class{visitType(t,r){throw new Error("Not implemented")}visitPrimitive(t,r){return this.visitType(t,r)}visitEmpty(t,r){return this.visitPrimitive(t,r)}visitBool(t,r){return this.visitPrimitive(t,r)}visitNull(t,r){return this.visitPrimitive(t,r)}visitReserved(t,r){return this.visitPrimitive(t,r)}visitText(t,r){return this.visitPrimitive(t,r)}visitNumber(t,r){return this.visitPrimitive(t,r)}visitInt(t,r){return this.visitNumber(t,r)}visitNat(t,r){return this.visitNumber(t,r)}visitFloat(t,r){return this.visitPrimitive(t,r)}visitFixedInt(t,r){return this.visitNumber(t,r)}visitFixedNat(t,r){return this.visitNumber(t,r)}visitPrincipal(t,r){return this.visitPrimitive(t,r)}visitConstruct(t,r){return this.visitType(t,r)}visitVec(t,r,n){return this.visitConstruct(t,n)}visitOpt(t,r,n){return this.visitConstruct(t,n)}visitRecord(t,r,n){return this.visitConstruct(t,n)}visitTuple(t,r,n){let o=r.map((i,s)=>[`_${s}_`,i]);return this.visitRecord(t,o,n)}visitVariant(t,r,n){return this.visitConstruct(t,n)}visitRec(t,r,n){return this.visitConstruct(r,n)}visitFunc(t,r){return this.visitConstruct(t,r)}visitService(t,r){return this.visitConstruct(t,r)}},H;(function(e){e.EmptyClass="__IDL_EmptyClass__",e.UnknownClass="__IDL_UnknownClass__",e.BoolClass="__IDL_BoolClass__",e.NullClass="__IDL_NullClass__",e.ReservedClass="__IDL_ReservedClass__",e.TextClass="__IDL_TextClass__",e.IntClass="__IDL_IntClass__",e.NatClass="__IDL_NatClass__",e.FloatClass="__IDL_FloatClass__",e.FixedIntClass="__IDL_FixedIntClass__",e.FixedNatClass="__IDL_FixedNatClass__",e.VecClass="__IDL_VecClass__",e.OptClass="__IDL_OptClass__",e.RecordClass="__IDL_RecordClass__",e.TupleClass="__IDL_TupleClass__",e.VariantClass="__IDL_VariantClass__",e.RecClass="__IDL_RecClass__",e.PrincipalClass="__IDL_PrincipalClass__",e.FuncClass="__IDL_FuncClass__",e.ServiceClass="__IDL_ServiceClass__"})(H||(H={}));var io=class{display(){return this.name}valueToString(t){return he(t)}buildTypeTable(t){t.has(this)||this._buildTypeTableImpl(t)}},Xe=class extends io{checkType(t){if(this.name!==t.name)throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);return t}_buildTypeTableImpl(t){}},Ht=class extends io{checkType(t){if(t instanceof dt){let r=t.getType();if(typeof r>"u")throw new Error("type mismatch with uninitialized type");return r}throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`)}encodeType(t){return t.indexOf(this.name)}},Jo=class extends Xe{get typeName(){return H.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===H.EmptyClass}accept(t,r){return t.visitEmpty(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return ye(Q.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},is=class extends io{get typeName(){return H.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===H.UnknownClass}checkType(t){throw new Error("Method not implemented for unknown.")}accept(t,r){throw t.visitType(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(){throw new Error("Unknown cannot appear as a function argument")}valueToString(){throw new Error("Unknown cannot appear as a value")}encodeType(){throw new Error("Unknown cannot be serialized")}decodeValue(t,r){let n=r.decodeValue(t,r);Object(n)!==n&&(n=Object(n));let o;return r instanceof dt?o=()=>r.getType():o=()=>r,Object.defineProperty(n,"type",{value:o,writable:!0,enumerable:!1,configurable:!0}),n}_buildTypeTableImpl(){throw new Error("Unknown cannot be serialized")}get name(){return"Unknown"}},ss=class extends Xe{get typeName(){return H.BoolClass}static[Symbol.hasInstance](t){return t.typeName===H.BoolClass}accept(t,r){return t.visitBool(this,r)}covariant(t){if(typeof t=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return new Uint8Array([t?1:0])}encodeType(){return ye(Q.Bool)}decodeValue(t,r){switch(this.checkType(r),Mr(t)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},Un=class extends Xe{get typeName(){return H.NullClass}static[Symbol.hasInstance](t){return t.typeName===H.NullClass}accept(t,r){return t.visitNull(this,r)}covariant(t){if(t===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return ye(Q.Null)}decodeValue(t,r){return this.checkType(r),null}get name(){return"null"}},Gt=class extends Xe{get typeName(){return H.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===H.ReservedClass}accept(t,r){return t.visitReserved(this,r)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return ye(Q.Reserved)}decodeValue(t,r){return r.name!==this.name&&r.decodeValue(t,r),null}get name(){return"reserved"}},as=class extends Xe{get typeName(){return H.TextClass}static[Symbol.hasInstance](t){return t.typeName===H.TextClass}accept(t,r){return t.visitText(this,r)}covariant(t){if(typeof t=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=new TextEncoder().encode(t),n=ie(r.byteLength);return Z(n,r)}encodeType(){return ye(Q.Text)}decodeValue(t,r){this.checkType(r);let n=_e(t),o=jr(t,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(o)}get name(){return"text"}valueToString(t){return'"'+t+'"'}},Wo=class extends Xe{get typeName(){return H.IntClass}static[Symbol.hasInstance](t){return t.typeName===H.IntClass}accept(t,r){return t.visitInt(this,r)}covariant(t){if(typeof t=="bigint"||Number.isInteger(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return ye(t)}encodeType(){return ye(Q.Int)}decodeValue(t,r){return this.checkType(r),mr(t)}get name(){return"int"}valueToString(t){return t.toString()}},zo=class extends Xe{get typeName(){return H.NatClass}static[Symbol.hasInstance](t){return t.typeName===H.NatClass}accept(t,r){return t.visitNat(this,r)}covariant(t){if(typeof t=="bigint"&&t>=BigInt(0)||Number.isInteger(t)&&t>=0)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return ie(t)}encodeType(){return ye(Q.Nat)}decodeValue(t,r){return this.checkType(r),_e(t)}get name(){return"nat"}valueToString(t){return t.toString()}},Yo=class extends Xe{get typeName(){return H.FloatClass}static[Symbol.hasInstance](t){return t.typeName===H.FloatClass}constructor(t){if(super(),this._bits=t,t!==32&&t!==64)throw new Error("not a valid float type")}accept(t,r){return t.visitFloat(this,r)}covariant(t){if(typeof t=="number"||t instanceof Number)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=new ArrayBuffer(this._bits/8),n=new DataView(r);return this._bits===32?n.setFloat32(0,t,!0):n.setFloat64(0,t,!0),new Uint8Array(r)}encodeType(){let t=this._bits===32?Q.Float32:Q.Float64;return ye(t)}decodeValue(t,r){this.checkType(r);let n=jr(t,this._bits/8),o=Sl(n);return this._bits===32?o.getFloat32(0,!0):o.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(t){return t.toString()}},yr=class extends Xe{get typeName(){return H.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===H.FixedIntClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedInt(this,r)}covariant(t){let r=rs(this._bits-1)*BigInt(-1),n=rs(this._bits-1)-BigInt(1),o=!1;if(typeof t=="bigint")o=t>=r&&t<=n;else if(Number.isInteger(t)){let i=BigInt(t);o=i>=r&&i<=n}else o=!1;if(o)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return Ta(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return ye(-9-t)}decodeValue(t,r){this.checkType(r);let n=Vl(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}},Kt=class extends Xe{get typeName(){return H.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===H.FixedNatClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedNat(this,r)}covariant(t){let r=rs(this._bits),n=!1;if(typeof t=="bigint"&&t>=BigInt(0)?n=t<r:Number.isInteger(t)&&t>=0?n=BigInt(t)<r:n=!1,n)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return Fl(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return ye(-5-t)}decodeValue(t,r){this.checkType(r);let n=Na(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(t){return t.toString()}},so=class e extends Ht{get typeName(){return H.VecClass}static[Symbol.hasInstance](t){return t.typeName===H.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof Kt&&t._bits===8&&(this._blobOptimization=!0)}accept(t,r){return t.visitVec(this,this._type,r)}covariant(t){let r=this._type instanceof Kt?this._type._bits:this._type instanceof yr?this._type._bits:0;if(ArrayBuffer.isView(t)&&r==t.BYTES_PER_ELEMENT*8||Array.isArray(t)&&t.every((n,o)=>{try{return this._type.covariant(n)}catch(i){throw new Error(`Invalid ${this.display()} argument:
38
+ `),t}},zo=class e extends K{constructor(){super(),this.name="HttpV4ApiNotSupportedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"HTTP request failed: v4 API is not supported"}},Yo=class e extends K{constructor(t){super(),this.error=t,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${Qo(this.error)}`}},Zo=class e extends K{constructor(t){super(),this.receivedCanisterId=t,this.name="MissingCanisterIdErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Canister ID is required, but received ${typeof this.receivedCanisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`}},gs=class e extends K{constructor(t){super(),this.request=t,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},Xo=class e extends K{constructor(t){super(),this.error=t,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function Qo(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e,za(K.verbosity))}catch{return String(e)}}var ft=new Error("unreachable");var Gn={};jf(Gn,{Bool:()=>_u,BoolClass:()=>Ns,CandidDecodeError:()=>Ze,ConstructType:()=>Jt,Empty:()=>hu,EmptyClass:()=>ti,FixedIntClass:()=>Er,FixedNatClass:()=>Gt,Float32:()=>wu,Float64:()=>Tu,FloatClass:()=>oi,Func:()=>ku,FuncClass:()=>Hn,Int:()=>xu,Int16:()=>Ou,Int32:()=>Eu,Int64:()=>Ru,Int8:()=>Nu,IntClass:()=>ri,Nat:()=>bu,Nat16:()=>Iu,Nat32:()=>Au,Nat64:()=>Su,Nat8:()=>vu,NatClass:()=>ni,Null:()=>yu,NullClass:()=>Kn,Opt:()=>Fu,OptClass:()=>Xr,PrimitiveType:()=>Xe,Principal:()=>Cu,PrincipalClass:()=>Rs,Rec:()=>Uu,RecClass:()=>ht,Record:()=>Bu,RecordClass:()=>$n,Reserved:()=>mu,ReservedClass:()=>Wt,Service:()=>Lu,ServiceClass:()=>_o,Text:()=>gu,TextClass:()=>Os,Tuple:()=>Vu,TupleClass:()=>Es,Type:()=>fo,Unknown:()=>Ah,UnknownClass:()=>Ts,Variant:()=>Du,VariantClass:()=>mo,Vec:()=>Pu,VecClass:()=>ho,Visitor:()=>tc,decode:()=>Ih,encode:()=>vh,resetSubtypeCache:()=>rc,subtype:()=>oc});function X(...e){let t=new Uint8Array(e.reduce((n,o)=>n+o.byteLength,0)),r=0;for(let n of e)t.set(n,r),r+=n.byteLength;return t}var Vt=class{save(){return this._view}restore(t){if(!(t instanceof Uint8Array))throw new Error("Checkpoint must be a Uint8Array");this._view=t}constructor(t,r=t?.byteLength||0){if(t&&!(t instanceof Uint8Array))try{t=Ht(t)}catch{throw new Error("Buffer must be a Uint8Array")}if(r<0||!Number.isInteger(r))throw new Error("Length must be a non-negative integer");if(t&&r>t.byteLength)throw new Error("Length cannot exceed buffer length");this._buffer=t||new Uint8Array(0),this._view=new Uint8Array(this._buffer.buffer,0,r)}get buffer(){return this._view.slice()}get byteLength(){return this._view.byteLength}read(t){let r=this._view.subarray(0,t);return this._view=this._view.subarray(t),r.slice()}readUint8(){if(this._view.byteLength===0)return;let t=this._view[0];return this._view=this._view.subarray(1),t}write(t){if(!(t instanceof Uint8Array))throw new Error("Buffer must be a Uint8Array");let r=this._view.byteLength;this._view.byteOffset+this._view.byteLength+t.byteLength>=this._buffer.byteLength?this.alloc(t.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+t.byteLength),this._view.set(t,r)}get end(){return this._view.byteLength===0}alloc(t){if(t<=0||!Number.isInteger(t))throw new Error("Amount must be a positive integer");let r=new Uint8Array((this._buffer.byteLength+t)*1.2|0),n=new Uint8Array(r.buffer,0,this._view.byteLength+t);n.set(this._view),this._buffer=r,this._view=n}};function Ht(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?Ht(e.buffer):new Uint8Array(e)}function po(e,t){if(e.byteLength!==t.byteLength)return e.byteLength-t.byteLength;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return e[r]-t[r];return 0}function cu(e,t){return po(e,t)===0}function lu(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Eh(e){let r=new TextEncoder().encode(e),n=0;for(let o of r)n=(n*223+o)%2**32;return n}function Me(e){if(/^_\d+_$/.test(e)||/^_0x[0-9a-fA-F]+_$/.test(e)){let t=+e.slice(1,-1);if(Number.isSafeInteger(t)&&t>=0&&t<2**32)return t}return Eh(e)}function Ya(e){let t=BigInt(e);if(e<=0)throw new RangeError("Input must be positive");return t.toString(2).length-1}function xs(e){let t=BigInt(e);if(e<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<t}function uu(){throw new Error("unexpected end of buffer")}function Zr(e,t){return e.byteLength<t&&uu(),e.read(t)}function Yr(e){let t=e.readUint8();return t===void 0&&uu(),t}function oe(e){if(typeof e=="number"&&(e=BigInt(e)),e<BigInt(0))throw new Error("Cannot leb encode negative values.");let t=(e===BigInt(0)?0:Ya(e))+1,r=new Vt(new Uint8Array(t),0);for(;;){let n=Number(e&BigInt(127));if(e/=BigInt(128),e===BigInt(0)){r.write(new Uint8Array([n]));break}else r.write(new Uint8Array([n|128]))}return r.buffer}function _e(e){let t=BigInt(1),r=BigInt(0),n;do n=Yr(e),r+=BigInt(n&127).valueOf()*t,t*=BigInt(128);while(n>=128);return r}function ye(e){typeof e=="number"&&(e=BigInt(e));let t=e<BigInt(0);t&&(e=-e-BigInt(1));let r=(e===BigInt(0)?0:Ya(e))+1,n=new Vt(new Uint8Array(r),0);for(;;){let i=o(e);if(e/=BigInt(128),t&&e===BigInt(0)&&(i&64)!==0||!t&&e===BigInt(0)&&(i&64)===0){n.write(new Uint8Array([i]));break}else n.write(new Uint8Array([i|128]))}function o(i){let s=i%BigInt(128);return Number(t?BigInt(128)-s-BigInt(1):s)}return n.buffer}function Nr(e){let t=new Uint8Array(e.buffer),r=0;for(;r<t.byteLength;r++)if(t[r]<128){if((t[r]&64)===0)return _e(e);break}let n=new Uint8Array(Zr(e,r+1)),o=BigInt(0);for(let i=n.byteLength-1;i>=0;i--)o=o*BigInt(128)+BigInt(128-(n[i]&127)-1);return-o-BigInt(1)}function du(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return Za(e,t)}function Za(e,t){e=BigInt(e);let r=new Vt(new Uint8Array(Math.min(1,t)),0),n=0,o=BigInt(256),i=BigInt(0),s=Number(e%o);for(r.write(new Uint8Array([s]));++n<t;)e<0&&i===BigInt(0)&&s!==0&&(i=BigInt(1)),s=Number((e/o-i)%BigInt(256)),r.write(new Uint8Array([s])),o*=BigInt(256);return r.buffer}function Xa(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=BigInt(Yr(e)),n=BigInt(1),o=0;for(;++o<t;){n*=BigInt(256);let i=BigInt(Yr(e));r=r+n*i}return r}function pu(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=Xa(e,t),n=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return r>=n&&(r-=n*BigInt(2)),r}var Ze=class e extends Error{constructor(t){super(t),this.name="CandidDecodeError",Object.setPrototypeOf(this,e.prototype)}},ee;(function(e){e[e.Null=-1]="Null",e[e.Bool=-2]="Bool",e[e.Nat=-3]="Nat",e[e.Int=-4]="Int",e[e.Float32=-13]="Float32",e[e.Float64=-14]="Float64",e[e.Text=-15]="Text",e[e.Reserved=-16]="Reserved",e[e.Empty=-17]="Empty",e[e.Opt=-18]="Opt",e[e.Vector=-19]="Vector",e[e.Record=-20]="Record",e[e.Variant=-21]="Variant",e[e.Func=-22]="Func",e[e.Service=-23]="Service",e[e.Principal=-24]="Principal"})(ee||(ee={}));var bs="DIDL",Rh=new TextEncoder().encode(bs),fu=400;function ei(e,t,r){return e.map((n,o)=>r(n,t[o]))}var ec=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(t){return this._idx.has(t.name)}add(t,r){let n=this._typs.length;this._idx.set(t.name,n),this._idxRefCount.set(n,1),this._typs.push(r)}merge(t,r){let n=this._idx.get(t.name),o=this._idx.get(r);if(n===void 0)throw new Error(`Missing type index for ${t}`);if(o===void 0)throw new Error(`Missing type index for ${r}`);this._typs[n]=this._typs[o];let i=this._getIdxRefCount(n),s=this._getIdxRefCount(o);this._idxRefCount.set(n,i+s),this._idx.set(r,n),this._idxRefCount.set(o,0),this._compactFromEnd()}_getIdxRefCount(t){return this._idxRefCount.get(t)||0}_compactFromEnd(){for(;this._typs.length>0;){let t=this._typs.length-1;if(this._getIdxRefCount(t)>0)break;this._typs.pop(),this._idxRefCount.delete(t)}}encode(){let t=oe(this._typs.length),r=X(...this._typs);return X(t,r)}indexOf(t){if(!this._idx.has(t))throw new Error(`Missing type index for ${t}`);return ye(this._idx.get(t)||0)}},tc=class{visitType(t,r){throw new Error("Not implemented")}visitPrimitive(t,r){return this.visitType(t,r)}visitEmpty(t,r){return this.visitPrimitive(t,r)}visitBool(t,r){return this.visitPrimitive(t,r)}visitNull(t,r){return this.visitPrimitive(t,r)}visitReserved(t,r){return this.visitPrimitive(t,r)}visitText(t,r){return this.visitPrimitive(t,r)}visitNumber(t,r){return this.visitPrimitive(t,r)}visitInt(t,r){return this.visitNumber(t,r)}visitNat(t,r){return this.visitNumber(t,r)}visitFloat(t,r){return this.visitPrimitive(t,r)}visitFixedInt(t,r){return this.visitNumber(t,r)}visitFixedNat(t,r){return this.visitNumber(t,r)}visitPrincipal(t,r){return this.visitPrimitive(t,r)}visitConstruct(t,r){return this.visitType(t,r)}visitVec(t,r,n){return this.visitConstruct(t,n)}visitOpt(t,r,n){return this.visitConstruct(t,n)}visitRecord(t,r,n){return this.visitConstruct(t,n)}visitTuple(t,r,n){let o=r.map((i,s)=>[`_${s}_`,i]);return this.visitRecord(t,o,n)}visitVariant(t,r,n){return this.visitConstruct(t,n)}visitRec(t,r,n){return this.visitConstruct(r,n)}visitFunc(t,r){return this.visitConstruct(t,r)}visitService(t,r){return this.visitConstruct(t,r)}},H;(function(e){e.EmptyClass="__IDL_EmptyClass__",e.UnknownClass="__IDL_UnknownClass__",e.BoolClass="__IDL_BoolClass__",e.NullClass="__IDL_NullClass__",e.ReservedClass="__IDL_ReservedClass__",e.TextClass="__IDL_TextClass__",e.IntClass="__IDL_IntClass__",e.NatClass="__IDL_NatClass__",e.FloatClass="__IDL_FloatClass__",e.FixedIntClass="__IDL_FixedIntClass__",e.FixedNatClass="__IDL_FixedNatClass__",e.VecClass="__IDL_VecClass__",e.OptClass="__IDL_OptClass__",e.RecordClass="__IDL_RecordClass__",e.TupleClass="__IDL_TupleClass__",e.VariantClass="__IDL_VariantClass__",e.RecClass="__IDL_RecClass__",e.PrincipalClass="__IDL_PrincipalClass__",e.FuncClass="__IDL_FuncClass__",e.ServiceClass="__IDL_ServiceClass__"})(H||(H={}));var fo=class{display(){return this.name}valueToString(t){return he(t)}buildTypeTable(t){t.has(this)||this._buildTypeTableImpl(t)}},Xe=class extends fo{checkType(t){if(this.name!==t.name)throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);return t}_buildTypeTableImpl(t){}},Jt=class extends fo{checkType(t){if(t instanceof ht){let r=t.getType();if(typeof r>"u")throw new Ze("Type mismatch: cannot decode from uninitialized recursive type");return r}throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`)}encodeType(t){return t.indexOf(this.name)}},ti=class extends Xe{get typeName(){return H.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===H.EmptyClass}accept(t,r){return t.visitEmpty(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return ye(ee.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},Ts=class extends fo{get typeName(){return H.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===H.UnknownClass}checkType(t){throw new Error("Method not implemented for unknown.")}accept(t,r){throw t.visitType(this,r)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(){throw new Error("Unknown cannot appear as a function argument")}valueToString(){throw new Error("Unknown cannot appear as a value")}encodeType(){throw new Error("Unknown cannot be serialized")}decodeValue(t,r){let n=r.decodeValue(t,r);Object(n)!==n&&(n=Object(n));let o;return r instanceof ht?o=()=>r.getType():o=()=>r,Object.defineProperty(n,"type",{value:o,writable:!0,enumerable:!1,configurable:!0}),n}_buildTypeTableImpl(){throw new Error("Unknown cannot be serialized")}get name(){return"Unknown"}},Ns=class extends Xe{get typeName(){return H.BoolClass}static[Symbol.hasInstance](t){return t.typeName===H.BoolClass}accept(t,r){return t.visitBool(this,r)}covariant(t){if(typeof t=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return new Uint8Array([t?1:0])}encodeType(){return ye(ee.Bool)}decodeValue(t,r){switch(this.checkType(r),Yr(t)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},Kn=class extends Xe{get typeName(){return H.NullClass}static[Symbol.hasInstance](t){return t.typeName===H.NullClass}accept(t,r){return t.visitNull(this,r)}covariant(t){if(t===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return ye(ee.Null)}decodeValue(t,r){return this.checkType(r),null}get name(){return"null"}},Wt=class extends Xe{get typeName(){return H.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===H.ReservedClass}accept(t,r){return t.visitReserved(this,r)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return ye(ee.Reserved)}decodeValue(t,r){return r.name!==this.name&&r.decodeValue(t,r),null}get name(){return"reserved"}},Os=class extends Xe{get typeName(){return H.TextClass}static[Symbol.hasInstance](t){return t.typeName===H.TextClass}accept(t,r){return t.visitText(this,r)}covariant(t){if(typeof t=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=new TextEncoder().encode(t),n=oe(r.byteLength);return X(n,r)}encodeType(){return ye(ee.Text)}decodeValue(t,r){this.checkType(r);let n=_e(t),o=Zr(t,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(o)}get name(){return"text"}valueToString(t){return`"${t}"`}},ri=class extends Xe{get typeName(){return H.IntClass}static[Symbol.hasInstance](t){return t.typeName===H.IntClass}accept(t,r){return t.visitInt(this,r)}covariant(t){if(typeof t=="bigint"||Number.isInteger(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return ye(t)}encodeType(){return ye(ee.Int)}decodeValue(t,r){return this.checkType(r),Nr(t)}get name(){return"int"}valueToString(t){return t.toString()}},ni=class extends Xe{get typeName(){return H.NatClass}static[Symbol.hasInstance](t){return t.typeName===H.NatClass}accept(t,r){return t.visitNat(this,r)}covariant(t){if(typeof t=="bigint"&&t>=BigInt(0)||Number.isInteger(t)&&t>=0)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return oe(t)}encodeType(){return ye(ee.Nat)}decodeValue(t,r){return this.checkType(r),_e(t)}get name(){return"nat"}valueToString(t){return t.toString()}},oi=class extends Xe{get typeName(){return H.FloatClass}static[Symbol.hasInstance](t){return t.typeName===H.FloatClass}constructor(t){if(super(),this._bits=t,t!==32&&t!==64)throw new Error("not a valid float type")}accept(t,r){return t.visitFloat(this,r)}covariant(t){if(typeof t=="number"||t instanceof Number)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=new ArrayBuffer(this._bits/8),n=new DataView(r);return this._bits===32?n.setFloat32(0,t,!0):n.setFloat64(0,t,!0),new Uint8Array(r)}encodeType(){let t=this._bits===32?ee.Float32:ee.Float64;return ye(t)}decodeValue(t,r){this.checkType(r);let n=Zr(t,this._bits/8),o=lu(n);return this._bits===32?o.getFloat32(0,!0):o.getFloat64(0,!0)}get name(){return`float${this._bits}`}valueToString(t){return t.toString()}},Er=class extends Xe{get typeName(){return H.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===H.FixedIntClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedInt(this,r)}covariant(t){let r=xs(this._bits-1)*BigInt(-1),n=xs(this._bits-1)-BigInt(1);if(typeof t=="bigint"){if(t>=r&&t<=n)return!0}else if(Number.isInteger(t)){let o=BigInt(t);if(o>=r&&o<=n)return!0}throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return Za(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return ye(-9-t)}decodeValue(t,r){this.checkType(r);let n=pu(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}},Gt=class extends Xe{get typeName(){return H.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===H.FixedNatClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedNat(this,r)}covariant(t){let r=xs(this._bits);if(typeof t=="bigint"&&t>=BigInt(0)){if(t<r)return!0}else if(Number.isInteger(t)&&t>=0&&BigInt(t)<r)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return du(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return ye(-5-t)}decodeValue(t,r){this.checkType(r);let n=Xa(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(t){return t.toString()}},ho=class e extends Jt{get typeName(){return H.VecClass}static[Symbol.hasInstance](t){return t.typeName===H.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof Gt&&t._bits===8&&(this._blobOptimization=!0)}accept(t,r){return t.visitVec(this,this._type,r)}covariant(t){let r=this._type instanceof Gt?this._type._bits:this._type instanceof Er?this._type._bits:0;if(ArrayBuffer.isView(t)&&r==t.BYTES_PER_ELEMENT*8||Array.isArray(t)&&t.every((n,o)=>{try{return this._type.covariant(n)}catch(i){throw new Error(`Invalid ${this.display()} argument:
37
39
 
38
- index ${o} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=ie(t.length);if(this._blobOptimization)return Z(r,new Uint8Array(t));if(ArrayBuffer.isView(t))if(t instanceof Int16Array||t instanceof Uint16Array){let o=new DataView(new ArrayBuffer(t.length*2));for(let i=0;i<t.length;i++)t instanceof Int16Array?o.setInt16(i*2,t[i],!0):o.setUint16(i*2,t[i],!0);return Z(r,new Uint8Array(o.buffer))}else if(t instanceof Int32Array||t instanceof Uint32Array){let o=new DataView(new ArrayBuffer(t.length*4));for(let i=0;i<t.length;i++)t instanceof Int32Array?o.setInt32(i*4,t[i],!0):o.setUint32(i*4,t[i],!0);return Z(r,new Uint8Array(o.buffer))}else if(t instanceof BigInt64Array||t instanceof BigUint64Array){let o=new DataView(new ArrayBuffer(t.length*8));for(let i=0;i<t.length;i++)t instanceof BigInt64Array?o.setBigInt64(i*8,t[i],!0):o.setBigUint64(i*8,t[i],!0);return Z(r,new Uint8Array(o.buffer))}else return Z(r,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));let n=new St(new Uint8Array(r.byteLength+t.length),0);n.write(r);for(let o of t){let i=this._type.encodeValue(o);n.write(new Uint8Array(i))}return n.buffer}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=ye(Q.Vector),n=this._type.encodeType(t);t.add(this,Z(r,n))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a vector type");let o=Number(_e(t));if(this._type instanceof Kt){if(this._type._bits==8)return new Uint8Array(t.read(o));if(this._type._bits==16){let s=t.read(o*2);return new Uint16Array(s.buffer,s.byteOffset,o)}if(this._type._bits==32){let s=t.read(o*4);return new Uint32Array(s.buffer,s.byteOffset,o)}if(this._type._bits==64)return new BigUint64Array(t.read(o*8).buffer)}if(this._type instanceof yr){if(this._type._bits==8)return new Int8Array(t.read(o));if(this._type._bits==16){let s=t.read(o*2),a=new DataView(s.buffer,s.byteOffset,s.byteLength),c=new Int16Array(o);for(let u=0;u<o;u++)c[u]=a.getInt16(u*2,!0);return c}if(this._type._bits==32){let s=t.read(o*4),a=new DataView(s.buffer,s.byteOffset,s.byteLength),c=new Int32Array(o);for(let u=0;u<o;u++)c[u]=a.getInt32(u*4,!0);return c}if(this._type._bits==64){let s=t.read(o*8),a=new DataView(s.buffer,s.byteOffset,s.byteLength),c=new BigInt64Array(o);for(let u=0;u<o;u++)c[u]=a.getBigInt64(u*8,!0);return c}}let i=[];for(let s=0;s<o;s++)i.push(this._type.decodeValue(t,n._type));return i}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(t){return"vec {"+t.map(n=>this._type.valueToString(n)).join("; ")+"}"}},Kr=class e extends Ht{get typeName(){return H.OptClass}static[Symbol.hasInstance](t){return t.typeName===H.OptClass}constructor(t){super(),this._type=t}accept(t,r){return t.visitOpt(this,this._type,r)}covariant(t){try{if(Array.isArray(t)&&(t.length===0||t.length===1&&this._type.covariant(t[0])))return!0}catch(r){throw new Error(`Invalid ${this.display()} argument: ${he(t)}
40
+ index ${o} -> ${i.message}`,{cause:i})}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=oe(t.length);if(this._blobOptimization)return X(r,new Uint8Array(t));if(ArrayBuffer.isView(t)){if(t instanceof Int16Array||t instanceof Uint16Array){let o=new DataView(new ArrayBuffer(t.length*2));for(let i=0;i<t.length;i++)t instanceof Int16Array?o.setInt16(i*2,t[i],!0):o.setUint16(i*2,t[i],!0);return X(r,new Uint8Array(o.buffer))}if(t instanceof Int32Array||t instanceof Uint32Array){let o=new DataView(new ArrayBuffer(t.length*4));for(let i=0;i<t.length;i++)t instanceof Int32Array?o.setInt32(i*4,t[i],!0):o.setUint32(i*4,t[i],!0);return X(r,new Uint8Array(o.buffer))}if(t instanceof BigInt64Array||t instanceof BigUint64Array){let o=new DataView(new ArrayBuffer(t.length*8));for(let i=0;i<t.length;i++)t instanceof BigInt64Array?o.setBigInt64(i*8,t[i],!0):o.setBigUint64(i*8,t[i],!0);return X(r,new Uint8Array(o.buffer))}return X(r,new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}let n=new Vt(new Uint8Array(r.byteLength+t.length),0);n.write(r);for(let o of t){let i=this._type.encodeValue(o);n.write(new Uint8Array(i))}return n.buffer}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=ye(ee.Vector),n=this._type.encodeType(t);t.add(this,X(r,n))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Ze(`Expected type '${this.display()}', but received non-vector type '${n.display()}'`);let o=Number(_e(t));if(this._type instanceof Gt){if(this._type._bits==8)return new Uint8Array(t.read(o));if(this._type._bits==16){let s=t.read(o*2);return new Uint16Array(s.buffer,s.byteOffset,o)}if(this._type._bits==32){let s=t.read(o*4);return new Uint32Array(s.buffer,s.byteOffset,o)}if(this._type._bits==64)return new BigUint64Array(t.read(o*8).buffer)}if(this._type instanceof Er){if(this._type._bits==8)return new Int8Array(t.read(o));if(this._type._bits==16){let s=t.read(o*2),a=new DataView(s.buffer,s.byteOffset,s.byteLength),c=new Int16Array(o);for(let l=0;l<o;l++)c[l]=a.getInt16(l*2,!0);return c}if(this._type._bits==32){let s=t.read(o*4),a=new DataView(s.buffer,s.byteOffset,s.byteLength),c=new Int32Array(o);for(let l=0;l<o;l++)c[l]=a.getInt32(l*4,!0);return c}if(this._type._bits==64){let s=t.read(o*8),a=new DataView(s.buffer,s.byteOffset,s.byteLength),c=new BigInt64Array(o);for(let l=0;l<o;l++)c[l]=a.getBigInt64(l*8,!0);return c}}let i=[];for(let s=0;s<o;s++)i.push(this._type.decodeValue(t,n._type));return i}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(t){return`vec {${t.map(n=>this._type.valueToString(n)).join("; ")}}`}},Xr=class e extends Jt{get typeName(){return H.OptClass}static[Symbol.hasInstance](t){return t.typeName===H.OptClass}constructor(t){super(),this._type=t}accept(t,r){return t.visitOpt(this,this._type,r)}covariant(t){try{if(Array.isArray(t)&&(t.length===0||t.length===1&&this._type.covariant(t[0])))return!0}catch(r){throw new Error(`Invalid ${this.display()} argument: ${he(t)}
39
41
 
40
- -> ${r.message}`)}throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return t.length===0?new Uint8Array([0]):Z(new Uint8Array([1]),this._type.encodeValue(t[0]))}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=ye(Q.Opt),n=this._type.encodeType(t);t.add(this,Z(r,n))}decodeValue(t,r){if(r instanceof Un)return[];if(r instanceof Gt)return[];let n=r;if(r instanceof dt){let o=r.getType();if(typeof o>"u")throw new Error("type mismatch with uninitialized type");n=o}if(n instanceof e)switch(Mr(t)){case 0:return[];case 1:{let o=t.save();try{return[this._type.decodeValue(t,n._type)]}catch{return t.restore(o),n._type.decodeValue(t,n._type),[]}}default:throw new Error("Not an option value")}else{if(this._type instanceof Un||this._type instanceof e||this._type instanceof Gt)return n.decodeValue(t,n),[];{let o=t.save();try{return[this._type.decodeValue(t,r)]}catch{return t.restore(o),n.decodeValue(t,r),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(t){return t.length===0?"null":`opt ${this._type.valueToString(t[0])}`}},kn=class e extends Ht{get typeName(){return H.RecordClass}static[Symbol.hasInstance](t){return t.typeName===H.RecordClass||t.typeName===H.TupleClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>je(r[0])-je(n[0]))}accept(t,r){return t.visitRecord(this,this._fields,r)}tryAsTuple(){let t=[];for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(n!==`_${r}_`)return null;t.push(o)}return t}covariant(t){if(typeof t=="object"&&this._fields.every(([r,n])=>{if(!t.hasOwnProperty(r))throw new Error(`Record is missing key "${r}".`);try{return n.covariant(t[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
42
+ -> ${r.message}`,{cause:r})}throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return t.length===0?new Uint8Array([0]):X(new Uint8Array([1]),this._type.encodeValue(t[0]))}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=ye(ee.Opt),n=this._type.encodeType(t);t.add(this,X(r,n))}decodeValue(t,r){if(r instanceof Kn)return[];if(r instanceof Wt)return[];let n=r;if(r instanceof ht){let o=r.getType();if(typeof o>"u")throw new Ze("Type mismatch: cannot decode from uninitialized recursive type");n=o}if(n instanceof e)switch(Yr(t)){case 0:return[];case 1:{let o=t.save();try{return[this._type.decodeValue(t,n._type)]}catch{return t.restore(o),n._type.decodeValue(t,n._type),[]}}default:throw new Ze(`Invalid option value: expected 0 (None) or 1 (Some) for type '${this.display()}'`)}else{if(this._type instanceof Kn||this._type instanceof e||this._type instanceof Wt)return n.decodeValue(t,n),[];{let o=t.save();try{return[this._type.decodeValue(t,r)]}catch{return t.restore(o),n.decodeValue(t,r),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(t){return t.length===0?"null":`opt ${this._type.valueToString(t[0])}`}},$n=class e extends Jt{get typeName(){return H.RecordClass}static[Symbol.hasInstance](t){return t.typeName===H.RecordClass||t.typeName===H.TupleClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>Me(r[0])-Me(n[0]))}accept(t,r){return t.visitRecord(this,this._fields,r)}tryAsTuple(){let t=[];for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(n!==`_${r}_`)return null;t.push(o)}return t}covariant(t){if(typeof t=="object"&&this._fields.every(([r,n])=>{if(!t.hasOwnProperty(r))throw new Error(`Record is missing key "${r}".`);try{return n.covariant(t[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
41
43
 
42
- field ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=this._fields.map(([o])=>t[o]),n=$o(this._fields,r,([,o],i)=>o.encodeValue(i));return Z(...n)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=ye(Q.Record),n=ie(this._fields.length),o=this._fields.map(([i,s])=>Z(ie(je(i)),s.encodeType(t)));t.add(this,Z(r,n,Z(...o)))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a record type");let o={},i=0,s=0;for(;s<n._fields.length;){let[a,c]=n._fields[s];if(i>=this._fields.length){c.decodeValue(t,c),s++;continue}let[u,p]=this._fields[i],d=je(this._fields[i][0]),l=je(a);if(d===l)o[u]=p.decodeValue(t,c),i++,s++;else if(l>d)if(p instanceof Kr||p instanceof Gt)o[u]=[],i++;else throw new Error("Cannot find required field "+u);else c.decodeValue(t,c),s++}for(let[a,c]of this._fields.slice(i))if(c instanceof Kr||c instanceof Gt)o[a]=[];else throw new Error("Cannot find required field "+a);return o}get fieldsAsObject(){let t={};for(let[r,n]of this._fields)t[je(r)]=n;return t}get name(){return`record {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}display(){return`record {${this._fields.map(([r,n])=>r+":"+n.display()).join("; ")}}`}valueToString(t){let r=this._fields.map(([o])=>t[o]);return`record {${$o(this._fields,r,([o,i],s)=>o+"="+i.valueToString(s)).join("; ")}}`}},cs=class e extends kn{get typeName(){return H.TupleClass}static[Symbol.hasInstance](t){return t.typeName===H.TupleClass}constructor(t){let r={};t.forEach((n,o)=>r["_"+o+"_"]=n),super(r),this._components=t}accept(t,r){return t.visitTuple(this,this._components,r)}covariant(t){if(Array.isArray(t)&&t.length>=this._fields.length&&this._components.every((r,n)=>{try{return r.covariant(t[n])}catch(o){throw new Error(`Invalid ${this.display()} argument:
44
+ field ${r} -> ${o.message}`,{cause:o})}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=this._fields.map(([o])=>t[o]),n=ei(this._fields,r,([,o],i)=>o.encodeValue(i));return X(...n)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=ye(ee.Record),n=oe(this._fields.length),o=this._fields.map(([i,s])=>X(oe(Me(i)),s.encodeType(t)));t.add(this,X(r,n,X(...o)))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Ze(`Expected type '${this.display()}', but received non-record type '${n.display()}'`);let o={},i=0,s=0;for(;s<n._fields.length;){let[a,c]=n._fields[s];if(i>=this._fields.length){c.decodeValue(t,c),s++;continue}let[l,d]=this._fields[i],p=Me(this._fields[i][0]),u=Me(a);if(p===u)o[l]=d.decodeValue(t,c),i++,s++;else if(u>p)if(d instanceof Xr||d instanceof Wt)o[l]=[],i++;else{let f=this._fields.map(([_])=>_).join(", "),h=n._fields.map(([_])=>_).join(", ");throw new Ze(`Cannot find required field '${l}' in record, expected fields: [${f}], received fields: [${h}]`)}else c.decodeValue(t,c),s++}for(let[a,c]of this._fields.slice(i))if(c instanceof Xr||c instanceof Wt)o[a]=[];else{let l=this._fields.map(([p])=>p).join(", "),d=n._fields.map(([p])=>p).join(", ");throw new Ze(`Cannot find required field '${a}' in record, expected fields: [${l}], received fields: [${d}]`)}return o}get fieldsAsObject(){let t={};for(let[r,n]of this._fields)t[Me(r)]=n;return t}get name(){return`record {${this._fields.map(([r,n])=>`${r}:${n.name}`).join("; ")}}`}display(){return`record {${this._fields.map(([r,n])=>`${r}:${n.display()}`).join("; ")}}`}valueToString(t){let r=this._fields.map(([o])=>t[o]);return`record {${ei(this._fields,r,([o,i],s)=>`${o}=${i.valueToString(s)}`).join("; ")}}`}},Es=class e extends $n{get typeName(){return H.TupleClass}static[Symbol.hasInstance](t){return t.typeName===H.TupleClass}constructor(t){let r={};t.forEach((n,o)=>r[`_${o}_`]=n),super(r),this._components=t}accept(t,r){return t.visitTuple(this,this._components,r)}covariant(t){if(Array.isArray(t)&&t.length>=this._fields.length&&this._components.every((r,n)=>{try{return r.covariant(t[n])}catch(o){throw new Error(`Invalid ${this.display()} argument:
43
45
 
44
- index ${n} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=$o(this._components,t,(n,o)=>n.encodeValue(o));return Z(...r)}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("not a tuple type");if(n._components.length<this._components.length)throw new Error("tuple mismatch");let o=[];for(let[i,s]of n._components.entries())i>=this._components.length?s.decodeValue(t,s):o.push(this._components[i].decodeValue(t,s));return o}display(){return`record {${this._components.map(r=>r.display()).join("; ")}}`}valueToString(t){return`record {${$o(this._components,t,(n,o)=>n.valueToString(o)).join("; ")}}`}},ao=class e extends Ht{get typeName(){return H.VariantClass}static[Symbol.hasInstance](t){return t.typeName===H.VariantClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>je(r[0])-je(n[0]))}accept(t,r){return t.visitVariant(this,this._fields,r)}covariant(t){if(typeof t=="object"&&Object.entries(t).length===1&&this._fields.every(([r,n])=>{try{return!t.hasOwnProperty(r)||n.covariant(t[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
46
+ index ${n} -> ${o.message}`,{cause:o})}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=ei(this._components,t,(n,o)=>n.encodeValue(o));return X(...r)}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Ze(`Expected type '${this.display()}', but received non-tuple type '${n.display()}'`);if(n._components.length<this._components.length)throw new Ze(`Tuple mismatch: expected ${this._components.length} components, but received ${n._components.length}`);let o=[];for(let[i,s]of n._components.entries())i>=this._components.length?s.decodeValue(t,s):o.push(this._components[i].decodeValue(t,s));return o}display(){return`record {${this._components.map(r=>r.display()).join("; ")}}`}valueToString(t){return`record {${ei(this._components,t,(n,o)=>n.valueToString(o)).join("; ")}}`}},mo=class e extends Jt{get typeName(){return H.VariantClass}static[Symbol.hasInstance](t){return t.typeName===H.VariantClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>Me(r[0])-Me(n[0]))}accept(t,r){return t.visitVariant(this,this._fields,r)}covariant(t){if(typeof t=="object"&&Object.entries(t).length===1&&this._fields.every(([r,n])=>{try{return!t.hasOwnProperty(r)||n.covariant(t[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
45
47
 
46
- variant ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(t.hasOwnProperty(n)){let i=ie(r),s=o.encodeValue(t[n]);return Z(i,s)}}throw Error("Variant has no data: "+t)}_buildTypeTableImpl(t){this._fields.forEach(([,i])=>{i.buildTypeTable(t)});let r=ye(Q.Variant),n=ie(this._fields.length),o=this._fields.map(([i,s])=>Z(ie(je(i)),s.encodeType(t)));t.add(this,Z(r,n,...o))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a variant type");let o=Number(_e(t));if(o>=n._fields.length)throw Error("Invalid variant index: "+o);let[i,s]=n._fields[o];for(let[a,c]of this._fields)if(je(i)===je(a)){let u=c.decodeValue(t,s);return{[a]:u}}throw new Error("Cannot find field hash "+i)}get name(){return`variant {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}display(){return`variant {${this._fields.map(([r,n])=>r+(n.name==="null"?"":`:${n.display()}`)).join("; ")}}`}valueToString(t){for(let[r,n]of this._fields)if(t.hasOwnProperty(r)){let o=n.valueToString(t[r]);return o==="null"?`variant {${r}}`:`variant {${r}=${o}}`}throw new Error("Variant has no data: "+t)}get alternativesAsObject(){let t={};for(let[r,n]of this._fields)t[je(r)]=n;return t}},dt=class e extends Ht{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return H.RecClass}static{this._counter=0}static[Symbol.hasInstance](t){return t.typeName===H.RecClass}accept(t,r){if(!this._type)throw Error("Recursive type uninitialized.");return t.visitRec(this,this._type,r)}fill(t){this._type=t}getType(){return this._type}covariant(t){if(this._type&&this._type.covariant(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(t)}_buildTypeTableImpl(t){if(!this._type)throw Error("Recursive type uninitialized.");t.add(this,new Uint8Array([])),this._type.buildTypeTable(t),t.merge(this,this._type.name)}decodeValue(t,r){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(t,r)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`\u03BC${this.name}.${this._type.name}`}valueToString(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(t)}};function Ia(e){if(Mr(e)!==1)throw new Error("Cannot decode principal");let r=Number(_e(e));return k.fromUint8Array(new Uint8Array(jr(e,r)))}var ls=class extends Xe{get typeName(){return H.PrincipalClass}static[Symbol.hasInstance](t){return t.typeName===H.PrincipalClass}accept(t,r){return t.visitPrincipal(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=ie(r.byteLength);return Z(new Uint8Array([1]),n,r)}encodeType(){return ye(Q.Principal)}decodeValue(t,r){return this.checkType(r),Ia(t)}get name(){return"principal"}valueToString(t){return`${this.name} "${t.toText()}"`}},Ln=class extends Ht{get typeName(){return H.FuncClass}static[Symbol.hasInstance](t){return t.typeName===H.FuncClass}static argsToString(t,r){if(t.length!==r.length)throw new Error("arity mismatch");return"("+t.map((n,o)=>n.valueToString(r[o])).join(", ")+")"}constructor(t,r,n=[]){super(),this.argTypes=t,this.retTypes=r,this.annotations=n}accept(t,r){return t.visitFunc(this,r)}covariant(t){if(Array.isArray(t)&&t.length===2&&t[0]&&t[0]._isPrincipal&&typeof t[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue([t,r]){let n=t.toUint8Array(),o=ie(n.byteLength),i=Z(new Uint8Array([1]),o,n),s=new TextEncoder().encode(r),a=ie(s.byteLength);return Z(new Uint8Array([1]),i,a,s)}_buildTypeTableImpl(t){this.argTypes.forEach(u=>u.buildTypeTable(t)),this.retTypes.forEach(u=>u.buildTypeTable(t));let r=ye(Q.Func),n=ie(this.argTypes.length),o=Z(...this.argTypes.map(u=>u.encodeType(t))),i=ie(this.retTypes.length),s=Z(...this.retTypes.map(u=>u.encodeType(t))),a=ie(this.annotations.length),c=Z(...this.annotations.map(u=>this.encodeAnnotation(u)));t.add(this,Z(r,n,o,i,s,a,c))}decodeValue(t,r){let n=r instanceof dt?r.getType()??r:r;if(!Aa(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(Mr(t)!==1)throw new Error("Cannot decode function reference");let i=Ia(t),s=Number(_e(t)),a=jr(t,s),u=new TextDecoder("utf8",{fatal:!0}).decode(a);return[i,u]}get name(){let t=this.argTypes.map(o=>o.name).join(", "),r=this.retTypes.map(o=>o.name).join(", "),n=" "+this.annotations.join(" ");return`(${t}) -> (${r})${n}`}valueToString([t,r]){return`func "${t.toText()}".${r}`}display(){let t=this.argTypes.map(o=>o.display()).join(", "),r=this.retTypes.map(o=>o.display()).join(", "),n=" "+this.annotations.join(" ");return`(${t}) \u2192 (${r})${n}`}encodeAnnotation(t){if(t==="query")return new Uint8Array([1]);if(t==="oneway")return new Uint8Array([2]);if(t==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}},co=class extends Ht{get typeName(){return H.ServiceClass}static[Symbol.hasInstance](t){return t.typeName===H.ServiceClass}constructor(t){super(),this._fields=Object.entries(t).sort((r,n)=>r[0]<n[0]?-1:r[0]>n[0]?1:0)}accept(t,r){return t.visitService(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=ie(r.length);return Z(new Uint8Array([1]),n,r)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=ye(Q.Service),n=ie(this._fields.length),o=this._fields.map(([i,s])=>{let a=new TextEncoder().encode(i),c=ie(a.length);return Z(c,a,s.encodeType(t))});t.add(this,Z(r,n,...o))}decodeValue(t,r){let n=r instanceof dt?r.getType()??r:r;if(!Aa(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return Ia(t)}get name(){return`service {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}valueToString(t){return`service "${t.toText()}"`}fieldsAsObject(){let t={};for(let[r,n]of this._fields)t[r]=n;return t}};function he(e){let t=JSON.stringify(e,(r,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return t&&t.length>Pl?t.substring(0,Pl-3)+"...":t}function If(e,t){if(t.length<e.length)throw Error("Wrong number of message arguments");let r=new Ea;e.forEach(a=>a.buildTypeTable(r));let n=r.encode(),o=ie(t.length),i=Z(...e.map(a=>a.encodeType(r))),s=Z(...$o(e,t,(a,c)=>{try{a.covariant(c)}catch(u){throw new Error(u.message+`
48
+ variant ${r} -> ${o.message}`,{cause:o})}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(t.hasOwnProperty(n)){let i=oe(r),s=o.encodeValue(t[n]);return X(i,s)}}throw Error(`Variant has no data: ${t}`)}_buildTypeTableImpl(t){this._fields.forEach(([,i])=>{i.buildTypeTable(t)});let r=ye(ee.Variant),n=oe(this._fields.length),o=this._fields.map(([i,s])=>X(oe(Me(i)),s.encodeType(t)));t.add(this,X(r,n,...o))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Ze(`Expected type '${this.display()}', but received non-variant type '${n.display()}'`);let o=Number(_e(t));if(o>=n._fields.length)throw Error(`Invalid variant index: ${o}`);let[i,s]=n._fields[o];for(let[c,l]of this._fields)if(Me(i)===Me(c)){let d=l.decodeValue(t,s);return{[c]:d}}let a=this._fields.map(([c])=>c).join(", ");throw new Ze(`Cannot find field hash ${i} in variant, expected fields: [${a}]`)}get name(){return`variant {${this._fields.map(([r,n])=>`${r}:${n.name}`).join("; ")}}`}display(){return`variant {${this._fields.map(([r,n])=>r+(n.name==="null"?"":`:${n.display()}`)).join("; ")}}`}valueToString(t){for(let[r,n]of this._fields)if(t.hasOwnProperty(r)){let o=n.valueToString(t[r]);return o==="null"?`variant {${r}}`:`variant {${r}=${o}}`}throw new Error(`Variant has no data: ${t}`)}get alternativesAsObject(){let t={};for(let[r,n]of this._fields)t[Me(r)]=n;return t}},ht=class e extends Jt{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return H.RecClass}static{this._counter=0}static[Symbol.hasInstance](t){return t.typeName===H.RecClass}accept(t,r){if(!this._type)throw Error("Recursive type uninitialized.");return t.visitRec(this,this._type,r)}fill(t){this._type=t}getType(){return this._type}covariant(t){if(this._type&&this._type.covariant(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(t)}_buildTypeTableImpl(t){if(!this._type)throw Error("Recursive type uninitialized.");t.add(this,new Uint8Array([])),this._type.buildTypeTable(t),t.merge(this,this._type.name)}decodeValue(t,r){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(t,r)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`\u03BC${this.name}.${this._type.name}`}valueToString(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(t)}};function nc(e){if(Yr(e)!==1)throw new Error("Cannot decode principal");let r=Number(_e(e));return q.fromUint8Array(new Uint8Array(Zr(e,r)))}var Rs=class extends Xe{get typeName(){return H.PrincipalClass}static[Symbol.hasInstance](t){return t.typeName===H.PrincipalClass}accept(t,r){return t.visitPrincipal(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=oe(r.byteLength);return X(new Uint8Array([1]),n,r)}encodeType(){return ye(ee.Principal)}decodeValue(t,r){return this.checkType(r),nc(t)}get name(){return"principal"}valueToString(t){return`${this.name} "${t.toText()}"`}},Hn=class extends Jt{get typeName(){return H.FuncClass}static[Symbol.hasInstance](t){return t.typeName===H.FuncClass}static argsToString(t,r){if(t.length!==r.length)throw new Error("arity mismatch");return`(${t.map((n,o)=>n.valueToString(r[o])).join(", ")})`}constructor(t,r,n=[]){super(),this.argTypes=t,this.retTypes=r,this.annotations=n}accept(t,r){return t.visitFunc(this,r)}covariant(t){if(Array.isArray(t)&&t.length===2&&t[0]&&t[0]._isPrincipal&&typeof t[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue([t,r]){let n=t.toUint8Array(),o=oe(n.byteLength),i=X(new Uint8Array([1]),o,n),s=new TextEncoder().encode(r),a=oe(s.byteLength);return X(new Uint8Array([1]),i,a,s)}_buildTypeTableImpl(t){this.argTypes.forEach(l=>l.buildTypeTable(t)),this.retTypes.forEach(l=>l.buildTypeTable(t));let r=ye(ee.Func),n=oe(this.argTypes.length),o=X(...this.argTypes.map(l=>l.encodeType(t))),i=oe(this.retTypes.length),s=X(...this.retTypes.map(l=>l.encodeType(t))),a=oe(this.annotations.length),c=X(...this.annotations.map(l=>this.encodeAnnotation(l)));t.add(this,X(r,n,o,i,s,a,c))}decodeValue(t,r){let n=r instanceof ht?r.getType()??r:r;if(!oc(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(Yr(t)!==1)throw new Error("Cannot decode function reference");let i=nc(t),s=Number(_e(t)),a=Zr(t,s),l=new TextDecoder("utf8",{fatal:!0}).decode(a);return[i,l]}get name(){let t=this.argTypes.map(o=>o.name).join(", "),r=this.retTypes.map(o=>o.name).join(", "),n=` ${this.annotations.join(" ")}`;return`(${t}) -> (${r})${n}`}valueToString([t,r]){return`func "${t.toText()}".${r}`}display(){let t=this.argTypes.map(o=>o.display()).join(", "),r=this.retTypes.map(o=>o.display()).join(", "),n=` ${this.annotations.join(" ")}`;return`(${t}) \u2192 (${r})${n}`}encodeAnnotation(t){if(t==="query")return new Uint8Array([1]);if(t==="oneway")return new Uint8Array([2]);if(t==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}},_o=class extends Jt{get typeName(){return H.ServiceClass}static[Symbol.hasInstance](t){return t.typeName===H.ServiceClass}constructor(t){super(),this._fields=Object.entries(t).sort((r,n)=>r[0]<n[0]?-1:r[0]>n[0]?1:0)}accept(t,r){return t.visitService(this,r)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=t.toUint8Array(),n=oe(r.length);return X(new Uint8Array([1]),n,r)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=ye(ee.Service),n=oe(this._fields.length),o=this._fields.map(([i,s])=>{let a=new TextEncoder().encode(i),c=oe(a.length);return X(c,a,s.encodeType(t))});t.add(this,X(r,n,...o))}decodeValue(t,r){let n=r instanceof ht?r.getType()??r:r;if(!oc(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return nc(t)}get name(){return`service {${this._fields.map(([r,n])=>`${r}:${n.name}`).join("; ")}}`}valueToString(t){return`service "${t.toText()}"`}fieldsAsObject(){let t={};for(let[r,n]of this._fields)t[r]=n;return t}};function he(e){let t=JSON.stringify(e,(r,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return t&&t.length>fu?`${t.substring(0,fu-3)}...`:t}function vh(e,t){if(t.length<e.length)throw Error("Wrong number of message arguments");let r=new ec;e.forEach(a=>a.buildTypeTable(r));let n=r.encode(),o=oe(t.length),i=X(...e.map(a=>a.encodeType(r))),s=X(...ei(e,t,(a,c)=>{try{a.covariant(c)}catch(l){throw new Error(`${l.message}
47
49
 
48
- `)}return a.encodeValue(c)}));return Z(vf,n,o,i,s)}function Af(e,t){let r=new St(t);if(t.byteLength<ns.length)throw new Error("Message length smaller than magic number");let n=jr(r,ns.length),o=new TextDecoder().decode(n);if(o!==ns)throw new Error("Wrong magic number: "+JSON.stringify(o));function i(l){let f=[],h=Number(_e(l));for(let m=0;m<h;m++){let b=Number(mr(l));switch(b){case Q.Opt:case Q.Vector:{let y=Number(mr(l));f.push([b,y]);break}case Q.Record:case Q.Variant:{let y=[],T=Number(_e(l)),O;for(;T--;){let R=Number(_e(l));if(R>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof O=="number"&&O>=R)throw new Error("field id collision or not sorted");O=R;let E=Number(mr(l));y.push([R,E])}f.push([b,y]);break}case Q.Func:{let y=[],T=Number(_e(l));for(;T--;)y.push(Number(mr(l)));let O=[],R=Number(_e(l));for(;R--;)O.push(Number(mr(l)));let E=[],I=Number(_e(l));for(;I--;)switch(Number(_e(l))){case 1:{E.push("query");break}case 2:{E.push("oneway");break}case 3:{E.push("composite_query");break}default:throw new Error("unknown annotation")}f.push([b,[y,O,E]]);break}case Q.Service:{let y=Number(_e(l)),T=[];for(;y--;){let O=Number(_e(l)),R=new TextDecoder().decode(jr(l,O)),E=mr(l);T.push([R,E])}f.push([b,T]);break}default:throw new Error("Illegal op_code: "+b)}}let _=[],g=Number(_e(l));for(let m=0;m<g;m++)_.push(Number(mr(l)));return[f,_]}let[s,a]=i(r);if(a.length<e.length)throw new Error("Wrong number of return values");let c=s.map(l=>ou());function u(l){if(l<-24)throw new Error("future value not supported");if(l<0)switch(l){case-1:return kl;case-2:return Ul;case-3:return Ml;case-4:return ql;case-5:return Wl;case-6:return zl;case-7:return Yl;case-8:return Zl;case-9:return Hl;case-10:return Gl;case-11:return $l;case-12:return Jl;case-13:return jl;case-14:return Kl;case-15:return Ll;case-16:return Dl;case-17:return Bl;case-24:return Xl;default:throw new Error("Illegal op_code: "+l)}if(l>=s.length)throw new Error("type index out of range");return c[l]}function p(l){switch(l[0]){case Q.Vector:{let f=u(l[1]);return eu(f)}case Q.Opt:{let f=u(l[1]);return tu(f)}case Q.Record:{let f={};for(let[g,m]of l[1]){let b=`_${g}_`;f[b]=u(m)}let h=ru(f),_=h.tryAsTuple();return Array.isArray(_)?Ql(..._):h}case Q.Variant:{let f={};for(let[h,_]of l[1]){let g=`_${h}_`;f[g]=u(_)}return nu(f)}case Q.Func:{let[f,h,_]=l[1];return iu(f.map(g=>u(g)),h.map(g=>u(g)),_)}case Q.Service:{let f={},h=l[1];for(let[_,g]of h){let m=u(g);if(m instanceof dt&&(m=m.getType()),!(m instanceof Ln))throw new Error("Illegal service definition: services can only contain functions");f[_]=m}return su(f)}default:throw new Error("Illegal op_code: "+l[0])}}s.forEach((l,f)=>{if(l[0]===Q.Func){let h=p(l);c[f].fill(h)}}),s.forEach((l,f)=>{if(l[0]!==Q.Func){let h=p(l);c[f].fill(h)}}),va();let d=a.map(l=>u(l));try{let l=e.map((f,h)=>f.decodeValue(r,d[h]));for(let f=e.length;f<d.length;f++)d[f].decodeValue(r,d[f]);if(r.byteLength>0)throw new Error("decode: Left-over bytes");return l}finally{va()}}var Bl=new Jo,Dl=new Gt,Sf=new is,Ul=new ss,kl=new Un,Ll=new as,ql=new Wo,Ml=new zo,jl=new Yo(32),Kl=new Yo(64),Hl=new yr(8),Gl=new yr(16),$l=new yr(32),Jl=new yr(64),Wl=new Kt(8),zl=new Kt(16),Yl=new Kt(32),Zl=new Kt(64),Xl=new ls;function Ql(...e){return new cs(e)}function eu(e){return new so(e)}function tu(e){return new Kr(e)}function ru(e){return new kn(e)}function nu(e){return new ao(e)}function ou(){return new dt}function iu(e,t,r=[]){return new Ln(e,t,r)}function su(e){return new co(e)}var us=class e{constructor(t=new Map){this.rels=t}copy(){let t=new Map;for(let[r,n]of this.rels.entries()){let o=new Map(n);t.set(r,o)}return new e(t)}known(t,r){return this.rels.get(t.name)?.get(r.name)}addNegative(t,r){this.addNames(t.name,r.name,!1)}add(t,r){this.addNames(t.name,r.name,!0)}display(){let t="";for(let[r,n]of this.rels)for(let[o,i]of n)t+=`${r} ${i?":<":"!<:"} ${o}
49
- `;return t}addNames(t,r,n){let o=this.rels.get(t);if(o==null){let i=new Map;i.set(r,n),this.rels.set(t,i)}else o.set(r,n)}},os=new us;function va(){os=new us}function Cf(e,t){let r=new Set(e.annotations),n=new Set(t.annotations);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o))return!1;return!0}function Oa(e){return e instanceof Kr||e instanceof Un||e instanceof Gt}function Aa(e,t){let r=os.copy(),n=_r(r,e,t);return n?os.add(e,t):os.addNegative(e,t),n}function _r(e,t,r){if(t.name===r.name)return!0;let n=e.known(t,r);if(n!==void 0)return n;if(e.add(t,r),r instanceof Gt||t instanceof Jo||t instanceof zo&&r instanceof Wo)return!0;if(t instanceof so&&r instanceof so)return _r(e,t._type,r._type);if(r instanceof Kr)return!0;if(t instanceof kn&&r instanceof kn){let o=t.fieldsAsObject;for(let[i,s]of r._fields){let a=o[je(i)];if(a){if(!_r(e,a,s))return!1}else if(!Oa(s))return!1}return!0}if(t instanceof Ln&&r instanceof Ln){if(!Cf(t,r))return!1;for(let o=0;o<t.argTypes.length;o++){let i=t.argTypes[o];if(o<r.argTypes.length){if(!_r(e,r.argTypes[o],i))return!1}else if(!Oa(i))return!1}for(let o=0;o<r.retTypes.length;o++){let i=r.retTypes[o];if(o<t.retTypes.length){if(!_r(e,t.retTypes[o],i))return!1}else if(!Oa(i))return!1}return!0}if(t instanceof ao&&r instanceof ao){let o=r.alternativesAsObject;for(let[i,s]of t._fields){let a=o[je(i)];if(!a||!_r(e,s,a))return!1}return!0}if(t instanceof co&&r instanceof co){let o=t.fieldsAsObject();for(let[i,s]of r._fields){let a=o[i];if(!a||!_r(e,a,s))return!1}return!0}return t instanceof dt?_r(e,t.getType(),r):r instanceof dt?_r(e,t,r.getType()):!1}function lo(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?lo(e.buffer):new Uint8Array(e)}function Mn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function Sa(e){if(typeof e=="string")return au(e);if(typeof e=="number")return Ve(ie(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return Ve(lo(e));if(Array.isArray(e)){let t=e.map(Sa);return Ve(K(...t))}else{if(e&&typeof e=="object"&&e._isPrincipal)return Ve(e.toUint8Array());if(typeof e=="object"&&e!==null&&typeof e.toHash=="function")return Sa(e.toHash());if(typeof e=="object")return Zo(e);if(typeof e=="bigint")return Ve(ie(e))}throw Y.fromCode(new zi(e))}var au=e=>{let t=new TextEncoder().encode(e);return Ve(t)};function gr(e){return Zo(e)}function Zo(e){let n=Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>{let c=au(s),u=Sa(a);return[c,u]}).sort(([s],[a])=>oo(s,a)),o=K(...n.map(s=>K(...s)));return Ve(o)}var Ca=new TextEncoder().encode("\ric-state-root"),Xo=new TextEncoder().encode(`
50
- ic-request`),Fa=new TextEncoder().encode("\vic-response"),Va=new TextEncoder().encode("ic-request-auth-delegation");var $t=class{getPrincipal(){return this._principal||(this._principal=k.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(t){let{body:r,...n}=t,o=gr(r);return{...n,body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign(K(Xo,o))}}}},it=class{getPrincipal(){return k.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}};var xr=class extends Error{constructor(t){super(t),this.name="DecodingError"}},lu=55799,uu=Symbol("CBOR_STOP_CODE"),Vt=(e=>(e[e.False=20]="False",e[e.True=21]="True",e[e.Null=22]="Null",e[e.Undefined=23]="Undefined",e[e.Break=31]="Break",e))(Vt||{}),Ne=(e=>(e[e.UnsignedInteger=0]="UnsignedInteger",e[e.NegativeInteger=1]="NegativeInteger",e[e.ByteString=2]="ByteString",e[e.TextString=3]="TextString",e[e.Array=4]="Array",e[e.Map=5]="Map",e[e.Tag=6]="Tag",e[e.Simple=7]="Simple",e))(Ne||{}),Ff=23,Vf=255,Pf=65535,Bf=4294967295,Df=BigInt("0xffffffffffffffff"),Ft=(e=>(e[e.Value=23]="Value",e[e.OneByte=24]="OneByte",e[e.TwoBytes=25]="TwoBytes",e[e.FourBytes=26]="FourBytes",e[e.EightBytes=27]="EightBytes",e[e.Indefinite=31]="Indefinite",e))(Ft||{}),uo=!1;function Uf(e){return e==null}function du(e,t){let r=new Uint8Array(t);return r.set(e),r}var kf=new TextDecoder;function Lf(e){return(e&224)>>5}function qf(e){return e&31}var ti=new Uint8Array,Qo,Pt=0;function pu(e,t){ti=e,Pt=0;let r=jn(t);return t?.(r)??r}function jn(e){let[t,r]=ds();switch(t){case Ne.UnsignedInteger:return po(r);case Ne.NegativeInteger:return Hf(r);case Ne.ByteString:return fu(r);case Ne.TextString:return Ba(r);case Ne.Array:return Mf(r,e);case Ne.Map:return Kf(r,e);case Ne.Tag:return Gf(r,e);case Ne.Simple:return jf(r)}throw new xr(`Unsupported major type: ${t}`)}function ds(){let e=ti.at(Pt);if(Uf(e))throw new xr("Provided CBOR data is empty");let t=Lf(e),r=qf(e);return Pt++,[t,r]}function Mf(e,t){let r=po(e);if(r===1/0){let o=[],i=jn(t);for(;i!==uu;)o.push(t?.(i)??i),i=jn(t);return o}let n=new Array(r);for(let o=0;o<r;o++){let i=jn(t);n[o]=t?.(i)??i}return n}function jf(e){switch(e){case Vt.False:return!1;case Vt.True:return!0;case Vt.Null:return null;case Vt.Undefined:return;case Vt.Break:return uu}throw new xr(`Unrecognized simple type: ${e.toString(2)}`)}function Kf(e,t){let r=po(e),n={};if(r===1/0){let[o,i]=ds();for(;o!==Ne.Simple&&i!==Vt.Break;){let s=Ba(i),a=jn(t);n[s]=t?.(a,s)??a,[o,i]=ds()}return n}for(let o=0;o<r;o++){let[i,s]=ds();if(i!==Ne.TextString)throw new xr("Map keys must be text strings");let a=Ba(s),c=jn(t);n[a]=t?.(c,a)??c}return n}function po(e){if(e<=Ft.Value)return e;switch(Qo=new DataView(ti.buffer,ti.byteOffset+Pt),e){case Ft.OneByte:return Pt++,Qo.getUint8(0);case Ft.TwoBytes:return Pt+=2,Qo.getUint16(0,uo);case Ft.FourBytes:return Pt+=4,Qo.getUint32(0,uo);case Ft.EightBytes:return Pt+=8,Qo.getBigUint64(0,uo);case Ft.Indefinite:return 1/0;default:throw new xr(`Unsupported integer info: ${e.toString(2)}`)}}function Hf(e){let t=po(e);return typeof t=="number"?-1-t:-1n-t}function fu(e){let t=po(e);if(t>Number.MAX_SAFE_INTEGER)throw new xr("Byte length is too large");let r=Number(t);return Pt+=r,ti.slice(Pt-r,Pt)}function Ba(e){let t=fu(e);return kf.decode(t)}function Gf(e,t){let r=po(e);if(r===lu)return jn(t);throw new xr(`Unsupported tag: ${r}.`)}var ri=class extends Error{constructor(t){super(t),this.name="SerializationError"}},$f=2*1024,Jf=100,Wf=new TextEncoder;function ei(e){return e<<5}var st=new Uint8Array($f),Ct=new DataView(st.buffer),Te=0,Pa=[];function hu(e,t){Te=0;let r=t?.(e)??e;return rh(lu,r,t),st.slice(0,Te)}function Da(e,t){if(Te>st.length-Jf&&(st=du(st,st.length*2),Ct=new DataView(st.buffer)),e===!1||e===!0||e===null||e===void 0){Zf(e);return}if(typeof e=="number"||typeof e=="bigint"){th(e);return}if(typeof e=="string"){yu(e);return}if(e instanceof Uint8Array){cu(e);return}if(e instanceof ArrayBuffer){cu(new Uint8Array(e));return}if(Array.isArray(e)){zf(e,t);return}if(typeof e=="object"){Yf(e,t);return}throw new ri(`Unsupported type: ${typeof e}`)}function zf(e,t){fo(Ne.Array,e.length),e.forEach((r,n)=>{Da(t?.(r,n.toString())??r,t)})}function Yf(e,t){Pa=Object.entries(e),fo(Ne.Map,Pa.length),Pa.forEach(([r,n])=>{yu(r),Da(t?.(n,r)??n,t)})}function fo(e,t){if(t<=Ff){Ct.setUint8(Te++,ei(e)|Number(t));return}if(t<=Vf){Ct.setUint8(Te++,ei(e)|Ft.OneByte),Ct.setUint8(Te,Number(t)),Te+=1;return}if(t<=Pf){Ct.setUint8(Te++,ei(e)|Ft.TwoBytes),Ct.setUint16(Te,Number(t),uo),Te+=2;return}if(t<=Bf){Ct.setUint8(Te++,ei(e)|Ft.FourBytes),Ct.setUint32(Te,Number(t),uo),Te+=4;return}if(t<=Df){Ct.setUint8(Te++,ei(e)|Ft.EightBytes),Ct.setBigUint64(Te,BigInt(t),uo),Te+=8;return}throw new ri(`Value too large to encode: ${t}`)}function Zf(e){fo(Ne.Simple,Xf(e))}function Xf(e){if(e===!1)return Vt.False;if(e===!0)return Vt.True;if(e===null)return Vt.Null;if(e===void 0)return Vt.Undefined;throw new ri(`Unrecognized simple value: ${e.toString()}`)}function mu(e,t){fo(e,t.length),Te>st.length-t.length&&(st=du(st,st.length+t.length),Ct=new DataView(st.buffer)),st.set(t,Te),Te+=t.length}function _u(e,t){fo(e,t)}function Qf(e){_u(Ne.UnsignedInteger,e)}function eh(e){_u(Ne.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function th(e){e>=0?Qf(e):eh(e)}function yu(e){mu(Ne.TextString,Wf.encode(e))}function cu(e){mu(Ne.ByteString,e)}function rh(e,t,r){fo(Ne.Tag,e),Da(t,r)}function oh(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function ni(e){try{return hu(e,t=>k.isPrincipal(t)?t.toUint8Array():ho.isExpiry(t)?t.toBigInt():oh(t)?t.toCborValue():t)}catch(t){throw Y.fromCode(new Hi(t,e))}}function Ke(e){try{return pu(e)}catch(t){throw Y.fromCode(new Ki(t,e))}}var ps={encode:ni,decode:Ke};var oi=()=>{if(typeof window<"u"&&window.crypto&&window.crypto.getRandomValues){let e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return typeof crypto<"u"&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)};var br;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(br||(br={}));var hs;(function(e){e.Call="call"})(hs||(hs={}));var Kn;(function(e){e.Query="query",e.ReadState="read_state"})(Kn||(Kn={}));function ii(){let e=new ArrayBuffer(16),t=new DataView(e),r=oi(),n=oi(),o=oi(),i=oi();return t.setUint32(0,r),t.setUint32(4,n),t.setUint32(8,o),t.setUint32(12,i),Object.assign(new Uint8Array(e),{__nonce__:void 0})}var ms="__expiry__",Ua=BigInt(1e3),ih=BigInt(1e6),sh=BigInt(60),ka=sh*Ua,ah=BigInt(1)*ka;function ch(e){return e/Ua*Ua}function lh(e){return e/ka*ka}var ho=class e{constructor(t){this.__expiry__=t,this._isExpiry=!0}static fromDeltaInMilliseconds(t,r=0){let n=BigInt(Date.now())+BigInt(r),o=n+BigInt(t),i=lh(o),s;return i>=n+ah?s=i:s=ch(o),new e(s*ih)}toBigInt(){return this.__expiry__}toHash(){return ie(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[ms]:this.toString()}}static fromJSON(t){let r=JSON.parse(t);if(r[ms])try{let n=BigInt(r[ms]);return new e(n)}catch(n){throw new Y(new Ho(`Not a valid BigInt: ${n}`))}throw new Y(new Ho(`The input does not contain the key ${ms}`))}static isExpiry(t){return t instanceof e||typeof t=="object"&&t!==null&&"_isExpiry"in t&&t._isExpiry===!0&&"__expiry__"in t&&typeof t.__expiry__=="bigint"}};function La(e=ii){return async t=>{let r=t.request.headers;t.request.headers=r,t.endpoint===br.Call&&(t.body.nonce=e())}}function qa(e){let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t}var ja=BigInt(0),_s=BigInt(1);function Hn(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function Hr(e,t,r=""){let n=Lt(e),o=e?.length,i=t!==void 0;if(!n||i&&o!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return e}function gu(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?ja:BigInt("0x"+e)}function Qe(e){return gu(j(e))}function wr(e){return fe(e),gu(j(Uint8Array.from(e).reverse()))}function Oe(e,t){return Ee(e.toString(16).padStart(t*2,"0"))}function Ka(e,t){return Oe(e,t).reverse()}function de(e,t,r){let n;if(typeof t=="string")try{n=Ee(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(Lt(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function xu(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function Ha(e){return Uint8Array.from(e)}var Ma=e=>typeof e=="bigint"&&ja<=e;function Ga(e,t,r){return Ma(e)&&Ma(t)&&Ma(r)&&t<=e&&e<r}function ys(e,t,r,n){if(!Ga(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Tr(e){let t;for(t=0;e>ja;e>>=_s,t+=1);return t}function bu(e,t){return e>>BigInt(t)&_s}var Bt=e=>(_s<<BigInt(e))-_s;function wu(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function Nr(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,i,s){let a=e[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(t).forEach(([o,i])=>n(o,i,!1)),Object.entries(r).forEach(([o,i])=>n(o,i,!0))}var mo=()=>{throw new Error("not implemented")};function Gr(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let i=e(r,...n);return t.set(r,i),i}}var He=BigInt(0),ve=BigInt(1),Gn=BigInt(2),Nu=BigInt(3),Ou=BigInt(4),Eu=BigInt(5),uh=BigInt(7),Ru=BigInt(8),dh=BigInt(9),vu=BigInt(16);function ce(e,t){let r=e%t;return r>=He?r:t+r}function Dt(e,t,r){let n=e;for(;t-- >He;)n*=n,n%=r;return n}function Tu(e,t){if(e===He)throw new Error("invert: expected non-zero number");if(t<=He)throw new Error("invert: expected positive modulus, got "+t);let r=ce(e,t),n=t,o=He,i=ve,s=ve,a=He;for(;r!==He;){let u=n/r,p=n%r,d=o-s*u,l=i-a*u;n=r,r=p,o=s,i=a,s=d,a=l}if(n!==ve)throw new Error("invert: does not exist");return ce(o,t)}function $a(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function Iu(e,t){let r=(e.ORDER+ve)/Ou,n=e.pow(t,r);return $a(e,n,t),n}function ph(e,t){let r=(e.ORDER-Eu)/Ru,n=e.mul(t,Gn),o=e.pow(n,r),i=e.mul(t,o),s=e.mul(e.mul(i,Gn),o),a=e.mul(i,e.sub(s,e.ONE));return $a(e,a,t),a}function fh(e){let t=Ge(e),r=Au(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+uh)/vu;return(a,c)=>{let u=a.pow(c,s),p=a.mul(u,n),d=a.mul(u,o),l=a.mul(u,i),f=a.eql(a.sqr(p),c),h=a.eql(a.sqr(d),c);u=a.cmov(u,p,f),p=a.cmov(l,d,h);let _=a.eql(a.sqr(p),c),g=a.cmov(u,p,_);return $a(a,g,c),g}}function Au(e){if(e<Nu)throw new Error("sqrt is not defined for small field");let t=e-ve,r=0;for(;t%Gn===He;)t/=Gn,r++;let n=Gn,o=Ge(e);for(;si(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Iu;let i=o.pow(n,t),s=(t+ve)/Gn;return function(c,u){if(c.is0(u))return u;if(si(c,u)!==1)throw new Error("Cannot find square root");let p=r,d=c.mul(c.ONE,i),l=c.pow(u,t),f=c.pow(u,s);for(;!c.eql(l,c.ONE);){if(c.is0(l))return c.ZERO;let h=1,_=c.sqr(l);for(;!c.eql(_,c.ONE);)if(h++,_=c.sqr(_),h===p)throw new Error("Cannot find square root");let g=ve<<BigInt(p-h-1),m=c.pow(d,g);p=h,d=c.sqr(m),l=c.mul(l,d),f=c.mul(f,m)}return f}}function hh(e){return e%Ou===Nu?Iu:e%Ru===Eu?ph:e%vu===dh?fh(e):Au(e)}var Or=(e,t)=>(ce(e,t)&ve)===ve,mh=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gs(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=mh.reduce((n,o)=>(n[o]="function",n),t);return Nr(e,r),e}function ai(e,t,r){if(r<He)throw new Error("invalid exponent, negatives unsupported");if(r===He)return e.ONE;if(r===ve)return t;let n=e.ONE,o=t;for(;r>He;)r&ve&&(n=e.mul(n,o)),o=e.sqr(o),r>>=ve;return n}function pt(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((s,a,c)=>e.is0(a)?s:(n[c]=s,e.mul(s,a)),e.ONE),i=e.inv(o);return t.reduceRight((s,a,c)=>e.is0(a)?s:(n[c]=e.mul(s,n[c]),e.mul(s,a)),i),n}function si(e,t){let r=(e.ORDER-ve)/Gn,n=e.pow(t,r),o=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Ja(e,t){t!==void 0&&ha(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Ge(e,t,r=!1,n={}){if(e<=He)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,i,s=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let l=t;l.BITS&&(o=l.BITS),l.sqrt&&(i=l.sqrt),typeof l.isLE=="boolean"&&(r=l.isLE),typeof l.modFromBytes=="boolean"&&(s=l.modFromBytes),a=l.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(i=n.sqrt);let{nBitLength:c,nByteLength:u}=Ja(e,o);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let p,d=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:u,MASK:Bt(c),ZERO:He,ONE:ve,allowedLengths:a,create:l=>ce(l,e),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return He<=l&&l<e},is0:l=>l===He,isValidNot0:l=>!d.is0(l)&&d.isValid(l),isOdd:l=>(l&ve)===ve,neg:l=>ce(-l,e),eql:(l,f)=>l===f,sqr:l=>ce(l*l,e),add:(l,f)=>ce(l+f,e),sub:(l,f)=>ce(l-f,e),mul:(l,f)=>ce(l*f,e),pow:(l,f)=>ai(d,l,f),div:(l,f)=>ce(l*Tu(f,e),e),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>Tu(l,e),sqrt:i||(l=>(p||(p=hh(e)),p(d,l))),toBytes:l=>r?Ka(l,u):Oe(l,u),fromBytes:(l,f=!0)=>{if(a){if(!a.includes(l.length)||l.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);let _=new Uint8Array(u);_.set(l,r?0:_.length-l.length),l=_}if(l.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+l.length);let h=r?wr(l):Qe(l);if(s&&(h=ce(h,e)),!f&&!d.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:l=>pt(d,l),cmov:(l,f,h)=>h?f:l});return Object.freeze(d)}function Su(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function xs(e){let t=Su(e);return t+Math.ceil(t/2)}function Wa(e,t,r=!1){let n=e.length,o=Su(t),i=xs(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?wr(e):Qe(e),a=ce(s,t-ve)+ve;return r?Ka(a,o):Oe(a,o)}var _o=BigInt(0),$n=BigInt(1);function ci(e,t){let r=t.negate();return e?r:t}function ft(e,t){let r=pt(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function Pu(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function za(e,t){Pu(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,i=Bt(e),s=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function Cu(e,t,r){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=r,a=Number(e&o),c=e>>s;a>n&&(a-=i,c+=$n);let u=t*n,p=u+Math.abs(a)-1,d=a===0,l=a<0,f=t%2!==0;return{nextN:c,offset:p,isZero:d,isNeg:l,isNegF:f,offsetF:u}}function yh(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function gh(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var Ya=new WeakMap,Bu=new WeakMap;function Za(e){return Bu.get(e)||1}function Fu(e){if(e!==_o)throw new Error("invalid wNAF")}var yo=class{constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>_o;)r&$n&&(n=n.add(o)),o=o.double(),r>>=$n;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=za(r,this.bits),i=[],s=t,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let u=1;u<o;u++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=za(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:p,isNeg:d,isNegF:l,offsetF:f}=Cu(n,a,s);n=c,p?i=i.add(ci(l,r[f])):o=o.add(ci(d,r[u]))}return Fu(n),{p:o,f:i}}wNAFUnsafe(t,r,n,o=this.ZERO){let i=za(t,this.bits);for(let s=0;s<i.windows&&n!==_o;s++){let{nextN:a,offset:c,isZero:u,isNeg:p}=Cu(n,s,i);if(n=a,!u){let d=r[c];o=o.add(p?d.negate():d)}}return Fu(n),o}getPrecomputes(t,r,n){let o=Ya.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),Ya.set(r,o))),o}cached(t,r,n){let o=Za(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let i=Za(t);return i===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),r,o)}createCache(t,r){Pu(r,this.bits),Bu.set(t,r),Ya.delete(t)}hasCache(t){return Za(t)!==1}};function Du(e,t,r,n){let o=t,i=e.ZERO,s=e.ZERO;for(;r>_o||n>_o;)r&$n&&(i=i.add(o)),n&$n&&(s=s.add(o)),o=o.double(),r>>=$n,n>>=$n;return{p1:i,p2:s}}function go(e,t,r,n){yh(r,e),gh(n,t);let o=r.length,i=n.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=e.ZERO,a=Tr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=Bt(c),p=new Array(Number(u)+1).fill(s),d=Math.floor((t.BITS-1)/c)*c,l=s;for(let f=d;f>=0;f-=c){p.fill(s);for(let _=0;_<i;_++){let g=n[_],m=Number(g>>BigInt(f)&u);p[m]=p[m].add(r[_])}let h=s;for(let _=p.length-1,g=s;_>0;_--)g=g.add(p[_]),h=h.add(g);if(l=l.add(h),f!==0)for(let _=0;_<c;_++)l=l.double()}return l}function Vu(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return gs(t),t}else return Ge(e,{isLE:r})}function bs(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let u=t[c];if(!(typeof u=="bigint"&&u>_o))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Vu(t.p,r.Fp,n),i=Vu(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}var xh=Qe;function $r(e,t){if(li(e),li(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function bh(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function li(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function Uu(e){if(!Lt(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?G(e):e}function wh(e,t,r,n){fe(e),li(r),t=Uu(t),t.length>255&&(t=n(K(G("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(r/o);if(r>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=K(t,$r(t.length,1)),c=$r(0,i),u=$r(r,2),p=new Array(s),d=n(K(c,e,u,$r(0,1),a));p[0]=n(K(d,$r(1,1),a));for(let f=1;f<=s;f++){let h=[bh(d,p[f-1]),$r(f+1,1),a];p[f]=n(K(...h))}return K(...p).slice(0,r)}function Th(e,t,r,n,o){if(fe(e),li(r),t=Uu(t),t.length>255){let i=Math.ceil(2*n/8);t=o.create({dkLen:i}).update(G("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(e).update($r(r,2)).update(t).update($r(t.length,1)).digest()}function Xa(e,t,r){Nr(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:i,hash:s,expand:a,DST:c}=r;if(!wu(r.hash))throw new Error("expected valid hash");fe(e),li(t);let u=n.toString(2).length,p=Math.ceil((u+o)/8),d=t*i*p,l;if(a==="xmd")l=wh(e,c,d,s);else if(a==="xof")l=Th(e,c,d,o,s);else if(a==="_internal_pass")l=e;else throw new Error('expand must be "xmd" or "xof"');let f=new Array(t);for(let h=0;h<t;h++){let _=new Array(i);for(let g=0;g<i;g++){let m=p*(g+h*i),b=l.subarray(m,m+p);_[g]=ce(xh(b),n)}f[h]=_}return f}function Qa(e,t){let r=t.map(n=>Array.from(n).reverse());return(n,o)=>{let[i,s,a,c]=r.map(d=>d.reduce((l,f)=>e.add(e.mul(l,n),f))),[u,p]=pt(e,[s,c],!0);return n=e.mul(i,u),o=e.mul(o,e.mul(a,p)),{x:n,y:o}}}var Nh=G("HashToScalar-");function ec(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(i){return e.fromAffine(t(i))}function o(i){let s=i.clearCofactor();return s.equals(e.ZERO)?e.ZERO:(s.assertValidity(),s)}return{defaults:r,hashToCurve(i,s){let a=Object.assign({},r,s),c=Xa(i,2,a),u=n(c[0]),p=n(c[1]);return o(u.add(p))},encodeToCurve(i,s){let a=r.encodeDST?{DST:r.encodeDST}:{},c=Object.assign({},r,a,s),u=Xa(i,1,c),p=n(u[0]);return o(p)},mapToCurve(i){if(!Array.isArray(i))throw new Error("expected array of bigints");for(let s of i)if(typeof s!="bigint")throw new Error("expected array of bigints");return o(n(i))},hashToScalar(i,s){let a=e.Fn.ORDER,c=Object.assign({},r,{p:a,m:1,DST:Nh},s);return Xa(i,1,c)[0][0]}}}var ku=(e,t)=>(e+(e>=0?t:-t)/Er)/t;function Oh(e,t,r){let[[n,o],[i,s]]=t,a=ku(s*e,r),c=ku(-o*e,r),u=e-a*n-c*i,p=-a*o-c*s,d=u<Jn,l=p<Jn;d&&(u=-u),l&&(p=-p);let f=Bt(Math.ceil(Tr(r)/2))+$e;if(u<Jn||u>=f||p<Jn||p>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:u,k2neg:l,k2:p}}var Jn=BigInt(0),$e=BigInt(1),Er=BigInt(2),xo=BigInt(3),tc=BigInt(4);function ui(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=de("private key",t);try{n=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Eh(e,t={}){let r=bs("weierstrass",e,t),{Fp:n,Fn:o}=r,i=r.CURVE,{h:s,n:a}=i;Nr(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Ih(n,o);function p(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(S,x,N){let{x:F,y:B}=x.toAffine(),L=n.toBytes(F);if(Hn(N,"isCompressed"),N){p();let A=!n.isOdd(B);return K(Rh(A),L)}else return K(Uint8Array.of(4),L,n.toBytes(B))}function l(S){Hr(S,void 0,"Point");let{publicKey:x,publicKeyUncompressed:N}=u,F=S.length,B=S[0],L=S.subarray(1);if(F===x&&(B===2||B===3)){let A=n.fromBytes(L);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let C=_(A),P;try{P=n.sqrt(C)}catch(te){let re=te instanceof Error?": "+te.message:"";throw new Error("bad point: is not on curve, sqrt error"+re)}p();let D=n.isOdd(P);return(B&1)===1!==D&&(P=n.neg(P)),{x:A,y:P}}else if(F===N&&B===4){let A=n.BYTES,C=n.fromBytes(L.subarray(0,A)),P=n.fromBytes(L.subarray(A,A*2));if(!g(C,P))throw new Error("bad point: is not on curve");return{x:C,y:P}}else throw new Error(`bad point: got length ${F}, expected compressed=${x} or uncompressed=${N}`)}let f=t.toBytes||d,h=t.fromBytes||l;function _(S){let x=n.sqr(S),N=n.mul(x,S);return n.add(n.add(N,n.mul(S,i.a)),i.b)}function g(S,x){let N=n.sqr(x),F=_(S);return n.eql(N,F)}if(!g(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(i.a,xo),tc),b=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(m,b)))throw new Error("bad curve params: a or b");function y(S,x,N=!1){if(!n.isValid(x)||N&&n.is0(x))throw new Error(`bad point coordinate ${S}`);return x}function T(S){if(!(S instanceof w))throw new Error("ProjectivePoint expected")}function O(S){if(!c||!c.basises)throw new Error("no endo");return Oh(S,c.basises,o.ORDER)}let R=Gr((S,x)=>{let{X:N,Y:F,Z:B}=S;if(n.eql(B,n.ONE))return{x:N,y:F};let L=S.is0();x==null&&(x=L?n.ONE:n.inv(B));let A=n.mul(N,x),C=n.mul(F,x),P=n.mul(B,x);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:A,y:C}}),E=Gr(S=>{if(S.is0()){if(t.allowInfinityPoint&&!n.is0(S.Y))return;throw new Error("bad point: ZERO")}let{x,y:N}=S.toAffine();if(!n.isValid(x)||!n.isValid(N))throw new Error("bad point: x or y not field elements");if(!g(x,N))throw new Error("bad point: equation left != right");if(!S.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function I(S,x,N,F,B){return N=new w(n.mul(N.X,S),N.Y,N.Z),x=ci(F,x),N=ci(B,N),x.add(N)}class w{constructor(x,N,F){this.X=y("x",x),this.Y=y("y",N,!0),this.Z=y("z",F),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:N,y:F}=x||{};if(!x||!n.isValid(N)||!n.isValid(F))throw new Error("invalid affine point");if(x instanceof w)throw new Error("projective point not allowed");return n.is0(N)&&n.is0(F)?w.ZERO:new w(N,F,n.ONE)}static fromBytes(x){let N=w.fromAffine(h(Hr(x,void 0,"point")));return N.assertValidity(),N}static fromHex(x){return w.fromBytes(de("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,N=!0){return V.createCache(this,x),N||this.multiply(xo),this}assertValidity(){E(this)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){T(x);let{X:N,Y:F,Z:B}=this,{X:L,Y:A,Z:C}=x,P=n.eql(n.mul(N,C),n.mul(L,B)),D=n.eql(n.mul(F,C),n.mul(A,B));return P&&D}negate(){return new w(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:N}=i,F=n.mul(N,xo),{X:B,Y:L,Z:A}=this,C=n.ZERO,P=n.ZERO,D=n.ZERO,M=n.mul(B,B),te=n.mul(L,L),re=n.mul(A,A),z=n.mul(B,L);return z=n.add(z,z),D=n.mul(B,A),D=n.add(D,D),C=n.mul(x,D),P=n.mul(F,re),P=n.add(C,P),C=n.sub(te,P),P=n.add(te,P),P=n.mul(C,P),C=n.mul(z,C),D=n.mul(F,D),re=n.mul(x,re),z=n.sub(M,re),z=n.mul(x,z),z=n.add(z,D),D=n.add(M,M),M=n.add(D,M),M=n.add(M,re),M=n.mul(M,z),P=n.add(P,M),re=n.mul(L,A),re=n.add(re,re),M=n.mul(re,z),C=n.sub(C,M),D=n.mul(re,te),D=n.add(D,D),D=n.add(D,D),new w(C,P,D)}add(x){T(x);let{X:N,Y:F,Z:B}=this,{X:L,Y:A,Z:C}=x,P=n.ZERO,D=n.ZERO,M=n.ZERO,te=i.a,re=n.mul(i.b,xo),z=n.mul(N,L),be=n.mul(F,A),we=n.mul(B,C),Ze=n.add(N,F),oe=n.add(L,A);Ze=n.mul(Ze,oe),oe=n.add(z,be),Ze=n.sub(Ze,oe),oe=n.add(N,B);let ne=n.add(L,C);return oe=n.mul(oe,ne),ne=n.add(z,we),oe=n.sub(oe,ne),ne=n.add(F,B),P=n.add(A,C),ne=n.mul(ne,P),P=n.add(be,we),ne=n.sub(ne,P),M=n.mul(te,oe),P=n.mul(re,we),M=n.add(P,M),P=n.sub(be,M),M=n.add(be,M),D=n.mul(P,M),be=n.add(z,z),be=n.add(be,z),we=n.mul(te,we),oe=n.mul(re,oe),be=n.add(be,we),we=n.sub(z,we),we=n.mul(te,we),oe=n.add(oe,we),z=n.mul(be,oe),D=n.add(D,z),z=n.mul(ne,oe),P=n.mul(Ze,P),P=n.sub(P,z),z=n.mul(Ze,be),M=n.mul(ne,M),M=n.add(M,z),new w(P,D,M)}subtract(x){return this.add(x.negate())}is0(){return this.equals(w.ZERO)}multiply(x){let{endo:N}=t;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let F,B,L=A=>V.cached(this,A,C=>ft(w,C));if(N){let{k1neg:A,k1:C,k2neg:P,k2:D}=O(x),{p:M,f:te}=L(C),{p:re,f:z}=L(D);B=te.add(z),F=I(N.beta,M,re,A,P)}else{let{p:A,f:C}=L(x);F=A,B=C}return ft(w,[F,B])[0]}multiplyUnsafe(x){let{endo:N}=t,F=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===Jn||F.is0())return w.ZERO;if(x===$e)return F;if(V.hasCache(this))return this.multiply(x);if(N){let{k1neg:B,k1:L,k2neg:A,k2:C}=O(x),{p1:P,p2:D}=Du(w,F,L,C);return I(N.beta,P,D,B,A)}else return V.unsafe(F,x)}multiplyAndAddUnsafe(x,N,F){let B=this.multiplyUnsafe(N).add(x.multiplyUnsafe(F));return B.is0()?void 0:B}toAffine(x){return R(this,x)}isTorsionFree(){let{isTorsionFree:x}=t;return s===$e?!0:x?x(w,this):V.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=t;return s===$e?this:x?x(w,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(x=!0){return Hn(x,"isCompressed"),this.assertValidity(),f(w,this,x)}toHex(x=!0){return j(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return ft(w,x)}static msm(x,N){return go(w,o,x,N)}static fromPrivateKey(x){return w.BASE.multiply(ui(o,x))}}w.BASE=new w(i.Gx,i.Gy,n.ONE),w.ZERO=new w(n.ZERO,n.ONE,n.ZERO),w.Fp=n,w.Fn=o;let v=o.BITS,V=new yo(w,t.endo?Math.ceil(v/2):v);return w.BASE.precompute(8),w}function Rh(e){return Uint8Array.of(e?2:3)}function vh(e,t){let r=e.ORDER,n=Jn;for(let h=r-$e;h%Er===Jn;h/=Er)n+=$e;let o=n,i=Er<<o-$e-$e,s=i*Er,a=(r-$e)/s,c=(a-$e)/Er,u=s-$e,p=i,d=e.pow(t,a),l=e.pow(t,(a+$e)/Er),f=(h,_)=>{let g=d,m=e.pow(_,u),b=e.sqr(m);b=e.mul(b,_);let y=e.mul(h,b);y=e.pow(y,c),y=e.mul(y,m),m=e.mul(y,_),b=e.mul(y,h);let T=e.mul(b,m);y=e.pow(T,p);let O=e.eql(y,e.ONE);m=e.mul(b,l),y=e.mul(T,g),b=e.cmov(m,b,O),T=e.cmov(y,T,O);for(let R=o;R>$e;R--){let E=R-Er;E=Er<<E-$e;let I=e.pow(T,E),w=e.eql(I,e.ONE);m=e.mul(b,g),g=e.mul(g,g),I=e.mul(T,g),b=e.cmov(m,b,w),T=e.cmov(I,T,w)}return{isValid:O,value:b}};if(e.ORDER%tc===xo){let h=(e.ORDER-xo)/tc,_=e.sqrt(e.neg(t));f=(g,m)=>{let b=e.sqr(m),y=e.mul(g,m);b=e.mul(b,y);let T=e.pow(b,h);T=e.mul(T,y);let O=e.mul(T,_),R=e.mul(e.sqr(T),m),E=e.eql(R,g),I=e.cmov(O,T,E);return{isValid:E,value:I}}}return f}function rc(e,t){gs(e);let{A:r,B:n,Z:o}=t;if(!e.isValid(r)||!e.isValid(n)||!e.isValid(o))throw new Error("mapToCurveSimpleSWU: invalid opts");let i=vh(e,o);if(!e.isOdd)throw new Error("Field does not have .isOdd()");return s=>{let a,c,u,p,d,l,f,h;a=e.sqr(s),a=e.mul(a,o),c=e.sqr(a),c=e.add(c,a),u=e.add(c,e.ONE),u=e.mul(u,n),p=e.cmov(o,e.neg(c),!e.eql(c,e.ZERO)),p=e.mul(p,r),c=e.sqr(u),l=e.sqr(p),d=e.mul(l,r),c=e.add(c,d),c=e.mul(c,u),l=e.mul(l,p),d=e.mul(l,n),c=e.add(c,d),f=e.mul(a,u);let{isValid:_,value:g}=i(c,l);h=e.mul(a,s),h=e.mul(h,g),f=e.cmov(f,u,_),h=e.cmov(h,g,_);let m=e.isOdd(s)===e.isOdd(h);h=e.cmov(e.neg(h),h,m);let b=pt(e,[p],!0)[0];return f=e.mul(f,b),{x:f,y:h}}}function Ih(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function nc(e){let{CURVE:t,curveOpts:r}=Ah(e),n=Eh(t,r);return Ch(e,n)}function Ah(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,o=Ge(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),i={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:i}}function Sh(e,t,r){function n(o){let i=e.sqr(o),s=e.mul(i,o);return e.add(e.add(s,e.mul(o,t)),r)}return n}function Ch(e,t){let{Fp:r,Fn:n}=t;function o(s){return Ga(s,$e,n.ORDER)}let i=Sh(r,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:s=>ui(n,s),weierstrassEquation:i,isWithinCurveOrder:o})}var Fh=BigInt(0),ws=BigInt(1),Lu=BigInt(2),bo=BigInt(3);function Vh(e){let t=[];for(;e>ws;e>>=ws)(e&ws)===Fh?t.unshift(0):(e&bo)===bo?(t.unshift(-1),e+=ws):t.unshift(1);return t}function oc(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function Ph(e,t,r,n){let{Fp2:o,Fp12:i}=e,{twistType:s,ateLoopSize:a,xNegative:c,postPrecompute:u}=n,p;if(s==="multiplicative")p=(y,T,O,R,E,I)=>i.mul014(R,y,o.mul(T,E),o.mul(O,I));else if(s==="divisive")p=(y,T,O,R,E,I)=>i.mul034(R,o.mul(O,I),o.mul(T,E),y);else throw new Error("bls: unknown twist type");let d=o.div(o.ONE,o.mul(o.ONE,Lu));function l(y,T,O,R){let E=o.sqr(O),I=o.sqr(R),w=o.mulByB(o.mul(I,bo)),v=o.mul(w,bo),V=o.sub(o.sub(o.sqr(o.add(O,R)),I),E),S=o.sub(w,E),x=o.mul(o.sqr(T),bo),N=o.neg(V);return y.push([S,x,N]),T=o.mul(o.mul(o.mul(o.sub(E,v),T),O),d),O=o.sub(o.sqr(o.mul(o.add(E,v),d)),o.mul(o.sqr(w),bo)),R=o.mul(E,V),{Rx:T,Ry:O,Rz:R}}function f(y,T,O,R,E,I){let w=o.sub(O,o.mul(I,R)),v=o.sub(T,o.mul(E,R)),V=o.sub(o.mul(w,E),o.mul(v,I)),S=o.neg(w),x=v;y.push([V,S,x]);let N=o.sqr(v),F=o.mul(N,v),B=o.mul(N,T),L=o.add(o.sub(F,o.mul(B,Lu)),o.mul(o.sqr(w),R));return T=o.mul(v,L),O=o.sub(o.mul(o.sub(B,L),w),o.mul(F,O)),R=o.mul(R,F),{Rx:T,Ry:O,Rz:R}}let h=Vh(a),_=Gr(y=>{let T=y,{x:O,y:R}=T.toAffine(),E=O,I=R,w=o.neg(R),v=E,V=I,S=o.ONE,x=[];for(let N of h){let F=[];({Rx:v,Ry:V,Rz:S}=l(F,v,V,S)),N&&({Rx:v,Ry:V,Rz:S}=f(F,v,V,S,E,N===-1?w:I)),x.push(F)}if(u){let N=x[x.length-1];u(v,V,S,E,I,f.bind(null,N))}return x});function g(y,T=!1){let O=i.ONE;if(y.length){let R=y[0][0].length;for(let E=0;E<R;E++){O=i.sqr(O);for(let[I,w,v]of y)for(let[V,S,x]of I[E])O=p(V,S,x,O,w,v)}}return c&&(O=i.conjugate(O)),T?i.finalExponentiate(O):O}function m(y,T=!0){let O=[];ft(t,y.map(({g1:R})=>R)),ft(r,y.map(({g2:R})=>R));for(let{g1:R,g2:E}of y){if(R.is0()||E.is0())throw new Error("pairing is not available for ZERO point");R.assertValidity(),E.assertValidity();let I=R.toAffine();O.push([_(E),I.x,I.y])}return g(O,T)}function b(y,T,O=!0){return m([{g1:y,g2:T}],O)}return{Fp12:i,millerLoopBatch:g,pairing:b,pairingBatch:m,calcPairingPrecomputes:_}}function qu(e,t,r,n,o){let{Fp12:i,pairingBatch:s}=e;function a(d){return d instanceof t.Point?d:t.Point.fromHex(d)}function c(d){return d instanceof r.Point?d:r.Point.fromHex(d)}function u(d){if(!(d instanceof r.Point))throw new Error(`expected valid message hashed to ${o?"G1":"G2"} curve`);return d}let p=o?(d,l)=>({g1:l,g2:d}):(d,l)=>({g1:d,g2:l});return{getPublicKey(d){let l=ui(t.Point.Fn,d);return t.Point.BASE.multiply(l)},sign(d,l,f){if(f!=null)throw new Error("sign() expects 2 arguments");let h=ui(t.Point.Fn,l);return u(d).assertValidity(),d.multiply(h)},verify(d,l,f,h){if(h!=null)throw new Error("verify() expects 3 arguments");d=c(d),f=a(f);let _=f.negate(),g=t.Point.BASE,m=u(l),b=d,y=s([p(_,m),p(g,b)]);return i.eql(y,i.ONE)},verifyBatch(d,l,f){if(oc(l),f.length!==l.length)throw new Error("amount of public keys and messages should be equal");let h=c(d),_=l,g=f.map(a),m=new Map;for(let T=0;T<g.length;T++){let O=g[T],R=_[T],E=m.get(R);E===void 0&&(E=[],m.set(R,E)),E.push(O)}let b=[],y=t.Point.BASE;try{for(let[T,O]of m){let R=O.reduce((E,I)=>E.add(I));b.push(p(R,T))}return b.push(p(y.negate(),h)),i.eql(s(b),i.ONE)}catch{return!1}},aggregatePublicKeys(d){oc(d),d=d.map(f=>a(f));let l=d.reduce((f,h)=>f.add(h),t.Point.ZERO);return l.assertValidity(),l},aggregateSignatures(d){oc(d),d=d.map(f=>c(f));let l=d.reduce((f,h)=>f.add(h),r.Point.ZERO);return l.assertValidity(),l},hash(d,l){fe(d);let f=l?{DST:l}:void 0;return r.hashToCurve(d,f)},Signature:n}}function Mu(e){let{Fp:t,Fr:r,Fp2:n,Fp6:o,Fp12:i}=e.fields,s=nc(e.G1),a=Object.assign(s,ec(s.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=nc(e.G2),u=Object.assign(c,ec(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),p=Ph(e.fields,a.Point,u.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:d,pairing:l,pairingBatch:f,calcPairingPrecomputes:h}=p,_=qu(p,a,u,e.G2.Signature,!1),g=qu(p,u,a,e.G1.ShortSignature,!0),m=e.randomBytes||eo,b=()=>{let A=xs(r.ORDER);return Wa(m(A),r.ORDER)},y={randomSecretKey:b,randomPrivateKey:b,calcPairingPrecomputes:h},{ShortSignature:T}=e.G1,{Signature:O}=e.G2;function R(A,C){return A instanceof a.Point?A:g.hash(de("point",A),C?.DST)}function E(A,C){return A instanceof u.Point?A:_.hash(de("point",A),C?.DST)}function I(A){return _.getPublicKey(A).toBytes(!0)}function w(A){return g.getPublicKey(A).toBytes(!0)}function v(A,C,P){let D=E(A,P),M=_.sign(D,C);return A instanceof u.Point?M:O.toBytes(M)}function V(A,C,P){let D=R(A,P),M=g.sign(D,C);return A instanceof a.Point?M:T.toBytes(M)}function S(A,C,P,D){let M=E(C,D);return _.verify(A,M,P)}function x(A,C,P,D){let M=R(C,D);return g.verify(A,M,P)}function N(A){let C=_.aggregatePublicKeys(A);return A[0]instanceof a.Point?C:C.toBytes(!0)}function F(A){let C=_.aggregateSignatures(A);return A[0]instanceof u.Point?C:O.toBytes(C)}function B(A){let C=g.aggregateSignatures(A);return A[0]instanceof a.Point?C:T.toBytes(C)}function L(A,C,P,D){let M=C.map(te=>E(te,D));return _.verifyBatch(A,M,P)}return a.Point.BASE.precompute(4),{longSignatures:_,shortSignatures:g,millerLoopBatch:d,pairing:l,pairingBatch:f,verifyBatch:L,fields:{Fr:r,Fp:t,Fp2:n,Fp6:o,Fp12:i},params:{ateLoopSize:e.params.ateLoopSize,twistType:e.params.twistType,r:e.params.r,G1b:e.G1.b,G2b:e.G2.b},utils:y,getPublicKey:I,getPublicKeyForShortSignatures:w,sign:v,signShortSignature:V,verify:S,verifyShortSignature:x,aggregatePublicKeys:N,aggregateSignatures:F,aggregateShortSignatures:B,G1:a,G2:u,Signature:O,ShortSignature:T}}var ju=BigInt(0),Rr=BigInt(1),Je=BigInt(2),Ku=BigInt(3);function cc(e,t,r,n,o=1,i){let s=BigInt(i===void 0?n:i),a=r**BigInt(n),c=[];for(let u=0;u<o;u++){let p=BigInt(u+1),d=[];for(let l=0,f=Rr;l<n;l++){let h=(p*f-p)/s%a;d.push(e.pow(t,h)),f*=r}c.push(d)}return c}function Gu(e,t,r){let n=t.pow(r,(e.ORDER-Rr)/Ku),o=t.pow(r,(e.ORDER-Rr)/Je);function i(l,f){let h=t.mul(t.frobeniusMap(l,1),n),_=t.mul(t.frobeniusMap(f,1),o);return[h,_]}let s=t.pow(r,(e.ORDER**Je-Rr)/Ku),a=t.pow(r,(e.ORDER**Je-Rr)/Je);if(!t.eql(a,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(l,f){return[t.mul(l,s),t.neg(f)]}let u=l=>(f,h)=>{let _=h.toAffine(),g=l(_.x,_.y);return f.fromAffine({x:g[0],y:g[1]})},p=u(i),d=u(c);return{psi:i,psi2:c,G2psi:p,G2psi2:d,PSI_X:n,PSI_Y:o,PSI2_X:s,PSI2_Y:a}}var Hu=(e,t)=>{if(t.length!==2)throw new Error("invalid tuple");let r=t.map(n=>e.create(n));return{c0:r[0],c1:r[1]}},ic=class{constructor(t,r={}){this.MASK=Rr;let n=t.ORDER,o=n*n;this.Fp=t,this.ORDER=o,this.BITS=Tr(o),this.BYTES=Math.ceil(Tr(o)/8),this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.Fp_NONRESIDUE=t.create(r.NONRESIDUE||BigInt(-1)),this.Fp_div2=t.div(t.ONE,Je),this.NONRESIDUE=Hu(t,r.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=cc(t,this.Fp_NONRESIDUE,t.ORDER,2)[0],this.mulByB=r.Fp2mulByB,Object.seal(this)}fromBigTuple(t){return Hu(this.Fp,t)}create(t){return t}isValid({c0:t,c1:r}){function n(o,i){return typeof o=="bigint"&&ju<=o&&o<i}return n(t,this.ORDER)&&n(r,this.ORDER)}is0({c0:t,c1:r}){return this.Fp.is0(t)&&this.Fp.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}eql({c0:t,c1:r},{c0:n,c1:o}){return this.Fp.eql(t,n)&&this.Fp.eql(r,o)}neg({c0:t,c1:r}){return{c0:this.Fp.neg(t),c1:this.Fp.neg(r)}}pow(t,r){return ai(this,t,r)}invertBatch(t){return pt(this,t)}add(t,r){let{c0:n,c1:o}=t,{c0:i,c1:s}=r;return{c0:this.Fp.add(n,i),c1:this.Fp.add(o,s)}}sub({c0:t,c1:r},{c0:n,c1:o}){return{c0:this.Fp.sub(t,n),c1:this.Fp.sub(r,o)}}mul({c0:t,c1:r},n){let{Fp:o}=this;if(typeof n=="bigint")return{c0:o.mul(t,n),c1:o.mul(r,n)};let{c0:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s),u=o.sub(a,c),p=o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c));return{c0:u,c1:p}}sqr({c0:t,c1:r}){let{Fp:n}=this,o=n.add(t,r),i=n.sub(t,r),s=n.add(t,t);return{c0:n.mul(o,i),c1:n.mul(s,r)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}div(t,r){let{Fp:n}=this;return this.mul(t,typeof r=="bigint"?n.inv(n.create(r)):this.inv(r))}inv({c0:t,c1:r}){let{Fp:n}=this,o=n.inv(n.create(t*t+r*r));return{c0:n.mul(o,n.create(t)),c1:n.mul(o,n.create(-r))}}sqrt(t){let{Fp:r}=this,n=this,{c0:o,c1:i}=t;if(r.is0(i))return si(r,o)===1?n.create({c0:r.sqrt(o),c1:r.ZERO}):n.create({c0:r.ZERO,c1:r.sqrt(r.div(o,this.Fp_NONRESIDUE))});let s=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(i),this.Fp_NONRESIDUE))),a=r.mul(r.add(s,o),this.Fp_div2);si(r,a)===-1&&(a=r.sub(a,s));let u=r.sqrt(a),p=n.create({c0:u,c1:r.div(r.mul(i,this.Fp_div2),u)});if(!n.eql(n.sqr(p),t))throw new Error("Cannot find square root");let d=p,l=n.neg(d),{re:f,im:h}=n.reim(d),{re:_,im:g}=n.reim(l);return h>g||h===g&&f>_?d:l}isOdd(t){let{re:r,im:n}=this.reim(t),o=r%Je,i=r===ju,s=n%Je;return BigInt(o||i&&s)==Rr}fromBytes(t){let{Fp:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))}}toBytes({c0:t,c1:r}){return K(this.Fp.toBytes(t),this.Fp.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},i){return{c0:this.Fp.cmov(t,n,i),c1:this.Fp.cmov(r,o,i)}}reim({c0:t,c1:r}){return{re:t,im:r}}Fp4Square(t,r){let n=this,o=n.sqr(t),i=n.sqr(r);return{first:n.add(n.mulByNonresidue(i),o),second:n.sub(n.sub(n.sqr(n.add(t,r)),o),i)}}mulByNonresidue({c0:t,c1:r}){return this.mul({c0:t,c1:r},this.NONRESIDUE)}frobeniusMap({c0:t,c1:r},n){return{c0:t,c1:this.Fp.mul(r,this.FROBENIUS_COEFFICIENTS[n%2])}}},sc=class{constructor(t){this.MASK=Rr,this.Fp2=t,this.ORDER=t.ORDER,this.BITS=3*t.BITS,this.BYTES=3*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO,c2:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO,c2:t.ZERO};let{Fp:r}=t,n=cc(t,t.NONRESIDUE,r.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=n[0],this.FROBENIUS_COEFFICIENTS_2=n[1],Object.seal(this)}add({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return{c0:a.add(t,o),c1:a.add(r,i),c2:a.add(n,s)}}sub({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return{c0:a.sub(t,o),c1:a.sub(r,i),c2:a.sub(n,s)}}mul({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;if(typeof o=="bigint")return{c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)};let{c0:s,c1:a,c2:c}=o,u=i.mul(t,s),p=i.mul(r,a),d=i.mul(n,c);return{c0:i.add(u,i.mulByNonresidue(i.sub(i.mul(i.add(r,n),i.add(a,c)),i.add(p,d)))),c1:i.add(i.sub(i.mul(i.add(t,r),i.add(s,a)),i.add(u,p)),i.mulByNonresidue(d)),c2:i.sub(i.add(p,i.mul(i.add(t,n),i.add(s,c))),i.add(u,d))}}sqr({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sqr(t),s=o.mul(o.mul(t,r),Je),a=o.mul(o.mul(r,n),Je),c=o.sqr(n);return{c0:o.add(o.mulByNonresidue(a),i),c1:o.add(o.mulByNonresidue(c),s),c2:o.sub(o.sub(o.add(o.add(s,o.sqr(o.add(o.sub(t,r),n))),a),i),c)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}create(t){return t}isValid({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return o.isValid(t)&&o.isValid(r)&&o.isValid(n)}is0({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return o.is0(t)&&o.is0(r)&&o.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.neg(t),c1:o.neg(r),c2:o.neg(n)}}eql({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return a.eql(t,o)&&a.eql(r,i)&&a.eql(n,s)}sqrt(t){return mo()}div(t,r){let{Fp2:n}=this,{Fp:o}=n;return this.mul(t,typeof r=="bigint"?o.inv(o.create(r)):this.inv(r))}pow(t,r){return ai(this,t,r)}invertBatch(t){return pt(this,t)}inv({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sub(o.sqr(t),o.mulByNonresidue(o.mul(n,r))),s=o.sub(o.mulByNonresidue(o.sqr(n)),o.mul(t,r)),a=o.sub(o.sqr(r),o.mul(t,n)),c=o.inv(o.add(o.mulByNonresidue(o.add(o.mul(n,s),o.mul(r,a))),o.mul(t,i)));return{c0:o.mul(c,i),c1:o.mul(c,s),c2:o.mul(c,a)}}fromBytes(t){let{Fp2:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);let n=r.BYTES;return{c0:r.fromBytes(t.subarray(0,n)),c1:r.fromBytes(t.subarray(n,n*2)),c2:r.fromBytes(t.subarray(2*n))}}toBytes({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return K(o.toBytes(t),o.toBytes(r),o.toBytes(n))}cmov({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s},a){let{Fp2:c}=this;return{c0:c.cmov(t,o,a),c1:c.cmov(r,i,a),c2:c.cmov(n,s,a)}}fromBigSix(t){let{Fp2:r}=this;if(!Array.isArray(t)||t.length!==6)throw new Error("invalid Fp6 usage");return{c0:r.fromBigTuple(t.slice(0,2)),c1:r.fromBigTuple(t.slice(2,4)),c2:r.fromBigTuple(t.slice(4,6))}}frobeniusMap({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return{c0:i.frobeniusMap(t,o),c1:i.mul(i.frobeniusMap(r,o),this.FROBENIUS_COEFFICIENTS_1[o%6]),c2:i.mul(i.frobeniusMap(n,o),this.FROBENIUS_COEFFICIENTS_2[o%6])}}mulByFp2({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return{c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)}}mulByNonresidue({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.mulByNonresidue(n),c1:t,c2:r}}mul1({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return{c0:i.mulByNonresidue(i.mul(n,o)),c1:i.mul(t,o),c2:i.mul(r,o)}}mul01({c0:t,c1:r,c2:n},o,i){let{Fp2:s}=this,a=s.mul(t,o),c=s.mul(r,i);return{c0:s.add(s.mulByNonresidue(s.sub(s.mul(s.add(r,n),i),c)),a),c1:s.sub(s.sub(s.mul(s.add(o,i),s.add(t,r)),a),c),c2:s.add(s.sub(s.mul(s.add(t,n),o),a),c)}}},ac=class{constructor(t,r){this.MASK=Rr;let{Fp2:n}=t,{Fp:o}=n;this.Fp6=t,this.ORDER=n.ORDER,this.BITS=2*t.BITS,this.BYTES=2*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.FROBENIUS_COEFFICIENTS=cc(n,n.NONRESIDUE,o.ORDER,12,1,6)[0],this.X_LEN=r.X_LEN,this.finalExponentiate=r.Fp12finalExponentiate}create(t){return t}isValid({c0:t,c1:r}){let{Fp6:n}=this;return n.isValid(t)&&n.isValid(r)}is0({c0:t,c1:r}){let{Fp6:n}=this;return n.is0(t)&&n.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r}){let{Fp6:n}=this;return{c0:n.neg(t),c1:n.neg(r)}}eql({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return i.eql(t,n)&&i.eql(r,o)}sqrt(t){mo()}inv({c0:t,c1:r}){let{Fp6:n}=this,o=n.inv(n.sub(n.sqr(t),n.mulByNonresidue(n.sqr(r))));return{c0:n.mul(t,o),c1:n.neg(n.mul(r,o))}}div(t,r){let{Fp6:n}=this,{Fp2:o}=n,{Fp:i}=o;return this.mul(t,typeof r=="bigint"?i.inv(i.create(r)):this.inv(r))}pow(t,r){return ai(this,t,r)}invertBatch(t){return pt(this,t)}add({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return{c0:i.add(t,n),c1:i.add(r,o)}}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return{c0:i.sub(t,n),c1:i.sub(r,o)}}mul({c0:t,c1:r},n){let{Fp6:o}=this;if(typeof n=="bigint")return{c0:o.mul(t,n),c1:o.mul(r,n)};let{c0:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s);return{c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c))}}sqr({c0:t,c1:r}){let{Fp6:n}=this,o=n.mul(t,r);return{c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(r),t),n.add(t,r)),o),n.mulByNonresidue(o)),c1:n.add(o,o)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}fromBytes(t){let{Fp6:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))}}toBytes({c0:t,c1:r}){let{Fp6:n}=this;return K(n.toBytes(t),n.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},i){let{Fp6:s}=this;return{c0:s.cmov(t,n,i),c1:s.cmov(r,o,i)}}fromBigTwelve(t){let{Fp6:r}=this;return{c0:r.fromBigSix(t.slice(0,6)),c1:r.fromBigSix(t.slice(6,12))}}frobeniusMap(t,r){let{Fp6:n}=this,{Fp2:o}=n,{c0:i,c1:s,c2:a}=n.frobeniusMap(t.c1,r),c=this.FROBENIUS_COEFFICIENTS[r%12];return{c0:n.frobeniusMap(t.c0,r),c1:n.create({c0:o.mul(i,c),c1:o.mul(s,c),c2:o.mul(a,c)})}}mulByFp2({c0:t,c1:r},n){let{Fp6:o}=this;return{c0:o.mulByFp2(t,n),c1:o.mulByFp2(r,n)}}conjugate({c0:t,c1:r}){return{c0:t,c1:this.Fp6.neg(r)}}mul014({c0:t,c1:r},n,o,i){let{Fp6:s}=this,{Fp2:a}=s,c=s.mul01(t,n,o),u=s.mul1(r,i);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(s.sub(s.mul01(s.add(r,t),n,a.add(o,i)),c),u)}}mul034({c0:t,c1:r},n,o,i){let{Fp6:s}=this,{Fp2:a}=s,c=s.create({c0:a.mul(t.c0,n),c1:a.mul(t.c1,n),c2:a.mul(t.c2,n)}),u=s.mul01(r,o,i),p=s.mul01(s.add(t,r),a.add(n,o),i);return{c0:s.add(s.mulByNonresidue(u),c),c1:s.sub(p,s.add(c,u))}}_cyclotomicSquare({c0:t,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:i,c1:s,c2:a}=t,{c0:c,c1:u,c2:p}=r,{first:d,second:l}=o.Fp4Square(i,u),{first:f,second:h}=o.Fp4Square(c,a),{first:_,second:g}=o.Fp4Square(s,p),m=o.mulByNonresidue(g);return{c0:n.create({c0:o.add(o.mul(o.sub(d,i),Je),d),c1:o.add(o.mul(o.sub(f,s),Je),f),c2:o.add(o.mul(o.sub(_,a),Je),_)}),c1:n.create({c0:o.add(o.mul(o.add(m,c),Je),m),c1:o.add(o.mul(o.add(l,u),Je),l),c2:o.add(o.mul(o.add(h,p),Je),h)})}}_cyclotomicExp(t,r){let n=this.ONE;for(let o=this.X_LEN-1;o>=0;o--)n=this._cyclotomicSquare(n),bu(r,o)&&(n=this.mul(n,t));return n}};function $u(e){let t=Ge(e.ORDER),r=new ic(t,e),n=new sc(r),o=new ac(n,e);return{Fp:t,Fp2:r,Fp6:n,Fp12:o}}var Pe=BigInt(0),Ts=BigInt(1),ht=BigInt(2),Ns=BigInt(3),di=BigInt(4),Jr=BigInt("0xd201000000010000"),Bh=Tr(Jr),Wn={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Pe,b:di,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},Dh=Ge(Wn.n,{modFromBytes:!0,isLE:!0}),{Fp:q,Fp2:W,Fp6:Uh,Fp12:X}=$u({ORDER:Wn.p,X_LEN:Bh,FP2_NONRESIDUE:[Ts,Ts],Fp2mulByB:({c0:e,c1:t})=>{let r=q.mul(e,di),n=q.mul(t,di);return{c0:q.sub(r,n),c1:q.add(r,n)}},Fp12finalExponentiate:e=>{let t=Jr,r=X.div(X.frobeniusMap(e,6),e),n=X.mul(X.frobeniusMap(r,2),r),o=X.conjugate(X._cyclotomicExp(n,t)),i=X.mul(X.conjugate(X._cyclotomicSquare(n)),o),s=X.conjugate(X._cyclotomicExp(i,t)),a=X.conjugate(X._cyclotomicExp(s,t)),c=X.mul(X.conjugate(X._cyclotomicExp(a,t)),X._cyclotomicSquare(o)),u=X.conjugate(X._cyclotomicExp(c,t)),p=X.frobeniusMap(X.mul(o,a),2),d=X.frobeniusMap(X.mul(s,n),3),l=X.frobeniusMap(X.mul(c,X.conjugate(n)),1),f=X.mul(X.mul(u,X.conjugate(i)),n);return X.mul(X.mul(X.mul(p,d),l),f)}}),{G2psi:Ju,G2psi2:kh}=Gu(q,W,W.div(W.ONE,W.NONRESIDUE)),lc=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:q.ORDER,m:2,k:128,expand:"xmd",hash:Ve}),pc={p:W.ORDER,n:Wn.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:W.ZERO,b:W.fromBigTuple([di,di]),Gx:W.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:W.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},Os=pi(q.toBytes(Pe),{infinity:!0,compressed:!0});function Es(e){e=e.slice();let t=e[0]&224,r=!!(t>>7&1),n=!!(t>>6&1),o=!!(t>>5&1);return e[0]&=31,{compressed:r,infinity:n,sort:o,value:e}}function pi(e,t){if(e[0]&224)throw new Error("setMask: non-empty mask");return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function Lh(e,t,r){let{BYTES:n,ORDER:o}=q,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return Os.slice();let c=!!(a*ht/o);return pi(Oe(s,n),{compressed:!0,sort:c})}else return i?K(Uint8Array.of(64),new Uint8Array(2*n-1)):K(Oe(s,n),Oe(a,n))}function uc(e){e.assertValidity();let{BYTES:t,ORDER:r}=q,{x:n,y:o}=e.toAffine();if(e.is0())return Os.slice();let i=!!(o*ht/r);return pi(Oe(n,t),{compressed:!0,sort:i})}function qh(e){let{compressed:t,infinity:r,sort:n,value:o}=Es(e),{BYTES:i,ORDER:s}=q;if(o.length===48&&t){let a=Qe(o),c=q.create(a&Bt(q.BITS));if(r){if(c!==Pe)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:Pe,y:Pe}}let u=q.add(q.pow(c,Ns),q.create(Wn.b)),p=q.sqrt(u);if(!p)throw new Error("invalid G1 point: compressed point");return p*ht/s!==BigInt(n)&&(p=q.neg(p)),{x:q.create(c),y:q.create(p)}}else if(o.length===96&&!t){let a=Qe(o.subarray(0,i)),c=Qe(o.subarray(i));if(r){if(a!==Pe||c!==Pe)throw new Error("G1: non-empty point at infinity");return fi.G1.Point.ZERO.toAffine()}return{x:q.create(a),y:q.create(c)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function Wu(e){let{infinity:t,sort:r,value:n}=Es(de("signatureHex",e,48)),o=q.ORDER,i=fi.G1.Point,s=Qe(n);if(t)return i.ZERO;let a=q.create(s&Bt(q.BITS)),c=q.add(q.pow(a,Ns),q.create(Wn.b)),u=q.sqrt(c);if(!u)throw new Error("invalid G1 point: compressed");let p=BigInt(r);u*ht/o!==p&&(u=q.neg(u));let d=i.fromAffine({x:a,y:u});return d.assertValidity(),d}function Mh(e,t,r){let{BYTES:n,ORDER:o}=q,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return K(Os,Oe(Pe,n));let c=!!(a.c1===Pe?a.c0*ht/o:a.c1*ht/o);return K(pi(Oe(s.c1,n),{compressed:!0,sort:c}),Oe(s.c0,n))}else{if(i)return K(Uint8Array.of(64),new Uint8Array(4*n-1));let{re:c,im:u}=W.reim(s),{re:p,im:d}=W.reim(a);return K(Oe(u,n),Oe(c,n),Oe(d,n),Oe(p,n))}}function dc(e){e.assertValidity();let{BYTES:t}=q;if(e.is0())return K(Os,Oe(Pe,t));let{x:r,y:n}=e.toAffine(),{re:o,im:i}=W.reim(r),{re:s,im:a}=W.reim(n),u=!!((a>Pe?a*ht:s*ht)/q.ORDER&Ts),p=o;return K(pi(Oe(i,t),{sort:u,compressed:!0}),Oe(p,t))}function jh(e){let{BYTES:t,ORDER:r}=q,{compressed:n,infinity:o,sort:i,value:s}=Es(e);if(!n&&!o&&i||!n&&o&&i||i&&o&&n)throw new Error("invalid encoding flag: "+(e[0]&224));let a=(c,u,p)=>Qe(c.slice(u,p));if(s.length===96&&n){if(o){if(s.reduce((h,_)=>h!==0?_+1:_,0)>0)throw new Error("invalid G2 point: compressed");return{x:W.ZERO,y:W.ZERO}}let c=a(s,0,t),u=a(s,t,2*t),p=W.create({c0:q.create(u),c1:q.create(c)}),d=W.add(W.pow(p,Ns),pc.b),l=W.sqrt(d),f=l.c1===Pe?l.c0*ht/r:l.c1*ht/r?Ts:Pe;return l=i&&f>0?l:W.neg(l),{x:p,y:l}}else if(s.length===192&&!n){if(o){if(s.reduce((l,f)=>l!==0?f+1:f,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:W.ZERO,y:W.ZERO}}let c=a(s,0*t,1*t),u=a(s,1*t,2*t),p=a(s,2*t,3*t),d=a(s,3*t,4*t);return{x:W.fromBigTuple([u,c]),y:W.fromBigTuple([d,p])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function zu(e){let{ORDER:t}=q,{infinity:r,sort:n,value:o}=Es(de("signatureHex",e)),i=fi.G2.Point,s=o.length/2;if(s!==48&&s!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");let a=Qe(o.slice(0,s)),c=Qe(o.slice(s));if(r)return i.ZERO;let u=q.create(a&Bt(q.BITS)),p=q.create(c),d=W.create({c0:p,c1:u}),l=W.add(W.pow(d,Ns),pc.b),f=W.sqrt(l);if(!f)throw new Error("Failed to find a square root");let{re:h,im:_}=W.reim(f),g=BigInt(n),m=_>Pe&&_*ht/t!==g,b=_===Pe&&h*ht/t!==g;(m||b)&&(f=W.neg(f));let y=i.fromAffine({x:d,y:f});return y.assertValidity(),y}var fi=Mu({fields:{Fp:q,Fp2:W,Fp6:Uh,Fp12:X,Fr:Dh},G1:{...Wn,Fp:q,htfDefaults:{...lc,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(e,t)=>{let r=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),n=new e(q.mul(t.X,r),t.Y,t.Z);return t.multiplyUnsafe(Jr).negate().multiplyUnsafe(Jr).equals(n)},clearCofactor:(e,t)=>t.multiplyUnsafe(Jr).add(t),mapToCurve:Jh,fromBytes:qh,toBytes:Lh,ShortSignature:{fromBytes(e){return fe(e),Wu(e)},fromHex(e){return Wu(e)},toBytes(e){return uc(e)},toRawBytes(e){return uc(e)},toHex(e){return j(uc(e))}}},G2:{...pc,Fp:W,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...lc},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:Wh,isTorsionFree:(e,t)=>t.multiplyUnsafe(Jr).negate().equals(Ju(e,t)),clearCofactor:(e,t)=>{let r=Jr,n=t.multiplyUnsafe(r).negate(),o=Ju(e,t),i=t.double();return i=kh(e,i),i=i.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),i=i.add(o),i=i.subtract(n),i.subtract(t)},fromBytes:jh,toBytes:Mh,Signature:{fromBytes(e){return fe(e),zu(e)},fromHex(e){return zu(e)},toBytes(e){return dc(e)},toRawBytes(e){return dc(e)},toHex(e){return j(dc(e))}}},params:{ateLoopSize:Jr,r:Wn.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:lc,hash:Ve}),Kh=Qa(W,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(e=>e.map(t=>W.fromBigTuple(t.map(BigInt))))),Hh=Qa(q,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),Gh=rc(q,{A:q.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:q.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:q.create(BigInt(11))}),$h=rc(W,{A:W.create({c0:q.create(Pe),c1:q.create(BigInt(240))}),B:W.create({c0:q.create(BigInt(1012)),c1:q.create(BigInt(1012))}),Z:W.create({c0:q.create(BigInt(-2)),c1:q.create(BigInt(-1))})});function Jh(e){let{x:t,y:r}=Gh(q.create(e[0]));return Hh(t,r)}function Wh(e){let{x:t,y:r}=$h(W.fromBigTuple(e));return Kh(t,r)}function Yu(e,t,r){let n=typeof e=="string"?e:j(e),o=typeof t=="string"?t:j(t),i=typeof r=="string"?r:j(r);return fi.verifyShortSignature(o,i,n)}var Yh=BigInt(1e6),fc=e=>_e(new St(e)),Wr=e=>{let r=fc(e)/Yh;return new Date(Number(r))};var Zu=60*1e3,Zh=60,Xh=24,Qh=Xh*Zh,em=5,tm=5,rm=30*Qh,pe;(function(e){e[e.Empty=0]="Empty",e[e.Fork=1]="Fork",e[e.Labeled=2]="Labeled",e[e.Leaf=3]="Leaf",e[e.Pruned=4]="Pruned"})(pe||(pe={}));function nm(e,t){for(let r=0;r<e.length;r++)if(e[r]>t[r])return!0;return!1}var at=class e{#e=!1;#t=void 0;static async create(t){let r=e.createUnverified(t);return await r.verify(),r}static createUnverified(t){return new e(t.certificate,t.rootKey,t.principal,t.blsVerify??Yu,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,r,n,o,i=em,s=!1,a){this._rootKey=r,this._principal=n,this._blsVerify=o,this._maxAgeInMinutes=i,this.#e=s,this.cert=Ke(t),a&&"getTimeDiffMsecs"in a&&"hasSyncedTime"in a&&"syncTime"in a&&"syncTimeWithSubnet"in a&&(this.#t=a)}lookup_path(t){return vr(t,this.cert.tree)}lookup_subtree(t){return _i(t,this.cert.tree)}async verify(){let t=await vs(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,o=im(r),i=K(Ca,t),s=Ie(this.lookup_path(["time"]));if(!s)throw ee.fromCode(new vt("Certificate does not contain a time"));if(!this.#e){let a=this.#t?.getTimeDiffMsecs()??0,c=this._maxAgeInMinutes*Zu,u=new Date,p=u.getTime()+a,d=p-c,l=p+tm*Zu,f=Wr(s),h=f.getTime()<d,_=f.getTime()>l;if((h||_)&&this.#t&&!this.#t.hasSyncedTime())return await this._syncTime(),await this.verify();if(h)throw Me.fromCode(new hr(this._maxAgeInMinutes,f,u,a,"past"));if(_)throw this.#t?.hasSyncedTime()?ae.fromCode(new Re("System time has been synced with the IC network, but certificate is still too far in the future.")):Me.fromCode(new hr(5,f,u,a,"future"))}try{if(!await this._blsVerify(o,n,i))throw Me.fromCode(new vt("Invalid signature"))}catch(a){throw Me.fromCode(new vt("Signature verification failed",a))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let r=e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,principal:this._principal,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:rm,agent:this.#t});if(r.cert.delegation)throw ee.fromCode(new Ui);await r.verify();let n;if(Qu(this._principal)){let i=this._principal.canisterId;if(n=k.fromUint8Array(t.subnet_id),!hc({canisterId:i,subnetId:n,tree:r.cert.tree}))throw Me.fromCode(new Bn(i,n))}else if(Xu(this._principal))n=this._principal.subnetId;else throw ut;let o=Ie(r.lookup_path(["subnet",n.toUint8Array(),"public_key"]));if(!o)throw Xu(this._principal)?Me.fromCode(new ki(n)):Me.fromCode(new qi(`Could not find subnet key for subnet ID ${n.toText()}`));return o}async _syncTime(){this.#t&&(Qu(this._principal)?await this.#t.syncTime(this._principal.canisterId):await this.#t.syncTimeWithSubnet(this._principal.subnetId))}};function Xu(e){return"subnetId"in e}function Qu(e){return"canisterId"in e}var hi=Ee("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),om=96;function im(e){let t=hi.byteLength+om;if(e.byteLength!==t)throw ee.fromCode(new to(t,e.byteLength));let r=e.slice(0,hi.byteLength);if(!Mn(r,hi))throw ee.fromCode(new Mi(hi,r));return e.slice(hi.byteLength)}function Ie(e){if(e.status===Be.Found&&e.value instanceof Uint8Array)return e.value}async function vs(e){switch(e[0]){case pe.Empty:return Ve(Rs("ic-hashtree-empty"));case pe.Pruned:return e[1];case pe.Leaf:return Ve(K(Rs("ic-hashtree-leaf"),e[1]));case pe.Labeled:return Ve(K(Rs("ic-hashtree-labeled"),e[1],await vs(e[2])));case pe.Fork:return Ve(K(Rs("ic-hashtree-fork"),await vs(e[1]),await vs(e[2])));default:throw ut}}function Rs(e){let t=new Uint8Array([e.length]),r=new TextEncoder().encode(e);return K(t,r)}function ed(e){return typeof e[0]=="string"?G(e[0]):e[0]}var Be;(function(e){e.Unknown="Unknown",e.Absent="Absent",e.Found="Found",e.Error="Error"})(Be||(Be={}));var zr;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(zr||(zr={}));var le;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(le||(le={}));function vr(e,t){if(e.length===0)switch(t[0]){case pe.Empty:return{status:Be.Absent};case pe.Leaf:{if(!t[1])throw ae.fromCode(new qr("Invalid tree structure for leaf"));if(t[1]instanceof Uint8Array)return{status:Be.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw ut}case pe.Pruned:return{status:Be.Unknown};case pe.Labeled:case pe.Fork:return{status:Be.Error};default:throw ut}let r=ed(e),n=mi(r,t);switch(n.status){case le.Found:return vr(e.slice(1),n.value);case le.Absent:case le.Greater:case le.Less:return{status:Be.Absent};case le.Unknown:return{status:Be.Unknown};default:throw ut}}function _i(e,t){if(e.length===0)return{status:zr.Found,value:t};let r=ed(e),n=mi(r,t);switch(n.status){case le.Found:return _i(e.slice(1),n.value);case le.Unknown:return{status:zr.Unknown};case le.Absent:case le.Greater:case le.Less:return{status:zr.Absent};default:throw ut}}function As(e){switch(e[0]){case pe.Empty:return[];case pe.Fork:return As(e[1]).concat(As(e[2]));default:return[e]}}function mi(e,t){switch(t[0]){case pe.Labeled:return nm(e,t[1])?{status:le.Greater}:Mn(e,t[1])?{status:le.Found,value:t[2]}:{status:le.Less};case pe.Fork:{let r=mi(e,t[1]);switch(r.status){case le.Greater:{let n=mi(e,t[2]);return n.status===le.Less?{status:le.Absent}:n}case le.Unknown:{let n=mi(e,t[2]);return n.status===le.Less?{status:le.Unknown}:n}default:return r}}case pe.Pruned:return{status:le.Unknown};default:return{status:le.Absent}}}function Is(e,t){switch(t[0]){case pe.Empty|pe.Pruned:return[];case pe.Leaf:return[e];case pe.Fork:return Is(e,t[1]).concat(Is(e,t[2]));case pe.Labeled:{let r=t[1],n=t[2],o=[...e,r];return Is(o,n)}default:throw ut}}function hc(e){let t=sm(e),r=mc(t),{canisterId:n}=e;return r.some(i=>i[0].ltEq(n)&&i[1].gtEq(n))}function sm(e){let{subnetId:t,tree:r,canisterId:n}=e,o=_i(["canister_ranges",t.toUint8Array()],r);if(o.status!==zr.Found)return am(t,r);let i=o.value,s=cm(i);if(s.length===0)throw ee.fromCode(new Bn(n,t));s.sort(oo);let a=lm(s,n),c=s[a];return um(c,i)}function am(e,t){let r=vr(["subnet",e.toUint8Array(),"canister_ranges"],t);if(r.status!==Be.Found)throw ee.fromCode(new It(`Could not find canister ranges for subnet ${e.toText()}`,r.status));return r.value}function mc(e){return Ke(e).map(n=>[k.fromUint8Array(n[0]),k.fromUint8Array(n[1])])}function cm(e){let t=[];for(let r of Is([],e)){let n=r[0];if(!n)throw ee.fromCode(new vt("Path is invalid"));t.push(n)}return t}function lm(e,t){let r=t.toUint8Array(),n=0,o=e.length-1;for(;n<o;){let i=Math.floor((n+o)/2);oo(e[i],r)<=0?o=i:n=i+1}return n}function um(e,t){let r=vr([e],t);if(r.status!==Be.Found)throw ee.fromCode(new It(`Could not find canister range for shard ${e.toString()}`,r.status));return r.value}function _c(e,t){return e.delegation?k.fromUint8Array(e.delegation.subnet_id):k.selfAuthenticating(t)}var td=k.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe");function Ss(e,t){switch(t){case"raw":return e;case"leb128":return fc(e);case"cbor":return Ke(e);case"hex":return j(e);case"utf-8":return new TextDecoder().decode(e)}}function rd(e){return Ke(e).map(r=>k.fromUint8Array(r))}function nd(e,t){let r=typeof e=="string"?G(e):e;return[G("canister"),t,G("metadata"),r]}function Yr(e){return typeof e=="object"&&e!==null&&"key"in e&&"path"in e}function wo(e,t){let r=_i(["subnet",t.toUint8Array(),"node"],e.tree);if(r.status!==zr.Found)throw ee.fromCode(new It("Node not found",r.status));if(r.value instanceof Uint8Array)throw ae.fromCode(new qr("Invalid node tree"));let n=As(r.value),o=new Map;return n.forEach(i=>{let s=k.from(i[1]).toText(),a=vr(["public_key"],i[2]);if(a.status!==Be.Found)throw ee.fromCode(new It("Public key not found",a.status));let c=a.value;if(c.byteLength!==44)throw ee.fromCode(new to(44,c.byteLength));o.set(s,c)}),o}var od=async e=>{let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=k.from(e.canisterId),i=[...new Set(r)],s=new Map,a=i.map((c,u)=>{let p=pm(c,o);return(async()=>{try{if(t.rootKey===null)throw me.fromCode(new lt);let d=t.rootKey,l=await t.readState(o,{paths:[p]}),f=await at.create({certificate:l.certificate,rootKey:d,principal:{canisterId:o},disableTimeVerification:n,agent:t}),h=(m,b)=>{if(b==="subnet"){let y=dm(l.certificate,o,d);return{path:b,data:y}}else return{path:b,data:Ie(m.lookup_path(p))}},{path:_,data:g}=h(f,i[u]);if(!g)typeof _=="string"?s.set(_,null):s.set(_.key,null);else switch(_){case"time":{s.set(_,Wr(g));break}case"controllers":{s.set(_,rd(g));break}case"module_hash":{s.set(_,j(g));break}case"subnet":{s.set(_,g);break}case"candid":{s.set(_,new TextDecoder().decode(g));break}default:Yr(_)&&s.set(_.key,Ss(g,_.decodeStrategy))}}catch(d){if(d instanceof ot&&(d.hasCode(vt)||d.hasCode(hr)))throw d;Yr(c)?s.set(c.key,null):s.set(c,null)}})()});return await Promise.all(a),s},dm=(e,t,r)=>{if(!t._isPrincipal)throw Y.fromCode(new Re("Invalid canisterId"));let n=Ke(e),{delegation:o}=n,i;o&&o.subnet_id?i=k.fromUint8Array(new Uint8Array(o.subnet_id)):!o&&typeof r<"u"?i=k.selfAuthenticating(new Uint8Array(r)):i=td;let s=wo(n,i);return{subnetId:i.toText(),nodeKeys:s}},pm=(e,t)=>{let r=t.toUint8Array();switch(e){case"time":return[G("time")];case"controllers":return[G("canister"),r,G("controllers")];case"module_hash":return[G("canister"),r,G("module_hash")];case"subnet":return[G("subnet")];case"candid":return[G("canister"),r,G("metadata"),G("candid:service")];default:if(Yr(e))return typeof e.path=="string"||e.path instanceof Uint8Array?nd(e.path,r):e.path}throw ae.fromCode(new Re(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))};async function id(e){let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=k.from(e.subnetId),i=[...new Set(r)],s=new Map,a=i.map((c,u)=>{let p=fm(c,o);return(async()=>{try{if(t.rootKey===null)throw me.fromCode(new lt);let d=t.rootKey,l=await t.readSubnetState(o,{paths:[p]}),f=await at.create({certificate:l.certificate,rootKey:d,principal:{subnetId:o},disableTimeVerification:n,agent:t}),h=(m,b)=>{if(b==="nodeKeys"){let y=wo(m.cert,o);return{path:b,data:y}}else return{path:b,data:Ie(m.lookup_path(p))}},{path:_,data:g}=h(f,i[u]);if(!g)typeof _=="string"?s.set(_,null):s.set(_.key,null);else switch(_){case"time":{s.set(_,Wr(g));break}case"canisterRanges":{s.set(_,mc(g));break}case"publicKey":{s.set(_,g);break}case"nodeKeys":{s.set(_,g);break}default:Yr(_)&&s.set(_.key,Ss(g,_.decodeStrategy))}}catch(d){if(d instanceof ot&&(d.hasCode(vt)||d.hasCode(hr)))throw d;Yr(c)?s.set(c.key,null):s.set(c,null)}})()});return await Promise.all(a),s}function fm(e,t){let r=t.toUint8Array();switch(e){case"time":return[G("time")];case"canisterRanges":return[G("canister_ranges"),r];case"publicKey":return[G("subnet"),r,G("public_key")];case"nodeKeys":return[G("subnet"),r,G("node")];default:if(Yr(e))if(typeof e.path=="string"||e.path instanceof Uint8Array){let n=typeof e.path=="string"?G(e.path):e.path;return[G("subnet"),r,n]}else return e.path}throw ae.fromCode(new Re(`Error while encoding your path for subnet status. Please ensure that your path ${e} was formatted correctly.`))}var Zr=BigInt(0),Ae=BigInt(1),yc=BigInt(2),hm=BigInt(8);function mm(e,t,r,n){let o=e.sqr(r),i=e.sqr(n),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function _m(e,t={}){let r=bs("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,i=r.CURVE,{h:s}=i;Nr(t,{},{uvRatio:"function"});let a=yc<<BigInt(o.BYTES*8)-Ae,c=g=>n.create(g),u=t.uvRatio||((g,m)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,m))}}catch{return{isValid:!1,value:Zr}}});if(!mm(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function p(g,m,b=!1){let y=b?Ae:Zr;return ys("coordinate "+g,m,y,a),m}function d(g){if(!(g instanceof h))throw new Error("ExtendedPoint expected")}let l=Gr((g,m)=>{let{X:b,Y:y,Z:T}=g,O=g.is0();m==null&&(m=O?hm:n.inv(T));let R=c(b*m),E=c(y*m),I=n.mul(T,m);if(O)return{x:Zr,y:Ae};if(I!==Ae)throw new Error("invZ was invalid");return{x:R,y:E}}),f=Gr(g=>{let{a:m,d:b}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:y,Y:T,Z:O,T:R}=g,E=c(y*y),I=c(T*T),w=c(O*O),v=c(w*w),V=c(E*m),S=c(w*c(V+I)),x=c(v+c(b*c(E*I)));if(S!==x)throw new Error("bad point: equation left != right (1)");let N=c(y*T),F=c(O*R);if(N!==F)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(m,b,y,T){this.X=p("x",m),this.Y=p("y",b),this.Z=p("z",y,!0),this.T=p("t",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:b,y}=m||{};return p("x",b),p("y",y),new h(b,y,Ae,c(b*y))}static fromBytes(m,b=!1){let y=n.BYTES,{a:T,d:O}=i;m=Ha(Hr(m,y,"point")),Hn(b,"zip215");let R=Ha(m),E=m[y-1];R[y-1]=E&-129;let I=wr(R),w=b?a:n.ORDER;ys("point.y",I,Zr,w);let v=c(I*I),V=c(v-Ae),S=c(O*v-T),{isValid:x,value:N}=u(V,S);if(!x)throw new Error("bad point: invalid y coordinate");let F=(N&Ae)===Ae,B=(E&128)!==0;if(!b&&N===Zr&&B)throw new Error("bad point: x=0 and x_0=1");return B!==F&&(N=c(-N)),h.fromAffine({x:N,y:I})}static fromHex(m,b=!1){return h.fromBytes(de("point",m),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,b=!0){return _.createCache(this,m),b||this.multiply(yc),this}assertValidity(){f(this)}equals(m){d(m);let{X:b,Y:y,Z:T}=this,{X:O,Y:R,Z:E}=m,I=c(b*E),w=c(O*T),v=c(y*E),V=c(R*T);return I===w&&v===V}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=i,{X:b,Y:y,Z:T}=this,O=c(b*b),R=c(y*y),E=c(yc*c(T*T)),I=c(m*O),w=b+y,v=c(c(w*w)-O-R),V=I+R,S=V-E,x=I-R,N=c(v*S),F=c(V*x),B=c(v*x),L=c(S*V);return new h(N,F,L,B)}add(m){d(m);let{a:b,d:y}=i,{X:T,Y:O,Z:R,T:E}=this,{X:I,Y:w,Z:v,T:V}=m,S=c(T*I),x=c(O*w),N=c(E*y*V),F=c(R*v),B=c((T+O)*(I+w)-S-x),L=F-N,A=F+N,C=c(x-b*S),P=c(B*L),D=c(A*C),M=c(B*C),te=c(L*A);return new h(P,D,te,M)}subtract(m){return this.add(m.negate())}multiply(m){if(!o.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:y}=_.cached(this,m,T=>ft(h,T));return ft(h,[b,y])[0]}multiplyUnsafe(m,b=h.ZERO){if(!o.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===Zr?h.ZERO:this.is0()||m===Ae?this:_.unsafe(this,m,y=>ft(h,y),b)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return _.unsafe(this,i.n).is0()}toAffine(m){return l(this,m)}clearCofactor(){return s===Ae?this:this.multiplyUnsafe(s)}toBytes(){let{x:m,y:b}=this.toAffine(),y=n.toBytes(b);return y[y.length-1]|=m&Ae?128:0,y}toHex(){return j(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(m){return ft(h,m)}static msm(m,b){return go(h,o,m,b)}_setWindowSize(m){this.precompute(m)}toRawBytes(){return this.toBytes()}}h.BASE=new h(i.Gx,i.Gy,Ae,c(i.Gx*i.Gy)),h.ZERO=new h(Zr,Ae,Ae,Zr),h.Fp=n,h.Fn=o;let _=new yo(h,o.BITS);return h.BASE.precompute(8),h}var Cs=class{constructor(t){this.ep=t}static fromBytes(t){mo()}static fromHex(t){mo()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return j(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.init(this.ep.precompute(t,r))}toRawBytes(){return this.toBytes()}};function ym(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Nr(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:i,Fn:s}=e,a=r.randomBytes||eo,c=r.adjustScalarBytes||(w=>w),u=r.domain||((w,v,V)=>{if(Hn(V,"phflag"),v.length||V)throw new Error("Contexts/pre-hash are not supported");return w});function p(w){return s.create(wr(w))}function d(w){let v=y.secretKey;w=de("private key",w,v);let V=de("hashed private key",t(w),2*v),S=c(V.slice(0,v)),x=V.slice(v,2*v),N=p(S);return{head:S,prefix:x,scalar:N}}function l(w){let{head:v,prefix:V,scalar:S}=d(w),x=o.multiply(S),N=x.toBytes();return{head:v,prefix:V,scalar:S,point:x,pointBytes:N}}function f(w){return l(w).pointBytes}function h(w=Uint8Array.of(),...v){let V=K(...v);return p(t(u(V,de("context",w),!!n)))}function _(w,v,V={}){w=de("message",w),n&&(w=n(w));let{prefix:S,scalar:x,pointBytes:N}=l(v),F=h(V.context,S,w),B=o.multiply(F).toBytes(),L=h(V.context,B,N,w),A=s.create(F+L*x);if(!s.isValid(A))throw new Error("sign failed: invalid s");let C=K(B,s.toBytes(A));return Hr(C,y.signature,"result")}let g={zip215:!0};function m(w,v,V,S=g){let{context:x,zip215:N}=S,F=y.signature;w=de("signature",w,F),v=de("message",v),V=de("publicKey",V,y.publicKey),N!==void 0&&Hn(N,"zip215"),n&&(v=n(v));let B=F/2,L=w.subarray(0,B),A=wr(w.subarray(B,F)),C,P,D;try{C=e.fromBytes(V,N),P=e.fromBytes(L,N),D=o.multiplyUnsafe(A)}catch{return!1}if(!N&&C.isSmallOrder())return!1;let M=h(x,P.toBytes(),C.toBytes(),v);return P.add(C.multiplyUnsafe(M)).subtract(D).clearCofactor().is0()}let b=i.BYTES,y={secretKey:b,publicKey:b,signature:2*b,seed:b};function T(w=a(y.seed)){return Hr(w,y.seed,"seed")}function O(w){let v=I.randomSecretKey(w);return{secretKey:v,publicKey:f(v)}}function R(w){return Lt(w)&&w.length===s.BYTES}function E(w,v){try{return!!e.fromBytes(w,v)}catch{return!1}}let I={getExtendedPublicKey:l,randomSecretKey:T,isValidSecretKey:R,isValidPublicKey:E,toMontgomery(w){let{y:v}=e.fromBytes(w),V=y.publicKey,S=V===32;if(!S&&V!==57)throw new Error("only defined for 25519 and 448");let x=S?i.div(Ae+v,Ae-v):i.div(v-Ae,v+Ae);return i.toBytes(x)},toMontgomerySecret(w){let v=y.secretKey;Hr(w,v);let V=t(w.subarray(0,v));return c(V).subarray(0,v)},randomPrivateKey:T,precompute(w=8,v=e.BASE){return v.precompute(w,!1)}};return Object.freeze({keygen:O,getPublicKey:f,sign:_,verify:m,utils:I,Point:e,lengths:y})}function gm(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=Ge(t.n,e.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:e.uvRatio},i={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:i}}function xm(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function sd(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=gm(e),i=_m(t,r),s=ym(i,n,o);return xm(e,s)}var bm=BigInt(0),Ir=BigInt(1),ad=BigInt(2),Lx=BigInt(3),wm=BigInt(5),Tm=BigInt(8),To=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),yi={p:To,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Tm,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Nm(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=To,a=e*e%i*e%i,c=Dt(a,ad,i)*a%i,u=Dt(c,Ir,i)*e%i,p=Dt(u,wm,i)*u%i,d=Dt(p,t,i)*p%i,l=Dt(d,r,i)*d%i,f=Dt(l,n,i)*l%i,h=Dt(f,o,i)*f%i,_=Dt(h,o,i)*f%i,g=Dt(_,t,i)*p%i;return{pow_p_5_8:Dt(g,ad,i)*e%i,b2:a}}function Om(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var gc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function wc(e,t){let r=To,n=ce(t*t*t,r),o=ce(n*n*t,r),i=Nm(e*o).pow_p_5_8,s=ce(e*n*i,r),a=ce(t*s*s,r),c=s,u=ce(s*gc,r),p=a===e,d=a===ce(-e,r),l=a===ce(-e*gc,r);return p&&(s=c),(d||l)&&(s=u),Or(s,r)&&(s=ce(-s,r)),{isValid:p||d,value:s}}var Xr=Ge(yi.p,{isLE:!0}),Em=Ge(yi.n,{isLE:!0}),Rm={...yi,Fp:Xr,hash:vl,adjustScalarBytes:Om,uvRatio:wc},We=sd(Rm);var xc=gc,vm=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Im=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Am=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Sm=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),cd=e=>wc(Ir,e),Cm=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),bc=e=>We.Point.Fp.create(wr(e)&Cm);function ld(e){let{d:t}=yi,r=To,n=m=>Xr.create(m),o=n(xc*e*e),i=n((o+Ir)*Am),s=BigInt(-1),a=n((s-t*o)*n(o+t)),{isValid:c,value:u}=wc(i,a),p=n(u*e);Or(p,r)||(p=n(-p)),c||(u=p),c||(s=o);let d=n(s*(o-Ir)*Sm-a),l=u*u,f=n((u+u)*a),h=n(d*vm),_=n(Ir-l),g=n(Ir+l);return new We.Point(n(f*g),n(_*h),n(h*g),n(f*_))}function Fm(e){fe(e,64);let t=bc(e.subarray(0,32)),r=ld(t),n=bc(e.subarray(32,64)),o=ld(n);return new Ar(r.add(o))}var Ar=class e extends Cs{constructor(t){super(t)}static fromAffine(t){return new e(We.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return Fm(de("ristrettoHash",t,64))}static fromBytes(t){fe(t,32);let{a:r,d:n}=yi,o=To,i=T=>Xr.create(T),s=bc(t);if(!xu(Xr.toBytes(s),t)||Or(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(Ir+r*a),u=i(Ir-r*a),p=i(c*c),d=i(u*u),l=i(r*n*p-d),{isValid:f,value:h}=cd(i(l*d)),_=i(h*u),g=i(h*_*l),m=i((s+s)*_);Or(m,o)&&(m=i(-m));let b=i(c*g),y=i(m*b);if(!f||Or(y,o)||b===bm)throw new Error("invalid ristretto255 encoding 2");return new e(new We.Point(m,b,Ir,y))}static fromHex(t){return e.fromBytes(de("ristrettoHex",t,32))}static msm(t,r){return go(e,We.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,i=To,s=g=>Xr.create(g),a=s(s(n+r)*s(n-r)),c=s(t*r),u=s(c*c),{value:p}=cd(s(a*u)),d=s(p*a),l=s(p*c),f=s(d*l*o),h;if(Or(o*f,i)){let g=s(r*xc),m=s(t*xc);t=g,r=m,h=s(d*Im)}else h=l;Or(t*f,i)&&(r=s(-r));let _=s((n-r)*h);return Or(_,i)&&(_=s(-_)),Xr.toBytes(_)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:i}=t.ep,s=u=>Xr.create(u),a=s(r*i)===s(n*o),c=s(n*i)===s(r*o);return a||c}is0(){return this.equals(e.ZERO)}};Ar.BASE=new Ar(We.Point.BASE);Ar.ZERO=new Ar(We.Point.ZERO);Ar.Fp=Xr;Ar.Fn=Em;var ud,dd,Fs=class{static{ud=Symbol.iterator,dd=Symbol.toStringTag}#e;#t;constructor(t={}){this[ud]=this.entries.bind(this),this[dd]="ExpirableMap";let{source:r=[],expirationTime:n=600*1e3}=t,o=Date.now();this.#e=new Map([...r].map(([i,s])=>[i,{value:s,timestamp:o}])),this.#t=n}prune(){let t=Date.now();for(let[r,n]of this.#e.entries())t-n.timestamp>this.#t&&this.#e.delete(r);return this}set(t,r){this.prune();let n={value:r,timestamp:Date.now()};return this.#e.set(t,n),this}get(t){let r=this.#e.get(t);if(r!==void 0){if(Date.now()-r.timestamp>this.#t){this.#e.delete(t);return}return r.value}}clear(){this.#e.clear()}entries(){let t=this.#e.entries();return function*(){for(let[n,o]of t)yield[n,o.value]}()}values(){let t=this.#e.values();return function*(){for(let n of t)yield n.value}()}keys(){return this.#e.keys()}forEach(t,r){for(let[n,o]of this.#e.entries())t.call(r,o.value,n,this)}has(t){return this.#e.has(t)}delete(t){return this.#e.delete(t)}get size(){return this.#e.size}};var pd=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw Y.fromCode(new Lo("Length too long (> 4 bytes)"))},fd=(e,t,r)=>{if(r<=127)return e[t]=r,1;if(r<=255)return e[t]=129,e[t+1]=r,2;if(r<=65535)return e[t]=130,e[t+1]=r>>8,e[t+2]=r,3;if(r<=16777215)return e[t]=131,e[t+1]=r>>16,e[t+2]=r>>8,e[t+3]=r,4;throw Y.fromCode(new Lo("Length too long (> 4 bytes)"))},Tc=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw Y.fromCode(new At("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw Y.fromCode(new At("Length too long (> 4 bytes)"))},Vm=(e,t)=>{let r=Tc(e,t);if(r===1)return e[t];if(r===2)return e[t+1];if(r===3)return(e[t+1]<<8)+e[t+2];if(r===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw Y.fromCode(new At("Length too long (> 4 bytes)"))},gi=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),zn=Uint8Array.from([48,5,6,3,43,101,112]),Hx=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),Gx=Uint8Array.from([48,29,6,13,43,6,1,4,1,130,220,124,5,3,1,2,1,6,12,43,6,1,4,1,130,220,124,5,3,2,1]);function Yn(e,t){let r=2+pd(e.byteLength+1),n=t.byteLength+r+e.byteLength,o=0,i=new Uint8Array(1+pd(n)+n);return i[o++]=48,o+=fd(i,o,n),i.set(t,o),o+=t.byteLength,i[o++]=3,o+=fd(i,o,e.byteLength+1),i[o++]=0,i.set(new Uint8Array(e),o),i}var Zn=(e,t)=>{let r=0,n=(a,c)=>{if(o[r++]!==a)throw Y.fromCode(new At(`Expected ${c} at offset ${r}`))},o=new Uint8Array(e);if(n(48,"sequence"),r+=Tc(o,r),!Mn(o.slice(r,r+t.byteLength),t))throw Y.fromCode(new At("Not the expected OID."));r+=t.byteLength,n(3,"bit string");let i=Vm(o,r)-1;r+=Tc(o,r),n(0,"0 padding");let s=o.slice(r);if(i!==s.length)throw Y.fromCode(new ji(i,s.length));return s};var Vs=class e{static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(t){return Yn(t,zn)}static derDecode(t){let r=Zn(t,zn);if(r.length!==this.RAW_KEY_LENGTH)throw Y.fromCode(new At("An Ed25519 public key must be exactly 32 bytes long"));return r}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw Y.fromCode(new At("An Ed25519 public key must be exactly 32 bytes long"));this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}};var Nc=class{constructor(){this.observers=[]}subscribe(t){this.observers.push(t)}unsubscribe(t){this.observers=this.observers.filter(r=>r!==t)}notify(t,...r){this.observers.forEach(n=>n(t,...r))}},Ps=class extends Nc{constructor(){super()}print(t,...r){this.notify({message:t,level:"info"},...r)}warn(t,...r){this.notify({message:t,level:"warn"},...r)}error(t,r,...n){this.notify({message:t,level:"error",error:r},...n)}};var Bs=class e{#e;#t;#r;#i;#a;#d;#n;#o;#c=0;static{this.default={initialInterval:500,randomizationFactor:.5,multiplier:1.5,maxInterval:6e4,maxElapsedTime:9e5,maxIterations:10,date:Date}}constructor(t=e.default){let{initialInterval:r=500,randomizationFactor:n=.5,multiplier:o=1.5,maxInterval:i=6e4,maxElapsedTime:s=9e5,maxIterations:a=10,date:c=Date}=t;this.#e=r,this.#t=n,this.#r=o,this.#i=i,this.#o=c,this.#a=c.now(),this.#d=s,this.#n=a}get ellapsedTimeInMsec(){return this.#o.now()-this.#a}get currentInterval(){return this.#e}get count(){return this.#c}get randomValueFromInterval(){let t=this.#t*this.#e,r=this.#e-t,n=this.#e+t;return Math.random()*(n-r)+r}incrementCurrentInterval(){return this.#e=Math.min(this.#e*this.#r,this.#i),this.#c++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#d||this.#c>=this.#n?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};var Jt;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(Jt||(Jt={}));var Rc=60*1e3,Pm=1e6,Bm=0,Dm="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";var Um="ic0.app",km=".ic0.app",Lm="icp0.io",qm=".icp0.io",Mm="icp-api.io",jm=".icp-api.io",Oc=200,Km=202,Hm=404;function Gm(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw me.fromCode(new no("Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present."));else if(typeof global<"u")if(global.fetch)e=global.fetch.bind(global);else throw me.fromCode(new no("Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available."));else typeof self<"u"&&self.fetch&&(e=self.fetch.bind(self));if(e)return e;throw me.fromCode(new no("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function $m(e){let t;if(e!==void 0)!e.match(/^[a-z]+:/)&&typeof window<"u"?t=new URL(window.location.protocol+"//"+e):t=new URL(e);else{let r=["ic0.app","icp0.io","127.0.0.1","localhost"],n=[".github.dev",".gitpod.io"],o=typeof window<"u"?window.location:void 0,i=o?.hostname,s;i&&typeof i=="string"&&(n.some(a=>i.endsWith(a))?s=i:s=r.find(a=>i.endsWith(a))),o&&s?t=new URL(`${o.protocol}//${s}${o.port?":"+o.port:""}`):t=new URL("https://icp-api.io")}return t.toString()}var Sr=class e{#e;#t;#r;#i;#a;#d;#n;#o;#c;#w;#s;#u;#f;#l;get#E(){return this.#l*Rc}#h;#m;#_;#y;constructor(t={}){this.#e=null,this.#t=!1,this.#r=Bm,this.#i=!1,this.#a=null,this.#d=!1,this._isAgent=!0,this.config={},this.log=new Ps,this.#h=[],this.#m=[],this.#_=new Fs({expirationTime:5*Rc}),this.#y=!0,this.#T=(o,i)=>{if(this.#y===!1)return o;let{status:s,signatures:a=[],requestId:c}=o;for(let u of a){let{timestamp:p,identity:d}=u,l=k.fromUint8Array(d).toText(),f;if(s===Pr.Replied){let{reply:b}=o;f=Zo({status:s,reply:b,timestamp:BigInt(p),request_id:c})}else if(s===Pr.Rejected){let{reject_code:b,reject_message:y,error_code:T}=o;f=Zo({status:s,reject_code:b,reject_message:y,error_code:T,timestamp:BigInt(p),request_id:c})}else throw ae.fromCode(new Re(`Unknown status: ${s}`));let h=K(Fa,f),_=i.get(l);if(!_)throw ee.fromCode(new Qi);let g=Vs.fromDer(_).rawKey;if(!We.verify(u.signature,h,g))throw Me.fromCode(new es(l))}return o},this.config=t,this.#o=t.fetch||Gm()||fetch.bind(global),this.#c=t.fetchOptions,this.#w=t.callOptions,this.#t=t.shouldFetchRootKey??!1,this.#d=t.shouldSyncTime??!1,t.rootKey?this.rootKey=t.rootKey:this.#t?this.rootKey=null:this.rootKey=Ee(Dm);let r=$m(t.host);this.host=new URL(r),t.verifyQuerySignatures!==void 0&&(this.#y=t.verifyQuerySignatures),this.#u=t.retryTimes??3;let n=()=>new Bs({maxIterations:this.#u});if(this.#f=t.backoffStrategy||n,this.host.hostname.endsWith(km)?this.host.hostname=Um:this.host.hostname.endsWith(qm)?this.host.hostname=Lm:this.host.hostname.endsWith(jm)&&(this.host.hostname=Mm),t.credentials){let{name:o,password:i}=t.credentials;this.#s=`${o}${i?":"+i:""}`}if(this.#n=Promise.resolve(t.identity||new it),t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes>5)throw Y.fromCode(new Mt("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw Y.fromCode(new Mt("Ingress expiry time must be greater than 0.",t.ingressExpiryInMinutes));this.#l=t.ingressExpiryInMinutes||5,this.addTransform("update",La(ii)),t.useQueryNonces&&this.addTransform("query",La(ii)),t.logToConsole&&this.log.subscribe(o=>{o.level==="error"?console.error(o.message):o.level==="warn"?console.warn(o.message):console.log(o.message)})}static createSync(t={}){return new this({...t})}static async create(t={}){let r=e.createSync(t);return await r.#p(),r}static async from(t){try{return"config"in t?await e.create(t.config):await e.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw Y.fromCode(new Yi)}}isLocal(){let t=this.host.hostname;return t==="127.0.0.1"||t.endsWith("127.0.0.1")}addTransform(t,r,n=r.priority||0){if(t==="update"){let o=this.#m.findIndex(i=>(i.priority||0)<n);this.#m.splice(o>=0?o:this.#m.length,0,Object.assign(r,{priority:n}))}else if(t==="query"){let o=this.#h.findIndex(i=>(i.priority||0)<n);this.#h.splice(o>=0?o:this.#h.length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this.#n)throw me.fromCode(new Lr);return(await this.#n).getPrincipal()}async call(t,r,n){let o=r.callSync??!0,i=await(n??this.#n);if(!i)throw me.fromCode(new Lr);let s=k.from(t),a=r.effectiveCanisterId?k.from(r.effectiveCanisterId):s;await this.#p(a);let c=i.getPrincipal(),u=Ec(this.#l,this.#r),p={request_type:hs.Call,canister_id:s,method_name:r.methodName,arg:r.arg,sender:c,ingress_expiry:u},d=await this._transform({request:{body:null,method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:br.Call,body:p}),l;r?.nonce?l=f(r.nonce):d.body.nonce?l=f(d.body.nonce):l=void 0,p.nonce=l;function f(m){return Object.assign(m,{__nonce__:void 0})}d=await i.transformRequest(d);let h=ni(d.body),_=this.#f(),g=gr(p);try{let y=o?()=>{let E=new URL(`/api/v4/canister/${a.toText()}/call`,this.host);return this.log.print(`fetching "${E.pathname}" with request:`,d),this.#o(E,{...this.#w,...d.request,body:h})}:()=>{let E=new URL(`/api/v2/canister/${a.toText()}/call`,this.host);return this.log.print(`fetching "${E.pathname}" with request:`,d),this.#o(E,{...this.#w,...d.request,body:h})},{responseBodyBytes:T,...O}=await this.#g({requestFn:y,backoff:_,tries:0}),R=T.byteLength>0?Ke(T):null;return{requestId:g,response:{...O,body:R},requestDetails:p}}catch(m){let b;if(m instanceof ot){if(m.hasCode(Mo))return this.log.warn("v4 api not supported. Fall back to v2"),this.call(t,{...r,callSync:!1},n);if(m.hasCode(Mt)&&!this.#i)return await this.syncTime(s),this.call(s,r,n);m.code.requestContext={requestId:g,senderPubKey:d.body.sender_pubkey,senderSignature:d.body.sender_sig,ingressExpiry:d.body.content.ingress_expiry},b=m}else b=ae.fromCode(new Re(m));throw this.log.error(`Error while making call: ${b.message}`,b),b}}async#b(t){let{ecid:r,transformedRequest:n,body:o,requestId:i,backoff:s,tries:a}=t,c=a===0?0:s.next(),u=new URL(`/api/v3/canister/${r.toString()}/query`,this.host);if(this.log.print(`fetching "${u.pathname}" with tries:`,{tries:a,backoff:s,delay:c}),c===null)throw ae.fromCode(new Dn(`Backoff strategy exhausted after ${a} attempts.`,i));c>0&&await new Promise(m=>setTimeout(m,c));let p;try{this.log.print(`fetching "${u.pathname}" with request:`,n),p=await this.#o(u,{...this.#c,...n.request,body:o})}catch(m){if(a<this.#u)return this.log.warn(`Caught exception while attempting to make query:
50
+ `)}return a.encodeValue(c)}));return X(Rh,n,o,i,s)}function Ih(e,t){let r=new Vt(t);if(t.byteLength<bs.length)throw new Error("Message length smaller than magic number");let n=Zr(r,bs.length),o=new TextDecoder().decode(n);if(o!==bs)throw new Error(`Wrong magic number: ${JSON.stringify(o)}`);function i(u){let f=[],h=Number(_e(u));for(let m=0;m<h;m++){let b=Number(Nr(u));switch(b){case ee.Opt:case ee.Vector:{let g=Number(Nr(u));f.push([b,g]);break}case ee.Record:case ee.Variant:{let g=[],T=Number(_e(u)),O;for(;T--;){let v=Number(_e(u));if(v>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof O=="number"&&O>=v)throw new Error("field id collision or not sorted");O=v;let E=Number(Nr(u));g.push([v,E])}f.push([b,g]);break}case ee.Func:{let g=[],T=Number(_e(u));for(;T--;)g.push(Number(Nr(u)));let O=[],v=Number(_e(u));for(;v--;)O.push(Number(Nr(u)));let E=[],C=Number(_e(u));for(;C--;)switch(Number(_e(u))){case 1:{E.push("query");break}case 2:{E.push("oneway");break}case 3:{E.push("composite_query");break}default:throw new Error("unknown annotation")}f.push([b,[g,O,E]]);break}case ee.Service:{let g=Number(_e(u)),T=[];for(;g--;){let O=Number(_e(u)),v=new TextDecoder().decode(Zr(u,O)),E=Nr(u);T.push([v,E])}f.push([b,T]);break}default:throw new Error(`Illegal op_code: ${b}`)}}let _=[],y=Number(_e(u));for(let m=0;m<y;m++)_.push(Number(Nr(u)));return[f,_]}let[s,a]=i(r);if(a.length<e.length)throw new Error("Wrong number of return values");let c=s.map(u=>Uu());function l(u){if(u<-24)throw new Error("future value not supported");if(u<0)switch(u){case-1:return yu;case-2:return _u;case-3:return bu;case-4:return xu;case-5:return vu;case-6:return Iu;case-7:return Au;case-8:return Su;case-9:return Nu;case-10:return Ou;case-11:return Eu;case-12:return Ru;case-13:return wu;case-14:return Tu;case-15:return gu;case-16:return mu;case-17:return hu;case-24:return Cu;default:throw new Error(`Illegal op_code: ${u}`)}if(u>=s.length)throw new Error("type index out of range");return c[u]}function d(u){switch(u[0]){case ee.Vector:{let f=l(u[1]);return Pu(f)}case ee.Opt:{let f=l(u[1]);return Fu(f)}case ee.Record:{let f={};for(let[y,m]of u[1]){let b=`_${y}_`;f[b]=l(m)}let h=Bu(f),_=h.tryAsTuple();return Array.isArray(_)?Vu(..._):h}case ee.Variant:{let f={};for(let[h,_]of u[1]){let y=`_${h}_`;f[y]=l(_)}return Du(f)}case ee.Func:{let[f,h,_]=u[1];return ku(f.map(y=>l(y)),h.map(y=>l(y)),_)}case ee.Service:{let f={},h=u[1];for(let[_,y]of h){let m=l(y);if(m instanceof ht&&(m=m.getType()),!(m instanceof Hn))throw new Error("Illegal service definition: services can only contain functions");f[_]=m}return Lu(f)}default:throw new Error(`Illegal op_code: ${u[0]}`)}}s.forEach((u,f)=>{if(u[0]===ee.Func){let h=d(u);c[f].fill(h)}}),s.forEach((u,f)=>{if(u[0]!==ee.Func){let h=d(u);c[f].fill(h)}}),rc();let p=a.map(u=>l(u));try{let u=e.map((f,h)=>f.decodeValue(r,p[h]));for(let f=e.length;f<p.length;f++)p[f].decodeValue(r,p[f]);if(r.byteLength>0)throw new Error("decode: Left-over bytes");return u}finally{rc()}}var hu=new ti,mu=new Wt,Ah=new Ts,_u=new Ns,yu=new Kn,gu=new Os,xu=new ri,bu=new ni,wu=new oi(32),Tu=new oi(64),Nu=new Er(8),Ou=new Er(16),Eu=new Er(32),Ru=new Er(64),vu=new Gt(8),Iu=new Gt(16),Au=new Gt(32),Su=new Gt(64),Cu=new Rs;function Vu(...e){return new Es(e)}function Pu(e){return new ho(e)}function Fu(e){return new Xr(e)}function Bu(e){return new $n(e)}function Du(e){return new mo(e)}function Uu(){return new ht}function ku(e,t,r=[]){return new Hn(e,t,r)}function Lu(e){return new _o(e)}var vs=class e{constructor(t=new Map){this.rels=t}copy(){let t=new Map;for(let[r,n]of this.rels.entries()){let o=new Map(n);t.set(r,o)}return new e(t)}known(t,r){return this.rels.get(t.name)?.get(r.name)}addNegative(t,r){this.addNames(t.name,r.name,!1)}add(t,r){this.addNames(t.name,r.name,!0)}display(){let t="";for(let[r,n]of this.rels)for(let[o,i]of n)t+=`${r} ${i?":<":"!<:"} ${o}
51
+ `;return t}addNames(t,r,n){let o=this.rels.get(t);if(o==null){let i=new Map;i.set(r,n),this.rels.set(t,i)}else o.set(r,n)}},ws=new vs;function rc(){ws=new vs}function Sh(e,t){let r=new Set(e.annotations),n=new Set(t.annotations);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o))return!1;return!0}function Qa(e){return e instanceof Xr||e instanceof Kn||e instanceof Wt}function oc(e,t){let r=ws.copy(),n=Or(r,e,t);return n?ws.add(e,t):ws.addNegative(e,t),n}function Or(e,t,r){if(t.name===r.name)return!0;let n=e.known(t,r);if(n!==void 0)return n;if(e.add(t,r),r instanceof Wt||t instanceof ti||t instanceof ni&&r instanceof ri)return!0;if(t instanceof ho&&r instanceof ho)return Or(e,t._type,r._type);if(r instanceof Xr)return!0;if(t instanceof $n&&r instanceof $n){let o=t.fieldsAsObject;for(let[i,s]of r._fields){let a=o[Me(i)];if(a){if(!Or(e,a,s))return!1}else if(!Qa(s))return!1}return!0}if(t instanceof Hn&&r instanceof Hn){if(!Sh(t,r))return!1;for(let o=0;o<t.argTypes.length;o++){let i=t.argTypes[o];if(o<r.argTypes.length){if(!Or(e,r.argTypes[o],i))return!1}else if(!Qa(i))return!1}for(let o=0;o<r.retTypes.length;o++){let i=r.retTypes[o];if(o<t.retTypes.length){if(!Or(e,t.retTypes[o],i))return!1}else if(!Qa(i))return!1}return!0}if(t instanceof mo&&r instanceof mo){let o=r.alternativesAsObject;for(let[i,s]of t._fields){let a=o[Me(i)];if(!a||!Or(e,s,a))return!1}return!0}if(t instanceof _o&&r instanceof _o){let o=t.fieldsAsObject();for(let[i,s]of r._fields){let a=o[i];if(!a||!Or(e,a,s))return!1}return!0}return t instanceof ht?Or(e,t.getType(),r):r instanceof ht?Or(e,t,r.getType()):!1}function yo(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?yo(e.buffer):new Uint8Array(e)}function Jn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function ic(e){if(typeof e=="string")return qu(e);if(typeof e=="number")return Ve(oe(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return Ve(yo(e));if(Array.isArray(e)){let t=e.map(ic);return Ve($(...t))}if(e&&typeof e=="object"&&e._isPrincipal)return Ve(e.toUint8Array());if(typeof e=="object"&&e!==null&&typeof e.toHash=="function")return ic(e.toHash());if(typeof e=="object")return ii(e);if(typeof e=="bigint")return Ve(oe(e));throw z.fromCode(new us(e))}var qu=e=>{let t=new TextEncoder().encode(e);return Ve(t)};function Rr(e){return ii(e)}function ii(e){let n=Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>{let c=qu(s),l=ic(a);return[c,l]}).sort(([s],[a])=>po(s,a)),o=$(...n.map(s=>$(...s)));return Ve(o)}var sc=new TextEncoder().encode("\ric-state-root"),si=new TextEncoder().encode(`
52
+ ic-request`),ac=new TextEncoder().encode("\vic-response"),cc=new TextEncoder().encode("ic-request-auth-delegation");var zt=class{getPrincipal(){return this._principal||(this._principal=q.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(t){let{body:r,...n}=t,o=Rr(r);return{...n,body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign($(si,o))}}}},at=class{getPrincipal(){return q.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}};var vr=class extends Error{constructor(t){super(t),this.name="DecodingError"}},ju=55799,Ku=Symbol("CBOR_STOP_CODE"),Bt=(e=>(e[e.False=20]="False",e[e.True=21]="True",e[e.Null=22]="Null",e[e.Undefined=23]="Undefined",e[e.Break=31]="Break",e))(Bt||{}),Ne=(e=>(e[e.UnsignedInteger=0]="UnsignedInteger",e[e.NegativeInteger=1]="NegativeInteger",e[e.ByteString=2]="ByteString",e[e.TextString=3]="TextString",e[e.Array=4]="Array",e[e.Map=5]="Map",e[e.Tag=6]="Tag",e[e.Simple=7]="Simple",e))(Ne||{}),Ch=23,Vh=255,Ph=65535,Fh=4294967295,Bh=BigInt("0xffffffffffffffff"),Ft=(e=>(e[e.Value=23]="Value",e[e.OneByte=24]="OneByte",e[e.TwoBytes=25]="TwoBytes",e[e.FourBytes=26]="FourBytes",e[e.EightBytes=27]="EightBytes",e[e.Indefinite=31]="Indefinite",e))(Ft||{}),go=!1;function Dh(e){return e==null}function $u(e,t){let r=new Uint8Array(t);return r.set(e),r}var Uh=new TextDecoder;function kh(e){return(e&224)>>5}function Lh(e){return e&31}var li=new Uint8Array,ai,Dt=0;function Hu(e,t){li=e,Dt=0;let r=Wn(t);return t?.(r)??r}function Wn(e){let[t,r]=Is();switch(t){case Ne.UnsignedInteger:return xo(r);case Ne.NegativeInteger:return Kh(r);case Ne.ByteString:return Gu(r);case Ne.TextString:return uc(r);case Ne.Array:return qh(r,e);case Ne.Map:return jh(r,e);case Ne.Tag:return $h(r,e);case Ne.Simple:return Mh(r)}throw new vr(`Unsupported major type: ${t}`)}function Is(){let e=li.at(Dt);if(Dh(e))throw new vr("Provided CBOR data is empty");let t=kh(e),r=Lh(e);return Dt++,[t,r]}function qh(e,t){let r=xo(e);if(r===1/0){let o=[],i=Wn(t);for(;i!==Ku;)o.push(t?.(i)??i),i=Wn(t);return o}let n=new Array(r);for(let o=0;o<r;o++){let i=Wn(t);n[o]=t?.(i)??i}return n}function Mh(e){switch(e){case Bt.False:return!1;case Bt.True:return!0;case Bt.Null:return null;case Bt.Undefined:return;case Bt.Break:return Ku}throw new vr(`Unrecognized simple type: ${e.toString(2)}`)}function jh(e,t){let r=xo(e),n={};if(r===1/0){let[o,i]=Is();for(;o!==Ne.Simple&&i!==Bt.Break;){let s=uc(i),a=Wn(t);n[s]=t?.(a,s)??a,[o,i]=Is()}return n}for(let o=0;o<r;o++){let[i,s]=Is();if(i!==Ne.TextString)throw new vr("Map keys must be text strings");let a=uc(s),c=Wn(t);n[a]=t?.(c,a)??c}return n}function xo(e){if(e<=Ft.Value)return e;switch(ai=new DataView(li.buffer,li.byteOffset+Dt),e){case Ft.OneByte:return Dt++,ai.getUint8(0);case Ft.TwoBytes:return Dt+=2,ai.getUint16(0,go);case Ft.FourBytes:return Dt+=4,ai.getUint32(0,go);case Ft.EightBytes:return Dt+=8,ai.getBigUint64(0,go);case Ft.Indefinite:return 1/0;default:throw new vr(`Unsupported integer info: ${e.toString(2)}`)}}function Kh(e){let t=xo(e);return typeof t=="number"?-1-t:-1n-t}function Gu(e){let t=xo(e);if(t>Number.MAX_SAFE_INTEGER)throw new vr("Byte length is too large");let r=Number(t);return Dt+=r,li.slice(Dt-r,Dt)}function uc(e){let t=Gu(e);return Uh.decode(t)}function $h(e,t){let r=xo(e);if(r===ju)return Wn(t);throw new vr(`Unsupported tag: ${r}.`)}var ui=class extends Error{constructor(t){super(t),this.name="SerializationError"}},Hh=2*1024,Gh=100,Jh=new TextEncoder;function ci(e){return e<<5}var ct=new Uint8Array(Hh),Pt=new DataView(ct.buffer),Te=0,lc=[];function Ju(e,t){Te=0;let r=t?.(e)??e;return tm(ju,r,t),ct.slice(0,Te)}function dc(e,t){if(Te>ct.length-Gh&&(ct=$u(ct,ct.length*2),Pt=new DataView(ct.buffer)),e===!1||e===!0||e===null||e===void 0){Yh(e);return}if(typeof e=="number"||typeof e=="bigint"){em(e);return}if(typeof e=="string"){Yu(e);return}if(e instanceof Uint8Array){Mu(e);return}if(e instanceof ArrayBuffer){Mu(new Uint8Array(e));return}if(Array.isArray(e)){Wh(e,t);return}if(typeof e=="object"){zh(e,t);return}throw new ui(`Unsupported type: ${typeof e}`)}function Wh(e,t){bo(Ne.Array,e.length),e.forEach((r,n)=>{dc(t?.(r,n.toString())??r,t)})}function zh(e,t){lc=Object.entries(e),bo(Ne.Map,lc.length),lc.forEach(([r,n])=>{Yu(r),dc(t?.(n,r)??n,t)})}function bo(e,t){if(t<=Ch){Pt.setUint8(Te++,ci(e)|Number(t));return}if(t<=Vh){Pt.setUint8(Te++,ci(e)|Ft.OneByte),Pt.setUint8(Te,Number(t)),Te+=1;return}if(t<=Ph){Pt.setUint8(Te++,ci(e)|Ft.TwoBytes),Pt.setUint16(Te,Number(t),go),Te+=2;return}if(t<=Fh){Pt.setUint8(Te++,ci(e)|Ft.FourBytes),Pt.setUint32(Te,Number(t),go),Te+=4;return}if(t<=Bh){Pt.setUint8(Te++,ci(e)|Ft.EightBytes),Pt.setBigUint64(Te,BigInt(t),go),Te+=8;return}throw new ui(`Value too large to encode: ${t}`)}function Yh(e){bo(Ne.Simple,Zh(e))}function Zh(e){if(e===!1)return Bt.False;if(e===!0)return Bt.True;if(e===null)return Bt.Null;if(e===void 0)return Bt.Undefined;throw new ui(`Unrecognized simple value: ${e.toString()}`)}function Wu(e,t){bo(e,t.length),Te>ct.length-t.length&&(ct=$u(ct,ct.length+t.length),Pt=new DataView(ct.buffer)),ct.set(t,Te),Te+=t.length}function zu(e,t){bo(e,t)}function Xh(e){zu(Ne.UnsignedInteger,e)}function Qh(e){zu(Ne.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function em(e){e>=0?Xh(e):Qh(e)}function Yu(e){Wu(Ne.TextString,Jh.encode(e))}function Mu(e){Wu(Ne.ByteString,e)}function tm(e,t,r){bo(Ne.Tag,e),dc(t,r)}var di="__expiry__",pc=BigInt(1e3),nm=BigInt(1e6),om=BigInt(60),fc=om*pc,im=BigInt(1)*fc;function sm(e){return e/pc*pc}function am(e){return e/fc*fc}var zn=class e{constructor(t){this.__expiry__=t,this._isExpiry=!0}static fromDeltaInMilliseconds(t,r=0){let n=BigInt(Date.now())+BigInt(r),o=n+BigInt(t),i=am(o),s;return i>=n+im?s=i:s=sm(o),new e(s*nm)}toBigInt(){return this.__expiry__}toHash(){return oe(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[di]:this.toString()}}static fromJSON(t){let r=JSON.parse(t);if(r[di])try{let n=BigInt(r[di]);return new e(n)}catch(n){throw new z(new Xo(`Not a valid BigInt: ${n}`))}throw new z(new Xo(`The input does not contain the key ${di}`))}static isExpiry(t){return t instanceof e||typeof t=="object"&&t!==null&&"_isExpiry"in t&&t._isExpiry===!0&&"__expiry__"in t&&typeof t.__expiry__=="bigint"}};function cm(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function pi(e){try{return Ju(e,t=>q.isPrincipal(t)?t.toUint8Array():zn.isExpiry(t)?t.toBigInt():cm(t)?t.toCborValue():t)}catch(t){throw z.fromCode(new os(t,e))}}function je(e){try{return Hu(e)}catch(t){throw z.fromCode(new ns(t,e))}}var As={encode:pi,decode:je};var fi=()=>{if(typeof window<"u"&&window.crypto&&window.crypto.getRandomValues){let e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return typeof crypto<"u"&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)};var Ir;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(Ir||(Ir={}));var Cs;(function(e){e.Call="call"})(Cs||(Cs={}));var Yn;(function(e){e.Query="query",e.ReadState="read_state"})(Yn||(Yn={}));var lt;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(lt||(lt={}));function hi(){let e=new ArrayBuffer(16),t=new DataView(e),r=fi(),n=fi(),o=fi(),i=fi();return t.setUint32(0,r),t.setUint32(4,n),t.setUint32(8,o),t.setUint32(12,i),Object.assign(new Uint8Array(e),{__nonce__:void 0})}function hc(e=hi){return async t=>{let r=t.request.headers;t.request.headers=r,t.endpoint===Ir.Call&&(t.body.nonce=e())}}function mc(e){let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t}var yc=BigInt(0),Vs=BigInt(1);function Zn(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function Qr(e,t,r=""){let n=jt(e),o=e?.length,i=t!==void 0;if(!n||i&&o!==t){let s=r&&`"${r}" `,a=i?` of length ${t}`:"",c=n?`length=${o}`:`type=${typeof e}`;throw new Error(s+"expected Uint8Array"+a+", got "+c)}return e}function Zu(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?yc:BigInt("0x"+e)}function Qe(e){return Zu(j(e))}function Ar(e){return fe(e),Zu(j(Uint8Array.from(e).reverse()))}function Oe(e,t){return Ee(e.toString(16).padStart(t*2,"0"))}function gc(e,t){return Oe(e,t).reverse()}function de(e,t,r){let n;if(typeof t=="string")try{n=Ee(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(jt(t))n=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(e+" of length "+r+" expected, got "+o);return n}function Xu(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e[n]^t[n];return r===0}function xc(e){return Uint8Array.from(e)}var _c=e=>typeof e=="bigint"&&yc<=e;function bc(e,t,r){return _c(e)&&_c(t)&&_c(r)&&t<=e&&e<r}function Ps(e,t,r,n){if(!bc(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function Sr(e){let t;for(t=0;e>yc;e>>=Vs,t+=1);return t}function Qu(e,t){return e>>BigInt(t)&Vs}var Ut=e=>(Vs<<BigInt(e))-Vs;function ed(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function Cr(e,t,r={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(o,i,s){let a=e[o];if(s&&a===void 0)return;let c=typeof a;if(c!==i||a===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${c}`)}Object.entries(t).forEach(([o,i])=>n(o,i,!1)),Object.entries(r).forEach(([o,i])=>n(o,i,!0))}var wo=()=>{throw new Error("not implemented")};function en(e){let t=new WeakMap;return(r,...n)=>{let o=t.get(r);if(o!==void 0)return o;let i=e(r,...n);return t.set(r,i),i}}var Ke=BigInt(0),Re=BigInt(1),Xn=BigInt(2),rd=BigInt(3),nd=BigInt(4),od=BigInt(5),lm=BigInt(7),id=BigInt(8),um=BigInt(9),sd=BigInt(16);function ce(e,t){let r=e%t;return r>=Ke?r:t+r}function kt(e,t,r){let n=e;for(;t-- >Ke;)n*=n,n%=r;return n}function td(e,t){if(e===Ke)throw new Error("invert: expected non-zero number");if(t<=Ke)throw new Error("invert: expected positive modulus, got "+t);let r=ce(e,t),n=t,o=Ke,i=Re,s=Re,a=Ke;for(;r!==Ke;){let l=n/r,d=n%r,p=o-s*l,u=i-a*l;n=r,r=d,o=s,i=a,s=p,a=u}if(n!==Re)throw new Error("invert: does not exist");return ce(o,t)}function wc(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function ad(e,t){let r=(e.ORDER+Re)/nd,n=e.pow(t,r);return wc(e,n,t),n}function dm(e,t){let r=(e.ORDER-od)/id,n=e.mul(t,Xn),o=e.pow(n,r),i=e.mul(t,o),s=e.mul(e.mul(i,Xn),o),a=e.mul(i,e.sub(s,e.ONE));return wc(e,a,t),a}function pm(e){let t=$e(e),r=cd(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+lm)/sd;return(a,c)=>{let l=a.pow(c,s),d=a.mul(l,n),p=a.mul(l,o),u=a.mul(l,i),f=a.eql(a.sqr(d),c),h=a.eql(a.sqr(p),c);l=a.cmov(l,d,f),d=a.cmov(u,p,h);let _=a.eql(a.sqr(d),c),y=a.cmov(l,d,_);return wc(a,y,c),y}}function cd(e){if(e<rd)throw new Error("sqrt is not defined for small field");let t=e-Re,r=0;for(;t%Xn===Ke;)t/=Xn,r++;let n=Xn,o=$e(e);for(;mi(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return ad;let i=o.pow(n,t),s=(t+Re)/Xn;return function(c,l){if(c.is0(l))return l;if(mi(c,l)!==1)throw new Error("Cannot find square root");let d=r,p=c.mul(c.ONE,i),u=c.pow(l,t),f=c.pow(l,s);for(;!c.eql(u,c.ONE);){if(c.is0(u))return c.ZERO;let h=1,_=c.sqr(u);for(;!c.eql(_,c.ONE);)if(h++,_=c.sqr(_),h===d)throw new Error("Cannot find square root");let y=Re<<BigInt(d-h-1),m=c.pow(p,y);d=h,p=c.sqr(m),u=c.mul(u,p),f=c.mul(f,m)}return f}}function fm(e){return e%nd===rd?ad:e%id===od?dm:e%sd===um?pm(e):cd(e)}var Vr=(e,t)=>(ce(e,t)&Re)===Re,hm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Fs(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=hm.reduce((n,o)=>(n[o]="function",n),t);return Cr(e,r),e}function _i(e,t,r){if(r<Ke)throw new Error("invalid exponent, negatives unsupported");if(r===Ke)return e.ONE;if(r===Re)return t;let n=e.ONE,o=t;for(;r>Ke;)r&Re&&(n=e.mul(n,o)),o=e.sqr(o),r>>=Re;return n}function mt(e,t,r=!1){let n=new Array(t.length).fill(r?e.ZERO:void 0),o=t.reduce((s,a,c)=>e.is0(a)?s:(n[c]=s,e.mul(s,a)),e.ONE),i=e.inv(o);return t.reduceRight((s,a,c)=>e.is0(a)?s:(n[c]=e.mul(s,n[c]),e.mul(s,a)),i),n}function mi(e,t){let r=(e.ORDER-Re)/Xn,n=e.pow(t,r),o=e.eql(n,e.ONE),i=e.eql(n,e.ZERO),s=e.eql(n,e.neg(e.ONE));if(!o&&!i&&!s)throw new Error("invalid Legendre symbol result");return o?1:i?0:-1}function Tc(e,t){t!==void 0&&ja(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function $e(e,t,r=!1,n={}){if(e<=Ke)throw new Error("invalid field: expected ORDER > 0, got "+e);let o,i,s=!1,a;if(typeof t=="object"&&t!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let u=t;u.BITS&&(o=u.BITS),u.sqrt&&(i=u.sqrt),typeof u.isLE=="boolean"&&(r=u.isLE),typeof u.modFromBytes=="boolean"&&(s=u.modFromBytes),a=u.allowedLengths}else typeof t=="number"&&(o=t),n.sqrt&&(i=n.sqrt);let{nBitLength:c,nByteLength:l}=Tc(e,o);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,p=Object.freeze({ORDER:e,isLE:r,BITS:c,BYTES:l,MASK:Ut(c),ZERO:Ke,ONE:Re,allowedLengths:a,create:u=>ce(u,e),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return Ke<=u&&u<e},is0:u=>u===Ke,isValidNot0:u=>!p.is0(u)&&p.isValid(u),isOdd:u=>(u&Re)===Re,neg:u=>ce(-u,e),eql:(u,f)=>u===f,sqr:u=>ce(u*u,e),add:(u,f)=>ce(u+f,e),sub:(u,f)=>ce(u-f,e),mul:(u,f)=>ce(u*f,e),pow:(u,f)=>_i(p,u,f),div:(u,f)=>ce(u*td(f,e),e),sqrN:u=>u*u,addN:(u,f)=>u+f,subN:(u,f)=>u-f,mulN:(u,f)=>u*f,inv:u=>td(u,e),sqrt:i||(u=>(d||(d=fm(e)),d(p,u))),toBytes:u=>r?gc(u,l):Oe(u,l),fromBytes:(u,f=!0)=>{if(a){if(!a.includes(u.length)||u.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);let _=new Uint8Array(l);_.set(u,r?0:_.length-u.length),u=_}if(u.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+u.length);let h=r?Ar(u):Qe(u);if(s&&(h=ce(h,e)),!f&&!p.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:u=>mt(p,u),cmov:(u,f,h)=>h?f:u});return Object.freeze(p)}function ld(e){if(typeof e!="bigint")throw new Error("field order must be bigint");let t=e.toString(2).length;return Math.ceil(t/8)}function Bs(e){let t=ld(e);return t+Math.ceil(t/2)}function Nc(e,t,r=!1){let n=e.length,o=ld(t),i=Bs(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?Ar(e):Qe(e),a=ce(s,t-Re)+Re;return r?gc(a,o):Oe(a,o)}var To=BigInt(0),Qn=BigInt(1);function yi(e,t){let r=t.negate();return e?r:t}function _t(e,t){let r=mt(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function fd(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function Oc(e,t){fd(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,i=Ut(e),s=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function ud(e,t,r){let{windowSize:n,mask:o,maxNumber:i,shiftBy:s}=r,a=Number(e&o),c=e>>s;a>n&&(a-=i,c+=Qn);let l=t*n,d=l+Math.abs(a)-1,p=a===0,u=a<0,f=t%2!==0;return{nextN:c,offset:d,isZero:p,isNeg:u,isNegF:f,offsetF:l}}function _m(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((r,n)=>{if(!(r instanceof t))throw new Error("invalid point at index "+n)})}function ym(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((r,n)=>{if(!t.isValid(r))throw new Error("invalid scalar at index "+n)})}var Ec=new WeakMap,hd=new WeakMap;function Rc(e){return hd.get(e)||1}function dd(e){if(e!==To)throw new Error("invalid wNAF")}var No=class{constructor(t,r){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=r}_unsafeLadder(t,r,n=this.ZERO){let o=t;for(;r>To;)r&Qn&&(n=n.add(o)),o=o.double(),r>>=Qn;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=Oc(r,this.bits),i=[],s=t,a=s;for(let c=0;c<n;c++){a=s,i.push(a);for(let l=1;l<o;l++)a=a.add(s),i.push(a);s=a.double()}return i}wNAF(t,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,i=this.BASE,s=Oc(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:l,isZero:d,isNeg:p,isNegF:u,offsetF:f}=ud(n,a,s);n=c,d?i=i.add(yi(u,r[f])):o=o.add(yi(p,r[l]))}return dd(n),{p:o,f:i}}wNAFUnsafe(t,r,n,o=this.ZERO){let i=Oc(t,this.bits);for(let s=0;s<i.windows&&n!==To;s++){let{nextN:a,offset:c,isZero:l,isNeg:d}=ud(n,s,i);if(n=a,!l){let p=r[c];o=o.add(d?p.negate():p)}}return dd(n),o}getPrecomputes(t,r,n){let o=Ec.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),Ec.set(r,o))),o}cached(t,r,n){let o=Rc(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let i=Rc(t);return i===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),r,o)}createCache(t,r){fd(r,this.bits),hd.set(t,r),Ec.delete(t)}hasCache(t){return Rc(t)!==1}};function md(e,t,r,n){let o=t,i=e.ZERO,s=e.ZERO;for(;r>To||n>To;)r&Qn&&(i=i.add(o)),n&Qn&&(s=s.add(o)),o=o.double(),r>>=Qn,n>>=Qn;return{p1:i,p2:s}}function Oo(e,t,r,n){_m(r,e),ym(n,t);let o=r.length,i=n.length;if(o!==i)throw new Error("arrays of points and scalars must have equal length");let s=e.ZERO,a=Sr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let l=Ut(c),d=new Array(Number(l)+1).fill(s),p=Math.floor((t.BITS-1)/c)*c,u=s;for(let f=p;f>=0;f-=c){d.fill(s);for(let _=0;_<i;_++){let y=n[_],m=Number(y>>BigInt(f)&l);d[m]=d[m].add(r[_])}let h=s;for(let _=d.length-1,y=s;_>0;_--)y=y.add(d[_]),h=h.add(y);if(u=u.add(h),f!==0)for(let _=0;_<c;_++)u=u.double()}return u}function pd(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Fs(t),t}else return $e(e,{isLE:r})}function Ds(e,t,r={},n){if(n===void 0&&(n=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(let c of["p","n","h"]){let l=t[c];if(!(typeof l=="bigint"&&l>To))throw new Error(`CURVE.${c} must be positive bigint`)}let o=pd(t.p,r.Fp,n),i=pd(t.n,r.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(t[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:o,Fn:i}}var gm=Qe;function tn(e,t){if(gi(e),gi(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);let r=Array.from({length:t}).fill(0);for(let n=t-1;n>=0;n--)r[n]=e&255,e>>>=8;return new Uint8Array(r)}function xm(e,t){let r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function gi(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function _d(e){if(!jt(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?G(e):e}function bm(e,t,r,n){fe(e),gi(r),t=_d(t),t.length>255&&(t=n($(G("H2C-OVERSIZE-DST-"),t)));let{outputLen:o,blockLen:i}=n,s=Math.ceil(r/o);if(r>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=$(t,tn(t.length,1)),c=tn(0,i),l=tn(r,2),d=new Array(s),p=n($(c,e,l,tn(0,1),a));d[0]=n($(p,tn(1,1),a));for(let f=1;f<=s;f++){let h=[xm(p,d[f-1]),tn(f+1,1),a];d[f]=n($(...h))}return $(...d).slice(0,r)}function wm(e,t,r,n,o){if(fe(e),gi(r),t=_d(t),t.length>255){let i=Math.ceil(2*n/8);t=o.create({dkLen:i}).update(G("H2C-OVERSIZE-DST-")).update(t).digest()}if(r>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(e).update(tn(r,2)).update(t).update(tn(t.length,1)).digest()}function vc(e,t,r){Cr(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:i,hash:s,expand:a,DST:c}=r;if(!ed(r.hash))throw new Error("expected valid hash");fe(e),gi(t);let l=n.toString(2).length,d=Math.ceil((l+o)/8),p=t*i*d,u;if(a==="xmd")u=bm(e,c,p,s);else if(a==="xof")u=wm(e,c,p,o,s);else if(a==="_internal_pass")u=e;else throw new Error('expand must be "xmd" or "xof"');let f=new Array(t);for(let h=0;h<t;h++){let _=new Array(i);for(let y=0;y<i;y++){let m=d*(y+h*i),b=u.subarray(m,m+d);_[y]=ce(gm(b),n)}f[h]=_}return f}function Ic(e,t){let r=t.map(n=>Array.from(n).reverse());return(n,o)=>{let[i,s,a,c]=r.map(p=>p.reduce((u,f)=>e.add(e.mul(u,n),f))),[l,d]=mt(e,[s,c],!0);return n=e.mul(i,l),o=e.mul(o,e.mul(a,d)),{x:n,y:o}}}var Tm=G("HashToScalar-");function Ac(e,t,r){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function n(i){return e.fromAffine(t(i))}function o(i){let s=i.clearCofactor();return s.equals(e.ZERO)?e.ZERO:(s.assertValidity(),s)}return{defaults:r,hashToCurve(i,s){let a=Object.assign({},r,s),c=vc(i,2,a),l=n(c[0]),d=n(c[1]);return o(l.add(d))},encodeToCurve(i,s){let a=r.encodeDST?{DST:r.encodeDST}:{},c=Object.assign({},r,a,s),l=vc(i,1,c),d=n(l[0]);return o(d)},mapToCurve(i){if(!Array.isArray(i))throw new Error("expected array of bigints");for(let s of i)if(typeof s!="bigint")throw new Error("expected array of bigints");return o(n(i))},hashToScalar(i,s){let a=e.Fn.ORDER,c=Object.assign({},r,{p:a,m:1,DST:Tm},s);return vc(i,1,c)[0][0]}}}var yd=(e,t)=>(e+(e>=0?t:-t)/Pr)/t;function Nm(e,t,r){let[[n,o],[i,s]]=t,a=yd(s*e,r),c=yd(-o*e,r),l=e-a*n-c*i,d=-a*o-c*s,p=l<eo,u=d<eo;p&&(l=-l),u&&(d=-d);let f=Ut(Math.ceil(Sr(r)/2))+He;if(l<eo||l>=f||d<eo||d>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:p,k1:l,k2neg:u,k2:d}}var eo=BigInt(0),He=BigInt(1),Pr=BigInt(2),Eo=BigInt(3),Sc=BigInt(4);function xi(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=de("private key",t);try{n=e.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof t}`)}}if(!e.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Om(e,t={}){let r=Ds("weierstrass",e,t),{Fp:n,Fn:o}=r,i=r.CURVE,{h:s,n:a}=i;Cr(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=t;if(c&&(!n.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let l=vm(n,o);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(A,x,N){let{x:S,y:B}=x.toAffine(),M=n.toBytes(S);if(Zn(N,"isCompressed"),N){d();let R=!n.isOdd(B);return $(Em(R),M)}else return $(Uint8Array.of(4),M,n.toBytes(B))}function u(A){Qr(A,void 0,"Point");let{publicKey:x,publicKeyUncompressed:N}=l,S=A.length,B=A[0],M=A.subarray(1);if(S===x&&(B===2||B===3)){let R=n.fromBytes(M);if(!n.isValid(R))throw new Error("bad point: is not on curve, wrong x");let V=_(R),F;try{F=n.sqrt(V)}catch(te){let Z=te instanceof Error?": "+te.message:"";throw new Error("bad point: is not on curve, sqrt error"+Z)}d();let D=n.isOdd(F);return(B&1)===1!==D&&(F=n.neg(F)),{x:R,y:F}}else if(S===N&&B===4){let R=n.BYTES,V=n.fromBytes(M.subarray(0,R)),F=n.fromBytes(M.subarray(R,R*2));if(!y(V,F))throw new Error("bad point: is not on curve");return{x:V,y:F}}else throw new Error(`bad point: got length ${S}, expected compressed=${x} or uncompressed=${N}`)}let f=t.toBytes||p,h=t.fromBytes||u;function _(A){let x=n.sqr(A),N=n.mul(x,A);return n.add(n.add(N,n.mul(A,i.a)),i.b)}function y(A,x){let N=n.sqr(x),S=_(A);return n.eql(N,S)}if(!y(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let m=n.mul(n.pow(i.a,Eo),Sc),b=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(m,b)))throw new Error("bad curve params: a or b");function g(A,x,N=!1){if(!n.isValid(x)||N&&n.is0(x))throw new Error(`bad point coordinate ${A}`);return x}function T(A){if(!(A instanceof w))throw new Error("ProjectivePoint expected")}function O(A){if(!c||!c.basises)throw new Error("no endo");return Nm(A,c.basises,o.ORDER)}let v=en((A,x)=>{let{X:N,Y:S,Z:B}=A;if(n.eql(B,n.ONE))return{x:N,y:S};let M=A.is0();x==null&&(x=M?n.ONE:n.inv(B));let R=n.mul(N,x),V=n.mul(S,x),F=n.mul(B,x);if(M)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:R,y:V}}),E=en(A=>{if(A.is0()){if(t.allowInfinityPoint&&!n.is0(A.Y))return;throw new Error("bad point: ZERO")}let{x,y:N}=A.toAffine();if(!n.isValid(x)||!n.isValid(N))throw new Error("bad point: x or y not field elements");if(!y(x,N))throw new Error("bad point: equation left != right");if(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function C(A,x,N,S,B){return N=new w(n.mul(N.X,A),N.Y,N.Z),x=yi(S,x),N=yi(B,N),x.add(N)}class w{constructor(x,N,S){this.X=g("x",x),this.Y=g("y",N,!0),this.Z=g("z",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){let{x:N,y:S}=x||{};if(!x||!n.isValid(N)||!n.isValid(S))throw new Error("invalid affine point");if(x instanceof w)throw new Error("projective point not allowed");return n.is0(N)&&n.is0(S)?w.ZERO:new w(N,S,n.ONE)}static fromBytes(x){let N=w.fromAffine(h(Qr(x,void 0,"point")));return N.assertValidity(),N}static fromHex(x){return w.fromBytes(de("pointHex",x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,N=!0){return P.createCache(this,x),N||this.multiply(Eo),this}assertValidity(){E(this)}hasEvenY(){let{y:x}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(x)}equals(x){T(x);let{X:N,Y:S,Z:B}=this,{X:M,Y:R,Z:V}=x,F=n.eql(n.mul(N,V),n.mul(M,B)),D=n.eql(n.mul(S,V),n.mul(R,B));return F&&D}negate(){return new w(this.X,n.neg(this.Y),this.Z)}double(){let{a:x,b:N}=i,S=n.mul(N,Eo),{X:B,Y:M,Z:R}=this,V=n.ZERO,F=n.ZERO,D=n.ZERO,k=n.mul(B,B),te=n.mul(M,M),Z=n.mul(R,R),Y=n.mul(B,M);return Y=n.add(Y,Y),D=n.mul(B,R),D=n.add(D,D),V=n.mul(x,D),F=n.mul(S,Z),F=n.add(V,F),V=n.sub(te,F),F=n.add(te,F),F=n.mul(V,F),V=n.mul(Y,V),D=n.mul(S,D),Z=n.mul(x,Z),Y=n.sub(k,Z),Y=n.mul(x,Y),Y=n.add(Y,D),D=n.add(k,k),k=n.add(D,k),k=n.add(k,Z),k=n.mul(k,Y),F=n.add(F,k),Z=n.mul(M,R),Z=n.add(Z,Z),k=n.mul(Z,Y),V=n.sub(V,k),D=n.mul(Z,te),D=n.add(D,D),D=n.add(D,D),new w(V,F,D)}add(x){T(x);let{X:N,Y:S,Z:B}=this,{X:M,Y:R,Z:V}=x,F=n.ZERO,D=n.ZERO,k=n.ZERO,te=i.a,Z=n.mul(i.b,Eo),Y=n.mul(N,M),xe=n.mul(S,R),be=n.mul(B,V),ze=n.add(N,S),ne=n.add(M,R);ze=n.mul(ze,ne),ne=n.add(Y,xe),ze=n.sub(ze,ne),ne=n.add(N,B);let ie=n.add(M,V);return ne=n.mul(ne,ie),ie=n.add(Y,be),ne=n.sub(ne,ie),ie=n.add(S,B),F=n.add(R,V),ie=n.mul(ie,F),F=n.add(xe,be),ie=n.sub(ie,F),k=n.mul(te,ne),F=n.mul(Z,be),k=n.add(F,k),F=n.sub(xe,k),k=n.add(xe,k),D=n.mul(F,k),xe=n.add(Y,Y),xe=n.add(xe,Y),be=n.mul(te,be),ne=n.mul(Z,ne),xe=n.add(xe,be),be=n.sub(Y,be),be=n.mul(te,be),ne=n.add(ne,be),Y=n.mul(xe,ne),D=n.add(D,Y),Y=n.mul(ie,ne),F=n.mul(ze,F),F=n.sub(F,Y),Y=n.mul(ze,xe),k=n.mul(ie,k),k=n.add(k,Y),new w(F,D,k)}subtract(x){return this.add(x.negate())}is0(){return this.equals(w.ZERO)}multiply(x){let{endo:N}=t;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let S,B,M=R=>P.cached(this,R,V=>_t(w,V));if(N){let{k1neg:R,k1:V,k2neg:F,k2:D}=O(x),{p:k,f:te}=M(V),{p:Z,f:Y}=M(D);B=te.add(Y),S=C(N.beta,k,Z,R,F)}else{let{p:R,f:V}=M(x);S=R,B=V}return _t(w,[S,B])[0]}multiplyUnsafe(x){let{endo:N}=t,S=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===eo||S.is0())return w.ZERO;if(x===He)return S;if(P.hasCache(this))return this.multiply(x);if(N){let{k1neg:B,k1:M,k2neg:R,k2:V}=O(x),{p1:F,p2:D}=md(w,S,M,V);return C(N.beta,F,D,B,R)}else return P.unsafe(S,x)}multiplyAndAddUnsafe(x,N,S){let B=this.multiplyUnsafe(N).add(x.multiplyUnsafe(S));return B.is0()?void 0:B}toAffine(x){return v(this,x)}isTorsionFree(){let{isTorsionFree:x}=t;return s===He?!0:x?x(w,this):P.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:x}=t;return s===He?this:x?x(w,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(x=!0){return Zn(x,"isCompressed"),this.assertValidity(),f(w,this,x)}toHex(x=!0){return j(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(x=!0){return this.toBytes(x)}_setWindowSize(x){this.precompute(x)}static normalizeZ(x){return _t(w,x)}static msm(x,N){return Oo(w,o,x,N)}static fromPrivateKey(x){return w.BASE.multiply(xi(o,x))}}w.BASE=new w(i.Gx,i.Gy,n.ONE),w.ZERO=new w(n.ZERO,n.ONE,n.ZERO),w.Fp=n,w.Fn=o;let I=o.BITS,P=new No(w,t.endo?Math.ceil(I/2):I);return w.BASE.precompute(8),w}function Em(e){return Uint8Array.of(e?2:3)}function Rm(e,t){let r=e.ORDER,n=eo;for(let h=r-He;h%Pr===eo;h/=Pr)n+=He;let o=n,i=Pr<<o-He-He,s=i*Pr,a=(r-He)/s,c=(a-He)/Pr,l=s-He,d=i,p=e.pow(t,a),u=e.pow(t,(a+He)/Pr),f=(h,_)=>{let y=p,m=e.pow(_,l),b=e.sqr(m);b=e.mul(b,_);let g=e.mul(h,b);g=e.pow(g,c),g=e.mul(g,m),m=e.mul(g,_),b=e.mul(g,h);let T=e.mul(b,m);g=e.pow(T,d);let O=e.eql(g,e.ONE);m=e.mul(b,u),g=e.mul(T,y),b=e.cmov(m,b,O),T=e.cmov(g,T,O);for(let v=o;v>He;v--){let E=v-Pr;E=Pr<<E-He;let C=e.pow(T,E),w=e.eql(C,e.ONE);m=e.mul(b,y),y=e.mul(y,y),C=e.mul(T,y),b=e.cmov(m,b,w),T=e.cmov(C,T,w)}return{isValid:O,value:b}};if(e.ORDER%Sc===Eo){let h=(e.ORDER-Eo)/Sc,_=e.sqrt(e.neg(t));f=(y,m)=>{let b=e.sqr(m),g=e.mul(y,m);b=e.mul(b,g);let T=e.pow(b,h);T=e.mul(T,g);let O=e.mul(T,_),v=e.mul(e.sqr(T),m),E=e.eql(v,y),C=e.cmov(O,T,E);return{isValid:E,value:C}}}return f}function Cc(e,t){Fs(e);let{A:r,B:n,Z:o}=t;if(!e.isValid(r)||!e.isValid(n)||!e.isValid(o))throw new Error("mapToCurveSimpleSWU: invalid opts");let i=Rm(e,o);if(!e.isOdd)throw new Error("Field does not have .isOdd()");return s=>{let a,c,l,d,p,u,f,h;a=e.sqr(s),a=e.mul(a,o),c=e.sqr(a),c=e.add(c,a),l=e.add(c,e.ONE),l=e.mul(l,n),d=e.cmov(o,e.neg(c),!e.eql(c,e.ZERO)),d=e.mul(d,r),c=e.sqr(l),u=e.sqr(d),p=e.mul(u,r),c=e.add(c,p),c=e.mul(c,l),u=e.mul(u,d),p=e.mul(u,n),c=e.add(c,p),f=e.mul(a,l);let{isValid:_,value:y}=i(c,u);h=e.mul(a,s),h=e.mul(h,y),f=e.cmov(f,l,_),h=e.cmov(h,y,_);let m=e.isOdd(s)===e.isOdd(h);h=e.cmov(e.neg(h),h,m);let b=mt(e,[d],!0)[0];return f=e.mul(f,b),{x:f,y:h}}}function vm(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Vc(e){let{CURVE:t,curveOpts:r}=Im(e),n=Om(t,r);return Sm(e,n)}function Im(e){let t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,o=$e(t.n,{BITS:e.nBitLength,allowedLengths:n,modFromBytes:e.wrapPrivateKey}),i={Fp:r,Fn:o,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:i}}function Am(e,t,r){function n(o){let i=e.sqr(o),s=e.mul(i,o);return e.add(e.add(s,e.mul(o,t)),r)}return n}function Sm(e,t){let{Fp:r,Fn:n}=t;function o(s){return bc(s,He,n.ORDER)}let i=Am(r,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:s=>xi(n,s),weierstrassEquation:i,isWithinCurveOrder:o})}var Cm=BigInt(0),Us=BigInt(1),gd=BigInt(2),Ro=BigInt(3);function Vm(e){let t=[];for(;e>Us;e>>=Us)(e&Us)===Cm?t.unshift(0):(e&Ro)===Ro?(t.unshift(-1),e+=Us):t.unshift(1);return t}function Pc(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function Pm(e,t,r,n){let{Fp2:o,Fp12:i}=e,{twistType:s,ateLoopSize:a,xNegative:c,postPrecompute:l}=n,d;if(s==="multiplicative")d=(g,T,O,v,E,C)=>i.mul014(v,g,o.mul(T,E),o.mul(O,C));else if(s==="divisive")d=(g,T,O,v,E,C)=>i.mul034(v,o.mul(O,C),o.mul(T,E),g);else throw new Error("bls: unknown twist type");let p=o.div(o.ONE,o.mul(o.ONE,gd));function u(g,T,O,v){let E=o.sqr(O),C=o.sqr(v),w=o.mulByB(o.mul(C,Ro)),I=o.mul(w,Ro),P=o.sub(o.sub(o.sqr(o.add(O,v)),C),E),A=o.sub(w,E),x=o.mul(o.sqr(T),Ro),N=o.neg(P);return g.push([A,x,N]),T=o.mul(o.mul(o.mul(o.sub(E,I),T),O),p),O=o.sub(o.sqr(o.mul(o.add(E,I),p)),o.mul(o.sqr(w),Ro)),v=o.mul(E,P),{Rx:T,Ry:O,Rz:v}}function f(g,T,O,v,E,C){let w=o.sub(O,o.mul(C,v)),I=o.sub(T,o.mul(E,v)),P=o.sub(o.mul(w,E),o.mul(I,C)),A=o.neg(w),x=I;g.push([P,A,x]);let N=o.sqr(I),S=o.mul(N,I),B=o.mul(N,T),M=o.add(o.sub(S,o.mul(B,gd)),o.mul(o.sqr(w),v));return T=o.mul(I,M),O=o.sub(o.mul(o.sub(B,M),w),o.mul(S,O)),v=o.mul(v,S),{Rx:T,Ry:O,Rz:v}}let h=Vm(a),_=en(g=>{let T=g,{x:O,y:v}=T.toAffine(),E=O,C=v,w=o.neg(v),I=E,P=C,A=o.ONE,x=[];for(let N of h){let S=[];({Rx:I,Ry:P,Rz:A}=u(S,I,P,A)),N&&({Rx:I,Ry:P,Rz:A}=f(S,I,P,A,E,N===-1?w:C)),x.push(S)}if(l){let N=x[x.length-1];l(I,P,A,E,C,f.bind(null,N))}return x});function y(g,T=!1){let O=i.ONE;if(g.length){let v=g[0][0].length;for(let E=0;E<v;E++){O=i.sqr(O);for(let[C,w,I]of g)for(let[P,A,x]of C[E])O=d(P,A,x,O,w,I)}}return c&&(O=i.conjugate(O)),T?i.finalExponentiate(O):O}function m(g,T=!0){let O=[];_t(t,g.map(({g1:v})=>v)),_t(r,g.map(({g2:v})=>v));for(let{g1:v,g2:E}of g){if(v.is0()||E.is0())throw new Error("pairing is not available for ZERO point");v.assertValidity(),E.assertValidity();let C=v.toAffine();O.push([_(E),C.x,C.y])}return y(O,T)}function b(g,T,O=!0){return m([{g1:g,g2:T}],O)}return{Fp12:i,millerLoopBatch:y,pairing:b,pairingBatch:m,calcPairingPrecomputes:_}}function xd(e,t,r,n,o){let{Fp12:i,pairingBatch:s}=e;function a(p){return p instanceof t.Point?p:t.Point.fromHex(p)}function c(p){return p instanceof r.Point?p:r.Point.fromHex(p)}function l(p){if(!(p instanceof r.Point))throw new Error(`expected valid message hashed to ${o?"G1":"G2"} curve`);return p}let d=o?(p,u)=>({g1:u,g2:p}):(p,u)=>({g1:p,g2:u});return{getPublicKey(p){let u=xi(t.Point.Fn,p);return t.Point.BASE.multiply(u)},sign(p,u,f){if(f!=null)throw new Error("sign() expects 2 arguments");let h=xi(t.Point.Fn,u);return l(p).assertValidity(),p.multiply(h)},verify(p,u,f,h){if(h!=null)throw new Error("verify() expects 3 arguments");p=c(p),f=a(f);let _=f.negate(),y=t.Point.BASE,m=l(u),b=p,g=s([d(_,m),d(y,b)]);return i.eql(g,i.ONE)},verifyBatch(p,u,f){if(Pc(u),f.length!==u.length)throw new Error("amount of public keys and messages should be equal");let h=c(p),_=u,y=f.map(a),m=new Map;for(let T=0;T<y.length;T++){let O=y[T],v=_[T],E=m.get(v);E===void 0&&(E=[],m.set(v,E)),E.push(O)}let b=[],g=t.Point.BASE;try{for(let[T,O]of m){let v=O.reduce((E,C)=>E.add(C));b.push(d(v,T))}return b.push(d(g.negate(),h)),i.eql(s(b),i.ONE)}catch{return!1}},aggregatePublicKeys(p){Pc(p),p=p.map(f=>a(f));let u=p.reduce((f,h)=>f.add(h),t.Point.ZERO);return u.assertValidity(),u},aggregateSignatures(p){Pc(p),p=p.map(f=>c(f));let u=p.reduce((f,h)=>f.add(h),r.Point.ZERO);return u.assertValidity(),u},hash(p,u){fe(p);let f=u?{DST:u}:void 0;return r.hashToCurve(p,f)},Signature:n}}function bd(e){let{Fp:t,Fr:r,Fp2:n,Fp6:o,Fp12:i}=e.fields,s=Vc(e.G1),a=Object.assign(s,Ac(s.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=Vc(e.G2),l=Object.assign(c,Ac(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),d=Pm(e.fields,a.Point,l.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:p,pairing:u,pairingBatch:f,calcPairingPrecomputes:h}=d,_=xd(d,a,l,e.G2.Signature,!1),y=xd(d,l,a,e.G1.ShortSignature,!0),m=e.randomBytes||lo,b=()=>{let R=Bs(r.ORDER);return Nc(m(R),r.ORDER)},g={randomSecretKey:b,randomPrivateKey:b,calcPairingPrecomputes:h},{ShortSignature:T}=e.G1,{Signature:O}=e.G2;function v(R,V){return R instanceof a.Point?R:y.hash(de("point",R),V?.DST)}function E(R,V){return R instanceof l.Point?R:_.hash(de("point",R),V?.DST)}function C(R){return _.getPublicKey(R).toBytes(!0)}function w(R){return y.getPublicKey(R).toBytes(!0)}function I(R,V,F){let D=E(R,F),k=_.sign(D,V);return R instanceof l.Point?k:O.toBytes(k)}function P(R,V,F){let D=v(R,F),k=y.sign(D,V);return R instanceof a.Point?k:T.toBytes(k)}function A(R,V,F,D){let k=E(V,D);return _.verify(R,k,F)}function x(R,V,F,D){let k=v(V,D);return y.verify(R,k,F)}function N(R){let V=_.aggregatePublicKeys(R);return R[0]instanceof a.Point?V:V.toBytes(!0)}function S(R){let V=_.aggregateSignatures(R);return R[0]instanceof l.Point?V:O.toBytes(V)}function B(R){let V=y.aggregateSignatures(R);return R[0]instanceof a.Point?V:T.toBytes(V)}function M(R,V,F,D){let k=V.map(te=>E(te,D));return _.verifyBatch(R,k,F)}return a.Point.BASE.precompute(4),{longSignatures:_,shortSignatures:y,millerLoopBatch:p,pairing:u,pairingBatch:f,verifyBatch:M,fields:{Fr:r,Fp:t,Fp2:n,Fp6:o,Fp12:i},params:{ateLoopSize:e.params.ateLoopSize,twistType:e.params.twistType,r:e.params.r,G1b:e.G1.b,G2b:e.G2.b},utils:g,getPublicKey:C,getPublicKeyForShortSignatures:w,sign:I,signShortSignature:P,verify:A,verifyShortSignature:x,aggregatePublicKeys:N,aggregateSignatures:S,aggregateShortSignatures:B,G1:a,G2:l,Signature:O,ShortSignature:T}}var wd=BigInt(0),Fr=BigInt(1),Ge=BigInt(2),Td=BigInt(3);function Uc(e,t,r,n,o=1,i){let s=BigInt(i===void 0?n:i),a=r**BigInt(n),c=[];for(let l=0;l<o;l++){let d=BigInt(l+1),p=[];for(let u=0,f=Fr;u<n;u++){let h=(d*f-d)/s%a;p.push(e.pow(t,h)),f*=r}c.push(p)}return c}function Od(e,t,r){let n=t.pow(r,(e.ORDER-Fr)/Td),o=t.pow(r,(e.ORDER-Fr)/Ge);function i(u,f){let h=t.mul(t.frobeniusMap(u,1),n),_=t.mul(t.frobeniusMap(f,1),o);return[h,_]}let s=t.pow(r,(e.ORDER**Ge-Fr)/Td),a=t.pow(r,(e.ORDER**Ge-Fr)/Ge);if(!t.eql(a,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(u,f){return[t.mul(u,s),t.neg(f)]}let l=u=>(f,h)=>{let _=h.toAffine(),y=u(_.x,_.y);return f.fromAffine({x:y[0],y:y[1]})},d=l(i),p=l(c);return{psi:i,psi2:c,G2psi:d,G2psi2:p,PSI_X:n,PSI_Y:o,PSI2_X:s,PSI2_Y:a}}var Nd=(e,t)=>{if(t.length!==2)throw new Error("invalid tuple");let r=t.map(n=>e.create(n));return{c0:r[0],c1:r[1]}},Fc=class{constructor(t,r={}){this.MASK=Fr;let n=t.ORDER,o=n*n;this.Fp=t,this.ORDER=o,this.BITS=Sr(o),this.BYTES=Math.ceil(Sr(o)/8),this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.Fp_NONRESIDUE=t.create(r.NONRESIDUE||BigInt(-1)),this.Fp_div2=t.div(t.ONE,Ge),this.NONRESIDUE=Nd(t,r.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=Uc(t,this.Fp_NONRESIDUE,t.ORDER,2)[0],this.mulByB=r.Fp2mulByB,Object.seal(this)}fromBigTuple(t){return Nd(this.Fp,t)}create(t){return t}isValid({c0:t,c1:r}){function n(o,i){return typeof o=="bigint"&&wd<=o&&o<i}return n(t,this.ORDER)&&n(r,this.ORDER)}is0({c0:t,c1:r}){return this.Fp.is0(t)&&this.Fp.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}eql({c0:t,c1:r},{c0:n,c1:o}){return this.Fp.eql(t,n)&&this.Fp.eql(r,o)}neg({c0:t,c1:r}){return{c0:this.Fp.neg(t),c1:this.Fp.neg(r)}}pow(t,r){return _i(this,t,r)}invertBatch(t){return mt(this,t)}add(t,r){let{c0:n,c1:o}=t,{c0:i,c1:s}=r;return{c0:this.Fp.add(n,i),c1:this.Fp.add(o,s)}}sub({c0:t,c1:r},{c0:n,c1:o}){return{c0:this.Fp.sub(t,n),c1:this.Fp.sub(r,o)}}mul({c0:t,c1:r},n){let{Fp:o}=this;if(typeof n=="bigint")return{c0:o.mul(t,n),c1:o.mul(r,n)};let{c0:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s),l=o.sub(a,c),d=o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c));return{c0:l,c1:d}}sqr({c0:t,c1:r}){let{Fp:n}=this,o=n.add(t,r),i=n.sub(t,r),s=n.add(t,t);return{c0:n.mul(o,i),c1:n.mul(s,r)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}div(t,r){let{Fp:n}=this;return this.mul(t,typeof r=="bigint"?n.inv(n.create(r)):this.inv(r))}inv({c0:t,c1:r}){let{Fp:n}=this,o=n.inv(n.create(t*t+r*r));return{c0:n.mul(o,n.create(t)),c1:n.mul(o,n.create(-r))}}sqrt(t){let{Fp:r}=this,n=this,{c0:o,c1:i}=t;if(r.is0(i))return mi(r,o)===1?n.create({c0:r.sqrt(o),c1:r.ZERO}):n.create({c0:r.ZERO,c1:r.sqrt(r.div(o,this.Fp_NONRESIDUE))});let s=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(i),this.Fp_NONRESIDUE))),a=r.mul(r.add(s,o),this.Fp_div2);mi(r,a)===-1&&(a=r.sub(a,s));let l=r.sqrt(a),d=n.create({c0:l,c1:r.div(r.mul(i,this.Fp_div2),l)});if(!n.eql(n.sqr(d),t))throw new Error("Cannot find square root");let p=d,u=n.neg(p),{re:f,im:h}=n.reim(p),{re:_,im:y}=n.reim(u);return h>y||h===y&&f>_?p:u}isOdd(t){let{re:r,im:n}=this.reim(t),o=r%Ge,i=r===wd,s=n%Ge;return BigInt(o||i&&s)==Fr}fromBytes(t){let{Fp:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))}}toBytes({c0:t,c1:r}){return $(this.Fp.toBytes(t),this.Fp.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},i){return{c0:this.Fp.cmov(t,n,i),c1:this.Fp.cmov(r,o,i)}}reim({c0:t,c1:r}){return{re:t,im:r}}Fp4Square(t,r){let n=this,o=n.sqr(t),i=n.sqr(r);return{first:n.add(n.mulByNonresidue(i),o),second:n.sub(n.sub(n.sqr(n.add(t,r)),o),i)}}mulByNonresidue({c0:t,c1:r}){return this.mul({c0:t,c1:r},this.NONRESIDUE)}frobeniusMap({c0:t,c1:r},n){return{c0:t,c1:this.Fp.mul(r,this.FROBENIUS_COEFFICIENTS[n%2])}}},Bc=class{constructor(t){this.MASK=Fr,this.Fp2=t,this.ORDER=t.ORDER,this.BITS=3*t.BITS,this.BYTES=3*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO,c2:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO,c2:t.ZERO};let{Fp:r}=t,n=Uc(t,t.NONRESIDUE,r.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=n[0],this.FROBENIUS_COEFFICIENTS_2=n[1],Object.seal(this)}add({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return{c0:a.add(t,o),c1:a.add(r,i),c2:a.add(n,s)}}sub({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return{c0:a.sub(t,o),c1:a.sub(r,i),c2:a.sub(n,s)}}mul({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;if(typeof o=="bigint")return{c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)};let{c0:s,c1:a,c2:c}=o,l=i.mul(t,s),d=i.mul(r,a),p=i.mul(n,c);return{c0:i.add(l,i.mulByNonresidue(i.sub(i.mul(i.add(r,n),i.add(a,c)),i.add(d,p)))),c1:i.add(i.sub(i.mul(i.add(t,r),i.add(s,a)),i.add(l,d)),i.mulByNonresidue(p)),c2:i.sub(i.add(d,i.mul(i.add(t,n),i.add(s,c))),i.add(l,p))}}sqr({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sqr(t),s=o.mul(o.mul(t,r),Ge),a=o.mul(o.mul(r,n),Ge),c=o.sqr(n);return{c0:o.add(o.mulByNonresidue(a),i),c1:o.add(o.mulByNonresidue(c),s),c2:o.sub(o.sub(o.add(o.add(s,o.sqr(o.add(o.sub(t,r),n))),a),i),c)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}create(t){return t}isValid({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return o.isValid(t)&&o.isValid(r)&&o.isValid(n)}is0({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return o.is0(t)&&o.is0(r)&&o.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.neg(t),c1:o.neg(r),c2:o.neg(n)}}eql({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s}){let{Fp2:a}=this;return a.eql(t,o)&&a.eql(r,i)&&a.eql(n,s)}sqrt(t){return wo()}div(t,r){let{Fp2:n}=this,{Fp:o}=n;return this.mul(t,typeof r=="bigint"?o.inv(o.create(r)):this.inv(r))}pow(t,r){return _i(this,t,r)}invertBatch(t){return mt(this,t)}inv({c0:t,c1:r,c2:n}){let{Fp2:o}=this,i=o.sub(o.sqr(t),o.mulByNonresidue(o.mul(n,r))),s=o.sub(o.mulByNonresidue(o.sqr(n)),o.mul(t,r)),a=o.sub(o.sqr(r),o.mul(t,n)),c=o.inv(o.add(o.mulByNonresidue(o.add(o.mul(n,s),o.mul(r,a))),o.mul(t,i)));return{c0:o.mul(c,i),c1:o.mul(c,s),c2:o.mul(c,a)}}fromBytes(t){let{Fp2:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);let n=r.BYTES;return{c0:r.fromBytes(t.subarray(0,n)),c1:r.fromBytes(t.subarray(n,n*2)),c2:r.fromBytes(t.subarray(2*n))}}toBytes({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return $(o.toBytes(t),o.toBytes(r),o.toBytes(n))}cmov({c0:t,c1:r,c2:n},{c0:o,c1:i,c2:s},a){let{Fp2:c}=this;return{c0:c.cmov(t,o,a),c1:c.cmov(r,i,a),c2:c.cmov(n,s,a)}}fromBigSix(t){let{Fp2:r}=this;if(!Array.isArray(t)||t.length!==6)throw new Error("invalid Fp6 usage");return{c0:r.fromBigTuple(t.slice(0,2)),c1:r.fromBigTuple(t.slice(2,4)),c2:r.fromBigTuple(t.slice(4,6))}}frobeniusMap({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return{c0:i.frobeniusMap(t,o),c1:i.mul(i.frobeniusMap(r,o),this.FROBENIUS_COEFFICIENTS_1[o%6]),c2:i.mul(i.frobeniusMap(n,o),this.FROBENIUS_COEFFICIENTS_2[o%6])}}mulByFp2({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return{c0:i.mul(t,o),c1:i.mul(r,o),c2:i.mul(n,o)}}mulByNonresidue({c0:t,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.mulByNonresidue(n),c1:t,c2:r}}mul1({c0:t,c1:r,c2:n},o){let{Fp2:i}=this;return{c0:i.mulByNonresidue(i.mul(n,o)),c1:i.mul(t,o),c2:i.mul(r,o)}}mul01({c0:t,c1:r,c2:n},o,i){let{Fp2:s}=this,a=s.mul(t,o),c=s.mul(r,i);return{c0:s.add(s.mulByNonresidue(s.sub(s.mul(s.add(r,n),i),c)),a),c1:s.sub(s.sub(s.mul(s.add(o,i),s.add(t,r)),a),c),c2:s.add(s.sub(s.mul(s.add(t,n),o),a),c)}}},Dc=class{constructor(t,r){this.MASK=Fr;let{Fp2:n}=t,{Fp:o}=n;this.Fp6=t,this.ORDER=n.ORDER,this.BITS=2*t.BITS,this.BYTES=2*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.FROBENIUS_COEFFICIENTS=Uc(n,n.NONRESIDUE,o.ORDER,12,1,6)[0],this.X_LEN=r.X_LEN,this.finalExponentiate=r.Fp12finalExponentiate}create(t){return t}isValid({c0:t,c1:r}){let{Fp6:n}=this;return n.isValid(t)&&n.isValid(r)}is0({c0:t,c1:r}){let{Fp6:n}=this;return n.is0(t)&&n.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:r}){let{Fp6:n}=this;return{c0:n.neg(t),c1:n.neg(r)}}eql({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return i.eql(t,n)&&i.eql(r,o)}sqrt(t){wo()}inv({c0:t,c1:r}){let{Fp6:n}=this,o=n.inv(n.sub(n.sqr(t),n.mulByNonresidue(n.sqr(r))));return{c0:n.mul(t,o),c1:n.neg(n.mul(r,o))}}div(t,r){let{Fp6:n}=this,{Fp2:o}=n,{Fp:i}=o;return this.mul(t,typeof r=="bigint"?i.inv(i.create(r)):this.inv(r))}pow(t,r){return _i(this,t,r)}invertBatch(t){return mt(this,t)}add({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return{c0:i.add(t,n),c1:i.add(r,o)}}sub({c0:t,c1:r},{c0:n,c1:o}){let{Fp6:i}=this;return{c0:i.sub(t,n),c1:i.sub(r,o)}}mul({c0:t,c1:r},n){let{Fp6:o}=this;if(typeof n=="bigint")return{c0:o.mul(t,n),c1:o.mul(r,n)};let{c0:i,c1:s}=n,a=o.mul(t,i),c=o.mul(r,s);return{c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(t,r),o.add(i,s)),o.add(a,c))}}sqr({c0:t,c1:r}){let{Fp6:n}=this,o=n.mul(t,r);return{c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(r),t),n.add(t,r)),o),n.mulByNonresidue(o)),c1:n.add(o,o)}}addN(t,r){return this.add(t,r)}subN(t,r){return this.sub(t,r)}mulN(t,r){return this.mul(t,r)}sqrN(t){return this.sqr(t)}fromBytes(t){let{Fp6:r}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:r.fromBytes(t.subarray(0,r.BYTES)),c1:r.fromBytes(t.subarray(r.BYTES))}}toBytes({c0:t,c1:r}){let{Fp6:n}=this;return $(n.toBytes(t),n.toBytes(r))}cmov({c0:t,c1:r},{c0:n,c1:o},i){let{Fp6:s}=this;return{c0:s.cmov(t,n,i),c1:s.cmov(r,o,i)}}fromBigTwelve(t){let{Fp6:r}=this;return{c0:r.fromBigSix(t.slice(0,6)),c1:r.fromBigSix(t.slice(6,12))}}frobeniusMap(t,r){let{Fp6:n}=this,{Fp2:o}=n,{c0:i,c1:s,c2:a}=n.frobeniusMap(t.c1,r),c=this.FROBENIUS_COEFFICIENTS[r%12];return{c0:n.frobeniusMap(t.c0,r),c1:n.create({c0:o.mul(i,c),c1:o.mul(s,c),c2:o.mul(a,c)})}}mulByFp2({c0:t,c1:r},n){let{Fp6:o}=this;return{c0:o.mulByFp2(t,n),c1:o.mulByFp2(r,n)}}conjugate({c0:t,c1:r}){return{c0:t,c1:this.Fp6.neg(r)}}mul014({c0:t,c1:r},n,o,i){let{Fp6:s}=this,{Fp2:a}=s,c=s.mul01(t,n,o),l=s.mul1(r,i);return{c0:s.add(s.mulByNonresidue(l),c),c1:s.sub(s.sub(s.mul01(s.add(r,t),n,a.add(o,i)),c),l)}}mul034({c0:t,c1:r},n,o,i){let{Fp6:s}=this,{Fp2:a}=s,c=s.create({c0:a.mul(t.c0,n),c1:a.mul(t.c1,n),c2:a.mul(t.c2,n)}),l=s.mul01(r,o,i),d=s.mul01(s.add(t,r),a.add(n,o),i);return{c0:s.add(s.mulByNonresidue(l),c),c1:s.sub(d,s.add(c,l))}}_cyclotomicSquare({c0:t,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:i,c1:s,c2:a}=t,{c0:c,c1:l,c2:d}=r,{first:p,second:u}=o.Fp4Square(i,l),{first:f,second:h}=o.Fp4Square(c,a),{first:_,second:y}=o.Fp4Square(s,d),m=o.mulByNonresidue(y);return{c0:n.create({c0:o.add(o.mul(o.sub(p,i),Ge),p),c1:o.add(o.mul(o.sub(f,s),Ge),f),c2:o.add(o.mul(o.sub(_,a),Ge),_)}),c1:n.create({c0:o.add(o.mul(o.add(m,c),Ge),m),c1:o.add(o.mul(o.add(u,l),Ge),u),c2:o.add(o.mul(o.add(h,d),Ge),h)})}}_cyclotomicExp(t,r){let n=this.ONE;for(let o=this.X_LEN-1;o>=0;o--)n=this._cyclotomicSquare(n),Qu(r,o)&&(n=this.mul(n,t));return n}};function Ed(e){let t=$e(e.ORDER),r=new Fc(t,e),n=new Bc(r),o=new Dc(n,e);return{Fp:t,Fp2:r,Fp6:n,Fp12:o}}var Fe=BigInt(0),ks=BigInt(1),yt=BigInt(2),Ls=BigInt(3),bi=BigInt(4),rn=BigInt("0xd201000000010000"),Fm=Sr(rn),to={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Fe,b:bi,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},Bm=$e(to.n,{modFromBytes:!0,isLE:!0}),{Fp:L,Fp2:W,Fp6:Dm,Fp12:Q}=Ed({ORDER:to.p,X_LEN:Fm,FP2_NONRESIDUE:[ks,ks],Fp2mulByB:({c0:e,c1:t})=>{let r=L.mul(e,bi),n=L.mul(t,bi);return{c0:L.sub(r,n),c1:L.add(r,n)}},Fp12finalExponentiate:e=>{let t=rn,r=Q.div(Q.frobeniusMap(e,6),e),n=Q.mul(Q.frobeniusMap(r,2),r),o=Q.conjugate(Q._cyclotomicExp(n,t)),i=Q.mul(Q.conjugate(Q._cyclotomicSquare(n)),o),s=Q.conjugate(Q._cyclotomicExp(i,t)),a=Q.conjugate(Q._cyclotomicExp(s,t)),c=Q.mul(Q.conjugate(Q._cyclotomicExp(a,t)),Q._cyclotomicSquare(o)),l=Q.conjugate(Q._cyclotomicExp(c,t)),d=Q.frobeniusMap(Q.mul(o,a),2),p=Q.frobeniusMap(Q.mul(s,n),3),u=Q.frobeniusMap(Q.mul(c,Q.conjugate(n)),1),f=Q.mul(Q.mul(l,Q.conjugate(i)),n);return Q.mul(Q.mul(Q.mul(d,p),u),f)}}),{G2psi:Rd,G2psi2:Um}=Od(L,W,W.div(W.ONE,W.NONRESIDUE)),kc=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:L.ORDER,m:2,k:128,expand:"xmd",hash:Ve}),Mc={p:W.ORDER,n:to.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:W.ZERO,b:W.fromBigTuple([bi,bi]),Gx:W.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:W.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},qs=wi(L.toBytes(Fe),{infinity:!0,compressed:!0});function Ms(e){e=e.slice();let t=e[0]&224,r=!!(t>>7&1),n=!!(t>>6&1),o=!!(t>>5&1);return e[0]&=31,{compressed:r,infinity:n,sort:o,value:e}}function wi(e,t){if(e[0]&224)throw new Error("setMask: non-empty mask");return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function km(e,t,r){let{BYTES:n,ORDER:o}=L,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return qs.slice();let c=!!(a*yt/o);return wi(Oe(s,n),{compressed:!0,sort:c})}else return i?$(Uint8Array.of(64),new Uint8Array(2*n-1)):$(Oe(s,n),Oe(a,n))}function Lc(e){e.assertValidity();let{BYTES:t,ORDER:r}=L,{x:n,y:o}=e.toAffine();if(e.is0())return qs.slice();let i=!!(o*yt/r);return wi(Oe(n,t),{compressed:!0,sort:i})}function Lm(e){let{compressed:t,infinity:r,sort:n,value:o}=Ms(e),{BYTES:i,ORDER:s}=L;if(o.length===48&&t){let a=Qe(o),c=L.create(a&Ut(L.BITS));if(r){if(c!==Fe)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:Fe,y:Fe}}let l=L.add(L.pow(c,Ls),L.create(to.b)),d=L.sqrt(l);if(!d)throw new Error("invalid G1 point: compressed point");return d*yt/s!==BigInt(n)&&(d=L.neg(d)),{x:L.create(c),y:L.create(d)}}else if(o.length===96&&!t){let a=Qe(o.subarray(0,i)),c=Qe(o.subarray(i));if(r){if(a!==Fe||c!==Fe)throw new Error("G1: non-empty point at infinity");return Ti.G1.Point.ZERO.toAffine()}return{x:L.create(a),y:L.create(c)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function vd(e){let{infinity:t,sort:r,value:n}=Ms(de("signatureHex",e,48)),o=L.ORDER,i=Ti.G1.Point,s=Qe(n);if(t)return i.ZERO;let a=L.create(s&Ut(L.BITS)),c=L.add(L.pow(a,Ls),L.create(to.b)),l=L.sqrt(c);if(!l)throw new Error("invalid G1 point: compressed");let d=BigInt(r);l*yt/o!==d&&(l=L.neg(l));let p=i.fromAffine({x:a,y:l});return p.assertValidity(),p}function qm(e,t,r){let{BYTES:n,ORDER:o}=L,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return $(qs,Oe(Fe,n));let c=!!(a.c1===Fe?a.c0*yt/o:a.c1*yt/o);return $(wi(Oe(s.c1,n),{compressed:!0,sort:c}),Oe(s.c0,n))}else{if(i)return $(Uint8Array.of(64),new Uint8Array(4*n-1));let{re:c,im:l}=W.reim(s),{re:d,im:p}=W.reim(a);return $(Oe(l,n),Oe(c,n),Oe(p,n),Oe(d,n))}}function qc(e){e.assertValidity();let{BYTES:t}=L;if(e.is0())return $(qs,Oe(Fe,t));let{x:r,y:n}=e.toAffine(),{re:o,im:i}=W.reim(r),{re:s,im:a}=W.reim(n),l=!!((a>Fe?a*yt:s*yt)/L.ORDER&ks),d=o;return $(wi(Oe(i,t),{sort:l,compressed:!0}),Oe(d,t))}function Mm(e){let{BYTES:t,ORDER:r}=L,{compressed:n,infinity:o,sort:i,value:s}=Ms(e);if(!n&&!o&&i||!n&&o&&i||i&&o&&n)throw new Error("invalid encoding flag: "+(e[0]&224));let a=(c,l,d)=>Qe(c.slice(l,d));if(s.length===96&&n){if(o){if(s.reduce((h,_)=>h!==0?_+1:_,0)>0)throw new Error("invalid G2 point: compressed");return{x:W.ZERO,y:W.ZERO}}let c=a(s,0,t),l=a(s,t,2*t),d=W.create({c0:L.create(l),c1:L.create(c)}),p=W.add(W.pow(d,Ls),Mc.b),u=W.sqrt(p),f=u.c1===Fe?u.c0*yt/r:u.c1*yt/r?ks:Fe;return u=i&&f>0?u:W.neg(u),{x:d,y:u}}else if(s.length===192&&!n){if(o){if(s.reduce((u,f)=>u!==0?f+1:f,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:W.ZERO,y:W.ZERO}}let c=a(s,0*t,1*t),l=a(s,1*t,2*t),d=a(s,2*t,3*t),p=a(s,3*t,4*t);return{x:W.fromBigTuple([l,c]),y:W.fromBigTuple([p,d])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function Id(e){let{ORDER:t}=L,{infinity:r,sort:n,value:o}=Ms(de("signatureHex",e)),i=Ti.G2.Point,s=o.length/2;if(s!==48&&s!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");let a=Qe(o.slice(0,s)),c=Qe(o.slice(s));if(r)return i.ZERO;let l=L.create(a&Ut(L.BITS)),d=L.create(c),p=W.create({c0:d,c1:l}),u=W.add(W.pow(p,Ls),Mc.b),f=W.sqrt(u);if(!f)throw new Error("Failed to find a square root");let{re:h,im:_}=W.reim(f),y=BigInt(n),m=_>Fe&&_*yt/t!==y,b=_===Fe&&h*yt/t!==y;(m||b)&&(f=W.neg(f));let g=i.fromAffine({x:p,y:f});return g.assertValidity(),g}var Ti=bd({fields:{Fp:L,Fp2:W,Fp6:Dm,Fp12:Q,Fr:Bm},G1:{...to,Fp:L,htfDefaults:{...kc,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(e,t)=>{let r=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),n=new e(L.mul(t.X,r),t.Y,t.Z);return t.multiplyUnsafe(rn).negate().multiplyUnsafe(rn).equals(n)},clearCofactor:(e,t)=>t.multiplyUnsafe(rn).add(t),mapToCurve:Gm,fromBytes:Lm,toBytes:km,ShortSignature:{fromBytes(e){return fe(e),vd(e)},fromHex(e){return vd(e)},toBytes(e){return Lc(e)},toRawBytes(e){return Lc(e)},toHex(e){return j(Lc(e))}}},G2:{...Mc,Fp:W,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...kc},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:Jm,isTorsionFree:(e,t)=>t.multiplyUnsafe(rn).negate().equals(Rd(e,t)),clearCofactor:(e,t)=>{let r=rn,n=t.multiplyUnsafe(r).negate(),o=Rd(e,t),i=t.double();return i=Um(e,i),i=i.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),i=i.add(o),i=i.subtract(n),i.subtract(t)},fromBytes:Mm,toBytes:qm,Signature:{fromBytes(e){return fe(e),Id(e)},fromHex(e){return Id(e)},toBytes(e){return qc(e)},toRawBytes(e){return qc(e)},toHex(e){return j(qc(e))}}},params:{ateLoopSize:rn,r:to.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:kc,hash:Ve}),jm=Ic(W,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(e=>e.map(t=>W.fromBigTuple(t.map(BigInt))))),Km=Ic(L,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),$m=Cc(L,{A:L.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:L.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:L.create(BigInt(11))}),Hm=Cc(W,{A:W.create({c0:L.create(Fe),c1:L.create(BigInt(240))}),B:W.create({c0:L.create(BigInt(1012)),c1:L.create(BigInt(1012))}),Z:W.create({c0:L.create(BigInt(-2)),c1:L.create(BigInt(-1))})});function Gm(e){let{x:t,y:r}=$m(L.create(e[0]));return Km(t,r)}function Jm(e){let{x:t,y:r}=Hm(W.fromBigTuple(e));return jm(t,r)}function Ad(e,t,r){let n=typeof e=="string"?e:j(e),o=typeof t=="string"?t:j(t),i=typeof r=="string"?r:j(r);return Ti.verifyShortSignature(o,i,n)}var zm=BigInt(1e6),jc=e=>_e(new Vt(e)),nn=e=>{let r=jc(e)/zm;return new Date(Number(r))};var Sd=60*1e3,Ym=60,Zm=24,Xm=Zm*Ym,Qm=5,e_=5,t_=30*Xm,pe;(function(e){e[e.Empty=0]="Empty",e[e.Fork=1]="Fork",e[e.Labeled=2]="Labeled",e[e.Leaf=3]="Leaf",e[e.Pruned=4]="Pruned"})(pe||(pe={}));function r_(e,t){for(let r=0;r<e.length;r++)if(e[r]>t[r])return!0;return!1}var gt=class e{#e=!1;#t=void 0;static async create(t){let r=e.createUnverified(t);return await r.verify(),r}static createUnverified(t){return new e(t.certificate,t.rootKey,t.principal,t.blsVerify??Ad,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,r,n,o,i=Qm,s=!1,a){this._rootKey=r,this._principal=n,this._blsVerify=o,this._maxAgeInMinutes=i,this.#e=s,this.cert=je(t),a&&"getTimeDiffMsecs"in a&&"hasSyncedTime"in a&&"syncTime"in a&&"syncTimeWithSubnet"in a&&(this.#t=a)}lookup_path(t){return Br(t,this.cert.tree)}lookup_subtree(t){return Ei(t,this.cert.tree)}async verify(){let t=await Ks(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,o=o_(r),i=$(sc,t),s=De(this.lookup_path(["time"]));if(!s)throw re.fromCode(new It("Certificate does not contain a time"));if(!this.#e){let a=this.#t?.getTimeDiffMsecs()??0,c=this._maxAgeInMinutes*Sd,l=new Date,d=l.getTime()+a,p=d-c,u=d+e_*Sd,f=nn(s),h=f.getTime()<p,_=f.getTime()>u;if((h||_)&&this.#t&&!this.#t.hasSyncedTime())return await this._syncTime(),await this.verify();if(h)throw Ye.fromCode(new Tr(this._maxAgeInMinutes,f,l,a,"past"));if(_)throw this.#t?.hasSyncedTime()?ae.fromCode(new Se("System time has been synced with the IC network, but certificate is still too far in the future.")):Ye.fromCode(new Tr(5,f,l,a,"future"))}try{if(!await this._blsVerify(o,n,i))throw Ye.fromCode(new It("Invalid signature"))}catch(a){throw Ye.fromCode(new It("Signature verification failed",a))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let r=e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,principal:this._principal,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:t_,agent:this.#t});if(r.cert.delegation)throw re.fromCode(new Zi);await r.verify();let n;if(Vd(this._principal)){let i=this._principal.canisterId;if(n=q.fromUint8Array(t.subnet_id),!Kc({canisterId:i,subnetId:n,tree:r.cert.tree}))throw Ye.fromCode(new Mn(i,n))}else if(Cd(this._principal))n=this._principal.subnetId;else throw ft;let o=De(r.lookup_path(["subnet",n.toUint8Array(),"public_key"]));if(!o)throw Cd(this._principal)?Ye.fromCode(new Xi(n)):Ye.fromCode(new es(`Could not find subnet key for subnet ID ${n.toText()}`));return o}async _syncTime(){this.#t&&(Vd(this._principal)?await this.#t.syncTime(this._principal.canisterId):await this.#t.syncTimeWithSubnet(this._principal.subnetId))}};function Cd(e){return"subnetId"in e}function Vd(e){return"canisterId"in e}var Ni=Ee("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),n_=96;function o_(e){let t=Ni.byteLength+n_;if(e.byteLength!==t)throw re.fromCode(new uo(t,e.byteLength));let r=e.slice(0,Ni.byteLength);if(!Jn(r,Ni))throw re.fromCode(new ts(Ni,r));return e.slice(Ni.byteLength)}function De(e){if(e.status===Be.Found&&e.value instanceof Uint8Array)return e.value}async function Ks(e){switch(e[0]){case pe.Empty:return Ve(js("ic-hashtree-empty"));case pe.Pruned:return e[1];case pe.Leaf:return Ve($(js("ic-hashtree-leaf"),e[1]));case pe.Labeled:return Ve($(js("ic-hashtree-labeled"),e[1],await Ks(e[2])));case pe.Fork:return Ve($(js("ic-hashtree-fork"),await Ks(e[1]),await Ks(e[2])));default:throw ft}}function js(e){let t=new Uint8Array([e.length]),r=new TextEncoder().encode(e);return $(t,r)}function Pd(e){return typeof e[0]=="string"?G(e[0]):e[0]}var Be;(function(e){e.Unknown="Unknown",e.Absent="Absent",e.Found="Found",e.Error="Error"})(Be||(Be={}));var on;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(on||(on={}));var le;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(le||(le={}));function Br(e,t){if(e.length===0)switch(t[0]){case pe.Empty:return{status:Be.Absent};case pe.Leaf:{if(!t[1])throw ae.fromCode(new zr("Invalid tree structure for leaf"));if(t[1]instanceof Uint8Array)return{status:Be.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw ft}case pe.Pruned:return{status:Be.Unknown};case pe.Labeled:case pe.Fork:return{status:Be.Error};default:throw ft}let r=Pd(e),n=Oi(r,t);switch(n.status){case le.Found:return Br(e.slice(1),n.value);case le.Absent:case le.Greater:case le.Less:return{status:Be.Absent};case le.Unknown:return{status:Be.Unknown};default:throw ft}}function Ei(e,t){if(e.length===0)return{status:on.Found,value:t};let r=Pd(e),n=Oi(r,t);switch(n.status){case le.Found:return Ei(e.slice(1),n.value);case le.Unknown:return{status:on.Unknown};case le.Absent:case le.Greater:case le.Less:return{status:on.Absent};default:throw ft}}function Hs(e){switch(e[0]){case pe.Empty:return[];case pe.Fork:return Hs(e[1]).concat(Hs(e[2]));default:return[e]}}function Oi(e,t){switch(t[0]){case pe.Labeled:return r_(e,t[1])?{status:le.Greater}:Jn(e,t[1])?{status:le.Found,value:t[2]}:{status:le.Less};case pe.Fork:{let r=Oi(e,t[1]);switch(r.status){case le.Greater:{let n=Oi(e,t[2]);return n.status===le.Less?{status:le.Absent}:n}case le.Unknown:{let n=Oi(e,t[2]);return n.status===le.Less?{status:le.Unknown}:n}default:return r}}case pe.Pruned:return{status:le.Unknown};default:return{status:le.Absent}}}function $s(e,t){switch(t[0]){case pe.Empty|pe.Pruned:return[];case pe.Leaf:return[e];case pe.Fork:return $s(e,t[1]).concat($s(e,t[2]));case pe.Labeled:{let r=t[1],n=t[2],o=[...e,r];return $s(o,n)}default:throw ft}}function Kc(e){let t=i_(e),r=$c(t),{canisterId:n}=e;return r.some(i=>i[0].ltEq(n)&&i[1].gtEq(n))}function i_(e){let{subnetId:t,tree:r,canisterId:n}=e,o=Ei(["canister_ranges",t.toUint8Array()],r);if(o.status!==on.Found)return s_(t,r);let i=o.value,s=a_(i);if(s.length===0)throw re.fromCode(new Mn(n,t));s.sort(po);let a=c_(s,n),c=s[a];return l_(c,i)}function s_(e,t){let r=Br(["subnet",e.toUint8Array(),"canister_ranges"],t);if(r.status!==Be.Found)throw re.fromCode(new At(`Could not find canister ranges for subnet ${e.toText()}`,r.status));return r.value}function $c(e){return je(e).map(n=>[q.fromUint8Array(n[0]),q.fromUint8Array(n[1])])}function a_(e){let t=[];for(let r of $s([],e)){let n=r[0];if(!n)throw re.fromCode(new It("Path is invalid"));t.push(n)}return t}function c_(e,t){let r=t.toUint8Array(),n=0,o=e.length-1;for(;n<o;){let i=Math.floor((n+o)/2);po(e[i],r)<=0?o=i:n=i+1}return n}function l_(e,t){let r=Br([e],t);if(r.status!==Be.Found)throw re.fromCode(new At(`Could not find canister range for shard ${e.toString()}`,r.status));return r.value}function Hc(e,t){return e.delegation?q.fromUint8Array(e.delegation.subnet_id):q.selfAuthenticating(t)}var Fd=q.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe");function Gs(e,t){switch(t){case"raw":return e;case"leb128":return jc(e);case"cbor":return je(e);case"hex":return j(e);case"utf-8":return new TextDecoder().decode(e)}}function Bd(e){return je(e).map(r=>q.fromUint8Array(r))}function Dd(e,t){let r=typeof e=="string"?G(e):e;return[G("canister"),t,G("metadata"),r]}function sn(e){return typeof e=="object"&&e!==null&&"key"in e&&"path"in e}function vo(e,t){let r=Ei(["subnet",t.toUint8Array(),"node"],e.tree);if(r.status!==on.Found)throw re.fromCode(new At("Node not found",r.status));if(r.value instanceof Uint8Array)throw ae.fromCode(new zr("Invalid node tree"));let n=Hs(r.value),o=new Map;return n.forEach(i=>{let s=q.from(i[1]).toText(),a=Br(["public_key"],i[2]);if(a.status!==Be.Found)throw re.fromCode(new At("Public key not found",a.status));let c=a.value;if(c.byteLength!==44)throw re.fromCode(new uo(44,c.byteLength));o.set(s,c)}),o}var Ud=async e=>{let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=q.from(e.canisterId),i=[...new Set(r)],s=new Map,a=i.map((c,l)=>{let d=d_(c,o);return(async()=>{try{if(t.rootKey===null)throw Pe.fromCode(new Ct);let p=t.rootKey,u=await t.readState(o,{paths:[d]}),f=await gt.create({certificate:u.certificate,rootKey:p,principal:{canisterId:o},disableTimeVerification:n,agent:t}),h=(m,b)=>{if(b==="subnet"){let g=u_(u.certificate,o,p);return{path:b,data:g}}return{path:b,data:De(m.lookup_path(d))}},{path:_,data:y}=h(f,i[l]);if(!y)typeof _=="string"?s.set(_,null):s.set(_.key,null);else switch(_){case"time":{s.set(_,nn(y));break}case"controllers":{s.set(_,Bd(y));break}case"module_hash":{s.set(_,j(y));break}case"subnet":{s.set(_,y);break}case"candid":{s.set(_,new TextDecoder().decode(y));break}default:sn(_)&&s.set(_.key,Gs(y,_.decodeStrategy))}}catch(p){if(p instanceof st&&(p.hasCode(It)||p.hasCode(Tr)))throw p;sn(c)?s.set(c.key,null):s.set(c,null)}})()});return await Promise.all(a),s},u_=(e,t,r)=>{if(!t._isPrincipal)throw z.fromCode(new Se("Invalid canisterId"));let n=je(e),{delegation:o}=n,i;o&&o.subnet_id?i=q.fromUint8Array(new Uint8Array(o.subnet_id)):!o&&typeof r<"u"?i=q.selfAuthenticating(new Uint8Array(r)):i=Fd;let s=vo(n,i);return{subnetId:i.toText(),nodeKeys:s}},d_=(e,t)=>{let r=t.toUint8Array();switch(e){case"time":return[G("time")];case"controllers":return[G("canister"),r,G("controllers")];case"module_hash":return[G("canister"),r,G("module_hash")];case"subnet":return[G("subnet")];case"candid":return[G("canister"),r,G("metadata"),G("candid:service")];default:if(sn(e))return typeof e.path=="string"||e.path instanceof Uint8Array?Dd(e.path,r):e.path}throw ae.fromCode(new Se(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))};async function kd(e){let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=q.from(e.subnetId),i=[...new Set(r)],s=new Map,a=i.map((c,l)=>{let d=p_(c,o);return(async()=>{try{if(t.rootKey===null)throw Pe.fromCode(new Ct);let p=t.rootKey,u=await t.readSubnetState(o,{paths:[d]}),f=await gt.create({certificate:u.certificate,rootKey:p,principal:{subnetId:o},disableTimeVerification:n,agent:t}),h=(m,b)=>{if(b==="nodeKeys"){let g=vo(m.cert,o);return{path:b,data:g}}return{path:b,data:De(m.lookup_path(d))}},{path:_,data:y}=h(f,i[l]);if(!y)typeof _=="string"?s.set(_,null):s.set(_.key,null);else switch(_){case"time":{s.set(_,nn(y));break}case"canisterRanges":{s.set(_,$c(y));break}case"publicKey":{s.set(_,y);break}case"nodeKeys":{s.set(_,y);break}default:sn(_)&&s.set(_.key,Gs(y,_.decodeStrategy))}}catch(p){if(p instanceof st&&(p.hasCode(It)||p.hasCode(Tr)))throw p;sn(c)?s.set(c.key,null):s.set(c,null)}})()});return await Promise.all(a),s}function p_(e,t){let r=t.toUint8Array();switch(e){case"time":return[G("time")];case"canisterRanges":return[G("canister_ranges"),r];case"publicKey":return[G("subnet"),r,G("public_key")];case"nodeKeys":return[G("subnet"),r,G("node")];default:if(sn(e)){if(typeof e.path=="string"||e.path instanceof Uint8Array){let n=typeof e.path=="string"?G(e.path):e.path;return[G("subnet"),r,n]}return e.path}}throw ae.fromCode(new Se(`Error while encoding your path for subnet status. Please ensure that your path ${e} was formatted correctly.`))}function Js(e,t,r){let n=new Uint8Array(De(e.lookup_path([...t,"reject_code"])))[0],o=new TextDecoder().decode(De(e.lookup_path([...t,"reject_message"]))),i=De(e.lookup_path([...t,"error_code"])),s=i?new TextDecoder().decode(i):void 0;return new ss(r,n,o,s)}var an=BigInt(0),ve=BigInt(1),Gc=BigInt(2),f_=BigInt(8);function h_(e,t,r,n){let o=e.sqr(r),i=e.sqr(n),s=e.add(e.mul(t.a,o),i),a=e.add(e.ONE,e.mul(t.d,e.mul(o,i)));return e.eql(s,a)}function m_(e,t={}){let r=Ds("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,i=r.CURVE,{h:s}=i;Cr(t,{},{uvRatio:"function"});let a=Gc<<BigInt(o.BYTES*8)-ve,c=y=>n.create(y),l=t.uvRatio||((y,m)=>{try{return{isValid:!0,value:n.sqrt(n.div(y,m))}}catch{return{isValid:!1,value:an}}});if(!h_(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function d(y,m,b=!1){let g=b?ve:an;return Ps("coordinate "+y,m,g,a),m}function p(y){if(!(y instanceof h))throw new Error("ExtendedPoint expected")}let u=en((y,m)=>{let{X:b,Y:g,Z:T}=y,O=y.is0();m==null&&(m=O?f_:n.inv(T));let v=c(b*m),E=c(g*m),C=n.mul(T,m);if(O)return{x:an,y:ve};if(C!==ve)throw new Error("invZ was invalid");return{x:v,y:E}}),f=en(y=>{let{a:m,d:b}=i;if(y.is0())throw new Error("bad point: ZERO");let{X:g,Y:T,Z:O,T:v}=y,E=c(g*g),C=c(T*T),w=c(O*O),I=c(w*w),P=c(E*m),A=c(w*c(P+C)),x=c(I+c(b*c(E*C)));if(A!==x)throw new Error("bad point: equation left != right (1)");let N=c(g*T),S=c(O*v);if(N!==S)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(m,b,g,T){this.X=d("x",m),this.Y=d("y",b),this.Z=d("z",g,!0),this.T=d("t",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){if(m instanceof h)throw new Error("extended point not allowed");let{x:b,y:g}=m||{};return d("x",b),d("y",g),new h(b,g,ve,c(b*g))}static fromBytes(m,b=!1){let g=n.BYTES,{a:T,d:O}=i;m=xc(Qr(m,g,"point")),Zn(b,"zip215");let v=xc(m),E=m[g-1];v[g-1]=E&-129;let C=Ar(v),w=b?a:n.ORDER;Ps("point.y",C,an,w);let I=c(C*C),P=c(I-ve),A=c(O*I-T),{isValid:x,value:N}=l(P,A);if(!x)throw new Error("bad point: invalid y coordinate");let S=(N&ve)===ve,B=(E&128)!==0;if(!b&&N===an&&B)throw new Error("bad point: x=0 and x_0=1");return B!==S&&(N=c(-N)),h.fromAffine({x:N,y:C})}static fromHex(m,b=!1){return h.fromBytes(de("point",m),b)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,b=!0){return _.createCache(this,m),b||this.multiply(Gc),this}assertValidity(){f(this)}equals(m){p(m);let{X:b,Y:g,Z:T}=this,{X:O,Y:v,Z:E}=m,C=c(b*E),w=c(O*T),I=c(g*E),P=c(v*T);return C===w&&I===P}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:m}=i,{X:b,Y:g,Z:T}=this,O=c(b*b),v=c(g*g),E=c(Gc*c(T*T)),C=c(m*O),w=b+g,I=c(c(w*w)-O-v),P=C+v,A=P-E,x=C-v,N=c(I*A),S=c(P*x),B=c(I*x),M=c(A*P);return new h(N,S,M,B)}add(m){p(m);let{a:b,d:g}=i,{X:T,Y:O,Z:v,T:E}=this,{X:C,Y:w,Z:I,T:P}=m,A=c(T*C),x=c(O*w),N=c(E*g*P),S=c(v*I),B=c((T+O)*(C+w)-A-x),M=S-N,R=S+N,V=c(x-b*A),F=c(B*M),D=c(R*V),k=c(B*V),te=c(M*R);return new h(F,D,te,k)}subtract(m){return this.add(m.negate())}multiply(m){if(!o.isValidNot0(m))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:b,f:g}=_.cached(this,m,T=>_t(h,T));return _t(h,[b,g])[0]}multiplyUnsafe(m,b=h.ZERO){if(!o.isValid(m))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return m===an?h.ZERO:this.is0()||m===ve?this:_.unsafe(this,m,g=>_t(h,g),b)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return _.unsafe(this,i.n).is0()}toAffine(m){return u(this,m)}clearCofactor(){return s===ve?this:this.multiplyUnsafe(s)}toBytes(){let{x:m,y:b}=this.toAffine(),g=n.toBytes(b);return g[g.length-1]|=m&ve?128:0,g}toHex(){return j(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(m){return _t(h,m)}static msm(m,b){return Oo(h,o,m,b)}_setWindowSize(m){this.precompute(m)}toRawBytes(){return this.toBytes()}}h.BASE=new h(i.Gx,i.Gy,ve,c(i.Gx*i.Gy)),h.ZERO=new h(an,ve,ve,an),h.Fp=n,h.Fn=o;let _=new No(h,o.BITS);return h.BASE.precompute(8),h}var Ws=class{constructor(t){this.ep=t}static fromBytes(t){wo()}static fromHex(t){wo()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(t){return this.ep.toAffine(t)}toHex(){return j(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(t){return this.assertSame(t),this.init(this.ep.add(t.ep))}subtract(t){return this.assertSame(t),this.init(this.ep.subtract(t.ep))}multiply(t){return this.init(this.ep.multiply(t))}multiplyUnsafe(t){return this.init(this.ep.multiplyUnsafe(t))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(t,r){return this.init(this.ep.precompute(t,r))}toRawBytes(){return this.toBytes()}};function __(e,t,r={}){if(typeof t!="function")throw new Error('"hash" function param is required');Cr(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:i,Fn:s}=e,a=r.randomBytes||lo,c=r.adjustScalarBytes||(w=>w),l=r.domain||((w,I,P)=>{if(Zn(P,"phflag"),I.length||P)throw new Error("Contexts/pre-hash are not supported");return w});function d(w){return s.create(Ar(w))}function p(w){let I=g.secretKey;w=de("private key",w,I);let P=de("hashed private key",t(w),2*I),A=c(P.slice(0,I)),x=P.slice(I,2*I),N=d(A);return{head:A,prefix:x,scalar:N}}function u(w){let{head:I,prefix:P,scalar:A}=p(w),x=o.multiply(A),N=x.toBytes();return{head:I,prefix:P,scalar:A,point:x,pointBytes:N}}function f(w){return u(w).pointBytes}function h(w=Uint8Array.of(),...I){let P=$(...I);return d(t(l(P,de("context",w),!!n)))}function _(w,I,P={}){w=de("message",w),n&&(w=n(w));let{prefix:A,scalar:x,pointBytes:N}=u(I),S=h(P.context,A,w),B=o.multiply(S).toBytes(),M=h(P.context,B,N,w),R=s.create(S+M*x);if(!s.isValid(R))throw new Error("sign failed: invalid s");let V=$(B,s.toBytes(R));return Qr(V,g.signature,"result")}let y={zip215:!0};function m(w,I,P,A=y){let{context:x,zip215:N}=A,S=g.signature;w=de("signature",w,S),I=de("message",I),P=de("publicKey",P,g.publicKey),N!==void 0&&Zn(N,"zip215"),n&&(I=n(I));let B=S/2,M=w.subarray(0,B),R=Ar(w.subarray(B,S)),V,F,D;try{V=e.fromBytes(P,N),F=e.fromBytes(M,N),D=o.multiplyUnsafe(R)}catch{return!1}if(!N&&V.isSmallOrder())return!1;let k=h(x,F.toBytes(),V.toBytes(),I);return F.add(V.multiplyUnsafe(k)).subtract(D).clearCofactor().is0()}let b=i.BYTES,g={secretKey:b,publicKey:b,signature:2*b,seed:b};function T(w=a(g.seed)){return Qr(w,g.seed,"seed")}function O(w){let I=C.randomSecretKey(w);return{secretKey:I,publicKey:f(I)}}function v(w){return jt(w)&&w.length===s.BYTES}function E(w,I){try{return!!e.fromBytes(w,I)}catch{return!1}}let C={getExtendedPublicKey:u,randomSecretKey:T,isValidSecretKey:v,isValidPublicKey:E,toMontgomery(w){let{y:I}=e.fromBytes(w),P=g.publicKey,A=P===32;if(!A&&P!==57)throw new Error("only defined for 25519 and 448");let x=A?i.div(ve+I,ve-I):i.div(I-ve,I+ve);return i.toBytes(x)},toMontgomerySecret(w){let I=g.secretKey;Qr(w,I);let P=t(w.subarray(0,I));return c(P).subarray(0,I)},randomPrivateKey:T,precompute(w=8,I=e.BASE){return I.precompute(w,!1)}};return Object.freeze({keygen:O,getPublicKey:f,sign:_,verify:m,utils:C,Point:e,lengths:g})}function y_(e){let t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},r=e.Fp,n=$e(t.n,e.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:e.uvRatio},i={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:o,hash:e.hash,eddsaOpts:i}}function g_(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function Ld(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=y_(e),i=m_(t,r),s=__(i,n,o);return g_(e,s)}var x_=BigInt(0),Dr=BigInt(1),qd=BigInt(2),Hb=BigInt(3),b_=BigInt(5),w_=BigInt(8),Io=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ri={p:Io,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:w_,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function T_(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=Io,a=e*e%i*e%i,c=kt(a,qd,i)*a%i,l=kt(c,Dr,i)*e%i,d=kt(l,b_,i)*l%i,p=kt(d,t,i)*d%i,u=kt(p,r,i)*p%i,f=kt(u,n,i)*u%i,h=kt(f,o,i)*f%i,_=kt(h,o,i)*f%i,y=kt(_,t,i)*d%i;return{pow_p_5_8:kt(y,qd,i)*e%i,b2:a}}function N_(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Jc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function Yc(e,t){let r=Io,n=ce(t*t*t,r),o=ce(n*n*t,r),i=T_(e*o).pow_p_5_8,s=ce(e*n*i,r),a=ce(t*s*s,r),c=s,l=ce(s*Jc,r),d=a===e,p=a===ce(-e,r),u=a===ce(-e*Jc,r);return d&&(s=c),(p||u)&&(s=l),Vr(s,r)&&(s=ce(-s,r)),{isValid:d||p,value:s}}var cn=$e(Ri.p,{isLE:!0}),O_=$e(Ri.n,{isLE:!0}),E_={...Ri,Fp:cn,hash:su,adjustScalarBytes:N_,uvRatio:Yc},Je=Ld(E_);var Wc=Jc,R_=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),v_=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),I_=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),A_=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Md=e=>Yc(Dr,e),S_=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),zc=e=>Je.Point.Fp.create(Ar(e)&S_);function jd(e){let{d:t}=Ri,r=Io,n=m=>cn.create(m),o=n(Wc*e*e),i=n((o+Dr)*I_),s=BigInt(-1),a=n((s-t*o)*n(o+t)),{isValid:c,value:l}=Yc(i,a),d=n(l*e);Vr(d,r)||(d=n(-d)),c||(l=d),c||(s=o);let p=n(s*(o-Dr)*A_-a),u=l*l,f=n((l+l)*a),h=n(p*R_),_=n(Dr-u),y=n(Dr+u);return new Je.Point(n(f*y),n(_*h),n(h*y),n(f*_))}function C_(e){fe(e,64);let t=zc(e.subarray(0,32)),r=jd(t),n=zc(e.subarray(32,64)),o=jd(n);return new Ur(r.add(o))}var Ur=class e extends Ws{constructor(t){super(t)}static fromAffine(t){return new e(Je.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return C_(de("ristrettoHash",t,64))}static fromBytes(t){fe(t,32);let{a:r,d:n}=Ri,o=Io,i=T=>cn.create(T),s=zc(t);if(!Xu(cn.toBytes(s),t)||Vr(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(Dr+r*a),l=i(Dr-r*a),d=i(c*c),p=i(l*l),u=i(r*n*d-p),{isValid:f,value:h}=Md(i(u*p)),_=i(h*l),y=i(h*_*u),m=i((s+s)*_);Vr(m,o)&&(m=i(-m));let b=i(c*y),g=i(m*b);if(!f||Vr(g,o)||b===x_)throw new Error("invalid ristretto255 encoding 2");return new e(new Je.Point(m,b,Dr,g))}static fromHex(t){return e.fromBytes(de("ristrettoHex",t,32))}static msm(t,r){return Oo(e,Je.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,i=Io,s=y=>cn.create(y),a=s(s(n+r)*s(n-r)),c=s(t*r),l=s(c*c),{value:d}=Md(s(a*l)),p=s(d*a),u=s(d*c),f=s(p*u*o),h;if(Vr(o*f,i)){let y=s(r*Wc),m=s(t*Wc);t=y,r=m,h=s(p*v_)}else h=u;Vr(t*f,i)&&(r=s(-r));let _=s((n-r)*h);return Vr(_,i)&&(_=s(-_)),cn.toBytes(_)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:i}=t.ep,s=l=>cn.create(l),a=s(r*i)===s(n*o),c=s(n*i)===s(r*o);return a||c}is0(){return this.equals(e.ZERO)}};Ur.BASE=new Ur(Je.Point.BASE);Ur.ZERO=new Ur(Je.Point.ZERO);Ur.Fp=cn;Ur.Fn=O_;function zs(e){if(!Number.isFinite(e)||e<=0)throw new Error(`expirationTime must be a positive finite number, got ${e}`)}var Ys=class{#e;#t;#r=null;constructor(t){if(typeof globalThis.indexedDB>"u")throw new Error("IndexedDBExpirableStore requires IndexedDB, which is not available in this environment");zs(t.expirationTime),this.#e=t.dbName,this.#t=t.storeName,this.expirationTime=t.expirationTime}#o(){return this.#r||(this.#r=this.#s().catch(t=>{throw this.#r=null,t})),this.#r}async#s(){let t=await this.#a();if(t.objectStoreNames.contains(this.#t))return t;let r=t.version+1;return t.close(),this.#a(r)}#a(t){let r=this.#t;return new Promise((n,o)=>{let i=globalThis.indexedDB.open(this.#e,t);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(r)||s.createObjectStore(r,{keyPath:"key"})},i.onsuccess=()=>{let s=i.result;s.onversionchange=()=>{s.close(),this.#r=null},n(s)},i.onerror=()=>o(i.error)})}async get(t){let r=await this.#o();return new Promise((n,o)=>{let a=r.transaction(this.#t,"readonly").objectStore(this.#t).get(t);a.onsuccess=()=>{let c=a.result;if(!c){n(void 0);return}if(Date.now()-c.timestamp>this.expirationTime){this.delete(t).then(()=>n(void 0),()=>n(void 0));return}n(c.value)},a.onerror=()=>o(a.error)})}async set(t,r){await this.#n();let n=await this.#o();return new Promise((o,i)=>{let s=n.transaction(this.#t,"readwrite"),a=s.objectStore(this.#t),c={key:t,value:r,timestamp:Date.now()};a.put(c),s.oncomplete=()=>o(),s.onerror=()=>i(s.error)})}async delete(t){let r=await this.#o();return new Promise((n,o)=>{let i=r.transaction(this.#t,"readwrite");i.objectStore(this.#t).delete(t),i.oncomplete=()=>n(),i.onerror=()=>o(i.error)})}async#n(){let t=await this.#o(),r=Date.now();return new Promise((n,o)=>{let i=t.transaction(this.#t,"readwrite"),a=i.objectStore(this.#t).openCursor();a.onsuccess=()=>{let c=a.result;if(!c)return;let l=c.value;r-l.timestamp>this.expirationTime&&c.delete(),c.continue()},i.oncomplete=()=>n(),i.onerror=()=>o(i.error)})}};var Zs=class{#e;constructor(t){zs(t.expirationTime),this.expirationTime=t.expirationTime,this.#e=new Map}get(t){let r=this.#e.get(t);return r?Date.now()-r.timestamp>this.expirationTime?(this.#e.delete(t),Promise.resolve(void 0)):Promise.resolve(r.value):Promise.resolve(void 0)}set(t,r){return this.#t(),this.#e.set(t,{value:r,timestamp:Date.now()}),Promise.resolve()}delete(t){return this.#e.delete(t),Promise.resolve()}#t(){let t=Date.now();for(let[r,n]of this.#e)t-n.timestamp>this.expirationTime&&this.#e.delete(r)}};function Kd(e){return typeof globalThis.indexedDB<"u"?new Ys(e):new Zs({expirationTime:e.expirationTime})}var $d=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw z.fromCode(new Jo("Length too long (> 4 bytes)"))},Hd=(e,t,r)=>{if(r<=127)return e[t]=r,1;if(r<=255)return e[t]=129,e[t+1]=r,2;if(r<=65535)return e[t]=130,e[t+1]=r>>8,e[t+2]=r,3;if(r<=16777215)return e[t]=131,e[t+1]=r>>16,e[t+2]=r>>8,e[t+3]=r,4;throw z.fromCode(new Jo("Length too long (> 4 bytes)"))},Zc=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw z.fromCode(new St("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw z.fromCode(new St("Length too long (> 4 bytes)"))},V_=(e,t)=>{let r=Zc(e,t);if(r===1)return e[t];if(r===2)return e[t+1];if(r===3)return(e[t+1]<<8)+e[t+2];if(r===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw z.fromCode(new St("Length too long (> 4 bytes)"))},vi=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),ro=Uint8Array.from([48,5,6,3,43,101,112]),nw=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),ow=Uint8Array.from([48,29,6,13,43,6,1,4,1,130,220,124,5,3,1,2,1,6,12,43,6,1,4,1,130,220,124,5,3,2,1]);function no(e,t){let r=2+$d(e.byteLength+1),n=t.byteLength+r+e.byteLength,o=0,i=new Uint8Array(1+$d(n)+n);return i[o++]=48,o+=Hd(i,o,n),i.set(t,o),o+=t.byteLength,i[o++]=3,o+=Hd(i,o,e.byteLength+1),i[o++]=0,i.set(new Uint8Array(e),o),i}var oo=(e,t)=>{let r=0,n=(a,c)=>{if(o[r++]!==a)throw z.fromCode(new St(`Expected ${c} at offset ${r}`))},o=new Uint8Array(e);if(n(48,"sequence"),r+=Zc(o,r),!Jn(o.slice(r,r+t.byteLength),t))throw z.fromCode(new St("Not the expected OID."));r+=t.byteLength,n(3,"bit string");let i=V_(o,r)-1;r+=Zc(o,r),n(0,"0 padding");let s=o.slice(r);if(i!==s.length)throw z.fromCode(new rs(i,s.length));return s};var Xs=class e{static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(t){return no(t,ro)}static derDecode(t){let r=oo(t,ro);if(r.length!==this.RAW_KEY_LENGTH)throw z.fromCode(new St("An Ed25519 public key must be exactly 32 bytes long"));return r}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw z.fromCode(new St("An Ed25519 public key must be exactly 32 bytes long"));this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}};var Xc=class{constructor(){this.observers=[]}subscribe(t){this.observers.push(t)}unsubscribe(t){this.observers=this.observers.filter(r=>r!==t)}notify(t,...r){this.observers.forEach(n=>n(t,...r))}},Qs=class extends Xc{constructor(){super()}print(t,...r){this.notify({message:t,level:"info"},...r)}warn(t,...r){this.notify({message:t,level:"warn"},...r)}error(t,r,...n){this.notify({message:t,level:"error",error:r},...n)}};var ea=class e{#e;#t;#r;#o;#s;#a;#n;#i;#l=0;static{this.default={initialInterval:500,randomizationFactor:.5,multiplier:1.5,maxInterval:6e4,maxElapsedTime:9e5,maxIterations:10,date:Date}}constructor(t=e.default){let{initialInterval:r=500,randomizationFactor:n=.5,multiplier:o=1.5,maxInterval:i=6e4,maxElapsedTime:s=9e5,maxIterations:a=10,date:c=Date}=t;this.#e=r,this.#t=n,this.#r=o,this.#o=i,this.#i=c,this.#s=c.now(),this.#a=s,this.#n=a}get ellapsedTimeInMsec(){return this.#i.now()-this.#s}get currentInterval(){return this.#e}get count(){return this.#l}get randomValueFromInterval(){let t=this.#t*this.#e,r=this.#e-t,n=this.#e+t;return Math.random()*(n-r)+r}incrementCurrentInterval(){return this.#e=Math.min(this.#e*this.#r,this.#o),this.#l++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#a||this.#l>=this.#n?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};var P_=300*1e3;function Gd(){return k_(B_(F_(),1e3),U_(1e3,1.2),D_(P_))}function F_(){let e=!0;return async()=>e?(e=!1,!0):!1}function B_(e,t){return async(r,n,o)=>{if(await e(r,n,o))return new Promise(i=>setTimeout(i,t))}}function D_(e){let t=Date.now()+e;return async(r,n,o)=>{if(Date.now()>t)throw re.fromCode(new jn(`Request timed out after ${e} msec`,n,o))}}function U_(e,t){let r=e;return()=>new Promise(n=>setTimeout(()=>{r*=t,n()},r))}function k_(...e){return async(t,r,n)=>{for(let o of e)await o(t,r,n)}}var Wd={preSignReadStateRequest:!1};function zd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Qc(e,t){return e!==null&&typeof e=="object"&&zd(e,t)}function q_(e,t){return zd(e,t)&&typeof e[t]=="function"}function Jd(e){return Qc(e,"body")&&Qc(e.body,"content")&&e.body.content.request_type===Yn.ReadState&&Qc(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&q_(e.body.content.ingress_expiry,"toHash")}async function ta(e,t,r,n={}){let o=[G("request_status"),r],i,s;if(n.preSignReadStateRequest??!1?(s=await M_({paths:[o],agent:e,pollingOptions:n}),i=await e.readState(t,{paths:[o]},void 0,s)):i=await e.readState(t,{paths:[o]}),e.rootKey==null)throw Pe.fromCode(new Ct);let c=await gt.create({certificate:i.certificate,rootKey:e.rootKey,principal:{canisterId:t},blsVerify:n.blsVerify,agent:e}),l=De(c.lookup_path([...o,G("status")])),d;switch(typeof l>"u"?d=lt.Unknown:d=new TextDecoder().decode(l),d){case lt.Replied:return{reply:De(c.lookup_path([...o,"reply"])),certificate:c,rawCertificate:i.certificate};case lt.Received:case lt.Unknown:case lt.Processing:{let p=n.strategy??Gd();return await p(t,r,d),ta(e,t,r,{...n,strategy:p,request:s})}case lt.Rejected:throw vt.fromCode(Js(c,o,r));case lt.Done:throw ae.fromCode(new ls(r))}throw ft}async function M_(e){let{paths:t,agent:r,pollingOptions:n}=e;if(n.request&&Jd(n.request))return n.request;let o=await r.createReadStateRequest?.({paths:t},void 0);if(!Jd(o))throw z.fromCode(new gs(o));return o}var rl=60*1e3,K_=1e6,$_=0,H_="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";var G_="ic0.app",J_=".ic0.app",W_="icp0.io",z_=".icp0.io",Y_="icp-api.io",Z_=".icp-api.io",el=200,Yd=202,X_=404;function Q_(e){let t;if(e!==void 0)!e.match(/^[a-z]+:/)&&typeof window<"u"?t=new URL(`${window.location.protocol}//${e}`):t=new URL(e);else{let r=["ic0.app","icp0.io","127.0.0.1","localhost"],n=[".github.dev",".gitpod.io"],o=typeof window<"u"?window.location:void 0,i=o?.hostname,s;i&&typeof i=="string"&&(n.some(a=>i.endsWith(a))?s=i:s=r.find(a=>i.endsWith(a))),o&&s?t=new URL(`${o.protocol}//${s}${o.port?`:${o.port}`:""}`):t=new URL("https://icp-api.io")}return t.toString()}var kr=class e{#e;#t;#r;#o;#s;#a;#n;#i;#l;#T;#c;#d;#f;#u;#x;get#R(){return this.#u*rl}#h;#m;#b;#_;constructor(t={}){if(this.#e=null,this.#t=!1,this.#r=$_,this.#o=!1,this.#s=null,this.#a=!1,this._isAgent=!0,this.config={},this.log=new Qs,this.#h=[],this.#m=[],this.#b=new Map,this.#_=!0,this.#N=(o,i)=>{if(this.#_===!1)return o;let{status:s,signatures:a=[],requestId:c}=o,l=i.size;if(a.length>l)throw re.fromCode(new fs(a.length,l));for(let d of a){let{timestamp:p,identity:u}=d,f=q.fromUint8Array(u).toText(),h;if(s===$r.Replied){let{reply:g}=o;h=ii({status:s,reply:g,timestamp:BigInt(p),request_id:c})}else if(s===$r.Rejected){let{reject_code:g,reject_message:T,error_code:O}=o;h=ii({status:s,reject_code:g,reject_message:T,error_code:O,timestamp:BigInt(p),request_id:c})}else throw ae.fromCode(new Se(`Unknown status: ${s}`));let _=$(ac,h),y=i.get(f);if(!y)throw re.fromCode(new ms);let m=Xs.fromDer(y).rawKey;if(!Je.verify(d.signature,_,m))throw Ye.fromCode(new _s(f))}return o},this.config=t,t.fetch)this.#i=t.fetch;else{let o=globalThis.fetch;if(typeof o!="function")throw z.fromCode(new ds);this.#i=o.bind(globalThis)}this.#l=t.fetchOptions,this.#T=t.callOptions,this.#t=t.shouldFetchRootKey??!1,this.#a=t.shouldSyncTime??!1,t.rootKey?this.rootKey=t.rootKey:this.#t?this.rootKey=null:this.rootKey=Ee(H_);let r=Q_(t.host);this.host=new URL(r),this.host.hostname.endsWith(J_)?this.host.hostname=G_:this.host.hostname.endsWith(z_)?this.host.hostname=W_:this.host.hostname.endsWith(Z_)&&(this.host.hostname=Y_),t.verifyQuerySignatures!==void 0&&(this.#_=t.verifyQuerySignatures),this.#x=t.subnetNodeKeyExpirableStore??Kd({dbName:`icp-sdk-${this.host.host}`,storeName:"subnetNodeKeys",expirationTime:5*rl}),this.#d=t.retryTimes??3;let n=()=>new ea({maxIterations:this.#d});if(this.#f=t.backoffStrategy||n,t.credentials){let{name:o,password:i}=t.credentials;this.#c=`${o}${i?`:${i}`:""}`}if(this.#n=Promise.resolve(t.identity||new at),t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes>5)throw z.fromCode(new $t("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw z.fromCode(new $t("Ingress expiry time must be greater than 0.",t.ingressExpiryInMinutes));this.#u=t.ingressExpiryInMinutes||5,this.addTransform("update",hc(hi)),t.useQueryNonces&&this.addTransform("query",hc(hi)),t.logToConsole&&this.log.subscribe(o=>{o.level==="error"?console.error(o.message):o.level==="warn"?console.warn(o.message):console.log(o.message)})}static createSync(t={}){return new this({...t})}static async create(t={}){let r=e.createSync(t);return await r.#p(),r}static async from(t){try{return"config"in t?await e.create(t.config):await e.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw z.fromCode(new ps)}}isLocal(){let t=this.host.hostname;return t==="127.0.0.1"||t.endsWith("127.0.0.1")}addTransform(t,r,n=r.priority||0){if(t==="update"){let o=this.#m.findIndex(i=>(i.priority||0)<n);this.#m.splice(o>=0?o:this.#m.length,0,Object.assign(r,{priority:n}))}else if(t==="query"){let o=this.#h.findIndex(i=>(i.priority||0)<n);this.#h.splice(o>=0?o:this.#h.length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this.#n)throw Pe.fromCode(new Wr);return(await this.#n).getPrincipal()}async call(t,r,n){let o=r.callSync??!0,i=await(n??this.#n);if(!i)throw Pe.fromCode(new Wr);let s=q.from(t),a=r.effectiveCanisterId?q.from(r.effectiveCanisterId):s;await this.#p(a);let c=i.getPrincipal(),l=tl(this.#u,this.#r),d={request_type:Cs.Call,canister_id:s,method_name:r.methodName,arg:r.arg,sender:c,ingress_expiry:l},p=await this._transform({request:{body:null,method:"POST",headers:{"Content-Type":"application/cbor",...this.#c?{Authorization:`Basic ${btoa(this.#c)}`}:{}}},endpoint:Ir.Call,body:d}),u;r?.nonce?u=f(r.nonce):p.body.nonce?u=f(p.body.nonce):u=void 0,d.nonce=u;function f(m){return Object.assign(m,{__nonce__:void 0})}p=await i.transformRequest(p);let h=pi(p.body),_=this.#f(),y=Rr(d);try{let g=o?()=>{let E=new URL(`/api/v4/canister/${a.toText()}/call`,this.host);return this.log.print(`fetching "${E.pathname}" with request:`,p),this.#i(E,{...this.#T,...p.request,body:h})}:()=>{let E=new URL(`/api/v2/canister/${a.toText()}/call`,this.host);return this.log.print(`fetching "${E.pathname}" with request:`,p),this.#i(E,{...this.#T,...p.request,body:h})},{responseBodyBytes:T,...O}=await this.#y({requestFn:g,backoff:_,tries:0}),v=T.byteLength>0?je(T):null;return{requestId:y,response:{...O,body:v},requestDetails:d}}catch(m){let b;if(m instanceof st){if(m.hasCode(zo))return this.log.warn("v4 api not supported. Fall back to v2"),this.call(t,{...r,callSync:!1},n);if(m.hasCode($t)&&!this.#o)return await this.syncTime(s),this.call(s,r,n);m.code.requestContext={requestId:y,senderPubKey:p.body.sender_pubkey,senderSignature:p.body.sender_sig,ingressExpiry:p.body.content.ingress_expiry},b=m}else b=ae.fromCode(new Se(m));throw this.log.error(`Error while making call: ${b.message}`,b),b}}async update(t,r,n={}){let o=q.from(r.effectiveCanisterId),{requestId:i,response:s,requestDetails:a}=await this.call(t,r),{body:c,...l}=s;if(Ml(c))return this.#v(c,s,i,o,r.methodName,l,a,n);if(ql(c)&&this.#I(c,i,o,r.methodName,l),s.status===Yd)return{...await ta(this,o,i,n),requestDetails:a,callResponse:s};let d=new Se(`Unexpected response from call: status ${s.status} with unrecognized body`);throw d.callContext={canisterId:o,methodName:r.methodName,httpDetails:l},ae.fromCode(d)}async#v(t,r,n,o,i,s,a,c){if(this.rootKey==null)throw Pe.fromCode(new Ct);let l=t.certificate,d=await gt.create({certificate:l,rootKey:this.rootKey,principal:{canisterId:o},blsVerify:c.blsVerify,agent:this}),p=[G("request_status"),n],u=De(d.lookup_path([...p,G("status")])),f=u?new TextDecoder().decode(u):void 0;switch(f){case lt.Replied:return{reply:De(d.lookup_path([...p,"reply"])),certificate:d,rawCertificate:l,requestDetails:a,callResponse:r};case lt.Rejected:{let h=Js(d,p,n);throw h.callContext={canisterId:o,methodName:i,httpDetails:s},vt.fromCode(h)}case void 0:return this.log.warn(`v4 sync response certificate does not contain request ID ${j(n)} status. Falling back to polling.`),{...await ta(this,o,n,c),requestDetails:a,callResponse:r};default:{let h=new ys(f,n,r,l);throw h.callContext={canisterId:o,methodName:i,httpDetails:s},ae.fromCode(h)}}}#I(t,r,n,o,i){let{reject_code:s,reject_message:a,error_code:c}=t,l=new cs(r,s,a,c);throw l.callContext={canisterId:n,methodName:o,httpDetails:i},vt.fromCode(l)}async#w(t){let{ecid:r,transformedRequest:n,body:o,requestId:i,backoff:s,tries:a}=t,c=a===0?0:s.next(),l=new URL(`/api/v3/canister/${r.toString()}/query`,this.host);if(this.log.print(`fetching "${l.pathname}" with tries:`,{tries:a,backoff:s,delay:c}),c===null)throw ae.fromCode(new jn(`Backoff strategy exhausted after ${a} attempts.`,i));c>0&&await new Promise(m=>setTimeout(m,c));let d;try{this.log.print(`fetching "${l.pathname}" with request:`,n),d=await this.#i(l,{...this.#l,...n.request,body:o})}catch(m){if(a<this.#d)return this.log.warn(`Caught exception while attempting to make query:
51
53
  ${m}
52
- Retrying query.`),await this.#b({...t,tries:a+1});throw ko.fromCode(new jo(m))}let d=qa(p.headers);if(p.status!==Oc){let m=await p.text();if(hd(m))throw Y.fromCode(new Mt(m,this.#l));if(a<this.#u)return await this.#b({...t,tries:a+1});throw ee.fromCode(new qo(p.status,p.statusText,d,m))}let f={...Ke(lo(await p.arrayBuffer())),httpDetails:{ok:p.ok,status:p.status,statusText:p.statusText,headers:d},requestId:i};if(!this.#y)return f;let h=f.signatures?.[0]?.timestamp;if(!h)throw ee.fromCode(new Zi("Timestamp not found in query response. This suggests a malformed or malicious response."));let _=Number(BigInt(h)/BigInt(Pm));if(Date.now()+this.#r-_>this.#E){if(a<this.#u)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:i,signatureTimestampMs:_}),await this.syncTime(r),await this.#b({...t,tries:a+1});throw Me.fromCode(new Gi(this.#l,i,a))}return f}async#g(t){let{requestFn:r,backoff:n,tries:o}=t,i=o===0?0:n.next();if(i===null)throw ee.fromCode(new Dn(`Retry strategy exhausted after ${o} attempts.`));i>0&&await new Promise(p=>setTimeout(p,i));let s,a=new Uint8Array;try{s=await r(),s.status===Oc&&(a=lo(await s.clone().arrayBuffer()))}catch(p){if(o<this.#u)return this.log.warn(`Caught exception while attempting to make request:
53
- ${p}
54
- Retrying request.`),await this.#g({requestFn:r,backoff:n,tries:o+1});throw ko.fromCode(new jo(p))}let c=qa(s.headers);if(s.status===Oc||s.status===Km)return{ok:s.ok,status:s.status,statusText:s.statusText,responseBodyBytes:a,headers:c};let u=await s.text();if(s.status===Hm&&s.url.includes("api/v4"))throw ee.fromCode(new Mo);if(hd(u))throw Y.fromCode(new Mt(u,this.#l));if(o<this.#u)return await this.#g({requestFn:r,backoff:n,tries:o+1});throw ee.fromCode(new qo(s.status,s.statusText,c,u))}async query(t,r,n){let o=this.#f(),i=r.effectiveCanisterId?k.from(r.effectiveCanisterId):k.from(t);await this.#p(i),this.log.print(`ecid ${i.toString()}`),this.log.print(`canisterId ${t.toString()}`);let s,a=await(n??this.#n);if(!a)throw me.fromCode(new Lr);let c=k.from(t),u=a.getPrincipal(),p=Ec(this.#l,this.#r),d={request_type:Kn.Query,canister_id:c,method_name:r.methodName,arg:r.arg,sender:u,ingress_expiry:p},l=gr(d);s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:br.Query,body:d}),s=await a.transformRequest(s);let f=ni(s.body),h={canister:c.toText(),ecid:i,transformedRequest:s,body:f,requestId:l,backoff:o,tries:0},_=async()=>{let m=await this.#b(h);return{requestDetails:d,...m}},g=async()=>{let m=this.#_.get(i.toString());if(m)return m;await this.fetchSubnetKeys(i.toString());let b=this.#_.get(i.toString());if(!b)throw Me.fromCode(new Xi);return b};try{if(!this.#y)return await _();let[m,b]=await Promise.all([_(),g()]);try{return this.#T(m,b)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#_.delete(i.toString());let y=await g();return this.#T(m,y)}}catch(m){let b;if(m instanceof ot){if(m.hasCode(Mt)&&!this.#i)return await this.syncTime(i),this.query(t,r,n);m.code.requestContext={requestId:l,senderPubKey:s.body.sender_pubkey,senderSignature:s.body.sender_sig,ingressExpiry:s.body.content.ingress_expiry},b=m}else b=ae.fromCode(new Re(m));throw this.log.error(`Error while making query: ${b.message}`,b),b}}#T;async createReadStateRequest(t,r){await this.#p();let n=await(r??this.#n);if(!n)throw me.fromCode(new Lr);let o=n.getPrincipal(),i=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:br.ReadState,body:{request_type:Kn.ReadState,paths:t.paths,sender:o,ingress_expiry:Ec(this.#l,this.#r)}});return n.transformRequest(i)}async readState(t,r,n,o){await this.#x();let i=k.from(t);function s(p){for(let d of p.paths){let[l,f]=d,h=new TextEncoder().encode("request_status");if(Mn(l,h))return f}}let a,c;if(o)a=o;else{c=s(r);let p=await this.#n;if(!p)throw me.fromCode(new Lr);a=await this.createReadStateRequest(r,p)}let u=new URL(`/api/v3/canister/${i.toString()}/read_state`,this.host);return await this.#N(u,{canisterId:i},a,c)}async readSubnetState(t,r){await this.#x();let n=k.from(t),o=new URL(`/api/v3/subnet/${n.toString()}/read_state`,this.host),i=await this.createReadStateRequest(r,this.#n??void 0);return await this.#N(o,{subnetId:n},i)}async#N(t,r,n,o){let i=this.#f();try{let{responseBodyBytes:s}=await this.#g({requestFn:()=>this.#o(t,{...this.#c,...n.request,body:ni(n.body)}),backoff:i,tries:0});return Ke(s)}catch(s){let a;if(s instanceof ot){if(s.hasCode(Mt)&&!this.#i){if("canisterId"in r)await this.syncTime(r.canisterId);else if("subnetId"in r)await this.syncTimeWithSubnet(r.subnetId);else throw ut;return await this.#N(t,r,n,o)}s.code.requestContext={requestId:o??gr(n),senderPubKey:n.body.sender_pubkey,senderSignature:n.body.sender_sig,ingressExpiry:n.body.content.ingress_expiry},a=s}else a=ae.fromCode(new Re(s));throw this.log.error(`Error while making read state: ${a.message}`,a),a}}parseTimeFromResponse(t){let r;if(t.certificate){let n=Ke(t.certificate);if(n&&"tree"in n)r=n.tree;else throw ee.fromCode(new qr("Could not decode time from response"));let o=vr(["time"],r);if(o.status!==Be.Found)throw ee.fromCode(new It("Time was not found in the response or was not in its expected format.",o.status));if(!(o.value instanceof Uint8Array)&&!ArrayBuffer.isView(o))throw ee.fromCode(new Li("Time was not in its expected format."));let i=Wr(o.value);return this.log.print("Time from response:",i),this.log.print("Time from response in milliseconds:",i.getTime()),i.getTime()}else this.log.warn("No certificate found in response");return 0}async syncTime(t){this.#a=this.#a??(async()=>{await this.#x();let r=Date.now();try{t||this.log.print("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");let n=t??k.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),o=e.createSync({identity:new it,host:this.host.toString(),fetch:this.#o,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),i=await Promise.all(Array(3).fill(null).map(async()=>{let a=(await od({canisterId:n,agent:o,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(a instanceof Date)return a.getTime()},[]));this.#O(r,i)}catch(n){let o=n instanceof ot?n:ae.fromCode(new Re(n));throw this.log.error("Caught exception while attempting to sync time",o),o}})(),await this.#a.finally(()=>{this.#a=null})}async syncTimeWithSubnet(t){await this.#x();let r=Date.now();try{let n=e.createSync({identity:new it,host:this.host.toString(),fetch:this.#o,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),o=await Promise.all(Array(3).fill(null).map(async()=>{let s=(await id({subnetId:t,agent:n,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(s instanceof Date)return s.getTime()},[]));this.#O(r,o)}catch(n){let o=n instanceof ot?n:ae.fromCode(new Re(n));throw this.log.error("Caught exception while attempting to sync time with subnet",o),o}}#O(t,r){let n=r.reduce((o,i)=>typeof i=="number"&&i>o?i:o,0);n>0&&(this.#r=n-t,this.#i=!0,this.log.notify({message:`Syncing time: offset of ${this.#r}`,level:"info"}))}async status(){let t=this.#s?{Authorization:"Basic "+btoa(this.#s)}:{},r=new URL("/api/v2/status",this.host);this.log.print(`fetching "${r.pathname}"`);let n=this.#f(),{responseBodyBytes:o}=await this.#g({backoff:n,requestFn:()=>this.#o(r,{headers:t,...this.#c}),tries:0});return Ke(o)}async fetchRootKey(){return this.#e=this.#e??(async()=>{let t=await this.status();return this.rootKey=t.root_key,this.rootKey})(),await this.#e.finally(()=>{this.#e=null})}async#p(t){await Promise.all([this.#x(),this.#R(t)])}async#x(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#t)await this.fetchRootKey();else throw me.fromCode(new lt(this.#t))}async#R(t){this.#d&&!this.hasSyncedTime()&&await this.syncTime(t)}invalidateIdentity(){this.#n=null}replaceIdentity(t){this.#n=Promise.resolve(t)}async fetchSubnetKeys(t){let r=k.from(t);await this.#p(r);let n=this.rootKey,o=await this.readState(r,{paths:[[G("subnet")]]}),i=await at.create({certificate:o.certificate,rootKey:n,principal:{canisterId:r},agent:this});if(!i.cert.delegation){let c=k.selfAuthenticating(n);if(!hc({canisterId:r,subnetId:c,tree:i.cert.tree}))throw Me.fromCode(new Bn(r,c))}let s=_c(i.cert,n),a=wo(i.cert,s);return this.#_.set(r.toText(),a),a}async getSubnetIdFromCanister(t){let r=k.from(t);await this.#p(r);let n=await this.readState(r,{paths:[[G("time")]]}),o=await at.create({certificate:n.certificate,rootKey:this.rootKey,principal:{canisterId:r},agent:this});return _c(o.cert,this.rootKey)}_transform(t){let r=Promise.resolve(t);if(t.endpoint===br.Call)for(let n of this.#m)r=r.then(o=>n(o).then(i=>i||o));else for(let n of this.#h)r=r.then(o=>n(o).then(i=>i||o));return r}getTimeDiffMsecs(){return this.#r}hasSyncedTime(){return this.#i}};function Ec(e,t){let r=e*Rc;return ho.fromDeltaInMilliseconds(r,t)}function hd(e){return e.includes("Invalid request expiry: ")}var Jm=300*1e3;function md(){return Xm(zm(Wm(),1e3),Zm(1e3,1.2),Ym(Jm))}function Wm(){let e=!0;return async()=>e?(e=!1,!0):!1}function zm(e,t){return async(r,n,o)=>{if(await e(r,n,o))return new Promise(i=>setTimeout(i,t))}}function Ym(e){let t=Date.now()+e;return async(r,n,o)=>{if(Date.now()>t)throw ee.fromCode(new Dn(`Request timed out after ${e} msec`,n,o))}}function Zm(e,t){let r=e;return()=>new Promise(n=>setTimeout(()=>{r*=t,n()},r))}function Xm(...e){return async(t,r,n)=>{for(let o of e)await o(t,r,n)}}var yd={preSignReadStateRequest:!1};function gd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function vc(e,t){return e!==null&&typeof e=="object"&&gd(e,t)}function e_(e,t){return gd(e,t)&&typeof e[t]=="function"}function _d(e){return vc(e,"body")&&vc(e.body,"content")&&e.body.content.request_type===Kn.ReadState&&vc(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&e_(e.body.content.ingress_expiry,"toHash")}async function Ic(e,t,r,n={}){let o=[G("request_status"),r],i,s;if(n.preSignReadStateRequest??!1?(s=await t_({paths:[o],agent:e,pollingOptions:n}),i=await e.readState(t,{paths:[o]},void 0,s)):i=await e.readState(t,{paths:[o]}),e.rootKey==null)throw me.fromCode(new lt);let c=await at.create({certificate:i.certificate,rootKey:e.rootKey,principal:{canisterId:t},blsVerify:n.blsVerify,agent:e}),u=Ie(c.lookup_path([...o,G("status")])),p;switch(typeof u>"u"?p=Jt.Unknown:p=new TextDecoder().decode(u),p){case Jt.Replied:return{reply:Ie(c.lookup_path([...o,"reply"])),certificate:c};case Jt.Received:case Jt.Unknown:case Jt.Processing:{let d=n.strategy??md();return await d(t,r,p),Ic(e,t,r,{...n,strategy:d,request:s})}case Jt.Rejected:{let d=new Uint8Array(Ie(c.lookup_path([...o,"reject_code"])))[0],l=new TextDecoder().decode(Ie(c.lookup_path([...o,"reject_message"]))),f=Ie(c.lookup_path([...o,"error_code"])),h=f?new TextDecoder().decode(f):void 0;throw kr.fromCode(new ro(r,d,l,h))}case Jt.Done:throw ae.fromCode(new Wi(r))}throw ut}async function t_(e){let{paths:t,agent:r,pollingOptions:n}=e;if(n.request&&_d(n.request))return n.request;let o=await r.createReadStateRequest?.({paths:t},void 0);if(!_d(o))throw Y.fromCode(new ts(o));return o}var mt=Symbol.for("ic-agent-metadata"),Oo=class e{static agentOf(t){return t[mt].config.agent}static interfaceOf(t){return t[mt].service}static canisterIdOf(t){return k.from(t[mt].config.canisterId)}static createActorClass(t,r){let n=t({IDL:qn});class o extends e{constructor(s){if(!s.canisterId)throw Y.fromCode(new Ko(s.canisterId));let a=typeof s.canisterId=="string"?k.fromText(s.canisterId):s.canisterId;super({config:{...xd,...s,canisterId:a},service:n});for(let[c,u]of n._fields)r?.httpDetails&&u.annotations.push(Ac),r?.certificate&&u.annotations.push(bd),this[c]=n_(this,c,u,s.blsVerify)}}return o}static createActor(t,r){if(!r.canisterId)throw Y.fromCode(new Ko(r.canisterId));return new(this.createActorClass(t))(r)}static createActorWithHttpDetails(t,r){return new(this.createActorClass(t,{httpDetails:!0}))(r)}static createActorWithExtendedDetails(t,r,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(t,n))(r)}constructor(t){this[mt]=Object.freeze(t)}};function No(e,t){let r=qn.decode(e,t);switch(r.length){case 0:return;case 1:return r[0];default:return r}}var xd={pollingOptions:yd},Ac="http-details",bd="certificate";function n_(e,t,r,n){let o;r.annotations.includes("query")||r.annotations.includes("composite_query")?o=async(s,...a)=>{s={...s,...e[mt].config.queryTransform?.(t,a,{...e[mt].config,...s})};let c=s.agent||e[mt].config.agent||new Sr,u=k.from(s.canisterId||e[mt].config.canisterId),p=qn.encode(r.argTypes,a),d=await c.query(u,{methodName:t,arg:p,effectiveCanisterId:s.effectiveCanisterId}),l={...d.httpDetails,requestDetails:d.requestDetails};switch(d.status){case Pr.Rejected:{let f=new $i(d.requestId,d.reject_code,d.reject_message,d.error_code,d.signatures);throw f.callContext={canisterId:u,methodName:t,httpDetails:l},kr.fromCode(f)}case Pr.Replied:return r.annotations.includes(Ac)?{httpDetails:l,result:No(r.retTypes,d.reply.arg)}:No(r.retTypes,d.reply.arg)}}:o=async(s,...a)=>{s={...s,...e[mt].config.callTransform?.(t,a,{...e[mt].config,...s})};let c=s.agent||e[mt].config.agent||Sr.createSync(),{canisterId:u,effectiveCanisterId:p,pollingOptions:d}={...xd,...e[mt].config,...s},l=k.from(u),f=p!==void 0?k.from(p):l,h=qn.encode(r.argTypes,a),{requestId:_,response:g,requestDetails:m}=await c.call(l,{methodName:t,arg:h,effectiveCanisterId:f,nonce:s.nonce}),b,y;if(cl(g.body)){if(c.rootKey==null)throw me.fromCode(new lt);let E=g.body.certificate;y=await at.create({certificate:E,rootKey:c.rootKey,principal:{canisterId:f},blsVerify:n,agent:c});let I=[G("request_status"),_];switch(new TextDecoder().decode(Ie(y.lookup_path([...I,"status"])))){case"replied":b=Ie(y.lookup_path([...I,"reply"]));break;case"rejected":{let v=new Uint8Array(Ie(y.lookup_path([...I,"reject_code"])))[0],V=new TextDecoder().decode(Ie(y.lookup_path([...I,"reject_message"]))),S=Ie(y.lookup_path([...I,"error_code"])),x=S?new TextDecoder().decode(S):void 0,N=new ro(_,v,V,x);throw N.callContext={canisterId:l,methodName:t,httpDetails:g},kr.fromCode(N)}}}else if(al(g.body)){let{reject_code:E,reject_message:I,error_code:w}=g.body,v=new Ji(_,E,I,w);throw v.callContext={canisterId:l,methodName:t,httpDetails:g},kr.fromCode(v)}if(g.status===202){let E={...d,blsVerify:n},I=await Ic(c,f,_,E);y=I.certificate,b=I.reply}let T=r.annotations.includes(Ac),O=r.annotations.includes(bd),R={...g,requestDetails:m};if(b!==void 0)return T&&O?{httpDetails:R,certificate:y,result:No(r.retTypes,b)}:O?{certificate:y,result:No(r.retTypes,b)}:T?{httpDetails:R,result:No(r.retTypes,b)}:No(r.retTypes,b);{let E=new Re(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${r.retTypes.map(I=>I.display()).join(",")}].`);throw E.callContext={canisterId:l,methodName:t,httpDetails:R},ae.fromCode(E)}};let i=(...s)=>o({},...s);return i.withOptions=s=>(...a)=>o(s,...a),i}var o_=(e=>(e[e.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",e[e.InvalidFormat=1]="InvalidFormat",e[e.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",e))(o_||{}),Qb=BigInt(1e8);var U=e=>e==null,J=e=>!U(e),Cr=e=>J(e)&&e!=="",_t=e=>!Cr(e);var i_=class extends Error{},bi=(e,t)=>{if(e==null)throw new i_(t)};var Fr=e=>new Uint8Array(e),Ds=e=>Array.from(e);var Td=({a:e,b:t})=>e.length===t.length&&e.every((r,n)=>r===t[n]);var wd="abcdefghijklmnopqrstuvwxyz234567",xi=Object.create(null);for(let e=0;e<wd.length;e++)xi[wd[e]]=e;xi[0]=xi.o;xi[1]=xi.i;var Qr=e=>btoa(String.fromCharCode(...new Uint8Array(e))),Nd=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0)),ew=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);var Sc="__bigint__",Cc="__principal__",Fc="__uint8array__",Od=(e,t)=>typeof t=="bigint"?{[Sc]:`${t}`}:J(t)&&k.isPrincipal(t)?{[Cc]:k.from(t).toText()}:J(t)&&t instanceof Uint8Array?{[Fc]:Array.from(t)}:t,Ed=(e,t)=>{let r=n=>t[n];return J(t)&&typeof t=="object"&&Sc in t?BigInt(r(Sc)):J(t)&&typeof t=="object"&&Cc in t?k.fromText(r(Cc)):J(t)&&typeof t=="object"&&Fc in t?Uint8Array.from(r(Fc)):t};var se=e=>J(e)?[e]:[],ge=e=>e?.[0];var s_=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),r=a_({bytes:t});return"aaguid"in r?{aaguidBytes:t,aaguidText:r.aaguid}:{unknownProvider:null}},a_=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let t=(e instanceof Uint8Array?Ds(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return t==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:t}};function c_(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((o,i)=>t.setUint8(i,o));let n=t.getUint16(0);return e.slice(55+n)}function l_(e){return Yn(e,gi)}var u_=class{constructor(e){this._cose=e,this.#e=l_(e)}#e;toDer(){return this.#e}toRaw(){return new Uint8Array(this.#e)}},Sd=class{#e;#t;constructor({rawId:e,cose:t}){this.#e=e,this.#t=new u_(t)}getPublicKey(){return this.#t}getCredentialId(){return this.#e}getCredentialIdText(){return Qr(this.#e)}},d_=class extends Sd{#e;#t;constructor({authData:e,...t}){super(t);let r=s_({authData:e});this.#e="aaguidText"in r?r.aaguidText:void 0,this.#t="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#t}getAAGUIDText(){return this.#e}},p_=class extends Sd{},f_=class extends Error{},h_=class extends Error{},m_=class extends Error{},__=class extends Error{},y_=class extends Error{},g_=class extends Error{},x_=class extends Error{},Rd=class extends Error{};var b_={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},w_=6e4,Cd=()=>window.crypto.getRandomValues(new Uint8Array(16)),T_=()=>Cd(),N_=()=>Cd(),O_=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new f_}},Fd=({appId:e})=>e?.id??O_(),E_=({appId:e,user:t}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:e?.name??r,id:Fd({appId:e})}}),o=()=>({user:{id:N_(),name:t?.name??t?.displayName??r,displayName:t?.displayName??r}});return{attestation:"direct",challenge:T_(),...n(),...o(),pubKeyCredParams:Object.values(b_).map(i=>({type:"public-key",alg:i})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},R_=(e={})=>({rpId:Fd(e),allowCredentials:[],userVerification:"required"}),Vc=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}},en=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))(en||{}),Vd=({timeout:e})=>AbortSignal.timeout(e??w_),v_=async({challenge:e,credentialIds:t,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...R_(r),challenge:e.buffer,allowCredentials:(t??[]).map(o=>({id:o.buffer,type:"public-key"}))},signal:Vd({timeout:n})}),vd=e=>{if(e.status!=="initialized")throw new h_},Id=e=>{if(U(e))throw new m_},Ad=({type:e})=>{if(e!=="public-key")throw new __},Pc=class wi extends $t{#e;#t;constructor({onProgress:t,...r}){if(super(),this.#e=t,"retrievePublicKey"in r){let{retrievePublicKey:n}=r;this.#t={status:"pending",retrievePublicKey:n};return}this.#t=wi.#r({credential:new d_(r)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:r,...n}={}){let o=await navigator.credentials.create({publicKey:E_(t),signal:Vd({timeout:r})});Id(o),Ad(o);let{response:{attestationObject:i},rawId:s}=o;if(U(i))throw new y_;let{authData:a}=ps.decode(Fr(i)),c=c_(a);return new wi({...n,rawId:Fr(s),cose:c,authData:a})}static async createWithExistingCredential(t){return new wi(t)}getPublicKey(){vd(this.#t);let{credential:t}=this.#t;return t.getPublicKey()}getCredential(){vd(this.#t);let{credential:t}=this.#t;return t}async sign(t){let r=await Vc({fn:async()=>{let n=await v_({challenge:t,...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return Id(n),Ad(n),n},step:0,onProgress:this.#e});return await Vc({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!Td({a:this.#t.credential.getCredentialId(),b:Fr(n)}))throw new g_;return}let{retrievePublicKey:o}=this.#t,i=await o({credentialId:Fr(n)});this.#t=wi.#r({credential:new p_({rawId:Fr(n),cose:i})})},step:1,onProgress:this.#e}),await Vc({fn:async()=>{let{response:n}=r,{clientDataJSON:o}=n,{authenticatorData:i,signature:s}="authenticatorData"in n&&"signature"in n?n:{};if(U(i))throw new Rd;if(U(s))throw new Rd;let a=ps.encode({authenticator_data:i,client_data_json:new TextDecoder().decode(o),signature:Fr(s)});if(U(a))throw new x_;return Object.assign(a,{__signature__:void 0}),a},step:2,onProgress:this.#e})}},I_=async()=>J(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var Eo=class{callbacks=[];populate(t){this.callbacks.forEach(({callback:r})=>r(t))}subscribe(t){let r=Symbol();return this.callbacks.push({id:r,callback:t}),()=>this.callbacks=this.callbacks.filter(({id:n})=>n!==r)}};var De=class e extends Eo{static instance;authUser=null;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.authUser=t,this.populate(t)}get(){return this.authUser}subscribe(t){let r=super.subscribe(t);return t(this.authUser),r}reset(){this.authUser=null,this.populate(this.authUser)}};var Ti=({message:e,detail:t})=>{let r=new CustomEvent(e,{detail:t,bubbles:!0});document.dispatchEvent(r)};var Ro="http://127.0.0.1:5987",Pd="rdmx6-jaaaa-aaaaa-aaadq-cai";var Bd=async({identity:e,container:t})=>{let n=J(t)&&t!==!1?t===!0?Ro:t:"https://icp-api.io",o=J(t);return await Sr.create({identity:e,shouldFetchRootKey:o,host:n})};var vo=class e{static instance;#e=void 0;constructor(){}static getInstance(){return U(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:t,...r}){let n=t.getPrincipal().toText();if(U(this.#e)||U(this.#e[n])){let o=await Bd({identity:t,...r});return this.#e={...this.#e??{},[n]:o},o}return this.#e[n]}reset(){this.#e=null}};var Io=class e{static instance;#e=void 0;constructor(){}static getInstance(){return U(e.instance)&&(e.instance=new e),e.instance}async getActor({satelliteId:t,identity:r,actorKey:n,...o}){let i=`${n}#${r.getPrincipal().toText()}#${t};`;if(U(this.#e)||U(this.#e[i])){let s=await this.createActor({satelliteId:t,identity:r,...o});return this.#e={...this.#e??{},[i]:s},s}return this.#e[i]}reset(){this.#e=null}async createActor({idlFactory:t,satelliteId:r,...n}){let o=await vo.getInstance().getAgent(n);return Oo.createActor(t,{agent:o,canisterId:r})}};function Dd(e){return e!==null&&typeof e=="object"}var Ni=class e{static from(t){if(typeof t=="string"){let r=Ee(t);return this.fromRaw(r)}else if(Dd(t)){let r=t;if(Dd(r)&&Object.hasOwnProperty.call(r,"__derEncodedPublicKey__"))return this.fromDer(r);if(ArrayBuffer.isView(r)){let n=r;return this.fromRaw(jt(n.buffer))}else{if(r instanceof ArrayBuffer)return this.fromRaw(jt(r));if("rawKey"in r&&r.rawKey instanceof Uint8Array)return this.fromRaw(r.rawKey);if("derKey"in r)return this.fromDer(r.derKey);if("toDer"in r)return this.fromDer(r.toDer())}}throw new Error("Cannot construct Ed25519PublicKey from the provided key.")}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(t){let r=Yn(t,zn);return r.__derEncodedPublicKey__=void 0,r}static derDecode(t){let r=Zn(t,zn);if(r.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return r}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}},ct=class e extends $t{static generate(t){if(t&&t.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");t||(t=We.utils.randomPrivateKey()),Al(t,new Uint8Array(new Array(32).fill(0)))&&console.warn("Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.");let r=new Uint8Array(32);for(let o=0;o<32;o++)r[o]=t[o];let n=We.getPublicKey(r);return e.fromKeyPair(n,r)}static fromParsedJson(t){let[r,n]=t;return new e(Ni.fromDer(Ee(r)),Ee(n))}static fromJSON(t){let r=JSON.parse(t);if(Array.isArray(r)){if(typeof r[0]=="string"&&typeof r[1]=="string")return this.fromParsedJson([r[0],r[1]]);throw new Error("Deserialization error: JSON must have at least 2 items.")}throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(t)}`)}static fromKeyPair(t,r){return new e(Ni.fromRaw(t),r)}static fromSecretKey(t){let r=We.getPublicKey(t);return e.fromKeyPair(r,t)}#e;#t;constructor(t,r){super(),this.#e=Ni.from(t),this.#t=r}toJSON(){return[j(this.#e.toDer()),j(this.#t)]}getKeyPair(){return{secretKey:this.#t,publicKey:this.#e}}getPublicKey(){return this.#e}async sign(t){let r=We.sign(t,this.#t.slice(0,32));return Object.defineProperty(r,"__signature__",{enumerable:!1,value:void 0}),r}static verify(t,r,n){let[o,i,s]=[t,r,n].map(a=>(typeof a=="string"&&(a=Ee(a)),jt(a)));return We.verify(o,i,s)}};var Bc=class e extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,e.prototype)}};function Ud(e){if(typeof global<"u"&&global.crypto&&global.crypto.subtle)return global.crypto.subtle;if(e)return e;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new Bc("Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto")}var yt=class e extends $t{static async generate(t){let{extractable:r=!1,keyUsages:n=["sign","verify"],subtleCrypto:o}=t??{},i=Ud(o),s=await i.generateKey({name:"ECDSA",namedCurve:"P-256"},r,n),a=jt(await i.exportKey("spki",s.publicKey));return Object.assign(a,{__derEncodedPublicKey__:void 0}),new this(s,a,i)}static async fromKeyPair(t,r){let n=Ud(r),o=jt(await n.exportKey("spki",t.publicKey));return Object.assign(o,{__derEncodedPublicKey__:void 0}),new e(t,o,n)}constructor(t,r,n){super(),this._keyPair=t,this._derKey=r,this._subtleCrypto=n}getKeyPair(){return this._keyPair}getPublicKey(){let t=this._derKey,r=Object.create(this._keyPair.publicKey);return r.toDer=function(){return t},r}async sign(t){let r={name:"ECDSA",hash:{name:"SHA-256"}},n=jt(await this._subtleCrypto.sign(r,this._keyPair.privateKey,t));return Object.assign(n,{__signature__:void 0}),n}};var Us=class{#e;get rawKey(){return this.#e.rawKey}get derKey(){return this.#e.derKey}toDer(){return this.#e.toDer()}getPublicKey(){return this.#e}getPrincipal(){if(!this.#e.rawKey)throw new Error("Cannot get principal from a public key without a raw key.");return k.fromUint8Array(new Uint8Array(this.#e.rawKey))}transformRequest(){return Promise.reject("Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.")}constructor(t){this.#e=t}};function ks(e){return e instanceof Uint8Array?j(e):j(new Uint8Array(e))}function Dc(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return Ee(e)}var tn=class{constructor(t,r,n){this.pubkey=t,this.expiration=r,this.targets=n}toCborValue(){return{pubkey:this.pubkey,expiration:this.expiration,...this.targets&&{targets:this.targets}}}toJSON(){return{expiration:this.expiration.toString(16),pubkey:ks(this.pubkey),...this.targets&&{targets:this.targets.map(t=>t.toHex())}}}};async function A_(e,t,r,n){let o=new tn(t.toDer(),BigInt(+r)*BigInt(1e6),n),i=new Uint8Array([...Va,...new Uint8Array(gr({...o}))]),s=await e.sign(i);return{delegation:o,signature:s}}var Ut=class e{static async create(t,r,n=new Date(Date.now()+900*1e3),o={}){let i=await A_(t,r,n,o.targets);return new e([...o.previous?.delegations||[],i],o.previous?.publicKey||t.getPublicKey().toDer())}static fromJSON(t){let{publicKey:r,delegations:n}=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(n))throw new Error("Invalid delegations.");let o=n.map(i=>{let{delegation:s,signature:a}=i,{pubkey:c,expiration:u,targets:p}=s;if(p!==void 0&&!Array.isArray(p))throw new Error("Invalid targets.");return{delegation:new tn(Dc(c),BigInt("0x"+u),p&&p.map(d=>{if(typeof d!="string")throw new Error("Invalid target.");return k.fromHex(d)})),signature:Dc(a)}});return new this(o,Dc(r))}static fromDelegations(t,r){return new this(t,r)}constructor(t,r){this.delegations=t,this.publicKey=r}toJSON(){return{delegations:this.delegations.map(t=>{let{delegation:r,signature:n}=t,{targets:o}=r;return{delegation:{expiration:r.expiration.toString(16),pubkey:ks(r.pubkey),...o&&{targets:o.map(i=>i.toHex())}},signature:ks(n)}}),publicKey:ks(this.publicKey)}}},kt=class extends $t{static fromDelegation(t,r){return new this(t,r)}constructor(t,r){super(),this._inner=t,this._delegation=r}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(t){return this._inner.sign(t)}async transformRequest(t){let{body:r,...n}=t,o=await gr(r);return{...n,body:{content:r,sender_sig:await this.sign(new Uint8Array([...Xo,...new Uint8Array(o)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}}}},Oi=class e extends Us{#e;get delegation(){return this.#e}constructor(t,r){super(t),this.#e=r}static fromDelegation(t,r){return new e(t,r)}};function Uc(e,t){for(let{delegation:o}of e.delegations)if(+new Date(Number(o.expiration/BigInt(1e6)))<=+Date.now())return!1;let r=[],n=t?.scope;n&&(Array.isArray(n)?r.push(...n.map(o=>typeof o=="string"?k.fromText(o):o)):r.push(typeof n=="string"?k.fromText(n):n));for(let o of r){let i=o.toText();for(let{delegation:s}of e.delegations){if(s.targets===void 0)continue;let a=!0;for(let c of s.targets)if(c.toText()===i){a=!1;break}if(a)return!1}}return!0}var kd=["mousedown","mousemove","keydown","touchstart","wheel"],Ei=class e{callbacks=[];idleTimeout=600*1e3;timeoutID=void 0;static create(t={}){return new e(t)}constructor(t={}){let{onIdle:r,idleTimeout:n=600*1e3}=t||{};this.callbacks=r?[r]:[],this.idleTimeout=n;let o=this._resetTimer.bind(this);window.addEventListener("load",o,!0),kd.forEach(s=>{document.addEventListener(s,o,!0)});let i=(s,a)=>{let c;return(...u)=>{let p=this,d=()=>{c=void 0,s.apply(p,u)};clearTimeout(c),c=window.setTimeout(d,a)}};if(t?.captureScroll){let s=i(o,t?.scrollDebounce??100);window.addEventListener("scroll",s,!0)}o()}registerCallback(t){this.callbacks.push(t)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let t=this._resetTimer.bind(this);kd.forEach(r=>{document.removeEventListener(r,t,!0)}),this.callbacks.forEach(r=>{r()})}_resetTimer(){let t=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(t,this.idleTimeout)}};var S_=(e,t)=>t.some(r=>e instanceof r),Ld,qd;function C_(){return Ld||(Ld=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function F_(){return qd||(qd=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Md=new WeakMap,Lc=new WeakMap,jd=new WeakMap,kc=new WeakMap,Mc=new WeakMap;function V_(e){let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{r(Wt(e.result)),o()},s=()=>{n(e.error),o()};e.addEventListener("success",i),e.addEventListener("error",s)});return t.then(r=>{r instanceof IDBCursor&&Md.set(r,e)}).catch(()=>{}),Mc.set(t,e),t}function P_(e){if(Lc.has(e))return;let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{r(),o()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)});Lc.set(e,t)}var qc={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return Lc.get(e);if(t==="objectStoreNames")return e.objectStoreNames||jd.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Wt(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function Kd(e){qc=e(qc)}function B_(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(Ls(this),t,...r);return jd.set(n,t.sort?t.sort():[t]),Wt(n)}:F_().includes(e)?function(...t){return e.apply(Ls(this),t),Wt(Md.get(this))}:function(...t){return Wt(e.apply(Ls(this),t))}}function D_(e){return typeof e=="function"?B_(e):(e instanceof IDBTransaction&&P_(e),S_(e,C_())?new Proxy(e,qc):e)}function Wt(e){if(e instanceof IDBRequest)return V_(e);if(kc.has(e))return kc.get(e);let t=D_(e);return t!==e&&(kc.set(e,t),Mc.set(t,e)),t}var Ls=e=>Mc.get(e);function Gd(e,t,{blocked:r,upgrade:n,blocking:o,terminated:i}={}){let s=indexedDB.open(e,t),a=Wt(s);return n&&s.addEventListener("upgradeneeded",c=>{n(Wt(s.result),c.oldVersion,c.newVersion,Wt(s.transaction),c)}),r&&s.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{i&&c.addEventListener("close",()=>i()),o&&c.addEventListener("versionchange",u=>o(u.oldVersion,u.newVersion,u))}).catch(()=>{}),a}var U_=["get","getKey","getAll","getAllKeys","count"],k_=["put","add","delete","clear"],jc=new Map;function Hd(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(jc.get(t))return jc.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=k_.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||U_.includes(r)))return;let i=async function(s,...a){let c=this.transaction(s,o?"readwrite":"readonly"),u=c.store;return n&&(u=u.index(a.shift())),(await Promise.all([u[r](...a),o&&c.done]))[0]};return jc.set(t,i),i}Kd(e=>({...e,get:(t,r,n)=>Hd(t,r)||e.get(t,r,n),has:(t,r)=>!!Hd(t,r)||e.has(t,r)}));var $d="auth-client-db",Jd="ic-keyval",L_=async(e=$d,t=Jd,r)=>(globalThis.localStorage?.getItem(ze)&&(globalThis.localStorage.removeItem(ze),globalThis.localStorage.removeItem(Ye)),await Gd(e,r,{upgrade:n=>{n.objectStoreNames.contains(t)&&n.clear(t),n.createObjectStore(t)}}));async function q_(e,t,r){return await e.get(t,r)}async function M_(e,t,r,n){return await e.put(t,n,r)}async function j_(e,t,r){return await e.delete(t,r)}var qs=class e{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=$d,storeName:n=Jd,version:o=Wd}=t??{},i=await L_(r,n,o);return new e(i,n)}async set(t,r){return await M_(this._db,this._storeName,t,r)}async get(t){return await q_(this._db,this._storeName,t)??null}async remove(t){return await j_(this._db,this._storeName,t)}};var Ye="identity",ze="delegation",zd="iv",Wd=1,Ri=class{constructor(t="ic-",r){this.prefix=t,this._localStorage=r}get(t){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+t))}set(t,r){return this._getLocalStorage().setItem(this.prefix+t,r),Promise.resolve()}remove(t){return this._getLocalStorage().removeItem(this.prefix+t),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let t=globalThis.localStorage;if(!t)throw new Error("Could not find local storage.");return t}},zt=class{#e;constructor(t){this.#e=t??{}}initializedDb;get _db(){return new Promise((t,r)=>{if(this.initializedDb){t(this.initializedDb);return}qs.create(this.#e).then(n=>{this.initializedDb=n,t(n)}).catch(r)})}async get(t){return await(await this._db).get(t)}async set(t,r){await(await this._db).set(t,r)}async remove(t){await(await this._db).remove(t)}};var K_=BigInt(1e9),H_=BigInt(3600),G_=K_*H_,$_="https://identity.internetcomputer.org",J_="#authorize",W_=BigInt(8)*G_,Kc="ECDSA",Hc="Ed25519",z_=500,Ms="UserInterrupt",vi=class e{constructor(t,r,n,o,i,s,a,c){this._identity=t,this._key=r,this._chain=n,this._storage=o,this.idleManager=i,this._createOptions=s,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(t={}){let r=t.storage??new zt,n=t.keyType??Kc,o=null;if(t.identity)o=t.identity;else{let c=await r.get(Ye);if(!c)try{let u=new Ri,p=await u.get(ze),d=await u.get(Ye);p&&d&&n===Kc&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await r.set(ze,p),await r.set(Ye,d),c=p,await u.remove(ze),await u.remove(Ye))}catch(u){console.error(`error while attempting to recover localstorage: ${u}`)}if(c)try{typeof c=="object"?n===Hc&&typeof c=="string"?o=ct.fromJSON(c):o=await yt.fromKeyPair(c):typeof c=="string"&&(o=ct.fromJSON(c))}catch{}}let i=new it,s=null;if(o)try{let c=await r.get(ze);if(typeof c=="object"&&c!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");t.identity?i=t.identity:c&&(s=Ut.fromJSON(c),Uc(s)?"toDer"in o?i=Oi.fromDelegation(o,s):i=kt.fromDelegation(o,s):(await Gc(r),o=null))}catch(c){console.error(c),await Gc(r),o=null}let a;return t.idleOptions?.disableIdle?a=void 0:(s||t.identity)&&(a=Ei.create(t.idleOptions)),o||(n===Hc?o=ct.generate():(t.storage&&n===Kc&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${Hc}' as the key type, as it can serialize to a string`),o=await yt.generate()),await Yd(r,o)),new e(i,o,s,r,a,t)}_registerDefaultIdleCallback(){let t=this._createOptions?.idleOptions;!t?.onIdle&&!t?.disableDefaultIdleCallback&&this.idleManager?.registerCallback(()=>{this.logout(),location.reload()})}async _handleSuccess(t,r){let n=t.delegations.map(a=>({delegation:new tn(a.delegation.pubkey,a.delegation.expiration,a.delegation.targets),signature:a.signature})),o=Ut.fromDelegations(n,t.userPublicKey),i=this._key;if(!i)return;this._chain=o,"toDer"in i?this._identity=Oi.fromDelegation(i,this._chain):this._identity=kt.fromDelegation(i,this._chain),this._idpWindow?.close();let s=this._createOptions?.idleOptions;!this.idleManager&&!s?.disableIdle&&(this.idleManager=Ei.create(s),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(ze,JSON.stringify(this._chain.toJSON())),await Yd(this._storage,this._key),r?.(t)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null&&Uc(this._chain)}async login(t){let r=Y_(this._createOptions?.loginOptions,t),n=r?.maxTimeToLive??W_,o=new URL(r?.identityProvider?.toString()||$_);o.hash=J_,this._idpWindow?.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(o,{maxTimeToLive:n,...r}),window.addEventListener("message",this._eventHandler),this._idpWindow=window.open(o.toString(),"idpWindow",r?.windowOpenerFeatures)??void 0;let i=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(Ms,r?.onError):setTimeout(i,z_))};i()}_getEventHandler(t,r){return async n=>{if(n.origin!==t.origin)return;let o=n.data;switch(o.kind){case"authorize-ready":{let i={kind:"authorize-client",sessionPublicKey:new Uint8Array(this._key?.getPublicKey().toDer()),maxTimeToLive:r?.maxTimeToLive,allowPinAuthentication:r?.allowPinAuthentication,derivationOrigin:r?.derivationOrigin?.toString(),...r?.customValues};this._idpWindow?.postMessage(i,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(o,r?.onSuccess)}catch(i){this._handleFailure(i.message,r?.onError)}break;case"authorize-client-failure":this._handleFailure(o.text,r?.onError);break}}}_handleFailure(t,r){this._idpWindow?.close(),r?.(t),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(t={}){if(await Gc(this._storage),this._identity=new it,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};async function Gc(e){await e.remove(Ye),await e.remove(ze),await e.remove(zd)}function Y_(e,t){if(!e&&!t)return;let r=e?.customValues||t?.customValues?{...e?.customValues,...t?.customValues}:void 0;return{...e,...t,customValues:r}}function Z_(e){if(e instanceof yt)return e.getKeyPair();if(e instanceof ct)return JSON.stringify(e.toJSON());throw new Error("Unsupported key type")}async function Yd(e,t){let r=Z_(t);await e.set(Ye,r)}var Fe=class e{static#e;#t;constructor(){}static getInstance(){return U(this.#e)&&(this.#e=new e),this.#e}createAuthClient=async()=>(this.#t=await vi.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),this.#t);safeCreateAuthClient=async()=>(await new zt().remove(Ye),await this.createAuthClient());getAuthClient=()=>this.#t;logout=async()=>{await this.#t?.logout(),this.#t=null};setAuthClientStorage=async({delegationChain:t,sessionKey:r})=>{let n=new zt;await Promise.all([n.set(Ye,r.getKeyPair()),n.set(ze,JSON.stringify(t.toJSON()))])}};var $c=async e=>{await X_(),await Fe.getInstance().createAuthClient(),e?.windowReload!==!1&&window.location.reload()},X_=async()=>{await Fe.getInstance().logout(),De.getInstance().reset(),Io.getInstance().reset(),vo.getInstance().reset()};var Zd=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),n=async()=>{Ti({message:"junoSignOutAuthTimer"}),await $c()};return r.onmessage=async({data:o})=>{let{msg:i,data:s}=o;switch(i){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":Ti({message:"junoDelegationRemainingTime",detail:s?.authRemainingTime})}},De.getInstance().subscribe(o=>{if(U(o)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var Ao=class e{static#e;#t;#r;static CHANNEL_NAME="juno_core_auth_channel";static MESSAGE_LOGIN_SUCCESS="authClientLoginSuccess";constructor(){this.#t=new BroadcastChannel(e.CHANNEL_NAME),this.#r=window.crypto.randomUUID()}static getInstance(){return U(this.#e)&&(this.#e=new e),this.#e}onLoginSuccess=t=>{let{location:{origin:r}}=window;this.#t.onmessage=async({origin:n,data:o})=>{n===r&&J(o)&&o.msg==="authClientLoginSuccess"&&Cr(o.emitterId)&&o.emitterId!==this.#r&&await t()}};destroy=()=>{this.#t.close(),e.#e=null};postLoginSuccess=()=>{let t={emitterId:this.#r,msg:e.MESSAGE_LOGIN_SUCCESS};this.#t.postMessage(t)};get __test__only__emitter_id__(){return this.#r}};var Se=class e extends Eo{static instance;env;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.env=t,this.populate(t)}get(){return this.env}reset(){this.env=null}subscribe(t){let r=super.subscribe(t);return t(this.env),r}};var Ii=async({fn:e,syncTabsOnSuccess:t})=>{let{authenticated:r}=await Q_({fn:e});!r||!t||Se.getInstance().get()?.syncTabs===!1||ey()},Xd=async({fn:e})=>{let{createAuthClient:t}=Fe.getInstance(),n=await(await t()).isAuthenticated();await e({authenticated:n})},Q_=async({fn:e})=>{let{createAuthClient:t,safeCreateAuthClient:r}=Fe.getInstance();return await(await t()).isAuthenticated()?(await e(),{authenticated:!0}):(await r(),{authenticated:!1})},ey=()=>{try{Ao.getInstance().postLoginSuccess()}catch(e){console.warn("Auth BroadcastChannel posting failed",e)}};var Jc=({error:e,type:t})=>typeof e=="string"?e.includes(t):e instanceof Error?e.message.includes(t):!1;var Qd="juno.datastore.error.user.cannot_update";var Yt={certified:!1};var js=()=>Fe.getInstance().getAuthClient()?.getIdentity(),ty=async()=>{let{getAuthClient:e,createAuthClient:t}=Fe.getInstance();return(e()??await t()).getIdentity()},ry=async()=>{let e=De.getInstance().get();if(U(e))return null;let t=Fe.getInstance().getAuthClient();return await t?.isAuthenticated()??!1?t?.getIdentity()??null:null};var ue=e=>J(e)?e:js()??new it;var Wc=({IDL:e})=>{let t=e.Variant({Heap:e.Null,Stable:e.Null}),r=e.Record({system_memory:e.Opt(t)}),n=e.Record({controllers:e.Vec(e.Principal),storage:e.Opt(r)}),o=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),i=e.Variant({OpenId:o}),s=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),a=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),c=e.Record({doc:s,delegation:a}),u=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),p=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),d=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),l=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),f=e.Variant({PrepareDelegation:l,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),_=e.Record({jwt:e.Text,salt:e.Vec(e.Nat8)}),g=e.Variant({OpenId:_}),m=e.Variant({Write:e.Null,Submit:e.Null}),b=e.Record({scope:m,expires_at:e.Nat64}),y=e.Variant({JwtFindProvider:u,InvalidController:e.Text,GetCachedJwks:e.Null,JwtVerify:p,GetOrFetchJwks:d,ControllerAlreadyExists:e.Null,InvalidObservatoryId:e.Text,TooManyControllers:e.Text}),T=e.Variant({PrepareAutomation:y,RegisterController:e.Text,SaveWorkflowMetadata:e.Text,SaveUniqueJtiToken:e.Text}),O=e.Variant({Ok:e.Tuple(e.Principal,b),Err:T}),R=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),E=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),I=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),w=e.Record({field:I,desc:e.Bool}),v=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),V=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(v),description:e.Opt(e.Text),created_at:e.Opt(v)}),S=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),x=e.Record({order:e.Opt(w),owner:e.Opt(e.Principal),matcher:e.Opt(V),paginate:e.Opt(S)}),N=e.Record({controllers:e.Vec(e.Principal)}),F=e.Variant({Emulator:e.Null,Automation:e.Null}),B=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),L=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(F),created_at:e.Nat64,scope:B,expires_at:e.Opt(e.Nat64)}),A=e.Record({version:e.Opt(e.Nat64)}),C=e.Variant({Db:e.Null,Storage:e.Null}),P=e.Record({version:e.Opt(e.Nat64)}),D=e.Record({proposal_ids:e.Vec(e.Nat)}),M=e.Record({cycles:e.Nat,destination_id:e.Principal}),te=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),re=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),z=e.Record({key:te,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,re)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),be=e.Variant({GitHub:e.Null,Google:e.Null}),we=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),Ze=e.Record({delegation:e.Opt(we),client_id:e.Text}),oe=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(be,Ze))}),ne=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),gt=e.Record({allowed_callers:e.Vec(e.Principal)}),xt=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(oe),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(ne),rules:e.Opt(gt)}),nn=e.Variant({GitHub:e.Null}),on=e.Record({scope:e.Opt(m),max_time_to_live:e.Opt(e.Nat64)}),sn=e.Record({owner:e.Text,name:e.Text}),Xt=e.Record({refs:e.Opt(e.Vec(e.Text))}),et=e.Record({controller:e.Opt(on),repositories:e.Vec(e.Tuple(sn,Xt))}),bt=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(nn,et))}),wt=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(bt),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64)}),tt=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),Ue=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(tt)}),Qt=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),er=e.Variant({Deny:e.Null,Allow:e.Null}),tr=e.Record({status_code:e.Nat16,location:e.Text}),rt=e.Record({iframe:e.Opt(Qt),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(tt),raw_access:e.Opt(er),redirects:e.Opt(e.Vec(e.Tuple(e.Text,tr)))}),rr=e.Record({db:e.Opt(Ue),authentication:e.Opt(xt),storage:rt,automation:e.Opt(wt)}),an=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),cn=e.Variant({OpenId:an}),nr=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),ln=e.Record({signature:e.Vec(e.Nat8),delegation:nr}),un=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),dn=e.Variant({Ok:ln,Err:un}),pn=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),fn=e.Record({clear_existing_assets:e.Opt(e.Bool)}),hn=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),or=e.Variant({AssetsUpgrade:fn,SegmentsDeployment:hn}),ke=e.Record({status:pn,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:or}),Le=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),ir=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),Tt=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:Le,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(ir),write:Le,max_changes_per_user:e.Opt(e.Nat32)}),sr=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),Nt=e.Record({memory:t,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),mn=e.Variant({Callback:e.Record({token:Nt,callback:e.Func([],[],["query"])})}),_n=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(mn),status_code:e.Nat16}),yn=e.Record({token:e.Opt(Nt),body:e.Vec(e.Nat8)}),Ot=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),Et=e.Record({batch_id:e.Nat}),gn=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,z)),items_length:e.Nat64}),xn=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),bn=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,s)),items_length:e.Nat64}),qe=e.Record({desc:e.Bool}),wn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Tn=e.Record({order:e.Opt(qe),paginate:e.Opt(wn)}),nt=e.Record({proposal_id:e.Nat}),Nn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(nt,ke)),items_length:e.Nat64}),On=e.Record({include_system:e.Bool}),En=e.Record({matcher:e.Opt(On)}),Rn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,Tt)),items_length:e.Nat64}),ar=e.Record({stable:e.Nat64,heap:e.Nat64}),vn=e.Record({openid:e.Opt(oe),version:e.Opt(e.Nat64),internet_identity:e.Opt(ne),rules:e.Opt(gt)}),In=e.Record({openid:e.Opt(bt),version:e.Opt(e.Nat64)}),cr=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(F),scope:B,expires_at:e.Opt(e.Nat64)}),An=e.Record({controller:cr,controllers:e.Vec(e.Principal)}),Sn=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(tt)}),Fo=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),pa=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:Le,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(ir),write:Le,max_changes_per_user:e.Opt(e.Nat32)}),fa=e.Record({iframe:e.Opt(Qt),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(tt),raw_access:e.Opt(er),redirects:e.Opt(e.Vec(e.Tuple(e.Text,tr)))}),Vo=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Po=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),authenticate_automation:e.Func([g],[O],[]),commit_asset_upload:e.Func([R],[],[]),commit_proposal:e.Func([E],[e.Null],[]),commit_proposal_asset_upload:e.Func([R],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(R)],[],[]),count_assets:e.Func([e.Text,x],[e.Nat64],["query"]),count_collection_assets:e.Func([e.Text],[e.Nat64],["query"]),count_collection_docs:e.Func([e.Text],[e.Nat64],["query"]),count_docs:e.Func([e.Text,x],[e.Nat64],["query"]),count_proposals:e.Func([],[e.Nat64],["query"]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controller_self:e.Func([],[],[]),del_controllers:e.Func([N],[e.Vec(e.Tuple(e.Principal,L))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,A],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,x],[],[]),del_filtered_docs:e.Func([e.Text,x],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,A))],[],[]),del_rule:e.Func([C,e.Text,P],[],[]),delete_proposal_assets:e.Func([D],[],[]),deposit_cycles:e.Func([M],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(z)],["query"]),get_auth_config:e.Func([],[e.Opt(xt)],["query"]),get_automation_config:e.Func([],[e.Opt(wt)],["query"]),get_config:e.Func([],[rr],[]),get_db_config:e.Func([],[e.Opt(Ue)],["query"]),get_delegation:e.Func([cn],[dn],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(s)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(z)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(s)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(ke)],["query"]),get_rule:e.Func([C,e.Text],[e.Opt(Tt)],["query"]),get_storage_config:e.Func([],[rt],["query"]),http_request:e.Func([sr],[_n],["query"]),http_request_streaming_callback:e.Func([Nt],[yn],["query"]),init_asset_upload:e.Func([Ot],[Et],[]),init_proposal:e.Func([or],[e.Nat,ke],[]),init_proposal_asset_upload:e.Func([Ot,e.Nat],[Et],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Ot),e.Nat],[e.Vec(e.Tuple(e.Text,Et))],[]),list_assets:e.Func([e.Text,x],[gn],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,L))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,xn))],["query"]),list_docs:e.Func([e.Text,x],[bn],["query"]),list_proposals:e.Func([Tn],[Nn],["query"]),list_rules:e.Func([C,En],[Rn],["query"]),memory_size:e.Func([],[ar],["query"]),reject_proposal:e.Func([E],[e.Null],[]),set_asset_token:e.Func([e.Text,e.Text,e.Opt(e.Text)],[],[]),set_auth_config:e.Func([vn],[xt],[]),set_automation_config:e.Func([In],[wt],[]),set_controllers:e.Func([An],[e.Vec(e.Tuple(e.Principal,L))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([Sn],[Ue],[]),set_doc:e.Func([e.Text,e.Text,Fo],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Fo))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([C,e.Text,pa],[Tt],[]),set_storage_config:e.Func([fa],[rt],[]),submit_proposal:e.Func([e.Nat],[e.Nat,ke],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([Vo],[Po],[]),upload_proposal_asset_chunk:e.Func([Vo],[Po],[])})},zc=({IDL:e})=>{let t=e.Variant({Heap:e.Null,Stable:e.Null}),r=e.Record({system_memory:e.Opt(t)}),n=e.Record({controllers:e.Vec(e.Principal),storage:e.Opt(r)}),o=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),i=e.Variant({OpenId:o}),s=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),a=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),c=e.Record({doc:s,delegation:a}),u=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),p=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),d=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),l=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),f=e.Variant({PrepareDelegation:l,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),_=e.Record({jwt:e.Text,salt:e.Vec(e.Nat8)}),g=e.Variant({OpenId:_}),m=e.Variant({Write:e.Null,Submit:e.Null}),b=e.Record({scope:m,expires_at:e.Nat64}),y=e.Variant({JwtFindProvider:u,InvalidController:e.Text,GetCachedJwks:e.Null,JwtVerify:p,GetOrFetchJwks:d,ControllerAlreadyExists:e.Null,InvalidObservatoryId:e.Text,TooManyControllers:e.Text}),T=e.Variant({PrepareAutomation:y,RegisterController:e.Text,SaveWorkflowMetadata:e.Text,SaveUniqueJtiToken:e.Text}),O=e.Variant({Ok:e.Tuple(e.Principal,b),Err:T}),R=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),E=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),I=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),w=e.Record({field:I,desc:e.Bool}),v=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),V=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(v),description:e.Opt(e.Text),created_at:e.Opt(v)}),S=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),x=e.Record({order:e.Opt(w),owner:e.Opt(e.Principal),matcher:e.Opt(V),paginate:e.Opt(S)}),N=e.Record({controllers:e.Vec(e.Principal)}),F=e.Variant({Emulator:e.Null,Automation:e.Null}),B=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),L=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(F),created_at:e.Nat64,scope:B,expires_at:e.Opt(e.Nat64)}),A=e.Record({version:e.Opt(e.Nat64)}),C=e.Variant({Db:e.Null,Storage:e.Null}),P=e.Record({version:e.Opt(e.Nat64)}),D=e.Record({proposal_ids:e.Vec(e.Nat)}),M=e.Record({cycles:e.Nat,destination_id:e.Principal}),te=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),re=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),z=e.Record({key:te,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,re)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),be=e.Variant({GitHub:e.Null,Google:e.Null}),we=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),Ze=e.Record({delegation:e.Opt(we),client_id:e.Text}),oe=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(be,Ze))}),ne=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),gt=e.Record({allowed_callers:e.Vec(e.Principal)}),xt=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(oe),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(ne),rules:e.Opt(gt)}),nn=e.Variant({GitHub:e.Null}),on=e.Record({scope:e.Opt(m),max_time_to_live:e.Opt(e.Nat64)}),sn=e.Record({owner:e.Text,name:e.Text}),Xt=e.Record({refs:e.Opt(e.Vec(e.Text))}),et=e.Record({controller:e.Opt(on),repositories:e.Vec(e.Tuple(sn,Xt))}),bt=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(nn,et))}),wt=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(bt),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64)}),tt=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),Ue=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(tt)}),Qt=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),er=e.Variant({Deny:e.Null,Allow:e.Null}),tr=e.Record({status_code:e.Nat16,location:e.Text}),rt=e.Record({iframe:e.Opt(Qt),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(tt),raw_access:e.Opt(er),redirects:e.Opt(e.Vec(e.Tuple(e.Text,tr)))}),rr=e.Record({db:e.Opt(Ue),authentication:e.Opt(xt),storage:rt,automation:e.Opt(wt)}),an=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),cn=e.Variant({OpenId:an}),nr=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),ln=e.Record({signature:e.Vec(e.Nat8),delegation:nr}),un=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),dn=e.Variant({Ok:ln,Err:un}),pn=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),fn=e.Record({clear_existing_assets:e.Opt(e.Bool)}),hn=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),or=e.Variant({AssetsUpgrade:fn,SegmentsDeployment:hn}),ke=e.Record({status:pn,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:or}),Le=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),ir=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),Tt=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:Le,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(ir),write:Le,max_changes_per_user:e.Opt(e.Nat32)}),sr=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),Nt=e.Record({memory:t,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),mn=e.Variant({Callback:e.Record({token:Nt,callback:e.Func([],[],[])})}),_n=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(mn),status_code:e.Nat16}),yn=e.Record({token:e.Opt(Nt),body:e.Vec(e.Nat8)}),Ot=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),Et=e.Record({batch_id:e.Nat}),gn=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,z)),items_length:e.Nat64}),xn=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),bn=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,s)),items_length:e.Nat64}),qe=e.Record({desc:e.Bool}),wn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Tn=e.Record({order:e.Opt(qe),paginate:e.Opt(wn)}),nt=e.Record({proposal_id:e.Nat}),Nn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(nt,ke)),items_length:e.Nat64}),On=e.Record({include_system:e.Bool}),En=e.Record({matcher:e.Opt(On)}),Rn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,Tt)),items_length:e.Nat64}),ar=e.Record({stable:e.Nat64,heap:e.Nat64}),vn=e.Record({openid:e.Opt(oe),version:e.Opt(e.Nat64),internet_identity:e.Opt(ne),rules:e.Opt(gt)}),In=e.Record({openid:e.Opt(bt),version:e.Opt(e.Nat64)}),cr=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(F),scope:B,expires_at:e.Opt(e.Nat64)}),An=e.Record({controller:cr,controllers:e.Vec(e.Principal)}),Sn=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(tt)}),Fo=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),pa=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:Le,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(ir),write:Le,max_changes_per_user:e.Opt(e.Nat32)}),fa=e.Record({iframe:e.Opt(Qt),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(tt),raw_access:e.Opt(er),redirects:e.Opt(e.Vec(e.Tuple(e.Text,tr)))}),Vo=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Po=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),authenticate_automation:e.Func([g],[O],[]),commit_asset_upload:e.Func([R],[],[]),commit_proposal:e.Func([E],[e.Null],[]),commit_proposal_asset_upload:e.Func([R],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(R)],[],[]),count_assets:e.Func([e.Text,x],[e.Nat64],[]),count_collection_assets:e.Func([e.Text],[e.Nat64],[]),count_collection_docs:e.Func([e.Text],[e.Nat64],[]),count_docs:e.Func([e.Text,x],[e.Nat64],[]),count_proposals:e.Func([],[e.Nat64],[]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controller_self:e.Func([],[],[]),del_controllers:e.Func([N],[e.Vec(e.Tuple(e.Principal,L))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,A],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,x],[],[]),del_filtered_docs:e.Func([e.Text,x],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,A))],[],[]),del_rule:e.Func([C,e.Text,P],[],[]),delete_proposal_assets:e.Func([D],[],[]),deposit_cycles:e.Func([M],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(z)],[]),get_auth_config:e.Func([],[e.Opt(xt)],[]),get_automation_config:e.Func([],[e.Opt(wt)],[]),get_config:e.Func([],[rr],[]),get_db_config:e.Func([],[e.Opt(Ue)],[]),get_delegation:e.Func([cn],[dn],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(s)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(z)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(s)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(ke)],[]),get_rule:e.Func([C,e.Text],[e.Opt(Tt)],[]),get_storage_config:e.Func([],[rt],[]),http_request:e.Func([sr],[_n],[]),http_request_streaming_callback:e.Func([Nt],[yn],[]),init_asset_upload:e.Func([Ot],[Et],[]),init_proposal:e.Func([or],[e.Nat,ke],[]),init_proposal_asset_upload:e.Func([Ot,e.Nat],[Et],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Ot),e.Nat],[e.Vec(e.Tuple(e.Text,Et))],[]),list_assets:e.Func([e.Text,x],[gn],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,L))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,xn))],[]),list_docs:e.Func([e.Text,x],[bn],[]),list_proposals:e.Func([Tn],[Nn],[]),list_rules:e.Func([C,En],[Rn],[]),memory_size:e.Func([],[ar],[]),reject_proposal:e.Func([E],[e.Null],[]),set_asset_token:e.Func([e.Text,e.Text,e.Opt(e.Text)],[],[]),set_auth_config:e.Func([vn],[xt],[]),set_automation_config:e.Func([In],[wt],[]),set_controllers:e.Func([An],[e.Vec(e.Tuple(e.Principal,L))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([Sn],[Ue],[]),set_doc:e.Func([e.Text,e.Text,Fo],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Fo))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([C,e.Text,pa],[Tt],[]),set_storage_config:e.Func([fa],[rt],[]),submit_proposal:e.Func([e.Nat],[e.Nat,ke],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([Vo],[Po],[]),upload_proposal_asset_chunk:e.Func([Vo],[Po],[])})},ny=({IDL:e})=>{let t=e.Record({e8s:e.Nat64}),r=e.Record({mission_control_id:e.Principal,user:e.Principal}),n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),o=e.Variant({OpenId:n}),i=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),s=e.Variant({GitHub:e.Null,Google:e.Null}),a=e.Record({name:e.Opt(e.Text),locale:e.Opt(e.Text),family_name:e.Opt(e.Text),email:e.Opt(e.Text),picture:e.Opt(e.Text),given_name:e.Opt(e.Text),preferred_username:e.Opt(e.Text)}),c=e.Record({provider:s,data:a}),u=e.Variant({InternetIdentity:e.Null,OpenId:c}),p=e.Record({updated_at:e.Nat64,credits:t,mission_control_id:e.Opt(e.Principal),provider:e.Opt(u),owner:e.Principal,created_at:e.Nat64}),d=e.Record({delegation:i,account:p}),l=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),f=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),h=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),_=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),g=e.Variant({PrepareDelegation:_,RegisterUser:e.Text}),m=e.Variant({Ok:d,Err:g}),b=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),y=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),T=e.Record({subnet_id:e.Opt(e.Principal)}),O=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),name:e.Opt(e.Text),user:e.Principal}),R=e.Variant({Heap:e.Null,Stable:e.Null}),E=e.Record({system_memory:e.Opt(R)}),I=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(E),name:e.Opt(e.Text),user:e.Principal}),w=e.Record({controllers:e.Vec(e.Principal)}),v=e.Record({proposal_ids:e.Vec(e.Nat)}),V=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),S=e.Record({delegation:e.Opt(V),client_id:e.Text}),x=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,S))}),N=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),F=e.Record({allowed_callers:e.Vec(e.Principal)}),B=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(x),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(F)}),L=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),A=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),C=e.Variant({Deny:e.Null,Allow:e.Null}),P=e.Record({status_code:e.Nat16,location:e.Text}),D=e.Record({iframe:e.Opt(L),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(A),raw_access:e.Opt(C),redirects:e.Opt(e.Vec(e.Tuple(e.Text,P)))}),M=e.Record({authentication:e.Opt(B),storage:D}),te=e.Record({user:e.Principal}),re=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),z=e.Variant({OpenId:re}),be=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),we=e.Record({signature:e.Vec(e.Nat8),delegation:be}),Ze=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),oe=e.Variant({Ok:we,Err:Ze}),ne=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),gt=e.Record({e12s:e.Nat64}),xt=e.Record({updated_at:e.Nat64,fee_cycles:gt,fee_icp:e.Opt(t)}),nn=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),on=e.Record({clear_existing_assets:e.Opt(e.Bool)}),sn=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Xt=e.Variant({AssetsUpgrade:on,SegmentsDeployment:sn}),et=e.Record({status:nn,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:Xt}),bt=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),wt=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),tt=e.Variant({Heap:e.Null,Stable:e.Null}),Ue=e.Record({memory:tt,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),Qt=e.Variant({Callback:e.Record({token:Ue,callback:e.Func([],[],["query"])})}),er=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Qt),status_code:e.Nat16}),tr=e.Record({token:e.Opt(Ue),body:e.Vec(e.Nat8)}),rt=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),rr=e.Record({batch_id:e.Nat}),an=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),cn=e.Record({field:an,desc:e.Bool}),nr=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),ln=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(nr),description:e.Opt(e.Text),created_at:e.Opt(nr)}),un=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),dn=e.Record({order:e.Opt(cn),owner:e.Opt(e.Principal),matcher:e.Opt(ln),paginate:e.Opt(un)}),pn=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),fn=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),hn=e.Record({key:pn,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,fn)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),or=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,hn)),items_length:e.Nat64}),ke=e.Variant({Emulator:e.Null,Automation:e.Null}),Le=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),ir=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(ke),created_at:e.Nat64,scope:Le,expires_at:e.Opt(e.Nat64)}),Tt=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),sr=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),Nt=e.Record({status:sr,updated_at:e.Nat64,block_index_payment:e.Nat64,mission_control_id:e.Opt(e.Principal),created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64)}),mn=e.Record({block_index:e.Nat64,ledger_id:e.Principal}),_n=e.Record({owner:e.Principal,subaccount:e.Opt(e.Vec(e.Nat8))}),yn=e.Record({status:sr,updated_at:e.Nat64,created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64),purchaser:_n}),Ot=e.Record({desc:e.Bool}),Et=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),gn=e.Record({order:e.Opt(Ot),paginate:e.Opt(Et)}),xn=e.Record({proposal_id:e.Nat}),bn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(xn,et)),items_length:e.Nat64}),qe=e.Variant({Orbiter:e.Null,Satellite:e.Null}),wn=e.Record({segment_id:e.Opt(e.Principal),segment_kind:e.Opt(qe)}),Tn=e.Record({user:e.Principal,segment_id:e.Principal,segment_kind:qe}),nt=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,created_at:e.Nat64}),Nn=e.Record({openid:e.Opt(x),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(F)}),On=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(ke),scope:Le,expires_at:e.Opt(e.Nat64)}),En=e.Record({controller:On,controllers:e.Vec(e.Principal)}),Rn=e.Record({fee_cycles:gt,fee_icp:e.Opt(t)}),ar=e.Record({metadata:e.Opt(e.Vec(e.Tuple(e.Text,e.Text))),segment_id:e.Principal,segment_kind:qe}),vn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,segment_kind:qe}),In=e.Record({iframe:e.Opt(L),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(A),raw_access:e.Opt(C),redirects:e.Opt(e.Vec(e.Tuple(e.Text,P)))}),cr=e.Record({segment_id:e.Principal,segment_kind:qe}),An=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Sn=e.Record({chunk_id:e.Nat});return e.Service({add_credits:e.Func([e.Principal,t],[],[]),add_invitation_code:e.Func([e.Text],[],[]),assert_mission_control_center:e.Func([r],[],["query"]),authenticate:e.Func([o],[m],[]),commit_proposal:e.Func([b],[e.Null],[]),commit_proposal_asset_upload:e.Func([y],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(y)],[],[]),count_proposals:e.Func([],[e.Nat64],["query"]),create_mission_control:e.Func([T],[e.Principal],[]),create_orbiter:e.Func([O],[e.Principal],[]),create_satellite:e.Func([I],[e.Principal],[]),del_controllers:e.Func([w],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([v],[],[]),get_account:e.Func([],[e.Opt(p)],["query"]),get_auth_config:e.Func([],[e.Opt(B)],["query"]),get_config:e.Func([],[M],["query"]),get_create_orbiter_fee:e.Func([te],[e.Opt(t)],["query"]),get_create_satellite_fee:e.Func([te],[e.Opt(t)],["query"]),get_credits:e.Func([],[t],["query"]),get_delegation:e.Func([z],[oe],["query"]),get_fee:e.Func([ne],[xt],["query"]),get_or_init_account:e.Func([],[p],[]),get_proposal:e.Func([e.Nat],[e.Opt(et)],["query"]),get_rate_config:e.Func([ne],[bt],["query"]),get_storage_config:e.Func([],[D],["query"]),http_request:e.Func([wt],[er],["query"]),http_request_streaming_callback:e.Func([Ue],[tr],["query"]),init_proposal:e.Func([Xt],[e.Nat,et],[]),init_proposal_asset_upload:e.Func([rt,e.Nat],[rr],[]),init_proposal_many_assets_upload:e.Func([e.Vec(rt),e.Nat],[e.Vec(e.Tuple(e.Text,rr))],[]),list_accounts:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],["query"]),list_assets:e.Func([e.Text,dn],[or],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,ir))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Tt))],["query"]),list_icp_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,Nt))],["query"]),list_icrc_payments:e.Func([],[e.Vec(e.Tuple(mn,yn))],["query"]),list_proposals:e.Func([gn],[bn],["query"]),list_segments:e.Func([wn],[e.Vec(e.Tuple(Tn,nt))],["query"]),reject_proposal:e.Func([b],[e.Null],[]),set_auth_config:e.Func([Nn],[B],[]),set_controllers:e.Func([En],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([ne,Rn],[],[]),set_many_segments:e.Func([e.Vec(ar)],[e.Vec(nt)],[]),set_rate_config:e.Func([ne,bt],[],[]),set_segment:e.Func([ar],[nt],[]),set_segment_metadata:e.Func([vn],[nt],[]),set_storage_config:e.Func([In],[D],[]),submit_proposal:e.Func([e.Nat],[e.Nat,et],[]),unset_many_segments:e.Func([e.Vec(cr)],[],[]),unset_segment:e.Func([cr],[],[]),upload_proposal_asset_chunk:e.Func([An],[Sn],[])})},oy=({IDL:e})=>{let t=e.Record({e8s:e.Nat64}),r=e.Record({mission_control_id:e.Principal,user:e.Principal}),n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),o=e.Variant({OpenId:n}),i=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),s=e.Variant({GitHub:e.Null,Google:e.Null}),a=e.Record({name:e.Opt(e.Text),locale:e.Opt(e.Text),family_name:e.Opt(e.Text),email:e.Opt(e.Text),picture:e.Opt(e.Text),given_name:e.Opt(e.Text),preferred_username:e.Opt(e.Text)}),c=e.Record({provider:s,data:a}),u=e.Variant({InternetIdentity:e.Null,OpenId:c}),p=e.Record({updated_at:e.Nat64,credits:t,mission_control_id:e.Opt(e.Principal),provider:e.Opt(u),owner:e.Principal,created_at:e.Nat64}),d=e.Record({delegation:i,account:p}),l=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),f=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),h=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),_=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),g=e.Variant({PrepareDelegation:_,RegisterUser:e.Text}),m=e.Variant({Ok:d,Err:g}),b=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),y=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),T=e.Record({subnet_id:e.Opt(e.Principal)}),O=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),name:e.Opt(e.Text),user:e.Principal}),R=e.Variant({Heap:e.Null,Stable:e.Null}),E=e.Record({system_memory:e.Opt(R)}),I=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(E),name:e.Opt(e.Text),user:e.Principal}),w=e.Record({controllers:e.Vec(e.Principal)}),v=e.Record({proposal_ids:e.Vec(e.Nat)}),V=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),S=e.Record({delegation:e.Opt(V),client_id:e.Text}),x=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,S))}),N=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),F=e.Record({allowed_callers:e.Vec(e.Principal)}),B=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(x),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(F)}),L=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),A=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),C=e.Variant({Deny:e.Null,Allow:e.Null}),P=e.Record({status_code:e.Nat16,location:e.Text}),D=e.Record({iframe:e.Opt(L),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(A),raw_access:e.Opt(C),redirects:e.Opt(e.Vec(e.Tuple(e.Text,P)))}),M=e.Record({authentication:e.Opt(B),storage:D}),te=e.Record({user:e.Principal}),re=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),z=e.Variant({OpenId:re}),be=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),we=e.Record({signature:e.Vec(e.Nat8),delegation:be}),Ze=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),oe=e.Variant({Ok:we,Err:Ze}),ne=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),gt=e.Record({e12s:e.Nat64}),xt=e.Record({updated_at:e.Nat64,fee_cycles:gt,fee_icp:e.Opt(t)}),nn=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),on=e.Record({clear_existing_assets:e.Opt(e.Bool)}),sn=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),Xt=e.Variant({AssetsUpgrade:on,SegmentsDeployment:sn}),et=e.Record({status:nn,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:Xt}),bt=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),wt=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),tt=e.Variant({Heap:e.Null,Stable:e.Null}),Ue=e.Record({memory:tt,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),Qt=e.Variant({Callback:e.Record({token:Ue,callback:e.Func([],[],[])})}),er=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Qt),status_code:e.Nat16}),tr=e.Record({token:e.Opt(Ue),body:e.Vec(e.Nat8)}),rt=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),rr=e.Record({batch_id:e.Nat}),an=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),cn=e.Record({field:an,desc:e.Bool}),nr=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),ln=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(nr),description:e.Opt(e.Text),created_at:e.Opt(nr)}),un=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),dn=e.Record({order:e.Opt(cn),owner:e.Opt(e.Principal),matcher:e.Opt(ln),paginate:e.Opt(un)}),pn=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),fn=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),hn=e.Record({key:pn,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,fn)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),or=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,hn)),items_length:e.Nat64}),ke=e.Variant({Emulator:e.Null,Automation:e.Null}),Le=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),ir=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(ke),created_at:e.Nat64,scope:Le,expires_at:e.Opt(e.Nat64)}),Tt=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),sr=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),Nt=e.Record({status:sr,updated_at:e.Nat64,block_index_payment:e.Nat64,mission_control_id:e.Opt(e.Principal),created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64)}),mn=e.Record({block_index:e.Nat64,ledger_id:e.Principal}),_n=e.Record({owner:e.Principal,subaccount:e.Opt(e.Vec(e.Nat8))}),yn=e.Record({status:sr,updated_at:e.Nat64,created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64),purchaser:_n}),Ot=e.Record({desc:e.Bool}),Et=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),gn=e.Record({order:e.Opt(Ot),paginate:e.Opt(Et)}),xn=e.Record({proposal_id:e.Nat}),bn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(xn,et)),items_length:e.Nat64}),qe=e.Variant({Orbiter:e.Null,Satellite:e.Null}),wn=e.Record({segment_id:e.Opt(e.Principal),segment_kind:e.Opt(qe)}),Tn=e.Record({user:e.Principal,segment_id:e.Principal,segment_kind:qe}),nt=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,created_at:e.Nat64}),Nn=e.Record({openid:e.Opt(x),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(F)}),On=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(ke),scope:Le,expires_at:e.Opt(e.Nat64)}),En=e.Record({controller:On,controllers:e.Vec(e.Principal)}),Rn=e.Record({fee_cycles:gt,fee_icp:e.Opt(t)}),ar=e.Record({metadata:e.Opt(e.Vec(e.Tuple(e.Text,e.Text))),segment_id:e.Principal,segment_kind:qe}),vn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,segment_kind:qe}),In=e.Record({iframe:e.Opt(L),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(A),raw_access:e.Opt(C),redirects:e.Opt(e.Vec(e.Tuple(e.Text,P)))}),cr=e.Record({segment_id:e.Principal,segment_kind:qe}),An=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Sn=e.Record({chunk_id:e.Nat});return e.Service({add_credits:e.Func([e.Principal,t],[],[]),add_invitation_code:e.Func([e.Text],[],[]),assert_mission_control_center:e.Func([r],[],[]),authenticate:e.Func([o],[m],[]),commit_proposal:e.Func([b],[e.Null],[]),commit_proposal_asset_upload:e.Func([y],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(y)],[],[]),count_proposals:e.Func([],[e.Nat64],[]),create_mission_control:e.Func([T],[e.Principal],[]),create_orbiter:e.Func([O],[e.Principal],[]),create_satellite:e.Func([I],[e.Principal],[]),del_controllers:e.Func([w],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([v],[],[]),get_account:e.Func([],[e.Opt(p)],[]),get_auth_config:e.Func([],[e.Opt(B)],[]),get_config:e.Func([],[M],[]),get_create_orbiter_fee:e.Func([te],[e.Opt(t)],[]),get_create_satellite_fee:e.Func([te],[e.Opt(t)],[]),get_credits:e.Func([],[t],[]),get_delegation:e.Func([z],[oe],[]),get_fee:e.Func([ne],[xt],[]),get_or_init_account:e.Func([],[p],[]),get_proposal:e.Func([e.Nat],[e.Opt(et)],[]),get_rate_config:e.Func([ne],[bt],[]),get_storage_config:e.Func([],[D],[]),http_request:e.Func([wt],[er],[]),http_request_streaming_callback:e.Func([Ue],[tr],[]),init_proposal:e.Func([Xt],[e.Nat,et],[]),init_proposal_asset_upload:e.Func([rt,e.Nat],[rr],[]),init_proposal_many_assets_upload:e.Func([e.Vec(rt),e.Nat],[e.Vec(e.Tuple(e.Text,rr))],[]),list_accounts:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],[]),list_assets:e.Func([e.Text,dn],[or],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,ir))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,Tt))],[]),list_icp_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,Nt))],[]),list_icrc_payments:e.Func([],[e.Vec(e.Tuple(mn,yn))],[]),list_proposals:e.Func([gn],[bn],[]),list_segments:e.Func([wn],[e.Vec(e.Tuple(Tn,nt))],[]),reject_proposal:e.Func([b],[e.Null],[]),set_auth_config:e.Func([Nn],[B],[]),set_controllers:e.Func([En],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([ne,Rn],[],[]),set_many_segments:e.Func([e.Vec(ar)],[e.Vec(nt)],[]),set_rate_config:e.Func([ne,bt],[],[]),set_segment:e.Func([ar],[nt],[]),set_segment_metadata:e.Func([vn],[nt],[]),set_storage_config:e.Func([In],[D],[]),submit_proposal:e.Func([e.Nat],[e.Nat,et],[]),unset_many_segments:e.Func([e.Vec(cr)],[],[]),unset_segment:e.Func([cr],[],[]),upload_proposal_asset_chunk:e.Func([An],[Sn],[])})};var iy=async({identity:e,host:t,localActor:r})=>await Sr.create({identity:e,host:t,retryTimes:10,shouldFetchRootKey:r}),sy=async({agent:e,...t})=>e??await ay(t),ay=async({identity:e,container:t})=>{let r=J(t)&&t!==!1;return await iy({identity:e,host:r?t===!0?"http://127.0.0.1:5987":t:"https://icp-api.io",localActor:r})};var ep=({satelliteId:e,certified:t=!1,...r})=>rp({canisterId:e,...r,idlFactory:t?zc:Wc});var tp=({consoleId:e,certified:t=!1,...r})=>rp({canisterId:e,...r,idlFactory:t?oy:ny}),rp=({canisterId:e,idlFactory:t,...r})=>{if(U(e))throw new Error("No canister ID provided.");return cy({canisterId:e,idlFactory:t,...r})},cy=async({canisterId:e,idlFactory:t,config:r,...n})=>{let o=await sy(n);return Oo.createActor(t,{agent:o,canisterId:e,...r??{}})};var np=({satelliteId:e,container:t})=>{let{satelliteId:r}=Yc({satelliteId:e}),{container:n}=Zc({container:t});if(J(n)&&n!==!1){let{host:o,protocol:i}=new URL(n===!0?Ro:n);return`${i}//${r??"unknown"}.${o.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},Yc=({satelliteId:e})=>J(e)?{satelliteId:e}:Se.getInstance().get()??{satelliteId:void 0},Zc=({container:e})=>J(e)?{container:e}:Se.getInstance().get()??{container:void 0};var xe=({satellite:e,options:{certified:t}})=>ip({idlFactory:t?zc:Wc,actorKey:`stock#${t?"update":"query"}`,...e}),op=({idlFactory:e,...t})=>ip({idlFactory:e,actorKey:"extended#query",...t}),ip=async({satelliteId:e,container:t,...r})=>{let{satelliteId:n}=Yc({satelliteId:e});bi(n,"No satellite ID defined. Did you initialize Juno?");let{container:o}=Zc({container:t});return await Io.getInstance().getActor({satelliteId:n,container:o,...r})};var Ks=class extends Error{},Vr=class extends Error{},Hs=class extends Error{},Gs=class extends Error{},So=class extends Error{},$s=class extends Error{},Js=class extends Error{},Ws=class extends Error{},zs=class extends Error{};var sp=e=>{if(U(e))return se();switch(e.matcher){case"equal":return se({Equal:e.timestamp});case"greaterThan":return se({GreaterThan:e.timestamp});case"lessThan":return se({LessThan:e.timestamp});case"between":return se({Between:[e.timestamps.start,e.timestamps.end]});default:throw new zs("Invalid list matcher for timestamp",e)}},rn=({matcher:e,paginate:t,order:r,owner:n})=>({matcher:U(e)?[]:[{key:se(e.key),description:se(e.description),created_at:sp(e.createdAt),updated_at:sp(e.updatedAt)}],paginate:se(U(t)?void 0:{start_after:se(t.startAfter),limit:se(U(t.limit)?void 0:BigInt(t.limit))}),order:se(U(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:se(U(n)?void 0:typeof n=="string"?k.fromText(n):n)});var ap=async e=>{let t=new Blob([JSON.stringify(e,Od)],{type:"application/json; charset=utf-8"});return new Uint8Array(await t.arrayBuffer())},Ys=async e=>{let t=new Blob([e instanceof Uint8Array?e:new Uint8Array(e)],{type:"application/json; charset=utf-8"});return JSON.parse(await t.text(),Ed)},Zs=()=>typeof window<"u";var cp=async({data:e})=>{try{return await Ys(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var Xc=async e=>{let{data:t,version:r,description:n}=e;return{description:se(n),data:await ap(t),version:se(r)}},Qc=e=>{let{version:t}=e;return{version:se(t)}},Xn=async({doc:e,key:t})=>{let{owner:r,version:n,description:o,data:i,...s}=e;return{key:t,description:ge(o),owner:r.toText(),data:await Ys(i),version:ge(n),...s}};var lp=async({collection:e,key:t,...r})=>{let{get_doc:n}=await xe(r),o=ge(await n(e,t));if(!U(o))return Xn({doc:o,key:t})},up=async({docs:e,...t})=>{let{get_many_docs:r}=await xe(t),n=e.map(({collection:s,key:a})=>[s,a]),o=await r(n),i=[];for(let[s,a]of o){let c=ge(a);i.push(J(c)?await Xn({key:s,doc:c}):void 0)}return i},dp=async({collection:e,doc:t,...r})=>{let{set_doc:n}=await xe(r),{key:o}=t,i=await Xc(t),s=await n(e,o,i);return await Xn({key:o,doc:s})},pp=async({docs:e,...t})=>{let{set_many_docs:r}=await xe(t),n=[];for(let{collection:s,doc:a}of e){let{key:c}=a;n.push([s,c,await Xc(a)])}let o=await r(n),i=[];for(let[s,a]of o)i.push(await Xn({key:s,doc:a}));return i},fp=async({collection:e,doc:t,...r})=>{let{del_doc:n}=await xe(r),{key:o}=t;return n(e,o,Qc(t))},hp=async({docs:e,...t})=>{let{del_many_docs:r}=await xe(t),n=e.map(({collection:o,doc:i})=>[o,i.key,Qc(i)]);await r(n)},mp=async({collection:e,filter:t,...r})=>{let{del_filtered_docs:n}=await xe(r);return n(e,rn(t))},_p=async({collection:e,filter:t,...r})=>{let{list_docs:n}=await xe(r),{items:o,items_page:i,items_length:s,matches_length:a,matches_pages:c}=await n(e,rn(t)),u=[];for(let[p,d]of o){let{data:l,owner:f,description:h,version:_,...g}=d;u.push({key:p,description:ge(h),owner:f.toText(),data:await cp({data:l}),version:ge(_),...g})}return{items:u,items_length:s,items_page:ge(i),matches_length:a,matches_pages:ge(c)}},yp=async({collection:e,filter:t,...r})=>{let{count_docs:n}=await xe(r);return n(e,rn(t))};var Xs=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await lp({...r,satellite:{...e,identity:n},options:t??Yt})},kN=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await up({...r,satellite:{...e,identity:n},options:t??Yt})},gp=async({satellite:e,...t})=>{let r=ue(e?.identity);return await dp({...t,satellite:{...e,identity:r},options:{certified:!0}})},xp=async({satellite:e,...t})=>{let r=ue(e?.identity);return await pp({...t,satellite:{...e,identity:r},options:{certified:!0}})},LN=async({satellite:e,...t})=>{let r=ue(e?.identity);return await fp({...t,satellite:{...e,identity:r},options:{certified:!0}})},qN=async({satellite:e,...t})=>{let r=ue(e?.identity);return await hp({...t,satellite:{...e,identity:r},options:{certified:!0}})},MN=async({satellite:e,filter:t,...r})=>{let n=ue(e?.identity);return await mp({...r,filter:t??{},satellite:{...e,identity:n},options:{certified:!0}})},jN=async({satellite:e,options:t,filter:r,...n})=>{let o=ue(e?.identity);return await _p({...n,filter:r??{},satellite:{...e,identity:o},options:t??Yt})},KN=async({satellite:e,options:t,filter:r,...n})=>{let o=ue(e?.identity);return await yp({...n,filter:r??{},satellite:{...e,identity:o},options:t??Yt})};var bp=async({provider:e})=>{let{user:t,userId:r}=await Qs();if(J(t))return t;try{return await ly({userId:r,provider:e})}catch(n){if(Jc({error:n,type:Qd})){let o=await wp({userId:r});if(J(o))return o}throw n}},Qs=async()=>{let e=js();if(U(e))throw new Ws("No identity to initialize the user. Have you initialized Juno?");let t=e.getPrincipal().toText(),r=await wp({userId:t});return{userId:t,user:r}},wp=({userId:e})=>Xs({collection:"#user",key:e}),ly=({userId:e,...t})=>gp({collection:"#user",doc:{key:e,data:t}});var ea=async({syncTabsOnSuccess:e}={syncTabsOnSuccess:!1})=>{await Ii({fn:async()=>{let{user:r}=await Qs();De.getInstance().set(r??null)},syncTabsOnSuccess:e})},Tp=async()=>{await Xd({fn:async({authenticated:t})=>{let n=t?Qs:()=>Promise.resolve({user:null}),{user:o}=await n();De.getInstance().set(o??null)}})},ta=async({user:e})=>{await Ii({fn:async()=>{De.getInstance().set(e)},syncTabsOnSuccess:!0})};var Np=()=>{try{let e=Ao.getInstance(),t=async()=>{await Tp(),Ti({message:"junoSignInReload"})};return e.onLoginSuccess(t),()=>{e?.destroy()}}catch(e){console.warn("Auth BroadcastChannel initialization failed",e);return}};var Op=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_SATELLITE_ID??import.meta.env?.PUBLIC_SATELLITE_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SATELLITE_ID??e():e()},Ep=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_CONTAINER??import.meta.env?.PUBLIC_CONTAINER:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_CONTAINER??e():e()},Rp=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_GOOGLE_CLIENT_ID??import.meta.env?.PUBLIC_GOOGLE_CLIENT_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID??e():e()},vp=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_GITHUB_CLIENT_ID??import.meta.env?.PUBLIC_GITHUB_CLIENT_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID??e():e()},ra=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_JUNO_API_URL??import.meta.env?.PUBLIC_JUNO_API_URL:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_JUNO_API_URL??e():e()};var Ip=BigInt(144e11),Ap=!1,Sp={width:576,height:576},Cp={width:424,height:576},el="internetcomputer.org",Fp="ic0.app",na="id.ai";var Vp=({width:e,height:t})=>{if(!Zs()||U(window)||U(window.top))return;let{top:{innerWidth:r,innerHeight:n}}=window,o=n/2+screenY-t/2,i=r/2+screenX-e/2;return`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${e}, height=${t}, top=${o}, left=${i}`};var Zt=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}};var Pp=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))(Pp||{});var oa=class{async signIn({options:t,authClient:r,initAuth:n}){await Zt({fn:async()=>await this.#e({options:t,authClient:r}),step:0,onProgress:t?.onProgress}),await Zt({fn:async()=>await n({provider:this.id}),step:1,onProgress:t?.onProgress})}#e({options:t,authClient:r}){return new Promise(async(n,o)=>{if(U(r)){o(new Vr("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:i=>{if(i===Ms){o(new Hs(i));return}o(new Ks(i))},maxTimeToLive:t?.maxTimeToLiveInNanoseconds??Ip,allowPinAuthentication:t?.allowPin??Ap,...t?.derivationOrigin!==void 0&&{derivationOrigin:t.derivationOrigin},...this.signInOptions({windowed:t?.windowed})})})}};var ia=class extends oa{#e;constructor({domain:t}){super(),this.#e=t}get id(){return"internet_identity"}signInOptions({windowed:t}){let n=(()=>{let i=Se.getInstance().get()?.container;if(U(i)||i===!1){let p=[el,Fp].includes(this.#e??na);return _t(this.#e)?`https://${na}`:p?`https://identity.${this.#e??el}`:`https://${this.#e}`}let s=Se.getInstance().get(),a=J(s)&&J(s?.internetIdentityId)?s.internetIdentityId:Pd,{host:c,protocol:u}=new URL(i===!0?Ro:i);return/apple/i.test(navigator?.vendor)?`${u}//${c}?canisterId=${a}`:`${u}//${a}.${c.replace("127.0.0.1","localhost")}`})();return{...t!==!1&&{windowOpenerFeatures:Vp((()=>{try{let{hostname:i}=new URL(n);return i.includes(na)}catch{return!1}})()?Cp:Sp)},identityProvider:n}}};var tl=e=>Qr(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),uy=()=>crypto.getRandomValues(new Uint8Array(32)),dy=async({salt:e,caller:t})=>{let r=t.getPrincipal().toUint8Array(),n=new Uint8Array(e.length+r.byteLength);n.set(e),n.set(r,e.length);let o=await crypto.subtle.digest("SHA-256",n);return tl(Fr(o))},Bp=async({caller:e})=>{let t=uy();return{nonce:await dy({salt:t,caller:e}),salt:t}};var kp="juno:auth:openid",Dp={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"},Lp={authUrl:"https://github.com/login/oauth/authorize",authScopes:["read:user","user:email"],initUrl:"https://api.juno.build/v1/auth/init/github",finalizeUrl:"https://api.juno.build/v1/auth/finalize/github"},py=class extends Error{},fy=class extends Error{},hy=class extends Error{},my=class extends Error{},_y=class extends Error{},yy=class extends Error{},gy=class extends Error{},qp=class extends Error{},xy=class extends Error{},by=class extends Error{},wy=class extends Error{constructor(e){super("GitHub OAuth initialization failed",e)}},Ty=class extends Error{constructor(e){super("GitHub OAuth finalization failed",e)}},Mp="__caller__",jp="__salt__",Kp="__state__",Ny=({caller:e,state:t,salt:r})=>{let n={[Mp]:e.toJSON(),[jp]:Qr(r),[Kp]:t};return JSON.stringify(n)},Oy=e=>{let{[Mp]:t,[jp]:r,[Kp]:n}=JSON.parse(e);return{caller:ct.fromParsedJson(t),salt:Nd(r),state:n}},Up=async({generateState:e})=>{let t=ct.generate(),{nonce:r,salt:n}=await Bp({caller:t}),o=await e({nonce:r}),i=Ny({caller:t,salt:n,state:o});return sessionStorage.setItem(kp,i),{nonce:r,state:o}},Ey=()=>{let e=sessionStorage.getItem(kp);if(U(e))throw new fy;return Oy(e)},Hp=({auth:e,identity:t})=>"satellite"in e?ep({...e.satellite,identity:t}):tp({...e.console,identity:t}),Ry=async({actorParams:e,args:t})=>{let{authenticate:r}=await Hp(e);return await r(t)},vy=async({actorParams:e,args:t})=>{let{get_delegation:r}=await Hp(e);return await r(t)},Iy=({delegations:e,sessionKey:t})=>{let[r,n]=e,o=Ut.fromDelegations(n,Uint8Array.from(r));return{identity:kt.fromDelegation(t,o),delegationChain:o,sessionKey:t}},rl=async({jwt:e,context:t,auth:r})=>{let n=await yt.generate({extractable:!1}),o=new Uint8Array(n.getPublicKey().toDer()),{delegations:i,data:s}=await Ay({jwt:e,publicKey:o,context:t,auth:r});return{identity:Iy({sessionKey:n,delegations:i}),data:s}},Ay=async({jwt:e,publicKey:t,context:{caller:r,salt:n},auth:o})=>{let i=await Ry({args:{OpenId:{jwt:e,session_key:t,salt:n}},actorParams:{auth:o,identity:r}});if("Err"in i)throw new _y("Authentication failed",{cause:i});let{delegation:{user_key:s,expiration:a},...c}=i.Ok,u=await Sy({jwt:e,context:{caller:r,salt:n},auth:o,publicKey:t,expiration:a}),{delegation:p,signature:d}=u,{pubkey:l,expiration:f,targets:h}=p;return{delegations:[s,[{delegation:new tn(Uint8Array.from(l),f,ge(h)),signature:Uint8Array.from(d)}]],data:c}},Sy=async({jwt:e,publicKey:t,context:{salt:r,caller:n},auth:o,expiration:i,maxRetries:s=5})=>{for(let a=0;a<s;a++){await new Promise(u=>{setInterval(u,1e3*a)});let c=await vy({args:{OpenId:{jwt:e,session_key:t,salt:r,expiration:i}},actorParams:{auth:o,identity:n}});if("Err"in c){let{Err:u}=c;if("NoSuchDelegation"in u||"GetCachedJwks"in u)continue;throw new xy("Getting delegation failed",{cause:c})}return c.Ok}throw new by},Cy=async({url:e})=>{try{let t=await fetch(e,{credentials:"include"});return t.ok?{success:await t.json()}:{error:new Error(`Failed to fetch ${e} (${t.status})`)}}catch(t){return{error:new wy({cause:t})}}},Fy=async({url:e,body:t})=>{try{let r=await fetch(e,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return r.ok?{success:await r.json()}:{error:new Error(`Failed to fetch ${e} (${r.status})`)}}catch(r){return{error:new Ty({cause:r})}}},Vy=async({auth:e,context:t,redirect:{finalizeUrl:r}})=>{let{location:{search:n}}=window,o=new URLSearchParams(n),i=o.get("code"),s=o.get("state"),a=await Fy({url:r,body:{code:i,state:s}});if("error"in a)throw a.error;let{success:{token:c}}=a;if(_t(c))throw new qp;return await rl({jwt:c,auth:e,context:t})},Py=async({auth:e,context:t})=>{let{location:{hash:r}}=window;if(_t(r)||!r.startsWith("#"))throw new yy("No hash found in the current location URL");let n=new URLSearchParams(r.slice(1)),o=n.get("state"),i=n.get("id_token"),{state:s}=t;if(_t(s)||o!==s)throw new gy("The provided state is invalid",{cause:o});if(_t(i))throw new qp;return await rl({jwt:i,auth:e,context:t})},Gp=async e=>{let t=Ey();if("github"in e){let{github:{redirect:n,auth:o}}=e,{finalizeUrl:i}=Lp;return await Vy({redirect:n??{finalizeUrl:i},auth:o,context:t})}let{google:r}=e;if("credentials"in r){let{credentials:{jwt:n},auth:o}=r;return await rl({jwt:n,context:t,auth:o})}return await Py({...r,context:t})},nl=({url:e})=>{try{return new URL(e)}catch{throw new py("Cannot parse authURL",{cause:e})}},By=({initUrl:e})=>async({nonce:t})=>{let r=nl({url:e});r.searchParams.set("nonce",t);let n=await Cy({url:r.toString()});if("error"in n)throw n.error;let{success:{state:o}}=n;return o},Dy=({authUrl:e,clientId:t,authScopes:r,state:n,redirectUrl:o})=>{let i=nl({url:e});i.searchParams.set("client_id",t);let{location:{origin:s}}=window;i.searchParams.set("redirect_uri",o??s),i.searchParams.set("scope",r.join(" ")),i.searchParams.set("state",n),window.location.href=i.toString()},Uy=()=>tl(crypto.getRandomValues(new Uint8Array(12))),ky=async e=>Uy(),Ly=({authUrl:e,clientId:t,nonce:r,loginHint:n,authScopes:o,state:i,redirectUrl:s})=>{let a=nl({url:e});a.searchParams.set("client_id",t);let{location:{origin:c}}=window;a.searchParams.set("redirect_uri",s??c),a.searchParams.set("response_type","code id_token"),a.searchParams.set("scope",o.join(" ")),a.searchParams.set("state",i),a.searchParams.set("nonce",r),Cr(n)?a.searchParams.set("login_hint",n):a.searchParams.set("prompt","select_account"),window.location.href=a.toString()},qy=async({configUrl:e,clientId:t,nonce:r,loginHint:n,domainHint:o})=>{let i=await navigator.credentials.get({identity:{context:"use",providers:[{configURL:e,clientId:t,nonce:r,loginHint:n,domainHint:o}],mode:"active"},mediation:"required"});if(U(i))throw new hy;let{type:s}=i;if(s!=="identity"||!("token"in i)||typeof i.token!="string")throw new my("Invalid credential received from FedCM API",{cause:i});let{token:a}=i;return{jwt:a}};async function sa(e){if("github"in e){let{github:s}=e,{redirect:a}=s,{initUrl:c,...u}=a,{authUrl:p,authScopes:d,initUrl:l}=Lp,f=await Up({generateState:By({initUrl:c??l})});Dy({...u,...f,authUrl:p,authScopes:d});return}let t=await Up({generateState:ky}),{google:r}=e;if("credentials"in r){let{credentials:s}=r,{configUrl:a}=Dp;return await qy({...s,...t,configUrl:a})}let{redirect:n}=r,{authUrl:o,authScopes:i}=Dp;Ly({...n,...t,authUrl:o,authScopes:i})}var aa=({url:e})=>{try{return new URL(e)}catch{return console.warn(`Cannot parse URL ${e}. Skipping option.`),null}};var My=async e=>{let{satelliteId:t}=Se.getInstance().get()??{satelliteId:void 0};if(U(t))throw new Vr("Satellite ID not set. Have you initialized the Satellite?");let r=Se.getInstance().get()?.container,n={auth:{satellite:{satelliteId:t,container:r}}},i=(()=>{let d="github"in e?e?.github?.options?.finalizeUrl:void 0;if(Cr(d))return d;let l=ra();return _t(l)?null:aa({url:`${l}/v1/auth/finalize/github`})?.toString()??null})(),{identity:{delegationChain:s,sessionKey:a,identity:c},data:{doc:u}}=await Gp("github"in e?{github:{redirect:J(i)?{finalizeUrl:i}:null,...n}}:{google:{redirect:null,...n}});await Fe.getInstance().setAuthClientStorage({delegationChain:s,sessionKey:a});let p=await Xn({doc:u,key:c.getPrincipal().toText()});await ta({user:p})};var $p=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),jy=()=>{window.addEventListener("beforeunload",$p,{capture:!0})},Ky=()=>{window.removeEventListener("beforeunload",$p,{capture:!0})},ca=async({fn:e})=>{try{return jy(),await e()}finally{Ky()}};function Jp(e){return new Promise((t,r)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)})}function il(e,t){let r,n=()=>{if(r)return r;let o=indexedDB.open(e);return o.onupgradeneeded=()=>o.result.createObjectStore(t),r=Jp(o),r.then(i=>{i.onclose=()=>r=void 0},()=>{}),r};return(o,i)=>n().then(s=>i(s.transaction(t,o).objectStore(t)))}var ol;function Hy(){return ol||(ol=il("keyval-store","keyval")),ol}function Wp(e,t,r=Hy()){return r("readwrite",n=>new Promise((o,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),o(Jp(n.transaction))}catch(s){i(s)}}}))}var Gy=class extends Error{constructor(){super("A dev identity can only be used in browser environments")}},$y=class extends Error{constructor(){super("A dev identity must only be used on localhost (127.0.0.1 or localhost)")}},Jy=class extends Error{constructor(e){super(`Identifier must be 32 characters or less, got ${e}`)}},Wy=il("juno-dev-identifiers","juno-dev-identifiers-store");var zp=async({identifier:e="dev",maxTimeToLiveInMilliseconds:t}={})=>{if(!(typeof window<"u"))throw new Gy;let{location:{hostname:r}}=window;if(!["127.0.0.1","localhost"].includes(r))throw new $y;let n=()=>{if(e.length>32)throw new Jy(e.length);return new TextEncoder().encode(e.padEnd(32,"0"))},o=async()=>{let a=n(),c=ct.generate(a),u=await yt.generate({extractable:!1}),p=t??6048e5,d=await Ut.create(c,u.getPublicKey(),new Date(Date.now()+p));return{identity:kt.fromDelegation(u,d),sessionKey:u,delegationChain:d}},i=async()=>{await Wp(e,a=>{let c=Date.now();return{createdAt:a?.createdAt??c,updatedAt:c}},Wy)},s=await o();return await i(),s};var la=class{async signIn({options:t,initAuth:r,setStorage:n}){let{sessionKey:o,delegationChain:i}=await zp(t);await n({sessionKey:o,delegationChain:i}),await r({provider:void 0})}};var ua=class{async signIn({options:t={}}){let r=t?.redirect?.clientId??vp();if(U(r))throw new So;let{redirect:n}=t;await sa({github:{redirect:{...n??{},clientId:r,initUrl:(()=>{let i=t?.redirect?.initUrl;if(Cr(i))return i;let s=ra();if(!_t(s))return aa({url:`${s}/v1/auth/init/github`})?.toString()})()}}})}};var da=class{async signIn({options:t={}}){let r=t?.redirect?.clientId??Rp();if(U(r))throw new So;let{redirect:n}=t;await sa({google:{redirect:{...n??{},clientId:r}}})}};var Yp=async({delegationIdentity:e,passkeyIdentity:t,satelliteId:r})=>{let n=t.getCredential().getAAGUID(),[o,i]=await xp({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...J(n)&&{aaguid:Ds(n)}}}}}},{collection:"#user-webauthn",doc:{key:t.getCredential().getCredentialIdText(),data:{publicKey:t.getPublicKey().toRaw()}}}],satellite:{identity:e,satelliteId:r}});return o};var Zp=(i=>(i[i.RequestingUserCredential=0]="RequestingUserCredential",i[i.FinalizingCredential=1]="FinalizingCredential",i[i.Signing=2]="Signing",i[i.FinalizingSession=3]="FinalizingSession",i[i.RetrievingUser=4]="RetrievingUser",i))(Zp||{}),Xp=(s=>(s[s.CreatingUserCredential=0]="CreatingUserCredential",s[s.ValidatingUserCredential=1]="ValidatingUserCredential",s[s.FinalizingCredential=2]="FinalizingCredential",s[s.Signing=3]="Signing",s[s.FinalizingSession=4]="FinalizingSession",s[s.RegisteringUser=5]="RegisteringUser",s))(Xp||{});var Co=class{async signUp({options:{onProgress:t,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:o}){let{satelliteId:i}=Se.getInstance().get()??{satelliteId:void 0};if(U(i))throw new Vr("Satellite ID not set. Have you initialized the Satellite?");let s=({step:_,state:g})=>{switch(_){case en.RequestingUserCredential:t?.({step:1,state:g});break;case en.FinalizingCredential:t?.({step:2,state:g});break;case en.Signing:t?.({step:3,state:g});break}},c=await Zt({fn:async()=>await Pc.createWithNewCredential({onProgress:s,passkeyOptions:n}),step:0,onProgress:t}),{delegationIdentity:u,sessionKey:p}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),l=await Zt({fn:async()=>await Yp({delegationIdentity:u,passkeyIdentity:c,satelliteId:i}),step:5,onProgress:t});await Zt({fn:async()=>await this.#t({delegationIdentity:u,sessionKey:p}),step:4,onProgress:t}),await Zt({fn:async()=>await o({user:l}),step:5,onProgress:t})}async signIn({options:{onProgress:t,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:o}=Se.getInstance().get()??{satelliteId:void 0};if(U(o))throw new Vr("Satellite ID not set. Have you initialized the Satellite?");let i=async({credentialId:d})=>{let l=await Xs({collection:"#user-webauthn",key:Qr(d),options:{certified:!0},satellite:{identity:new it,satelliteId:o}});if(U(l))throw new $s("No public key found for the selected passkey.");let{data:f}=l,{publicKey:h}=f;return Zn(h,gi)},s=({step:d,state:l})=>{switch(d){case en.RequestingUserCredential:t?.({step:0,state:l});break;case en.FinalizingCredential:t?.({step:1,state:l});break;case en.Signing:t?.({step:2,state:l});break}},a=await Pc.createWithExistingCredential({retrievePublicKey:i,onProgress:s}),{delegationIdentity:c,sessionKey:u}=await this.#e({identity:a,maxTimeToLiveInMilliseconds:r});await Zt({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:u}),step:3,onProgress:t}),await Zt({fn:n,step:4,onProgress:t})}async#e({identity:t,maxTimeToLiveInMilliseconds:r}){let n=await yt.generate({extractable:!1}),o=r??144e5,i=await Ut.create(t,n.getPublicKey(),new Date(Date.now()+o));return{delegationIdentity:kt.fromDelegation(n,i),sessionKey:n}}async#t({sessionKey:t,delegationIdentity:r}){let n=new zt;await Promise.all([n.set(Ye,t.getKeyPair()),n.set(ze,JSON.stringify(r.getDelegation().toJSON()))])}};var Qp=async({provider:e})=>{await Ii({fn:async()=>{let r=await bp({provider:e});De.getInstance().set(r)},syncTabsOnSuccess:!0})},Yy=async e=>{if("google"in e){let{google:{options:t}}=e;await Ai({fn:()=>new da().signIn({options:t}),context:{windowGuard:!1}});return}if("github"in e){let{github:{options:t}}=e;await Ai({fn:()=>new ua().signIn({options:t}),context:{windowGuard:!1}});return}if("webauthn"in e){let{webauthn:{options:t,context:r}}=e;await Ai({fn:()=>new Co().signIn({options:t,loadAuth:()=>ea({syncTabsOnSuccess:!0})}),context:r});return}if("internet_identity"in e){let{internet_identity:{options:t,context:r}}=e,{domain:n,...o}=t??{};await Ai({fn:()=>new ia({domain:n}).signIn({options:o,authClient:Fe.getInstance().getAuthClient(),initAuth:Qp}),context:r});return}if("dev"in e){let{dev:{options:t}}=e,{setAuthClientStorage:r}=Fe.getInstance();await Ai({fn:()=>new la().signIn({options:t,initAuth:Qp,setStorage:r}),context:{windowGuard:!1}});return}throw new Gs("An unknown or unsupported provider was provided for sign-in.")},Ai=async({fn:e,context:t})=>{if(t?.windowGuard===!1){await e();return}await ca({fn:e})};var Zy=async e=>{let t=async()=>await Xy(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await t();return}await ca({fn:t})},Xy=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new Co().signUp({options:t,loadAuthWithUser:ta});return}throw new Js("An unknown or unsupported provider was provided for sign-up.")};var m1=e=>e?.data?.provider==="webauthn",_1=e=>e?.data?.provider==="google",y1=e=>e?.data?.provider==="github";var w1=async({idlFactory:e,satellite:t})=>{let r=ue(t?.identity);return await op({idlFactory:e,...t,identity:r})};var ef=async({asset:{data:e,headers:t,...r},actor:n,progress:o})=>{let{init_asset_upload:i,upload_asset_chunk:s,commit_asset_upload:a}=n,{batch_id:c}=await i(Qy(r));o?.onInitiatedBatch();let{chunkIds:u}=await rg({data:e,uploadFn:s,batchId:c});o?.onUploadedFileChunks(r.fullPath),await tg({commitFn:a,batchId:c,data:e,headers:t,chunkIds:u}),o?.onCommittedBatch()};var Qy=({filename:e,collection:t,token:r,fullPath:n,encoding:o,description:i})=>({collection:t,full_path:n,name:e,token:se(r),encoding_type:se(o),description:se(i)}),eg=({batchId:e,chunkIds:t,headers:r,data:n})=>{let o=r.find(([i,s])=>i.toLowerCase()==="content-type")===void 0&&n.type!==void 0&&n.type!==""?[["Content-Type",n.type]]:void 0;return{batch_id:e,chunk_ids:t.map(({chunk_id:i})=>i),headers:[...r,...o??[]]}},tg=async({commitFn:e,...t})=>{let r=eg(t);await e(r)},rg=async({data:e,uploadFn:t,batchId:r})=>{let n=[],o=Zs()?new Blob([await e.arrayBuffer()]):e,i=0n;for(let a=0;a<o.size;a+=19e5){let c=o.slice(a,a+19e5);n.push({batchId:r,chunk:c,uploadFn:t,orderId:i}),i++}let s=[];for await(let a of ng({uploadChunks:n}))s=[...s,...a];return{chunkIds:s}};async function*ng({uploadChunks:e,limit:t=12}){for(let r=0;r<e.length;r=r+t){let n=e.slice(r,r+t);yield await Promise.all(n.map(o=>og(o)))}}var og=async({batchId:e,chunk:t,uploadFn:r,orderId:n})=>r({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:se(n)});var tf=async({asset:e,...t})=>{let r=await xe(t);await ef({actor:r,asset:e})},rf=async({collection:e,filter:t,...r})=>{let{list_assets:n}=await xe(r),{items:o,items_length:i,items_page:s,matches_length:a,matches_pages:c}=await n(e,rn(t));return{items:o.map(([u,p])=>p),items_length:i,items_page:ge(s),matches_length:a,matches_pages:ge(c)}},nf=async({collection:e,filter:t,...r})=>{let{count_assets:n}=await xe(r);return n(e,rn(t))},of=async({collection:e,fullPath:t,...r})=>(await xe(r)).del_asset(e,t),sf=async({assets:e,satellite:t})=>{let{del_many_assets:r}=await xe({satellite:t,options:{certified:!0}}),n=e.map(({collection:o,fullPath:i})=>[o,i]);await r(n)},af=async({collection:e,filter:t,...r})=>{let{del_filtered_assets:n}=await xe(r);return n(e,rn(t))},cf=async({collection:e,fullPath:t,token:r,...n})=>{let{set_asset_token:o}=await xe(n);return o(e,t,se(r))},lf=async({collection:e,fullPath:t,...r})=>{let{get_asset:n}=await xe(r);return ge(await n(e,t))},uf=async({assets:e,...t})=>{let{get_many_assets:r}=await xe(t),n=e.map(({collection:i,fullPath:s})=>[i,s]);return(await r(n)).map(([i,s])=>ge(s))};var df=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var k1=e=>pf(e),L1=e=>pf({filename:e.data.name,...e}),pf=async({filename:e,data:t,collection:r,headers:n=[],fullPath:o,token:i,satellite:s,encoding:a,description:c})=>{let u=ue(s?.identity),p=decodeURI(e),d=o??`/${r}/${p}`,l={...s,identity:u};return await tf({asset:{data:t,filename:p,collection:r,token:i,headers:n,fullPath:d,encoding:a,description:c},satellite:l,options:{certified:!0}}),{downloadUrl:ff({satellite:l,assetKey:{fullPath:d,token:i}}),fullPath:d,...J(i)&&{token:i},name:p}},q1=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:ue(r?.identity)},{items:i,...s}=await rf({collection:e,filter:t??{},satellite:o,options:n??Yt}),a=i.map(({key:{full_path:c,token:u,name:p,owner:d,description:l},headers:f,encodings:h,created_at:_,updated_at:g})=>{let m=ge(u);return{fullPath:c,description:ge(l),name:p,downloadUrl:ff({satellite:o,assetKey:{fullPath:c,token:m}}),token:m,headers:f,encodings:h.reduce((b,[y,{modified:T,sha256:O,total_length:R}])=>({...b,[y]:{modified:T,sha256:df(O),total_length:R}}),{}),owner:d.toText(),created_at:_,updated_at:g}});return{items:a,assets:a,...s}},M1=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:ue(r?.identity)};return await nf({collection:e,satellite:o,filter:t??{},options:n??Yt})},j1=({collection:e,fullPath:t,satellite:r})=>of({collection:e,fullPath:t,satellite:{...r,identity:ue(r?.identity)},options:{certified:!0}}),K1=({collection:e,fullPath:t,token:r,satellite:n})=>cf({collection:e,fullPath:t,token:r,satellite:{...n,identity:ue(n?.identity)},options:{certified:!0}}),H1=({assets:e,satellite:t})=>sf({assets:e,satellite:{...t,identity:ue(t?.identity)},options:{certified:!0}}),G1=async({collection:e,satellite:t,filter:r})=>{let n={...t,identity:ue(t?.identity)};return await af({collection:e,satellite:n,filter:r??{},options:{certified:!0}})},$1=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await lf({...r,satellite:{...e,identity:n},options:t??Yt})},J1=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await uf({...r,satellite:{...e,identity:n},options:t??Yt})},ff=({assetKey:{fullPath:e,token:t},satellite:r})=>{let n={...r,identity:ue(r?.identity)};return`${np(n)}${e}${J(t)?`?token=${t}`:""}`};var ig=e=>{let t=e?.satelliteId??Op();bi(t,"Satellite ID is not configured. Juno cannot be initialized.");let r=e?.container??Ep();return{satelliteId:t,internetIdentityId:e?.internetIdentityId,workers:e?.workers,syncTabs:e?.syncTabs,container:r}},nE=e=>sg(e),sg=async e=>{let t=ig(e);Se.getInstance().set(t),await ea();let r=t.workers?.auth!==void 0?Zd(t.workers.auth):void 0,n=t.syncTabs===!1?void 0:Np();return[...J(r)?[r]:[],...J(n)?[n]:[]]},ag=e=>De.getInstance().subscribe(e),oE=ag;export{Pp as AuthClientSignInProgressStep,Ws as InitError,ia as InternetIdentityProvider,zs as ListError,Ks as SignInError,Vr as SignInInitError,So as SignInMissingClientIdError,Gs as SignInProviderNotSupportedError,Hs as SignInUserInterruptError,Js as SignUpProviderNotSupportedError,Zp as WebAuthnSignInProgressStep,$s as WebAuthnSignInRetrievePublicKeyError,Xp as WebAuthnSignUpProgressStep,oE as authSubscribe,M1 as countAssets,KN as countDocs,j1 as deleteAsset,LN as deleteDoc,G1 as deleteFilteredAssets,MN as deleteFilteredDocs,H1 as deleteManyAssets,qN as deleteManyDocs,ff as downloadUrl,$1 as getAsset,Xs as getDoc,ry as getIdentityOnce,J1 as getManyAssets,kN as getManyDocs,w1 as getSatelliteExtendedActor,My as handleRedirectCallback,nE as initJuno,sg as initSatellite,y1 as isGitHubUser,_1 as isGoogleUser,I_ as isWebAuthnAvailable,m1 as isWebAuthnUser,q1 as listAssets,jN as listDocs,ag as onAuthStateChange,K1 as setAssetToken,gp as setDoc,xp as setManyDocs,Yy as signIn,$c as signOut,Zy as signUp,ty as unsafeIdentity,k1 as uploadBlob,L1 as uploadFile};
54
+ Retrying query.`),await this.#w({...t,tries:a+1});throw Go.fromCode(new Yo(m))}let p=mc(d.headers);if(d.status!==el){let m=await d.text();if(Zd(m))throw z.fromCode(new $t(m,this.#u));if(a<this.#d)return await this.#w({...t,tries:a+1});throw re.fromCode(new Wo(d.status,d.statusText,p,m))}let f={...je(yo(await d.arrayBuffer())),httpDetails:{ok:d.ok,status:d.status,statusText:d.statusText,headers:p},requestId:i};if(!this.#_)return f;let h=f.signatures?.[0]?.timestamp;if(!h)throw re.fromCode(new hs("Timestamp not found in query response. This suggests a malformed or malicious response."));let _=Number(BigInt(h)/BigInt(K_));if(Date.now()+this.#r-_>this.#R){if(a<this.#d)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:i,signatureTimestampMs:_}),await this.syncTime(r),await this.#w({...t,tries:a+1});throw Ye.fromCode(new is(this.#u,i,a))}return f}async#y(t){let{requestFn:r,backoff:n,tries:o}=t,i=o===0?0:n.next();if(i===null)throw re.fromCode(new jn(`Retry strategy exhausted after ${o} attempts.`));i>0&&await new Promise(d=>setTimeout(d,i));let s,a=new Uint8Array;try{s=await r(),s.status===el&&(a=yo(await s.clone().arrayBuffer()))}catch(d){if(o<this.#d)return this.log.warn(`Caught exception while attempting to make request:
55
+ ${d}
56
+ Retrying request.`),await this.#y({requestFn:r,backoff:n,tries:o+1});throw Go.fromCode(new Yo(d))}let c=mc(s.headers);if(s.status===el||s.status===Yd)return{ok:s.ok,status:s.status,statusText:s.statusText,responseBodyBytes:a,headers:c};let l=await s.text();if(s.status===X_&&s.url.includes("api/v4"))throw re.fromCode(new zo);if(Zd(l))throw z.fromCode(new $t(l,this.#u));if(o<this.#d)return await this.#y({requestFn:r,backoff:n,tries:o+1});throw re.fromCode(new Wo(s.status,s.statusText,c,l))}async query(t,r,n){let o=this.#f(),i=r.effectiveCanisterId?q.from(r.effectiveCanisterId):q.from(t);await this.#p(i),this.log.print(`ecid ${i.toString()}`),this.log.print(`canisterId ${t.toString()}`);let s,a=await(n??this.#n);if(!a)throw Pe.fromCode(new Wr);let c=q.from(t),l=a.getPrincipal(),d=tl(this.#u,this.#r),p={request_type:Yn.Query,canister_id:c,method_name:r.methodName,arg:r.arg,sender:l,ingress_expiry:d},u=Rr(p);s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#c?{Authorization:`Basic ${btoa(this.#c)}`}:{}}},endpoint:Ir.Query,body:p}),s=await a.transformRequest(s);let f=pi(s.body),h={canister:c.toText(),ecid:i,transformedRequest:s,body:f,requestId:u,backoff:o,tries:0},_=async()=>{let y=await this.#w(h);return{requestDetails:p,...y}};try{if(!this.#_)return await _();let[y,m]=await Promise.all([_(),this.fetchSubnetKeys(i)]);try{return this.#N(y,m)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),await this.#x.delete(i.toString());let b=await this.fetchSubnetKeys(i);return this.#N(y,b)}}catch(y){let m;if(y instanceof st){if(y.hasCode($t)&&!this.#o)return await this.syncTime(i),this.query(t,r,n);y.code.requestContext={requestId:u,senderPubKey:s.body.sender_pubkey,senderSignature:s.body.sender_sig,ingressExpiry:s.body.content.ingress_expiry},m=y}else m=ae.fromCode(new Se(y));throw this.log.error(`Error while making query: ${m.message}`,m),m}}#N;async createReadStateRequest(t,r){await this.#p();let n=await(r??this.#n);if(!n)throw Pe.fromCode(new Wr);let o=n.getPrincipal(),i=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#c?{Authorization:`Basic ${btoa(this.#c)}`}:{}}},endpoint:Ir.ReadState,body:{request_type:Yn.ReadState,paths:t.paths,sender:o,ingress_expiry:tl(this.#u,this.#r)}});return n.transformRequest(i)}async readState(t,r,n,o){await this.#g();let i=q.from(t);function s(d){for(let p of d.paths){let[u,f]=p,h=new TextEncoder().encode("request_status");if(Jn(u,h))return f}}let a,c;if(o)a=o;else{c=s(r);let d=await this.#n;if(!d)throw Pe.fromCode(new Wr);a=await this.createReadStateRequest(r,d)}let l=new URL(`/api/v3/canister/${i.toString()}/read_state`,this.host);return await this.#O(l,{canisterId:i},a,c)}async readSubnetState(t,r){await this.#g();let n=q.from(t),o=new URL(`/api/v3/subnet/${n.toString()}/read_state`,this.host),i=await this.createReadStateRequest(r,this.#n??void 0);return await this.#O(o,{subnetId:n},i)}async#O(t,r,n,o){let i=this.#f();try{let{responseBodyBytes:s}=await this.#y({requestFn:()=>this.#i(t,{...this.#l,...n.request,body:pi(n.body)}),backoff:i,tries:0});return je(s)}catch(s){let a;if(s instanceof st){if(s.hasCode($t)&&!this.#o){if("canisterId"in r)await this.syncTime(r.canisterId);else if("subnetId"in r)await this.syncTimeWithSubnet(r.subnetId);else throw ft;return await this.#O(t,r,n,o)}s.code.requestContext={requestId:o??Rr(n),senderPubKey:n.body.sender_pubkey,senderSignature:n.body.sender_sig,ingressExpiry:n.body.content.ingress_expiry},a=s}else a=ae.fromCode(new Se(s));throw this.log.error(`Error while making read state: ${a.message}`,a),a}}parseTimeFromResponse(t){let r;if(t.certificate){let n=je(t.certificate);if(n&&"tree"in n)r=n.tree;else throw re.fromCode(new zr("Could not decode time from response"));let o=Br(["time"],r);if(o.status!==Be.Found)throw re.fromCode(new At("Time was not found in the response or was not in its expected format.",o.status));if(!(o.value instanceof Uint8Array)&&!ArrayBuffer.isView(o))throw re.fromCode(new Qi("Time was not in its expected format."));let i=nn(o.value);return this.log.print("Time from response:",i),this.log.print("Time from response in milliseconds:",i.getTime()),i.getTime()}return this.log.warn("No certificate found in response"),0}async syncTime(t){this.#s=this.#s??(async()=>{await this.#g();let r=Date.now();try{t||this.log.print("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");let n=t??q.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),o=e.createSync({identity:new at,host:this.host.toString(),fetch:this.#i,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),i=await Promise.all(Array(3).fill(null).map(async()=>{let a=(await Ud({canisterId:n,agent:o,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(a instanceof Date)return a.getTime()},[]));this.#E(r,i)}catch(n){let o=n instanceof st?n:ae.fromCode(new Se(n));throw this.log.error("Caught exception while attempting to sync time",o),o}})(),await this.#s.finally(()=>{this.#s=null})}async syncTimeWithSubnet(t){await this.#g();let r=Date.now();try{let n=e.createSync({identity:new at,host:this.host.toString(),fetch:this.#i,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),o=await Promise.all(Array(3).fill(null).map(async()=>{let s=(await kd({subnetId:t,agent:n,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(s instanceof Date)return s.getTime()},[]));this.#E(r,o)}catch(n){let o=n instanceof st?n:ae.fromCode(new Se(n));throw this.log.error("Caught exception while attempting to sync time with subnet",o),o}}#E(t,r){let n=r.reduce((o,i)=>typeof i=="number"&&i>o?i:o,0);n>0&&(this.#r=n-t,this.#o=!0,this.log.notify({message:`Syncing time: offset of ${this.#r}`,level:"info"}))}async status(){let t=this.#c?{Authorization:`Basic ${btoa(this.#c)}`}:{},r=new URL("/api/v2/status",this.host);this.log.print(`fetching "${r.pathname}"`);let n=this.#f(),{responseBodyBytes:o}=await this.#y({backoff:n,requestFn:()=>this.#i(r,{headers:t,...this.#l}),tries:0});return je(o)}async fetchRootKey(){return this.#e=this.#e??(async()=>{let t=await this.status();return this.rootKey=t.root_key,this.rootKey})(),await this.#e.finally(()=>{this.#e=null})}async#p(t){await Promise.all([this.#g(),this.#A(t)])}async#g(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#t)await this.fetchRootKey();else throw Pe.fromCode(new Ct(this.#t))}async#A(t){this.#a&&!this.hasSyncedTime()&&await this.syncTime(t)}invalidateIdentity(){this.#n=null}replaceIdentity(t){this.#n=Promise.resolve(t)}async fetchSubnetKeys(t){let r=q.from(t),n=await this.#x.get(r.toText());if(n)return n;let o=this.#b.get(r.toText());if(o)return o;let i=this.#S(r).finally(()=>{this.#b.delete(r.toText())});return this.#b.set(r.toText(),i),i}async#S(t){await this.#p(t);let r=this.rootKey,n=await this.readState(t,{paths:[[G("subnet")]]}),o=await gt.create({certificate:n.certificate,rootKey:r,principal:{canisterId:t},agent:this});if(!o.cert.delegation){let a=q.selfAuthenticating(r);if(!Kc({canisterId:t,subnetId:a,tree:o.cert.tree}))throw Ye.fromCode(new Mn(t,a))}let i=Hc(o.cert,r),s=vo(o.cert,i);return await this.#x.set(t.toText(),s),s}async getSubnetIdFromCanister(t){let r=q.from(t);await this.#p(r);let n=await this.readState(r,{paths:[[G("time")]]}),o=await gt.create({certificate:n.certificate,rootKey:this.rootKey,principal:{canisterId:r},agent:this});return Hc(o.cert,this.rootKey)}_transform(t){let r=Promise.resolve(t);if(t.endpoint===Ir.Call)for(let n of this.#m)r=r.then(o=>n(o).then(i=>i||o));else for(let n of this.#h)r=r.then(o=>n(o).then(i=>i||o));return r}getTimeDiffMsecs(){return this.#r}hasSyncedTime(){return this.#o}};function tl(e,t){let r=e*rl;return zn.fromDeltaInMilliseconds(r,t)}function Zd(e){return e.includes("Invalid request expiry: ")}var ut=Symbol.for("ic-agent-metadata"),So=class e{static agentOf(t){return t[ut].config.agent}static interfaceOf(t){return t[ut].service}static canisterIdOf(t){return q.from(t[ut].config.canisterId)}static createActorClass(t,r){let n=t({IDL:Gn});class o extends e{constructor(s){if(!s.canisterId)throw z.fromCode(new Zo(s.canisterId));let a=typeof s.canisterId=="string"?q.fromText(s.canisterId):s.canisterId;super({config:{...Xd,...s,canisterId:a},service:n});for(let[c,l]of n._fields)r?.httpDetails&&l.annotations.push(nl),r?.certificate&&l.annotations.push(Qd),this[c]=ey(this,c,l,s.blsVerify)}}return o}static createActor(t,r){if(!r.canisterId)throw z.fromCode(new Zo(r.canisterId));return new(this.createActorClass(t))(r)}static createActorWithHttpDetails(t,r){return new(this.createActorClass(t,{httpDetails:!0}))(r)}static createActorWithExtendedDetails(t,r,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(t,n))(r)}constructor(t){this[ut]=Object.freeze(t)}};function Ao(e,t){let r=Gn.decode(e,t);switch(r.length){case 0:return;case 1:return r[0];default:return r}}var Xd={pollingOptions:Wd,queryStrategy:"query"},nl="http-details",Qd="certificate";function ey(e,t,r,n){let o,i=r.annotations.includes("query")||r.annotations.includes("composite_query"),s=e[ut].config.queryStrategy;i&&s==="query"?o=async(c,...l)=>{c={...c,...e[ut].config.queryTransform?.(t,l,{...e[ut].config,...c})};let d=c.agent||e[ut].config.agent||new kr,p=q.from(c.canisterId||e[ut].config.canisterId),u=Gn.encode(r.argTypes,l),f=await d.query(p,{methodName:t,arg:u,effectiveCanisterId:c.effectiveCanisterId}),h={...f.httpDetails,requestDetails:f.requestDetails};switch(f.status){case $r.Rejected:{let _=new as(f.requestId,f.reject_code,f.reject_message,f.error_code,f.signatures);throw _.callContext={canisterId:p,methodName:t,httpDetails:h},vt.fromCode(_)}case $r.Replied:return r.annotations.includes(nl)?{httpDetails:h,result:Ao(r.retTypes,f.reply.arg)}:Ao(r.retTypes,f.reply.arg)}}:o=async(c,...l)=>{c={...c,...e[ut].config.callTransform?.(t,l,{...e[ut].config,...c})};let d=c.agent||e[ut].config.agent||kr.createSync(),{canisterId:p,effectiveCanisterId:u,pollingOptions:f}={...Xd,...e[ut].config,...c},h=q.from(p),_=u!==void 0?q.from(u):h,y=Gn.encode(r.argTypes,l),m,b,g,T;try{({reply:m,certificate:b,callResponse:g,requestDetails:T}=await d.update(h,{methodName:t,arg:y,effectiveCanisterId:_,nonce:c.nonce},{...f,blsVerify:n}))}catch(C){if(C instanceof vt){let w=Object.create(Object.getPrototypeOf(C.code),Object.getOwnPropertyDescriptors(C.code));throw w.callContext={...C.code.callContext,canisterId:h,methodName:t},vt.fromCode(w)}throw C}let O=r.annotations.includes(nl),v=r.annotations.includes(Qd),E={...g,requestDetails:T};return O&&v?{httpDetails:E,certificate:b,result:Ao(r.retTypes,m)}:v?{certificate:b,result:Ao(r.retTypes,m)}:O?{httpDetails:E,result:Ao(r.retTypes,m)}:Ao(r.retTypes,m)};let a=(...c)=>o({},...c);return a.withOptions=c=>(...l)=>o(c,...l),a}var ty=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),r=ry({bytes:t});return"aaguid"in r?{aaguidBytes:t,aaguidText:r.aaguid}:{unknownProvider:null}},ry=({bytes:e})=>{if(e.length!==16)return{invalidBytes:null};let t=(e instanceof Uint8Array?Li(e):e).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return t==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:t}};function ny(e){let t=new DataView(new ArrayBuffer(2)),r=e.slice(53,55);[...new Uint8Array(r)].forEach((o,i)=>t.setUint8(i,o));let n=t.getUint16(0);return e.slice(55+n)}function oy(e){return no(e,vi)}var iy=class{constructor(e){this._cose=e,this.#e=oy(e)}_cose;#e;toDer(){return this.#e}toRaw(){return new Uint8Array(this.#e)}},op=class{#e;#t;constructor({rawId:e,cose:t}){this.#e=e,this.#t=new iy(t)}getPublicKey(){return this.#t}getCredentialId(){return this.#e}getCredentialIdText(){return Kr(this.#e)}},sy=class extends op{#e;#t;constructor({authData:e,...t}){super(t);let r=ty({authData:e});this.#e="aaguidText"in r?r.aaguidText:void 0,this.#t="aaguidBytes"in r?r.aaguidBytes:void 0}getAAGUID(){return this.#t}getAAGUIDText(){return this.#e}},ay=class extends op{},cy=class extends Error{},ly=class extends Error{},uy=class extends Error{},dy=class extends Error{},py=class extends Error{},fy=class extends Error{},hy=class extends Error{},ep=class extends Error{};var my={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},_y=6e4,ip=()=>window.crypto.getRandomValues(new Uint8Array(16)),yy=()=>ip(),gy=()=>ip(),xy=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new cy}},sp=({appId:e})=>e?.id??xy(),by=({appId:e,user:t}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:e?.name??r,id:sp({appId:e})}}),o=()=>({user:{id:gy(),name:t?.name??t?.displayName??r,displayName:t?.displayName??r}});return{attestation:"direct",challenge:yy(),...n(),...o(),pubKeyCredParams:Object.values(my).map(i=>({type:"public-key",alg:i})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},wy=(e={})=>({rpId:sp(e),allowCredentials:[],userVerification:"required"}),ol=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}},ln=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))(ln||{}),ap=({timeout:e})=>AbortSignal.timeout(e??_y),Ty=async({challenge:e,credentialIds:t,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...wy(r),challenge:e.buffer,allowCredentials:(t??[]).map(o=>({id:o.buffer,type:"public-key"}))},signal:ap({timeout:n})}),tp=e=>{if(e.status!=="initialized")throw new ly},rp=e=>{if(U(e))throw new uy},np=({type:e})=>{if(e!=="public-key")throw new dy},il=class Ii extends zt{#e;#t;constructor({onProgress:t,...r}){if(super(),this.#e=t,"retrievePublicKey"in r){let{retrievePublicKey:n}=r;this.#t={status:"pending",retrievePublicKey:n};return}this.#t=Ii.#r({credential:new sy(r)})}static#r({credential:t}){return{status:"initialized",credential:t}}static async createWithNewCredential({passkeyOptions:t,timeout:r,...n}={}){let o=await navigator.credentials.create({publicKey:by(t),signal:ap({timeout:r})});rp(o),np(o);let{response:{attestationObject:i},rawId:s}=o;if(U(i))throw new py;let{authData:a}=As.decode(mr(i)),c=ny(a);return new Ii({...n,rawId:mr(s),cose:c,authData:a})}static async createWithExistingCredential(t){return new Ii(t)}getPublicKey(){tp(this.#t);let{credential:t}=this.#t;return t.getPublicKey()}getCredential(){tp(this.#t);let{credential:t}=this.#t;return t}async sign(t){let r=await ol({fn:async()=>{let n=await Ty({challenge:t,...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return rp(n),np(n),n},step:0,onProgress:this.#e});return await ol({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!Fl({a:this.#t.credential.getCredentialId(),b:mr(n)}))throw new fy;return}let{retrievePublicKey:o}=this.#t,i=await o({credentialId:mr(n)});this.#t=Ii.#r({credential:new ay({rawId:mr(n),cose:i})})},step:1,onProgress:this.#e}),await ol({fn:async()=>{let{response:n}=r,{clientDataJSON:o}=n,{authenticatorData:i,signature:s}="authenticatorData"in n&&"signature"in n?n:{};if(U(i))throw new ep;if(U(s))throw new ep;let a=As.encode({authenticator_data:i,client_data_json:new TextDecoder().decode(o),signature:mr(s)});if(U(a))throw new hy;return Object.assign(a,{__signature__:void 0}),a},step:2,onProgress:this.#e})}},Ny=async()=>J(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var Co=class{callbacks=[];populate(t){this.callbacks.forEach(({callback:r})=>r(t))}subscribe(t){let r=Symbol();return this.callbacks.push({id:r,callback:t}),()=>this.callbacks=this.callbacks.filter(({id:n})=>n!==r)}};var Ue=class e extends Co{static instance;authUser=null;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.authUser=t,this.populate(t)}get(){return this.authUser}subscribe(t){let r=super.subscribe(t);return t(this.authUser),r}reset(){this.authUser=null,this.populate(this.authUser)}};var Ai=({message:e,detail:t})=>{let r=new CustomEvent(e,{detail:t,bubbles:!0});document.dispatchEvent(r)};var Vo="http://127.0.0.1:5987",cp="rdmx6-jaaaa-aaaaa-aaadq-cai";var lp=async({identity:e,container:t})=>{let n=J(t)&&t!==!1?t===!0?Vo:t:"https://icp-api.io",o=J(t);return await kr.create({identity:e,shouldFetchRootKey:o,host:n})};var Po=class e{static instance;#e=void 0;constructor(){}static getInstance(){return U(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:t,...r}){let n=t.getPrincipal().toText();if(U(this.#e)||U(this.#e[n])){let o=await lp({identity:t,...r});return this.#e={...this.#e??{},[n]:o},o}return this.#e[n]}reset(){this.#e=null}};var Fo=class e{static instance;#e=void 0;constructor(){}static getInstance(){return U(e.instance)&&(e.instance=new e),e.instance}async getActor({satelliteId:t,identity:r,actorKey:n,...o}){let i=`${n}#${r.getPrincipal().toText()}#${t};`;if(U(this.#e)||U(this.#e[i])){let s=await this.createActor({satelliteId:t,identity:r,...o});return this.#e={...this.#e??{},[i]:s},s}return this.#e[i]}reset(){this.#e=null}async createActor({idlFactory:t,satelliteId:r,...n}){let o=await Po.getInstance().getAgent(n);return So.createActor(t,{agent:o,canisterId:r})}};function up(e){return e!==null&&typeof e=="object"}var Si=class e{static from(t){if(typeof t=="string"){let r=Ee(t);return this.fromRaw(r)}if(up(t)){let r=t;if(up(r)&&Object.hasOwnProperty.call(r,"__derEncodedPublicKey__"))return this.fromDer(r);if(ArrayBuffer.isView(r)){let n=r;return this.fromRaw(Ht(n.buffer))}if(r instanceof ArrayBuffer)return this.fromRaw(Ht(r));if("rawKey"in r&&r.rawKey instanceof Uint8Array)return this.fromRaw(r.rawKey);if("derKey"in r)return this.fromDer(r.derKey);if("toDer"in r)return this.fromDer(r.toDer())}throw new Error("Cannot construct Ed25519PublicKey from the provided key.")}static fromRaw(t){return new e(t)}static fromDer(t){return new e(this.derDecode(t))}static{this.RAW_KEY_LENGTH=32}static derEncode(t){let r=no(t,ro);return r.__derEncodedPublicKey__=void 0,r}static derDecode(t){let r=oo(t,ro);if(r.length!==this.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");return r}#e;get rawKey(){return this.#e}#t;get derKey(){return this.#t}constructor(t){if(t.byteLength!==e.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");this.#e=t,this.#t=e.derEncode(t)}toDer(){return this.derKey}toRaw(){return this.rawKey}},dt=class e extends zt{static generate(t){if(t&&t.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");t||(t=Je.utils.randomPrivateKey()),cu(t,new Uint8Array(new Array(32).fill(0)))&&console.warn("Seed is all zeros. This is not a secure seed. Please provide a seed with sufficient entropy if this is a production environment.");let r=new Uint8Array(32);for(let o=0;o<32;o++)r[o]=t[o];let n=Je.getPublicKey(r);return e.fromKeyPair(n,r)}static fromParsedJson(t){let[r,n]=t;return new e(Si.fromDer(Ee(r)),Ee(n))}static fromJSON(t){let r=JSON.parse(t);if(Array.isArray(r)){if(typeof r[0]=="string"&&typeof r[1]=="string")return this.fromParsedJson([r[0],r[1]]);throw new Error("Deserialization error: JSON must have at least 2 items.")}throw new Error(`Deserialization error: Invalid JSON type for string: ${JSON.stringify(t)}`)}static fromKeyPair(t,r){return new e(Si.fromRaw(t),r)}static fromSecretKey(t){let r=Je.getPublicKey(t);return e.fromKeyPair(r,t)}#e;#t;constructor(t,r){super(),this.#e=Si.from(t),this.#t=r}toJSON(){return[j(this.#e.toDer()),j(this.#t)]}getKeyPair(){return{secretKey:this.#t,publicKey:this.#e}}getPublicKey(){return this.#e}async sign(t){let r=Je.sign(t,this.#t.slice(0,32));return Object.defineProperty(r,"__signature__",{enumerable:!1,value:void 0}),r}static verify(t,r,n){let[o,i,s]=[t,r,n].map(a=>(typeof a=="string"&&(a=Ee(a)),Ht(a)));return Je.verify(o,i,s)}};var sl=class e extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,e.prototype)}};function dp(e){if(typeof global<"u"&&global.crypto&&global.crypto.subtle)return global.crypto.subtle;if(e)return e;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new sl("Global crypto was not available and none was provided. Please inlcude a SubtleCrypto implementation. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto")}var xt=class e extends zt{static async generate(t){let{extractable:r=!1,keyUsages:n=["sign","verify"],subtleCrypto:o}=t??{},i=dp(o),s=await i.generateKey({name:"ECDSA",namedCurve:"P-256"},r,n),a=Ht(await i.exportKey("spki",s.publicKey));return Object.assign(a,{__derEncodedPublicKey__:void 0}),new this(s,a,i)}static async fromKeyPair(t,r){let n=dp(r),o=Ht(await n.exportKey("spki",t.publicKey));return Object.assign(o,{__derEncodedPublicKey__:void 0}),new e(t,o,n)}constructor(t,r,n){super(),this._keyPair=t,this._derKey=r,this._subtleCrypto=n}getKeyPair(){return this._keyPair}getPublicKey(){let t=this._derKey,r=Object.create(this._keyPair.publicKey);return r.toDer=function(){return t},r}async sign(t){let r={name:"ECDSA",hash:{name:"SHA-256"}},n=Ht(await this._subtleCrypto.sign(r,this._keyPair.privateKey,t));return Object.assign(n,{__signature__:void 0}),n}};var ra=class{#e;get rawKey(){return this.#e.rawKey}get derKey(){return this.#e.derKey}toDer(){return this.#e.toDer()}getPublicKey(){return this.#e}getPrincipal(){if(!this.#e.rawKey)throw new Error("Cannot get principal from a public key without a raw key.");return q.fromUint8Array(new Uint8Array(this.#e.rawKey))}transformRequest(){return Promise.reject("Not implemented. You are attempting to use a partial identity to sign calls, but this identity only has access to the public key.To sign calls, use a DelegationIdentity instead.")}constructor(t){this.#e=t}};function na(e){return e instanceof Uint8Array?j(e):j(new Uint8Array(e))}function al(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return Ee(e)}var un=class{constructor(t,r,n){this.pubkey=t,this.expiration=r,this.targets=n}toCborValue(){return{pubkey:this.pubkey,expiration:this.expiration,...this.targets&&{targets:this.targets}}}toJSON(){return{expiration:this.expiration.toString(16),pubkey:na(this.pubkey),...this.targets&&{targets:this.targets.map(t=>t.toHex())}}}};async function Oy(e,t,r,n){let o=new un(t.toDer(),BigInt(+r)*BigInt(1e6),n),i=new Uint8Array([...cc,...new Uint8Array(Rr({...o}))]),s=await e.sign(i);return{delegation:o,signature:s}}var Lt=class e{static async create(t,r,n=new Date(Date.now()+900*1e3),o={}){let i=await Oy(t,r,n,o.targets);return new e([...o.previous?.delegations||[],i],o.previous?.publicKey||t.getPublicKey().toDer())}static fromJSON(t){let{publicKey:r,delegations:n}=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(n))throw new Error("Invalid delegations.");let o=n.map(i=>{let{delegation:s,signature:a}=i,{pubkey:c,expiration:l,targets:d}=s;if(d!==void 0&&!Array.isArray(d))throw new Error("Invalid targets.");return{delegation:new un(al(c),BigInt(`0x${l}`),d&&d.map(p=>{if(typeof p!="string")throw new Error("Invalid target.");return q.fromHex(p)})),signature:al(a)}});return new this(o,al(r))}static fromDelegations(t,r){return new this(t,r)}constructor(t,r){this.delegations=t,this.publicKey=r}toJSON(){return{delegations:this.delegations.map(t=>{let{delegation:r,signature:n}=t,{targets:o}=r;return{delegation:{expiration:r.expiration.toString(16),pubkey:na(r.pubkey),...o&&{targets:o.map(i=>i.toHex())}},signature:na(n)}}),publicKey:na(this.publicKey)}}},qt=class extends zt{static fromDelegation(t,r){return new this(t,r)}constructor(t,r){super(),this._inner=t,this._delegation=r}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(t){return this._inner.sign(t)}async transformRequest(t){let{body:r,...n}=t,o=await Rr(r);return{...n,body:{content:r,sender_sig:await this.sign(new Uint8Array([...si,...new Uint8Array(o)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}}}},Ci=class e extends ra{#e;get delegation(){return this.#e}constructor(t,r){super(t),this.#e=r}static fromDelegation(t,r){return new e(t,r)}};function cl(e,t){for(let{delegation:o}of e.delegations)if(+new Date(Number(o.expiration/BigInt(1e6)))<=+Date.now())return!1;let r=[],n=t?.scope;n&&(Array.isArray(n)?r.push(...n.map(o=>typeof o=="string"?q.fromText(o):o)):r.push(typeof n=="string"?q.fromText(n):n));for(let o of r){let i=o.toText();for(let{delegation:s}of e.delegations){if(s.targets===void 0)continue;let a=!0;for(let c of s.targets)if(c.toText()===i){a=!1;break}if(a)return!1}}return!0}var pp=["mousedown","mousemove","keydown","touchstart","wheel"],Vi=class e{callbacks=[];idleTimeout=600*1e3;timeoutID=void 0;static create(t={}){return new e(t)}constructor(t={}){let{onIdle:r,idleTimeout:n=600*1e3}=t||{};this.callbacks=r?[r]:[],this.idleTimeout=n;let o=this._resetTimer.bind(this);window.addEventListener("load",o,!0),pp.forEach(s=>{document.addEventListener(s,o,!0)});let i=(s,a)=>{let c;return(...l)=>{let d=this,p=()=>{c=void 0,s.apply(d,l)};clearTimeout(c),c=window.setTimeout(p,a)}};if(t?.captureScroll){let s=i(o,t?.scrollDebounce??100);window.addEventListener("scroll",s,!0)}o()}registerCallback(t){this.callbacks.push(t)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let t=this._resetTimer.bind(this);pp.forEach(r=>{document.removeEventListener(r,t,!0)}),this.callbacks.forEach(r=>{r()})}_resetTimer(){let t=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(t,this.idleTimeout)}};var Ey=(e,t)=>t.some(r=>e instanceof r),fp,hp;function Ry(){return fp||(fp=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function vy(){return hp||(hp=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var mp=new WeakMap,ul=new WeakMap,_p=new WeakMap,ll=new WeakMap,pl=new WeakMap;function Iy(e){let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{r(Yt(e.result)),o()},s=()=>{n(e.error),o()};e.addEventListener("success",i),e.addEventListener("error",s)});return t.then(r=>{r instanceof IDBCursor&&mp.set(r,e)}).catch(()=>{}),pl.set(t,e),t}function Ay(e){if(ul.has(e))return;let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{r(),o()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),o()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)});ul.set(e,t)}var dl={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return ul.get(e);if(t==="objectStoreNames")return e.objectStoreNames||_p.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Yt(e[t])},set(e,t,r){return e[t]=r,!0},has(e,t){return e instanceof IDBTransaction&&(t==="done"||t==="store")?!0:t in e}};function yp(e){dl=e(dl)}function Sy(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(oa(this),t,...r);return _p.set(n,t.sort?t.sort():[t]),Yt(n)}:vy().includes(e)?function(...t){return e.apply(oa(this),t),Yt(mp.get(this))}:function(...t){return Yt(e.apply(oa(this),t))}}function Cy(e){return typeof e=="function"?Sy(e):(e instanceof IDBTransaction&&Ay(e),Ey(e,Ry())?new Proxy(e,dl):e)}function Yt(e){if(e instanceof IDBRequest)return Iy(e);if(ll.has(e))return ll.get(e);let t=Cy(e);return t!==e&&(ll.set(e,t),pl.set(t,e)),t}var oa=e=>pl.get(e);function xp(e,t,{blocked:r,upgrade:n,blocking:o,terminated:i}={}){let s=indexedDB.open(e,t),a=Yt(s);return n&&s.addEventListener("upgradeneeded",c=>{n(Yt(s.result),c.oldVersion,c.newVersion,Yt(s.transaction),c)}),r&&s.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{i&&c.addEventListener("close",()=>i()),o&&c.addEventListener("versionchange",l=>o(l.oldVersion,l.newVersion,l))}).catch(()=>{}),a}var Vy=["get","getKey","getAll","getAllKeys","count"],Py=["put","add","delete","clear"],fl=new Map;function gp(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(fl.get(t))return fl.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=Py.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||Vy.includes(r)))return;let i=async function(s,...a){let c=this.transaction(s,o?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[r](...a),o&&c.done]))[0]};return fl.set(t,i),i}yp(e=>({...e,get:(t,r,n)=>gp(t,r)||e.get(t,r,n),has:(t,r)=>!!gp(t,r)||e.has(t,r)}));var bp="auth-client-db",wp="ic-keyval",Fy=async(e=bp,t=wp,r)=>(globalThis.localStorage?.getItem(ke)&&(globalThis.localStorage.removeItem(ke),globalThis.localStorage.removeItem(We)),await xp(e,r,{upgrade:n=>{n.objectStoreNames.contains(t)&&n.clear(t),n.createObjectStore(t)}}));async function By(e,t,r){return await e.get(t,r)}async function Dy(e,t,r,n){return await e.put(t,n,r)}async function Uy(e,t,r){return await e.delete(t,r)}var ia=class e{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=bp,storeName:n=wp,version:o=Tp}=t??{},i=await Fy(r,n,o);return new e(i,n)}async set(t,r){return await Dy(this._db,this._storeName,t,r)}async get(t){return await By(this._db,this._storeName,t)??null}async remove(t){return await Uy(this._db,this._storeName,t)}};var We="identity",ke="delegation",Np="iv",Tp=1,Pi=class{constructor(t="ic-",r){this.prefix=t,this._localStorage=r}get(t){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+t))}set(t,r){return this._getLocalStorage().setItem(this.prefix+t,r),Promise.resolve()}remove(t){return this._getLocalStorage().removeItem(this.prefix+t),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let t=globalThis.localStorage;if(!t)throw new Error("Could not find local storage.");return t}},Zt=class{#e;constructor(t){this.#e=t??{}}initializedDb;get _db(){return new Promise((t,r)=>{if(this.initializedDb){t(this.initializedDb);return}ia.create(this.#e).then(n=>{this.initializedDb=n,t(n)}).catch(r)})}async get(t){return await(await this._db).get(t)}async set(t,r){await(await this._db).set(t,r)}async remove(t){await(await this._db).remove(t)}};var ky=BigInt(1e9),Ly=BigInt(3600),qy=ky*Ly,My="https://identity.internetcomputer.org",jy="#authorize",Ky=BigInt(8)*qy,hl="ECDSA",ml="Ed25519",$y=500,sa="UserInterrupt",Fi=class e{constructor(t,r,n,o,i,s,a,c){this._identity=t,this._key=r,this._chain=n,this._storage=o,this.idleManager=i,this._createOptions=s,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}static async create(t={}){let r=t.storage??new Zt,n=t.keyType??hl,o=null;if(t.identity)o=t.identity;else{let c=await r.get(We);if(!c)try{let l=new Pi,d=await l.get(ke),p=await l.get(We);d&&p&&n===hl&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await r.set(ke,d),await r.set(We,p),c=d,await l.remove(ke),await l.remove(We))}catch(l){console.error(`error while attempting to recover localstorage: ${l}`)}if(c)try{typeof c=="object"?n===ml&&typeof c=="string"?o=dt.fromJSON(c):o=await xt.fromKeyPair(c):typeof c=="string"&&(o=dt.fromJSON(c))}catch{}}let i=new at,s=null;if(o)try{let c=await r.get(ke);if(typeof c=="object"&&c!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");t.identity?i=t.identity:c&&(s=Lt.fromJSON(c),cl(s)?"toDer"in o?i=Ci.fromDelegation(o,s):i=qt.fromDelegation(o,s):(await _l(r),o=null))}catch(c){console.error(c),await _l(r),o=null}let a;return t.idleOptions?.disableIdle?a=void 0:(s||t.identity)&&(a=Vi.create(t.idleOptions)),o||(n===ml?o=dt.generate():(t.storage&&n===hl&&console.warn(`You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${ml}' as the key type, as it can serialize to a string`),o=await xt.generate()),await Op(r,o)),new e(i,o,s,r,a,t)}_registerDefaultIdleCallback(){let t=this._createOptions?.idleOptions;!t?.onIdle&&!t?.disableDefaultIdleCallback&&this.idleManager?.registerCallback(()=>{this.logout(),location.reload()})}async _handleSuccess(t,r){let n=t.delegations.map(a=>({delegation:new un(a.delegation.pubkey,a.delegation.expiration,a.delegation.targets),signature:a.signature})),o=Lt.fromDelegations(n,t.userPublicKey),i=this._key;if(!i)return;this._chain=o,"toDer"in i?this._identity=Ci.fromDelegation(i,this._chain):this._identity=qt.fromDelegation(i,this._chain),this._idpWindow?.close();let s=this._createOptions?.idleOptions;!this.idleManager&&!s?.disableIdle&&(this.idleManager=Vi.create(s),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(ke,JSON.stringify(this._chain.toJSON())),await Op(this._storage,this._key),r?.(t)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null&&cl(this._chain)}async login(t){let r=Hy(this._createOptions?.loginOptions,t),n=r?.maxTimeToLive??Ky,o=new URL(r?.identityProvider?.toString()||My);o.hash=jy,this._idpWindow?.close(),this._removeEventListener(),this._eventHandler=this._getEventHandler(o,{maxTimeToLive:n,...r}),window.addEventListener("message",this._eventHandler),this._idpWindow=window.open(o.toString(),"idpWindow",r?.windowOpenerFeatures)??void 0;let i=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(sa,r?.onError):setTimeout(i,$y))};i()}_getEventHandler(t,r){return async n=>{if(n.origin!==t.origin)return;let o=n.data;switch(o.kind){case"authorize-ready":{let i={kind:"authorize-client",sessionPublicKey:new Uint8Array(this._key?.getPublicKey().toDer()),maxTimeToLive:r?.maxTimeToLive,allowPinAuthentication:r?.allowPinAuthentication,derivationOrigin:r?.derivationOrigin?.toString(),...r?.customValues};this._idpWindow?.postMessage(i,t.origin);break}case"authorize-client-success":try{await this._handleSuccess(o,r?.onSuccess)}catch(i){this._handleFailure(i.message,r?.onError)}break;case"authorize-client-failure":this._handleFailure(o.text,r?.onError);break}}}_handleFailure(t,r){this._idpWindow?.close(),r?.(t),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(t={}){if(await _l(this._storage),this._identity=new at,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};async function _l(e){await e.remove(We),await e.remove(ke),await e.remove(Np)}function Hy(e,t){if(!e&&!t)return;let r=e?.customValues||t?.customValues?{...e?.customValues,...t?.customValues}:void 0;return{...e,...t,customValues:r}}function Gy(e){if(e instanceof xt)return e.getKeyPair();if(e instanceof dt)return JSON.stringify(e.toJSON());throw new Error("Unsupported key type")}async function Op(e,t){let r=Gy(t);await e.set(We,r)}var Ce=class e{static#e;#t;constructor(){}static getInstance(){return U(this.#e)&&(this.#e=new e),this.#e}createAuthClient=async()=>(this.#t=await Fi.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),this.#t);safeCreateAuthClient=async()=>{let t=new Zt;return await Promise.all([t.remove(We),t.remove(ke)]),await this.createAuthClient()};getAuthClient=()=>this.#t;logout=async()=>{await this.#t?.logout(),this.#t=null};setAuthClientStorage=async({delegationChain:t,sessionKey:r})=>{let n=new Zt;await Promise.all([n.set(We,r.getKeyPair()),n.set(ke,JSON.stringify(t.toJSON()))])}};var yl=async e=>{await Jy(),await Ce.getInstance().createAuthClient(),e?.windowReload!==!1&&window.location.reload()},Jy=async()=>{await Ce.getInstance().logout(),Ue.getInstance().reset(),Fo.getInstance().reset(),Po.getInstance().reset()};var Ep=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),n=async()=>{Ai({message:"junoSignOutAuthTimer"}),await yl()};return r.onmessage=async({data:o})=>{let{msg:i,data:s}=o;switch(i){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":Ai({message:"junoDelegationRemainingTime",detail:s?.authRemainingTime})}},Ue.getInstance().subscribe(o=>{if(U(o)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var Bo=class e{static#e;#t;#r;static CHANNEL_NAME="juno_core_auth_channel";static MESSAGE_LOGIN_SUCCESS="authClientLoginSuccess";constructor(){this.#t=new BroadcastChannel(e.CHANNEL_NAME),this.#r=window.crypto.randomUUID()}static getInstance(){return U(this.#e)&&(this.#e=new e),this.#e}onLoginSuccess=t=>{let{location:{origin:r}}=window;this.#t.onmessage=async({origin:n,data:o})=>{n===r&&J(o)&&o.msg==="authClientLoginSuccess"&&_r(o.emitterId)&&o.emitterId!==this.#r&&await t()}};destroy=()=>{this.#t.close(),e.#e=null};postLoginSuccess=()=>{let t={emitterId:this.#r,msg:e.MESSAGE_LOGIN_SUCCESS};this.#t.postMessage(t)};get __test__only__emitter_id__(){return this.#r}};var Ie=class e extends Co{static instance;env;constructor(){super()}static getInstance(){return e.instance||(e.instance=new e),e.instance}set(t){this.env=t,this.populate(t)}get(){return this.env}reset(){this.env=null}subscribe(t){let r=super.subscribe(t);return t(this.env),r}};var Bi=async({fn:e,syncTabsOnSuccess:t})=>{let{authenticated:r}=await Wy({fn:e});!r||!t||Ie.getInstance().get()?.syncTabs===!1||zy()},Rp=async({fn:e})=>{let{createAuthClient:t}=Ce.getInstance(),n=await(await t()).isAuthenticated();await e({authenticated:n})},Wy=async({fn:e})=>{let{createAuthClient:t,safeCreateAuthClient:r}=Ce.getInstance();return await(await t()).isAuthenticated()?(await e(),{authenticated:!0}):(await r(),{authenticated:!1})},zy=()=>{try{Bo.getInstance().postLoginSuccess()}catch(e){console.warn("Auth BroadcastChannel posting failed",e)}};var gl=({error:e,type:t})=>typeof e=="string"?e.includes(t):e instanceof Error?e.message.includes(t):!1;var vp="juno.datastore.error.user.cannot_update";var Xt={certified:!1};var aa=()=>Ce.getInstance().getAuthClient()?.getIdentity(),Yy=async()=>{let{getAuthClient:e,createAuthClient:t}=Ce.getInstance();return(e()??await t()).getIdentity()},Zy=async()=>{let e=Ue.getInstance().get();if(U(e))return null;let t=Ce.getInstance().getAuthClient();return await t?.isAuthenticated()??!1?t?.getIdentity()??null:null};var ue=e=>J(e)?e:aa()??new at;var xl=({IDL:e})=>{let t=e.Variant({Heap:e.Null,Stable:e.Null}),r=e.Record({system_memory:e.Opt(t)}),n=e.Record({controllers:e.Vec(e.Principal),storage:e.Opt(r)}),o=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),i=e.Variant({OpenId:o}),s=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),a=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),c=e.Record({doc:s,delegation:a}),l=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),d=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),p=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),u=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:d,GetOrFetchJwks:p,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),f=e.Variant({PrepareDelegation:u,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),_=e.Record({jwt:e.Text,salt:e.Vec(e.Nat8)}),y=e.Variant({OpenId:_}),m=e.Variant({Write:e.Null,Submit:e.Null}),b=e.Record({scope:m,expires_at:e.Nat64}),g=e.Variant({JwtFindProvider:l,InvalidController:e.Text,GetCachedJwks:e.Null,JwtVerify:d,GetOrFetchJwks:p,ControllerAlreadyExists:e.Null,InvalidObservatoryId:e.Text,TooManyControllers:e.Text}),T=e.Variant({PrepareAutomation:g,RegisterController:e.Text,SaveWorkflowMetadata:e.Text,SaveUniqueJtiToken:e.Text}),O=e.Variant({Ok:e.Tuple(e.Principal,b),Err:T}),v=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),E=e.Variant({Heap:e.Record({offset:e.Nat64}),Stable:e.Record({key:e.Opt(v)})}),C=e.Variant({Append:e.Null,Clear:e.Null,AppendWithRouting:e.Null}),w=e.Record({cursor:E,strategy:C,chunk_size:e.Opt(e.Nat32)}),I=e.Record({next_cursor:e.Opt(E)}),P=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),A=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),x=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),N=e.Record({field:x,desc:e.Bool}),S=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),B=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(S),description:e.Opt(e.Text),created_at:e.Opt(S)}),M=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),R=e.Record({order:e.Opt(N),owner:e.Opt(e.Principal),matcher:e.Opt(B),paginate:e.Opt(M)}),V=e.Record({controllers:e.Vec(e.Principal)}),F=e.Variant({Emulator:e.Null,Automation:e.Null}),D=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),k=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(F),created_at:e.Nat64,scope:D,expires_at:e.Opt(e.Nat64)}),te=e.Record({version:e.Opt(e.Nat64)}),Z=e.Variant({Db:e.Null,Storage:e.Null}),Y=e.Record({version:e.Opt(e.Nat64)}),xe=e.Record({proposal_ids:e.Vec(e.Nat)}),be=e.Record({cycles:e.Nat,destination_id:e.Principal}),ze=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),ne=e.Record({key:v,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,ze)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),ie=e.Variant({GitHub:e.Null,Google:e.Null}),er=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),pn=e.Record({delegation:e.Opt(er),client_id:e.Text}),tr=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(ie,pn))}),rr=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),nr=e.Record({allowed_callers:e.Vec(e.Principal)}),et=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(tr),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(rr),rules:e.Opt(nr)}),tt=e.Variant({GitHub:e.Null}),or=e.Record({scope:e.Opt(m),max_time_to_live:e.Opt(e.Nat64)}),fn=e.Record({owner:e.Text,name:e.Text}),hn=e.Record({refs:e.Opt(e.Vec(e.Text))}),bt=e.Record({controller:e.Opt(or),repositories:e.Vec(e.Tuple(fn,hn))}),ir=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(tt,bt))}),wt=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(ir),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64)}),rt=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),nt=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(rt)}),Tt=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),sr=e.Variant({Deny:e.Null,Allow:e.Null}),ar=e.Record({status_code:e.Nat16,location:e.Text}),Le=e.Record({iframe:e.Opt(Tt),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(rt),raw_access:e.Opt(sr),redirects:e.Opt(e.Vec(e.Tuple(e.Text,ar)))}),mn=e.Record({db:e.Opt(nt),authentication:e.Opt(et),storage:Le,automation:e.Opt(wt)}),_n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),yn=e.Variant({OpenId:_n}),gn=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),xn=e.Record({signature:e.Vec(e.Nat8),delegation:gn}),bn=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:d,GetOrFetchJwks:p,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),wn=e.Variant({Ok:xn,Err:bn}),cr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),lr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Tn=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),ur=e.Variant({AssetsUpgrade:lr,SegmentsDeployment:Tn}),qe=e.Record({status:cr,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:ur}),ot=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),dr=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),Nt=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:ot,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(dr),write:ot,max_changes_per_user:e.Opt(e.Nat32)}),Nn=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),Ot=e.Record({memory:t,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),On=e.Variant({Callback:e.Record({token:Ot,callback:e.Func([],[],["query"])})}),En=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(On),status_code:e.Nat16}),Rn=e.Record({token:e.Opt(Ot),body:e.Vec(e.Nat8)}),Et=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),we=e.Record({batch_id:e.Nat}),vn=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,ne)),items_length:e.Nat64}),In=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),it=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,s)),items_length:e.Nat64}),An=e.Record({desc:e.Bool}),Sn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Cn=e.Record({order:e.Opt(An),paginate:e.Opt(Sn)}),Vn=e.Record({proposal_id:e.Nat}),pr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Vn,qe)),items_length:e.Nat64}),Pn=e.Record({include_system:e.Bool}),Fn=e.Record({matcher:e.Opt(Pn)}),fr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,Nt)),items_length:e.Nat64}),Bn=e.Record({stable:e.Nat64,heap:e.Nat64}),Dn=e.Record({openid:e.Opt(tr),version:e.Opt(e.Nat64),internet_identity:e.Opt(rr),rules:e.Opt(nr)}),Aa=e.Record({openid:e.Opt(ir),version:e.Opt(e.Nat64)}),Sa=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(F),scope:D,expires_at:e.Opt(e.Nat64)}),Ca=e.Record({controller:Sa,controllers:e.Vec(e.Principal)}),Va=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(rt)}),ko=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Pa=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:ot,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(dr),write:ot,max_changes_per_user:e.Opt(e.Nat32)}),Lo=e.Record({iframe:e.Opt(Tt),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(rt),raw_access:e.Opt(sr),redirects:e.Opt(e.Vec(e.Tuple(e.Text,ar)))}),Fa=e.Record({skip_certification:e.Opt(e.Bool)}),Ba=e.Record({config:Lo,options:Fa}),qo=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Mo=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),authenticate_automation:e.Func([y],[O],[]),certify_assets_chunk:e.Func([w],[I],[]),commit_asset_upload:e.Func([P],[],[]),commit_proposal:e.Func([A],[e.Null],[]),commit_proposal_asset_upload:e.Func([P],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(P)],[],[]),count_assets:e.Func([e.Text,R],[e.Nat64],["query"]),count_collection_assets:e.Func([e.Text],[e.Nat64],["query"]),count_collection_docs:e.Func([e.Text],[e.Nat64],["query"]),count_docs:e.Func([e.Text,R],[e.Nat64],["query"]),count_proposals:e.Func([],[e.Nat64],["query"]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controller_self:e.Func([],[],[]),del_controllers:e.Func([V],[e.Vec(e.Tuple(e.Principal,k))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,te],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,R],[],[]),del_filtered_docs:e.Func([e.Text,R],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,te))],[],[]),del_rule:e.Func([Z,e.Text,Y],[],[]),delete_proposal_assets:e.Func([xe],[],[]),deposit_cycles:e.Func([be],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(ne)],["query"]),get_auth_config:e.Func([],[e.Opt(et)],["query"]),get_automation_config:e.Func([],[e.Opt(wt)],["query"]),get_config:e.Func([],[mn],[]),get_db_config:e.Func([],[e.Opt(nt)],["query"]),get_delegation:e.Func([yn],[wn],["query"]),get_doc:e.Func([e.Text,e.Text],[e.Opt(s)],["query"]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(ne)))],["query"]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(s)))],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(qe)],["query"]),get_rule:e.Func([Z,e.Text],[e.Opt(Nt)],["query"]),get_storage_config:e.Func([],[Le],["query"]),http_request:e.Func([Nn],[En],["query"]),http_request_streaming_callback:e.Func([Ot],[Rn],["query"]),init_asset_upload:e.Func([Et],[we],[]),init_proposal:e.Func([ur],[e.Nat,qe],[]),init_proposal_asset_upload:e.Func([Et,e.Nat],[we],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Et),e.Nat],[e.Vec(e.Tuple(e.Text,we))],[]),list_assets:e.Func([e.Text,R],[vn],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,k))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,In))],["query"]),list_docs:e.Func([e.Text,R],[it],["query"]),list_proposals:e.Func([Cn],[pr],["query"]),list_rules:e.Func([Z,Fn],[fr],["query"]),memory_size:e.Func([],[Bn],["query"]),reject_proposal:e.Func([A],[e.Null],[]),set_asset_token:e.Func([e.Text,e.Text,e.Opt(e.Text)],[],[]),set_auth_config:e.Func([Dn],[et],[]),set_automation_config:e.Func([Aa],[wt],[]),set_controllers:e.Func([Ca],[e.Vec(e.Tuple(e.Principal,k))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([Va],[nt],[]),set_doc:e.Func([e.Text,e.Text,ko],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,ko))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([Z,e.Text,Pa],[Nt],[]),set_storage_config:e.Func([Lo],[Le],[]),set_storage_config_with_options:e.Func([Ba],[Le],[]),submit_proposal:e.Func([e.Nat],[e.Nat,qe],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([qo],[Mo],[]),upload_proposal_asset_chunk:e.Func([qo],[Mo],[])})},bl=({IDL:e})=>{let t=e.Variant({Heap:e.Null,Stable:e.Null}),r=e.Record({system_memory:e.Opt(t)}),n=e.Record({controllers:e.Vec(e.Principal),storage:e.Opt(r)}),o=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),i=e.Variant({OpenId:o}),s=e.Record({updated_at:e.Nat64,owner:e.Principal,data:e.Vec(e.Nat8),description:e.Opt(e.Text),created_at:e.Nat64,version:e.Opt(e.Nat64)}),a=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),c=e.Record({doc:s,delegation:a}),l=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),d=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),p=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),u=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:d,GetOrFetchJwks:p,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),f=e.Variant({PrepareDelegation:u,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),_=e.Record({jwt:e.Text,salt:e.Vec(e.Nat8)}),y=e.Variant({OpenId:_}),m=e.Variant({Write:e.Null,Submit:e.Null}),b=e.Record({scope:m,expires_at:e.Nat64}),g=e.Variant({JwtFindProvider:l,InvalidController:e.Text,GetCachedJwks:e.Null,JwtVerify:d,GetOrFetchJwks:p,ControllerAlreadyExists:e.Null,InvalidObservatoryId:e.Text,TooManyControllers:e.Text}),T=e.Variant({PrepareAutomation:g,RegisterController:e.Text,SaveWorkflowMetadata:e.Text,SaveUniqueJtiToken:e.Text}),O=e.Variant({Ok:e.Tuple(e.Principal,b),Err:T}),v=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),E=e.Variant({Heap:e.Record({offset:e.Nat64}),Stable:e.Record({key:e.Opt(v)})}),C=e.Variant({Append:e.Null,Clear:e.Null,AppendWithRouting:e.Null}),w=e.Record({cursor:E,strategy:C,chunk_size:e.Opt(e.Nat32)}),I=e.Record({next_cursor:e.Opt(E)}),P=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),A=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),x=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),N=e.Record({field:x,desc:e.Bool}),S=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),B=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(S),description:e.Opt(e.Text),created_at:e.Opt(S)}),M=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),R=e.Record({order:e.Opt(N),owner:e.Opt(e.Principal),matcher:e.Opt(B),paginate:e.Opt(M)}),V=e.Record({controllers:e.Vec(e.Principal)}),F=e.Variant({Emulator:e.Null,Automation:e.Null}),D=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),k=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(F),created_at:e.Nat64,scope:D,expires_at:e.Opt(e.Nat64)}),te=e.Record({version:e.Opt(e.Nat64)}),Z=e.Variant({Db:e.Null,Storage:e.Null}),Y=e.Record({version:e.Opt(e.Nat64)}),xe=e.Record({proposal_ids:e.Vec(e.Nat)}),be=e.Record({cycles:e.Nat,destination_id:e.Principal}),ze=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),ne=e.Record({key:v,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,ze)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),ie=e.Variant({GitHub:e.Null,Google:e.Null}),er=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),pn=e.Record({delegation:e.Opt(er),client_id:e.Text}),tr=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(ie,pn))}),rr=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),nr=e.Record({allowed_callers:e.Vec(e.Principal)}),et=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(tr),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(rr),rules:e.Opt(nr)}),tt=e.Variant({GitHub:e.Null}),or=e.Record({scope:e.Opt(m),max_time_to_live:e.Opt(e.Nat64)}),fn=e.Record({owner:e.Text,name:e.Text}),hn=e.Record({refs:e.Opt(e.Vec(e.Text))}),bt=e.Record({controller:e.Opt(or),repositories:e.Vec(e.Tuple(fn,hn))}),ir=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(tt,bt))}),wt=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(ir),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64)}),rt=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),nt=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(rt)}),Tt=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),sr=e.Variant({Deny:e.Null,Allow:e.Null}),ar=e.Record({status_code:e.Nat16,location:e.Text}),Le=e.Record({iframe:e.Opt(Tt),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(rt),raw_access:e.Opt(sr),redirects:e.Opt(e.Vec(e.Tuple(e.Text,ar)))}),mn=e.Record({db:e.Opt(nt),authentication:e.Opt(et),storage:Le,automation:e.Opt(wt)}),_n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),yn=e.Variant({OpenId:_n}),gn=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),xn=e.Record({signature:e.Vec(e.Nat8),delegation:gn}),bn=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:d,GetOrFetchJwks:p,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),wn=e.Variant({Ok:xn,Err:bn}),cr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),lr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Tn=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),ur=e.Variant({AssetsUpgrade:lr,SegmentsDeployment:Tn}),qe=e.Record({status:cr,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:ur}),ot=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),dr=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),Nt=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:ot,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(dr),write:ot,max_changes_per_user:e.Opt(e.Nat32)}),Nn=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),Ot=e.Record({memory:t,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),On=e.Variant({Callback:e.Record({token:Ot,callback:e.Func([],[],[])})}),En=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(On),status_code:e.Nat16}),Rn=e.Record({token:e.Opt(Ot),body:e.Vec(e.Nat8)}),Et=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),we=e.Record({batch_id:e.Nat}),vn=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,ne)),items_length:e.Nat64}),In=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),it=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,s)),items_length:e.Nat64}),An=e.Record({desc:e.Bool}),Sn=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Cn=e.Record({order:e.Opt(An),paginate:e.Opt(Sn)}),Vn=e.Record({proposal_id:e.Nat}),pr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Vn,qe)),items_length:e.Nat64}),Pn=e.Record({include_system:e.Bool}),Fn=e.Record({matcher:e.Opt(Pn)}),fr=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,Nt)),items_length:e.Nat64}),Bn=e.Record({stable:e.Nat64,heap:e.Nat64}),Dn=e.Record({openid:e.Opt(tr),version:e.Opt(e.Nat64),internet_identity:e.Opt(rr),rules:e.Opt(nr)}),Aa=e.Record({openid:e.Opt(ir),version:e.Opt(e.Nat64)}),Sa=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(F),scope:D,expires_at:e.Opt(e.Nat64)}),Ca=e.Record({controller:Sa,controllers:e.Vec(e.Principal)}),Va=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt(rt)}),ko=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Pa=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:ot,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(dr),write:ot,max_changes_per_user:e.Opt(e.Nat32)}),Lo=e.Record({iframe:e.Opt(Tt),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(rt),raw_access:e.Opt(sr),redirects:e.Opt(e.Vec(e.Tuple(e.Text,ar)))}),Fa=e.Record({skip_certification:e.Opt(e.Bool)}),Ba=e.Record({config:Lo,options:Fa}),qo=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Mo=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),authenticate_automation:e.Func([y],[O],[]),certify_assets_chunk:e.Func([w],[I],[]),commit_asset_upload:e.Func([P],[],[]),commit_proposal:e.Func([A],[e.Null],[]),commit_proposal_asset_upload:e.Func([P],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(P)],[],[]),count_assets:e.Func([e.Text,R],[e.Nat64],[]),count_collection_assets:e.Func([e.Text],[e.Nat64],[]),count_collection_docs:e.Func([e.Text],[e.Nat64],[]),count_docs:e.Func([e.Text,R],[e.Nat64],[]),count_proposals:e.Func([],[e.Nat64],[]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controller_self:e.Func([],[],[]),del_controllers:e.Func([V],[e.Vec(e.Tuple(e.Principal,k))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,te],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,R],[],[]),del_filtered_docs:e.Func([e.Text,R],[],[]),del_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[],[]),del_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,te))],[],[]),del_rule:e.Func([Z,e.Text,Y],[],[]),delete_proposal_assets:e.Func([xe],[],[]),deposit_cycles:e.Func([be],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(ne)],[]),get_auth_config:e.Func([],[e.Opt(et)],[]),get_automation_config:e.Func([],[e.Opt(wt)],[]),get_config:e.Func([],[mn],[]),get_db_config:e.Func([],[e.Opt(nt)],[]),get_delegation:e.Func([yn],[wn],[]),get_doc:e.Func([e.Text,e.Text],[e.Opt(s)],[]),get_many_assets:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(ne)))],[]),get_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text))],[e.Vec(e.Tuple(e.Text,e.Opt(s)))],[]),get_proposal:e.Func([e.Nat],[e.Opt(qe)],[]),get_rule:e.Func([Z,e.Text],[e.Opt(Nt)],[]),get_storage_config:e.Func([],[Le],[]),http_request:e.Func([Nn],[En],[]),http_request_streaming_callback:e.Func([Ot],[Rn],[]),init_asset_upload:e.Func([Et],[we],[]),init_proposal:e.Func([ur],[e.Nat,qe],[]),init_proposal_asset_upload:e.Func([Et,e.Nat],[we],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Et),e.Nat],[e.Vec(e.Tuple(e.Text,we))],[]),list_assets:e.Func([e.Text,R],[vn],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,k))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,In))],[]),list_docs:e.Func([e.Text,R],[it],[]),list_proposals:e.Func([Cn],[pr],[]),list_rules:e.Func([Z,Fn],[fr],[]),memory_size:e.Func([],[Bn],[]),reject_proposal:e.Func([A],[e.Null],[]),set_asset_token:e.Func([e.Text,e.Text,e.Opt(e.Text)],[],[]),set_auth_config:e.Func([Dn],[et],[]),set_automation_config:e.Func([Aa],[wt],[]),set_controllers:e.Func([Ca],[e.Vec(e.Tuple(e.Principal,k))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([Va],[nt],[]),set_doc:e.Func([e.Text,e.Text,ko],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,ko))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([Z,e.Text,Pa],[Nt],[]),set_storage_config:e.Func([Lo],[Le],[]),set_storage_config_with_options:e.Func([Ba],[Le],[]),submit_proposal:e.Func([e.Nat],[e.Nat,qe],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([qo],[Mo],[]),upload_proposal_asset_chunk:e.Func([qo],[Mo],[])})},Xy=({IDL:e})=>{let t=e.Record({e8s:e.Nat64}),r=e.Record({mission_control_id:e.Principal,user:e.Principal}),n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),o=e.Variant({OpenId:n}),i=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),s=e.Variant({GitHub:e.Null,Google:e.Null}),a=e.Record({name:e.Opt(e.Text),locale:e.Opt(e.Text),family_name:e.Opt(e.Text),email:e.Opt(e.Text),picture:e.Opt(e.Text),given_name:e.Opt(e.Text),preferred_username:e.Opt(e.Text)}),c=e.Record({provider:s,data:a}),l=e.Variant({InternetIdentity:e.Null,OpenId:c}),d=e.Record({updated_at:e.Nat64,credits:t,mission_control_id:e.Opt(e.Principal),provider:e.Opt(l),owner:e.Principal,created_at:e.Nat64}),p=e.Record({delegation:i,account:d}),u=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),f=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),h=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),_=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),y=e.Variant({PrepareDelegation:_,RegisterUser:e.Text}),m=e.Variant({Ok:p,Err:y}),b=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),g=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),T=e.Record({subnet_id:e.Opt(e.Principal)}),O=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),name:e.Opt(e.Text),user:e.Principal}),v=e.Variant({Heap:e.Null,Stable:e.Null}),E=e.Record({system_memory:e.Opt(v)}),C=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(E),name:e.Opt(e.Text),user:e.Principal}),w=e.Record({controllers:e.Vec(e.Principal)}),I=e.Record({proposal_ids:e.Vec(e.Nat)}),P=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),A=e.Record({delegation:e.Opt(P),client_id:e.Text}),x=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,A))}),N=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),S=e.Record({allowed_callers:e.Vec(e.Principal)}),B=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(x),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(S)}),M=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),R=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),V=e.Variant({Deny:e.Null,Allow:e.Null}),F=e.Record({status_code:e.Nat16,location:e.Text}),D=e.Record({iframe:e.Opt(M),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(R),raw_access:e.Opt(V),redirects:e.Opt(e.Vec(e.Tuple(e.Text,F)))}),k=e.Record({authentication:e.Opt(B),storage:D}),te=e.Record({user:e.Principal}),Z=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),Y=e.Variant({OpenId:Z}),xe=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),be=e.Record({signature:e.Vec(e.Nat8),delegation:xe}),ze=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),ne=e.Variant({Ok:be,Err:ze}),ie=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),er=e.Record({e12s:e.Nat64}),pn=e.Record({updated_at:e.Nat64,fee_cycles:er,fee_icp:e.Opt(t)}),tr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),rr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),nr=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),et=e.Variant({AssetsUpgrade:rr,SegmentsDeployment:nr}),tt=e.Record({status:tr,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:et}),or=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),fn=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),hn=e.Variant({Heap:e.Null,Stable:e.Null}),bt=e.Record({memory:hn,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),ir=e.Variant({Callback:e.Record({token:bt,callback:e.Func([],[],["query"])})}),wt=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(ir),status_code:e.Nat16}),rt=e.Record({token:e.Opt(bt),body:e.Vec(e.Nat8)}),nt=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),Tt=e.Record({batch_id:e.Nat}),sr=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),ar=e.Record({field:sr,desc:e.Bool}),Le=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),mn=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(Le),description:e.Opt(e.Text),created_at:e.Opt(Le)}),_n=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),yn=e.Record({order:e.Opt(ar),owner:e.Opt(e.Principal),matcher:e.Opt(mn),paginate:e.Opt(_n)}),gn=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),xn=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),bn=e.Record({key:gn,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,xn)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),wn=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,bn)),items_length:e.Nat64}),cr=e.Variant({Emulator:e.Null,Automation:e.Null}),lr=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),Tn=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(cr),created_at:e.Nat64,scope:lr,expires_at:e.Opt(e.Nat64)}),ur=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),qe=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),ot=e.Record({status:qe,updated_at:e.Nat64,block_index_payment:e.Nat64,mission_control_id:e.Opt(e.Principal),created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64)}),dr=e.Record({block_index:e.Nat64,ledger_id:e.Principal}),Nt=e.Record({owner:e.Principal,subaccount:e.Opt(e.Vec(e.Nat8))}),Nn=e.Record({status:qe,updated_at:e.Nat64,created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64),purchaser:Nt}),Ot=e.Record({desc:e.Bool}),On=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),En=e.Record({order:e.Opt(Ot),paginate:e.Opt(On)}),Rn=e.Record({proposal_id:e.Nat}),Et=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Rn,tt)),items_length:e.Nat64}),we=e.Variant({Orbiter:e.Null,Satellite:e.Null}),vn=e.Record({segment_id:e.Opt(e.Principal),segment_kind:e.Opt(we)}),In=e.Record({user:e.Principal,segment_id:e.Principal,segment_kind:we}),it=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,created_at:e.Nat64}),An=e.Record({openid:e.Opt(x),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(S)}),Sn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(cr),scope:lr,expires_at:e.Opt(e.Nat64)}),Cn=e.Record({controller:Sn,controllers:e.Vec(e.Principal)}),Vn=e.Record({fee_cycles:er,fee_icp:e.Opt(t)}),pr=e.Record({metadata:e.Opt(e.Vec(e.Tuple(e.Text,e.Text))),segment_id:e.Principal,segment_kind:we}),Pn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,segment_kind:we}),Fn=e.Record({iframe:e.Opt(M),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(R),raw_access:e.Opt(V),redirects:e.Opt(e.Vec(e.Tuple(e.Text,F)))}),fr=e.Record({segment_id:e.Principal,segment_kind:we}),Bn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Dn=e.Record({chunk_id:e.Nat});return e.Service({add_credits:e.Func([e.Principal,t],[],[]),add_invitation_code:e.Func([e.Text],[],[]),assert_mission_control_center:e.Func([r],[],["query"]),authenticate:e.Func([o],[m],[]),commit_proposal:e.Func([b],[e.Null],[]),commit_proposal_asset_upload:e.Func([g],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(g)],[],[]),count_proposals:e.Func([],[e.Nat64],["query"]),create_mission_control:e.Func([T],[e.Principal],[]),create_orbiter:e.Func([O],[e.Principal],[]),create_satellite:e.Func([C],[e.Principal],[]),del_controllers:e.Func([w],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([I],[],[]),get_account:e.Func([],[e.Opt(d)],["query"]),get_auth_config:e.Func([],[e.Opt(B)],["query"]),get_config:e.Func([],[k],["query"]),get_create_orbiter_fee:e.Func([te],[e.Opt(t)],["query"]),get_create_satellite_fee:e.Func([te],[e.Opt(t)],["query"]),get_credits:e.Func([],[t],["query"]),get_delegation:e.Func([Y],[ne],["query"]),get_fee:e.Func([ie],[pn],["query"]),get_or_init_account:e.Func([],[d],[]),get_proposal:e.Func([e.Nat],[e.Opt(tt)],["query"]),get_rate_config:e.Func([ie],[or],["query"]),get_storage_config:e.Func([],[D],["query"]),http_request:e.Func([fn],[wt],["query"]),http_request_streaming_callback:e.Func([bt],[rt],["query"]),init_proposal:e.Func([et],[e.Nat,tt],[]),init_proposal_asset_upload:e.Func([nt,e.Nat],[Tt],[]),init_proposal_many_assets_upload:e.Func([e.Vec(nt),e.Nat],[e.Vec(e.Tuple(e.Text,Tt))],[]),list_accounts:e.Func([],[e.Vec(e.Tuple(e.Principal,d))],["query"]),list_assets:e.Func([e.Text,yn],[wn],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,Tn))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,ur))],["query"]),list_icp_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,ot))],["query"]),list_icrc_payments:e.Func([],[e.Vec(e.Tuple(dr,Nn))],["query"]),list_proposals:e.Func([En],[Et],["query"]),list_segments:e.Func([vn],[e.Vec(e.Tuple(In,it))],["query"]),reject_proposal:e.Func([b],[e.Null],[]),set_auth_config:e.Func([An],[B],[]),set_controllers:e.Func([Cn],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([ie,Vn],[],[]),set_many_segments:e.Func([e.Vec(pr)],[e.Vec(it)],[]),set_rate_config:e.Func([ie,or],[],[]),set_segment:e.Func([pr],[it],[]),set_segment_metadata:e.Func([Pn],[it],[]),set_storage_config:e.Func([Fn],[D],[]),submit_proposal:e.Func([e.Nat],[e.Nat,tt],[]),unset_many_segments:e.Func([e.Vec(fr)],[],[]),unset_segment:e.Func([fr],[],[]),upload_proposal_asset_chunk:e.Func([Bn],[Dn],[])})},Qy=({IDL:e})=>{let t=e.Record({e8s:e.Nat64}),r=e.Record({mission_control_id:e.Principal,user:e.Principal}),n=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8)}),o=e.Variant({OpenId:n}),i=e.Record({user_key:e.Vec(e.Nat8),expiration:e.Nat64}),s=e.Variant({GitHub:e.Null,Google:e.Null}),a=e.Record({name:e.Opt(e.Text),locale:e.Opt(e.Text),family_name:e.Opt(e.Text),email:e.Opt(e.Text),picture:e.Opt(e.Text),given_name:e.Opt(e.Text),preferred_username:e.Opt(e.Text)}),c=e.Record({provider:s,data:a}),l=e.Variant({InternetIdentity:e.Null,OpenId:c}),d=e.Record({updated_at:e.Nat64,credits:t,mission_control_id:e.Opt(e.Principal),provider:e.Opt(l),owner:e.Principal,created_at:e.Nat64}),p=e.Record({delegation:i,account:d}),u=e.Variant({BadClaim:e.Text,BadSig:e.Text,NoMatchingProvider:e.Null}),f=e.Variant({WrongKeyType:e.Null,MissingKid:e.Null,BadClaim:e.Text,BadSig:e.Text,NoKeyForKid:e.Null}),h=e.Variant({InvalidConfig:e.Text,MissingKid:e.Null,BadClaim:e.Text,KeyNotFoundCooldown:e.Null,CertificateNotFound:e.Null,BadSig:e.Text,MissingLastAttempt:e.Text,KeyNotFound:e.Null,FetchFailed:e.Text}),_=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),y=e.Variant({PrepareDelegation:_,RegisterUser:e.Text}),m=e.Variant({Ok:p,Err:y}),b=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),g=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),T=e.Record({subnet_id:e.Opt(e.Principal)}),O=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),name:e.Opt(e.Text),user:e.Principal}),v=e.Variant({Heap:e.Null,Stable:e.Null}),E=e.Record({system_memory:e.Opt(v)}),C=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(E),name:e.Opt(e.Text),user:e.Principal}),w=e.Record({controllers:e.Vec(e.Principal)}),I=e.Record({proposal_ids:e.Vec(e.Nat)}),P=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),A=e.Record({delegation:e.Opt(P),client_id:e.Text}),x=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,A))}),N=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),S=e.Record({allowed_callers:e.Vec(e.Principal)}),B=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(x),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(S)}),M=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),R=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),V=e.Variant({Deny:e.Null,Allow:e.Null}),F=e.Record({status_code:e.Nat16,location:e.Text}),D=e.Record({iframe:e.Opt(M),updated_at:e.Opt(e.Nat64),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt(R),raw_access:e.Opt(V),redirects:e.Opt(e.Vec(e.Tuple(e.Text,F)))}),k=e.Record({authentication:e.Opt(B),storage:D}),te=e.Record({user:e.Principal}),Z=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),Y=e.Variant({OpenId:Z}),xe=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),be=e.Record({signature:e.Vec(e.Nat8),delegation:xe}),ze=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text,InvalidObservatoryId:e.Text}),ne=e.Variant({Ok:be,Err:ze}),ie=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),er=e.Record({e12s:e.Nat64}),pn=e.Record({updated_at:e.Nat64,fee_cycles:er,fee_icp:e.Opt(t)}),tr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),rr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),nr=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),et=e.Variant({AssetsUpgrade:rr,SegmentsDeployment:nr}),tt=e.Record({status:tr,updated_at:e.Nat64,sha256:e.Opt(e.Vec(e.Nat8)),executed_at:e.Opt(e.Nat64),owner:e.Principal,created_at:e.Nat64,version:e.Opt(e.Nat64),proposal_type:et}),or=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),fn=e.Record({url:e.Text,method:e.Text,body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),certificate_version:e.Opt(e.Nat16)}),hn=e.Variant({Heap:e.Null,Stable:e.Null}),bt=e.Record({memory:hn,token:e.Opt(e.Text),sha256:e.Opt(e.Vec(e.Nat8)),headers:e.Vec(e.Tuple(e.Text,e.Text)),index:e.Nat64,encoding_type:e.Text,full_path:e.Text}),ir=e.Variant({Callback:e.Record({token:bt,callback:e.Func([],[],[])})}),wt=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(ir),status_code:e.Nat16}),rt=e.Record({token:e.Opt(bt),body:e.Vec(e.Nat8)}),nt=e.Record({token:e.Opt(e.Text),collection:e.Text,name:e.Text,description:e.Opt(e.Text),encoding_type:e.Opt(e.Text),full_path:e.Text}),Tt=e.Record({batch_id:e.Nat}),sr=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),ar=e.Record({field:sr,desc:e.Bool}),Le=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),mn=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(Le),description:e.Opt(e.Text),created_at:e.Opt(Le)}),_n=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),yn=e.Record({order:e.Opt(ar),owner:e.Opt(e.Principal),matcher:e.Opt(mn),paginate:e.Opt(_n)}),gn=e.Record({token:e.Opt(e.Text),collection:e.Text,owner:e.Principal,name:e.Text,description:e.Opt(e.Text),full_path:e.Text}),xn=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),bn=e.Record({key:gn,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,xn)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),wn=e.Record({matches_pages:e.Opt(e.Nat64),matches_length:e.Nat64,items_page:e.Opt(e.Nat64),items:e.Vec(e.Tuple(e.Text,bn)),items_length:e.Nat64}),cr=e.Variant({Emulator:e.Null,Automation:e.Null}),lr=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),Tn=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(cr),created_at:e.Nat64,scope:lr,expires_at:e.Opt(e.Nat64)}),ur=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),qe=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),ot=e.Record({status:qe,updated_at:e.Nat64,block_index_payment:e.Nat64,mission_control_id:e.Opt(e.Principal),created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64)}),dr=e.Record({block_index:e.Nat64,ledger_id:e.Principal}),Nt=e.Record({owner:e.Principal,subaccount:e.Opt(e.Vec(e.Nat8))}),Nn=e.Record({status:qe,updated_at:e.Nat64,created_at:e.Nat64,block_index_refunded:e.Opt(e.Nat64),purchaser:Nt}),Ot=e.Record({desc:e.Bool}),On=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),En=e.Record({order:e.Opt(Ot),paginate:e.Opt(On)}),Rn=e.Record({proposal_id:e.Nat}),Et=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Rn,tt)),items_length:e.Nat64}),we=e.Variant({Orbiter:e.Null,Satellite:e.Null}),vn=e.Record({segment_id:e.Opt(e.Principal),segment_kind:e.Opt(we)}),In=e.Record({user:e.Principal,segment_id:e.Principal,segment_kind:we}),it=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,created_at:e.Nat64}),An=e.Record({openid:e.Opt(x),version:e.Opt(e.Nat64),internet_identity:e.Opt(N),rules:e.Opt(S)}),Sn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),kind:e.Opt(cr),scope:lr,expires_at:e.Opt(e.Nat64)}),Cn=e.Record({controller:Sn,controllers:e.Vec(e.Principal)}),Vn=e.Record({fee_cycles:er,fee_icp:e.Opt(t)}),pr=e.Record({metadata:e.Opt(e.Vec(e.Tuple(e.Text,e.Text))),segment_id:e.Principal,segment_kind:we}),Pn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),segment_id:e.Principal,segment_kind:we}),Fn=e.Record({iframe:e.Opt(M),rewrites:e.Vec(e.Tuple(e.Text,e.Text)),headers:e.Vec(e.Tuple(e.Text,e.Vec(e.Tuple(e.Text,e.Text)))),version:e.Opt(e.Nat64),max_memory_size:e.Opt(R),raw_access:e.Opt(V),redirects:e.Opt(e.Vec(e.Tuple(e.Text,F)))}),fr=e.Record({segment_id:e.Principal,segment_kind:we}),Bn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Dn=e.Record({chunk_id:e.Nat});return e.Service({add_credits:e.Func([e.Principal,t],[],[]),add_invitation_code:e.Func([e.Text],[],[]),assert_mission_control_center:e.Func([r],[],[]),authenticate:e.Func([o],[m],[]),commit_proposal:e.Func([b],[e.Null],[]),commit_proposal_asset_upload:e.Func([g],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(g)],[],[]),count_proposals:e.Func([],[e.Nat64],[]),create_mission_control:e.Func([T],[e.Principal],[]),create_orbiter:e.Func([O],[e.Principal],[]),create_satellite:e.Func([C],[e.Principal],[]),del_controllers:e.Func([w],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([I],[],[]),get_account:e.Func([],[e.Opt(d)],[]),get_auth_config:e.Func([],[e.Opt(B)],[]),get_config:e.Func([],[k],[]),get_create_orbiter_fee:e.Func([te],[e.Opt(t)],[]),get_create_satellite_fee:e.Func([te],[e.Opt(t)],[]),get_credits:e.Func([],[t],[]),get_delegation:e.Func([Y],[ne],[]),get_fee:e.Func([ie],[pn],[]),get_or_init_account:e.Func([],[d],[]),get_proposal:e.Func([e.Nat],[e.Opt(tt)],[]),get_rate_config:e.Func([ie],[or],[]),get_storage_config:e.Func([],[D],[]),http_request:e.Func([fn],[wt],[]),http_request_streaming_callback:e.Func([bt],[rt],[]),init_proposal:e.Func([et],[e.Nat,tt],[]),init_proposal_asset_upload:e.Func([nt,e.Nat],[Tt],[]),init_proposal_many_assets_upload:e.Func([e.Vec(nt),e.Nat],[e.Vec(e.Tuple(e.Text,Tt))],[]),list_accounts:e.Func([],[e.Vec(e.Tuple(e.Principal,d))],[]),list_assets:e.Func([e.Text,yn],[wn],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,Tn))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,ur))],[]),list_icp_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,ot))],[]),list_icrc_payments:e.Func([],[e.Vec(e.Tuple(dr,Nn))],[]),list_proposals:e.Func([En],[Et],[]),list_segments:e.Func([vn],[e.Vec(e.Tuple(In,it))],[]),reject_proposal:e.Func([b],[e.Null],[]),set_auth_config:e.Func([An],[B],[]),set_controllers:e.Func([Cn],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([ie,Vn],[],[]),set_many_segments:e.Func([e.Vec(pr)],[e.Vec(it)],[]),set_rate_config:e.Func([ie,or],[],[]),set_segment:e.Func([pr],[it],[]),set_segment_metadata:e.Func([Pn],[it],[]),set_storage_config:e.Func([Fn],[D],[]),submit_proposal:e.Func([e.Nat],[e.Nat,tt],[]),unset_many_segments:e.Func([e.Vec(fr)],[],[]),unset_segment:e.Func([fr],[],[]),upload_proposal_asset_chunk:e.Func([Bn],[Dn],[])})};var e0=async({identity:e,host:t,localActor:r})=>await kr.create({identity:e,host:t,retryTimes:10,shouldFetchRootKey:r}),t0=async({agent:e,...t})=>e??await r0(t),r0=async({identity:e,container:t})=>{let r=J(t)&&t!==!1;return await e0({identity:e,host:r?t===!0?"http://127.0.0.1:5987":t:"https://icp-api.io",localActor:r})};var Ip=({satelliteId:e,certified:t=!1,...r})=>Sp({canisterId:e,...r,idlFactory:t?bl:xl});var Ap=({consoleId:e,certified:t=!1,...r})=>Sp({canisterId:e,...r,idlFactory:t?Qy:Xy}),Sp=({canisterId:e,idlFactory:t,...r})=>{if(U(e))throw new Error("No canister ID provided.");return n0({canisterId:e,idlFactory:t,...r})},n0=async({canisterId:e,idlFactory:t,config:r,...n})=>{let o=await t0(n);return So.createActor(t,{agent:o,canisterId:e,...r??{}})};var Cp=({satelliteId:e,container:t})=>{let{satelliteId:r}=wl({satelliteId:e}),{container:n}=Tl({container:t});if(J(n)&&n!==!1){let{host:o,protocol:i}=new URL(n===!0?Vo:n);return`${i}//${r??"unknown"}.${o.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},wl=({satelliteId:e})=>J(e)?{satelliteId:e}:Ie.getInstance().get()??{satelliteId:void 0},Tl=({container:e})=>J(e)?{container:e}:Ie.getInstance().get()??{container:void 0};var ge=({satellite:e,options:{certified:t}})=>Pp({idlFactory:t?bl:xl,actorKey:`stock#${t?"update":"query"}`,...e}),Vp=({idlFactory:e,...t})=>Pp({idlFactory:e,actorKey:"extended#query",...t}),Pp=async({satelliteId:e,container:t,...r})=>{let{satelliteId:n}=wl({satelliteId:e});jo(n,"No satellite ID defined. Did you initialize Juno?");let{container:o}=Tl({container:t});return await Fo.getInstance().getActor({satelliteId:n,container:o,...r})};var ca=class extends Error{},Lr=class extends Error{},la=class extends Error{},ua=class extends Error{},Do=class extends Error{},da=class extends Error{},pa=class extends Error{},fa=class extends Error{},ha=class extends Error{};var Fp=e=>{if(U(e))return se();switch(e.matcher){case"equal":return se({Equal:e.timestamp});case"greaterThan":return se({GreaterThan:e.timestamp});case"lessThan":return se({LessThan:e.timestamp});case"between":return se({Between:[e.timestamps.start,e.timestamps.end]});default:throw new ha("Invalid list matcher for timestamp",e)}},dn=({matcher:e,paginate:t,order:r,owner:n})=>({matcher:U(e)?[]:[{key:se(e.key),description:se(e.description),created_at:Fp(e.createdAt),updated_at:Fp(e.updatedAt)}],paginate:se(U(t)?void 0:{start_after:se(t.startAfter),limit:se(U(t.limit)?void 0:BigInt(t.limit))}),order:se(U(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:se(U(n)?void 0:typeof n=="string"?q.fromText(n):n)});var Bp=async({data:e})=>{try{return await Mi(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var Nl=async e=>{let{data:t,version:r,description:n}=e;return{description:se(n),data:await kl(t),version:se(r)}},Ol=e=>{let{version:t}=e;return{version:se(t)}},io=async({doc:e,key:t})=>{let{owner:r,version:n,description:o,data:i,...s}=e;return{key:t,description:me(o),owner:r.toText(),data:await Mi(i),version:me(n),...s}};var Dp=async({collection:e,key:t,...r})=>{let{get_doc:n}=await ge(r),o=me(await n(e,t));if(!U(o))return io({doc:o,key:t})},Up=async({docs:e,...t})=>{let{get_many_docs:r}=await ge(t),n=e.map(({collection:s,key:a})=>[s,a]),o=await r(n),i=[];for(let[s,a]of o){let c=me(a);i.push(J(c)?await io({key:s,doc:c}):void 0)}return i},kp=async({collection:e,doc:t,...r})=>{let{set_doc:n}=await ge(r),{key:o}=t,i=await Nl(t),s=await n(e,o,i);return await io({key:o,doc:s})},Lp=async({docs:e,...t})=>{let{set_many_docs:r}=await ge(t),n=[];for(let{collection:s,doc:a}of e){let{key:c}=a;n.push([s,c,await Nl(a)])}let o=await r(n),i=[];for(let[s,a]of o)i.push(await io({key:s,doc:a}));return i},qp=async({collection:e,doc:t,...r})=>{let{del_doc:n}=await ge(r),{key:o}=t;return n(e,o,Ol(t))},Mp=async({docs:e,...t})=>{let{del_many_docs:r}=await ge(t),n=e.map(({collection:o,doc:i})=>[o,i.key,Ol(i)]);await r(n)},jp=async({collection:e,filter:t,...r})=>{let{del_filtered_docs:n}=await ge(r);return n(e,dn(t))},Kp=async({collection:e,filter:t,...r})=>{let{list_docs:n}=await ge(r),{items:o,items_page:i,items_length:s,matches_length:a,matches_pages:c}=await n(e,dn(t)),l=[];for(let[d,p]of o){let{data:u,owner:f,description:h,version:_,...y}=p;l.push({key:d,description:me(h),owner:f.toText(),data:await Bp({data:u}),version:me(_),...y})}return{items:l,items_length:s,items_page:me(i),matches_length:a,matches_pages:me(c)}},$p=async({collection:e,filter:t,...r})=>{let{count_docs:n}=await ge(r);return n(e,dn(t))};var ma=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Dp({...r,satellite:{...e,identity:n},options:t??Xt})},HO=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Up({...r,satellite:{...e,identity:n},options:t??Xt})},Hp=async({satellite:e,...t})=>{let r=ue(e?.identity);return await kp({...t,satellite:{...e,identity:r},options:{certified:!0}})},Gp=async({satellite:e,...t})=>{let r=ue(e?.identity);return await Lp({...t,satellite:{...e,identity:r},options:{certified:!0}})},GO=async({satellite:e,...t})=>{let r=ue(e?.identity);return await qp({...t,satellite:{...e,identity:r},options:{certified:!0}})},JO=async({satellite:e,...t})=>{let r=ue(e?.identity);return await Mp({...t,satellite:{...e,identity:r},options:{certified:!0}})},WO=async({satellite:e,filter:t,...r})=>{let n=ue(e?.identity);return await jp({...r,filter:t??{},satellite:{...e,identity:n},options:{certified:!0}})},zO=async({satellite:e,options:t,filter:r,...n})=>{let o=ue(e?.identity);return await Kp({...n,filter:r??{},satellite:{...e,identity:o},options:t??Xt})},YO=async({satellite:e,options:t,filter:r,...n})=>{let o=ue(e?.identity);return await $p({...n,filter:r??{},satellite:{...e,identity:o},options:t??Xt})};var Jp=async({provider:e})=>{let{user:t,userId:r}=await _a();if(J(t))return t;try{return await o0({userId:r,provider:e})}catch(n){if(gl({error:n,type:vp})){let o=await Wp({userId:r});if(J(o))return o}throw n}},_a=async()=>{let e=aa();if(U(e))throw new fa("No identity to initialize the user. Have you initialized Juno?");let t=e.getPrincipal().toText(),r=await Wp({userId:t});return{userId:t,user:r}},Wp=({userId:e})=>ma({collection:"#user",key:e}),o0=({userId:e,...t})=>Hp({collection:"#user",doc:{key:e,data:t}});var ya=async({syncTabsOnSuccess:e}={syncTabsOnSuccess:!1})=>{await Bi({fn:async()=>{let{user:r}=await _a();Ue.getInstance().set(r??null)},syncTabsOnSuccess:e})},zp=async()=>{await Rp({fn:async({authenticated:t})=>{let n=t?_a:()=>Promise.resolve({user:null}),{user:o}=await n();Ue.getInstance().set(o??null)}})},ga=async({user:e})=>{await Bi({fn:async()=>{Ue.getInstance().set(e)},syncTabsOnSuccess:!0})};var Yp=()=>{try{let e=Bo.getInstance(),t=async()=>{await zp(),Ai({message:"junoSignInReload"})};return e.onLoginSuccess(t),()=>{e?.destroy()}}catch(e){console.warn("Auth BroadcastChannel initialization failed",e);return}};var Zp=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_SATELLITE_ID??import.meta.env?.PUBLIC_SATELLITE_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_SATELLITE_ID??e():e()},Xp=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_CONTAINER??import.meta.env?.PUBLIC_CONTAINER:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_CONTAINER??e():e()},Qp=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_GOOGLE_CLIENT_ID??import.meta.env?.PUBLIC_GOOGLE_CLIENT_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID??e():e()},ef=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_GITHUB_CLIENT_ID??import.meta.env?.PUBLIC_GITHUB_CLIENT_ID:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_GITHUB_CLIENT_ID??e():e()},xa=()=>{let e=()=>typeof import.meta<"u"&&typeof import.meta.env<"u"?import.meta.env?.VITE_JUNO_API_URL??import.meta.env?.PUBLIC_JUNO_API_URL:void 0;return typeof process<"u"&&typeof process.env<"u"?process.env.NEXT_PUBLIC_JUNO_API_URL??e():e()};var tf=BigInt(144e11),rf=!1,nf={width:576,height:576},of={width:424,height:576},El="internetcomputer.org",sf="ic0.app",ba="id.ai";var af=({width:e,height:t})=>{if(!ji()||U(window)||U(window.top))return;let{top:{innerWidth:r,innerHeight:n}}=window,o=n/2+screenY-t/2,i=r/2+screenX-e/2;return`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${e}, height=${t}, top=${o}, left=${i}`};var Qt=async({fn:e,step:t,onProgress:r})=>{r?.({step:t,state:"in_progress"});try{let n=await e();return r?.({step:t,state:"success"}),n}catch(n){throw r?.({step:t,state:"error"}),n}};var cf=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))(cf||{});var wa=class{async signIn({options:t,authClient:r,initAuth:n}){await Qt({fn:async()=>await this.#e({options:t,authClient:r}),step:0,onProgress:t?.onProgress}),await Qt({fn:async()=>await n({provider:this.id}),step:1,onProgress:t?.onProgress})}#e({options:t,authClient:r}){return new Promise(async(n,o)=>{if(U(r)){o(new Lr("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:i=>{if(i===sa){o(new la(i));return}o(new ca(i))},maxTimeToLive:t?.maxTimeToLiveInNanoseconds??tf,allowPinAuthentication:t?.allowPin??rf,...t?.derivationOrigin!==void 0&&{derivationOrigin:t.derivationOrigin},...this.signInOptions({windowed:t?.windowed})})})}};var Ta=class extends wa{#e;constructor({domain:t}){super(),this.#e=t}get id(){return"internet_identity"}signInOptions({windowed:t}){let n=(()=>{let i=Ie.getInstance().get()?.container;if(U(i)||i===!1){let d=[El,sf].includes(this.#e??ba);return pt(this.#e)?`https://${ba}`:d?`https://identity.${this.#e??El}`:`https://${this.#e}`}let s=Ie.getInstance().get(),a=J(s)&&J(s?.internetIdentityId)?s.internetIdentityId:cp,{host:c,protocol:l}=new URL(i===!0?Vo:i);return/apple/i.test(navigator?.vendor)?`${l}//${c}?canisterId=${a}`:`${l}//${a}.${c.replace("127.0.0.1","localhost")}`})();return{...t!==!1&&{windowOpenerFeatures:af((()=>{try{let{hostname:i}=new URL(n);return i.includes(ba)}catch{return!1}})()?of:nf)},identityProvider:n}}};var Rl=e=>Kr(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),i0=()=>crypto.getRandomValues(new Uint8Array(32)),s0=async({salt:e,caller:t})=>{let r=t.getPrincipal().toUint8Array(),n=new Uint8Array(e.length+r.byteLength);n.set(e),n.set(r,e.length);let o=await crypto.subtle.digest("SHA-256",n);return Rl(mr(o))},lf=async({caller:e})=>{let t=i0();return{nonce:await s0({salt:t,caller:e}),salt:t}};var pf="juno:auth:openid",uf={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"},ff={authUrl:"https://github.com/login/oauth/authorize",authScopes:["read:user","user:email"],initUrl:"https://api.juno.build/v1/auth/init/github",finalizeUrl:"https://api.juno.build/v1/auth/finalize/github"},a0=class extends Error{},c0=class extends Error{},l0=class extends Error{},u0=class extends Error{},d0=class extends Error{},p0=class extends Error{},f0=class extends Error{},hf=class extends Error{},h0=class extends Error{},m0=class extends Error{},_0=class extends Error{constructor(e){super("GitHub OAuth initialization failed",e)}},y0=class extends Error{constructor(e){super("GitHub OAuth finalization failed",e)}},mf="__caller__",_f="__salt__",yf="__state__",g0=({caller:e,state:t,salt:r})=>{let n={[mf]:e.toJSON(),[_f]:Kr(r),[yf]:t};return JSON.stringify(n)},x0=e=>{let{[mf]:t,[_f]:r,[yf]:n}=JSON.parse(e);return{caller:dt.fromParsedJson(t),salt:Bl(r),state:n}},df=async({generateState:e})=>{let t=dt.generate(),{nonce:r,salt:n}=await lf({caller:t}),o=await e({nonce:r}),i=g0({caller:t,salt:n,state:o});return sessionStorage.setItem(pf,i),{nonce:r,state:o}},b0=()=>{let e=sessionStorage.getItem(pf);if(U(e))throw new c0;return x0(e)},gf=({auth:e,identity:t})=>"satellite"in e?Ip({...e.satellite,identity:t}):Ap({...e.console,identity:t}),w0=async({actorParams:e,args:t})=>{let{authenticate:r}=await gf(e);return await r(t)},T0=async({actorParams:e,args:t})=>{let{get_delegation:r}=await gf(e);return await r(t)},N0=({delegations:e,sessionKey:t})=>{let[r,n]=e,o=Lt.fromDelegations(n,Uint8Array.from(r));return{identity:qt.fromDelegation(t,o),delegationChain:o,sessionKey:t}},vl=async({jwt:e,context:t,auth:r})=>{let n=await xt.generate({extractable:!1}),o=new Uint8Array(n.getPublicKey().toDer()),{delegations:i,data:s}=await O0({jwt:e,publicKey:o,context:t,auth:r});return{identity:N0({sessionKey:n,delegations:i}),data:s}},O0=async({jwt:e,publicKey:t,context:{caller:r,salt:n},auth:o})=>{let i=await w0({args:{OpenId:{jwt:e,session_key:t,salt:n}},actorParams:{auth:o,identity:r}});if("Err"in i)throw new d0("Authentication failed",{cause:i});let{delegation:{user_key:s,expiration:a},...c}=i.Ok,l=await E0({jwt:e,context:{caller:r,salt:n},auth:o,publicKey:t,expiration:a}),{delegation:d,signature:p}=l,{pubkey:u,expiration:f,targets:h}=d;return{delegations:[s,[{delegation:new un(Uint8Array.from(u),f,me(h)),signature:Uint8Array.from(p)}]],data:c}},E0=async({jwt:e,publicKey:t,context:{salt:r,caller:n},auth:o,expiration:i,maxRetries:s=5})=>{for(let a=0;a<s;a++){await new Promise(l=>{setInterval(l,1e3*a)});let c=await T0({args:{OpenId:{jwt:e,session_key:t,salt:r,expiration:i}},actorParams:{auth:o,identity:n}});if("Err"in c){let{Err:l}=c;if("NoSuchDelegation"in l||"GetCachedJwks"in l)continue;throw new h0("Getting delegation failed",{cause:c})}return c.Ok}throw new m0},R0=async({url:e})=>{try{let t=await fetch(e,{credentials:"include"});return t.ok?{success:await t.json()}:{error:new Error(`Failed to fetch ${e} (${t.status})`)}}catch(t){return{error:new _0({cause:t})}}},v0=async({url:e,body:t})=>{try{let r=await fetch(e,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return r.ok?{success:await r.json()}:{error:new Error(`Failed to fetch ${e} (${r.status})`)}}catch(r){return{error:new y0({cause:r})}}},I0=async({auth:e,context:t,redirect:{finalizeUrl:r}})=>{let{location:{search:n}}=window,o=new URLSearchParams(n),i=o.get("code"),s=o.get("state"),a=await v0({url:r,body:{code:i,state:s}});if("error"in a)throw a.error;let{success:{token:c}}=a;if(pt(c))throw new hf;return await vl({jwt:c,auth:e,context:t})},A0=async({auth:e,context:t})=>{let{location:{hash:r}}=window;if(pt(r)||!r.startsWith("#"))throw new p0("No hash found in the current location URL");let n=new URLSearchParams(r.slice(1)),o=n.get("state"),i=n.get("id_token"),{state:s}=t;if(pt(s)||o!==s)throw new f0("The provided state is invalid",{cause:o});if(pt(i))throw new hf;return await vl({jwt:i,auth:e,context:t})},xf=async e=>{let t=b0();if("github"in e){let{github:{redirect:n,auth:o}}=e,{finalizeUrl:i}=ff;return await I0({redirect:n??{finalizeUrl:i},auth:o,context:t})}let{google:r}=e;if("credentials"in r){let{credentials:{jwt:n},auth:o}=r;return await vl({jwt:n,context:t,auth:o})}return await A0({...r,context:t})},Il=({url:e})=>{try{return new URL(e)}catch{throw new a0("Cannot parse authURL",{cause:e})}},S0=({initUrl:e})=>async({nonce:t})=>{let r=Il({url:e});r.searchParams.set("nonce",t);let n=await R0({url:r.toString()});if("error"in n)throw n.error;let{success:{state:o}}=n;return o},C0=({authUrl:e,clientId:t,authScopes:r,state:n,redirectUrl:o})=>{let i=Il({url:e});i.searchParams.set("client_id",t);let{location:{origin:s}}=window;i.searchParams.set("redirect_uri",o??s),i.searchParams.set("scope",r.join(" ")),i.searchParams.set("state",n),window.location.href=i.toString()},V0=()=>Rl(crypto.getRandomValues(new Uint8Array(12))),P0=async e=>V0(),F0=({authUrl:e,clientId:t,nonce:r,loginHint:n,authScopes:o,state:i,redirectUrl:s})=>{let a=Il({url:e});a.searchParams.set("client_id",t);let{location:{origin:c}}=window;a.searchParams.set("redirect_uri",s??c),a.searchParams.set("response_type","code id_token"),a.searchParams.set("scope",o.join(" ")),a.searchParams.set("state",i),a.searchParams.set("nonce",r),_r(n)?a.searchParams.set("login_hint",n):a.searchParams.set("prompt","select_account"),window.location.href=a.toString()},B0=async({configUrl:e,clientId:t,nonce:r,loginHint:n,domainHint:o})=>{let i=await navigator.credentials.get({identity:{context:"use",providers:[{configURL:e,clientId:t,nonce:r,loginHint:n,domainHint:o}],mode:"active"},mediation:"required"});if(U(i))throw new l0;let{type:s}=i;if(s!=="identity"||!("token"in i)||typeof i.token!="string")throw new u0("Invalid credential received from FedCM API",{cause:i});let{token:a}=i;return{jwt:a}};async function Na(e){if("github"in e){let{github:s}=e,{redirect:a}=s,{initUrl:c,...l}=a,{authUrl:d,authScopes:p,initUrl:u}=ff,f=await df({generateState:S0({initUrl:c??u})});C0({...l,...f,authUrl:d,authScopes:p});return}let t=await df({generateState:P0}),{google:r}=e;if("credentials"in r){let{credentials:s}=r,{configUrl:a}=uf;return await B0({...s,...t,configUrl:a})}let{redirect:n}=r,{authUrl:o,authScopes:i}=uf;F0({...n,...t,authUrl:o,authScopes:i})}var Oa=({url:e})=>{try{return new URL(e)}catch{return console.warn(`Cannot parse URL ${e}. Skipping option.`),null}};var D0=async e=>{let{satelliteId:t}=Ie.getInstance().get()??{satelliteId:void 0};if(U(t))throw new Lr("Satellite ID not set. Have you initialized the Satellite?");let r=Ie.getInstance().get()?.container,n={auth:{satellite:{satelliteId:t,container:r}}},i=(()=>{let p="github"in e?e?.github?.options?.finalizeUrl:void 0;if(_r(p))return p;let u=xa();return pt(u)?null:Oa({url:`${u}/v1/auth/finalize/github`})?.toString()??null})(),{identity:{delegationChain:s,sessionKey:a,identity:c},data:{doc:l}}=await xf("github"in e?{github:{redirect:J(i)?{finalizeUrl:i}:null,...n}}:{google:{redirect:null,...n}});await Ce.getInstance().setAuthClientStorage({delegationChain:s,sessionKey:a});let d=await io({doc:l,key:c.getPrincipal().toText()});await ga({user:d})};var bf=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),U0=()=>{window.addEventListener("beforeunload",bf,{capture:!0})},k0=()=>{window.removeEventListener("beforeunload",bf,{capture:!0})},Ea=async({fn:e})=>{try{return U0(),await e()}finally{k0()}};function wf(e){return new Promise((t,r)=>{e.oncomplete=e.onsuccess=()=>t(e.result),e.onabort=e.onerror=()=>r(e.error)})}function Sl(e,t){let r,n=()=>{if(r)return r;let o=indexedDB.open(e);return o.onupgradeneeded=()=>o.result.createObjectStore(t),r=wf(o),r.then(i=>{i.onclose=()=>r=void 0},()=>{}),r};return(o,i)=>n().then(s=>i(s.transaction(t,o).objectStore(t)))}var Al;function L0(){return Al||(Al=Sl("keyval-store","keyval")),Al}function Tf(e,t,r=L0()){return r("readwrite",n=>new Promise((o,i)=>{n.get(e).onsuccess=function(){try{n.put(t(this.result),e),o(wf(n.transaction))}catch(s){i(s)}}}))}var q0=class extends Error{constructor(){super("A dev identity can only be used in browser environments")}},M0=class extends Error{constructor(){super("A dev identity must only be used on localhost (127.0.0.1 or localhost)")}},j0=class extends Error{constructor(e){super(`Identifier must be 32 characters or less, got ${e}`)}},K0=Sl("juno-dev-identifiers","juno-dev-identifiers-store");var Nf=async({identifier:e="dev",maxTimeToLiveInMilliseconds:t}={})=>{if(!(typeof window<"u"))throw new q0;let{location:{hostname:r}}=window;if(!["127.0.0.1","localhost"].includes(r))throw new M0;let n=()=>{if(e.length>32)throw new j0(e.length);return new TextEncoder().encode(e.padEnd(32,"0"))},o=async()=>{let a=n(),c=dt.generate(a),l=await xt.generate({extractable:!1}),d=t??6048e5,p=await Lt.create(c,l.getPublicKey(),new Date(Date.now()+d));return{identity:qt.fromDelegation(l,p),sessionKey:l,delegationChain:p}},i=async()=>{await Tf(e,a=>{let c=Date.now();return{createdAt:a?.createdAt??c,updatedAt:c}},K0)},s=await o();return await i(),s};var Ra=class{async signIn({options:t,initAuth:r,setStorage:n}){let{sessionKey:o,delegationChain:i}=await Nf(t);await n({sessionKey:o,delegationChain:i}),await r({provider:void 0})}};var va=class{async signIn({options:t={}}){let r=t?.redirect?.clientId??ef();if(U(r))throw new Do;let{redirect:n}=t;await Na({github:{redirect:{...n??{},clientId:r,initUrl:(()=>{let i=t?.redirect?.initUrl;if(_r(i))return i;let s=xa();if(!pt(s))return Oa({url:`${s}/v1/auth/init/github`})?.toString()})()}}})}};var Ia=class{async signIn({options:t={}}){let r=t?.redirect?.clientId??Qp();if(U(r))throw new Do;let{redirect:n}=t;await Na({google:{redirect:{...n??{},clientId:r}}})}};var Of=async({delegationIdentity:e,passkeyIdentity:t,satelliteId:r})=>{let n=t.getCredential().getAAGUID(),[o,i]=await Gp({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...J(n)&&{aaguid:Li(n)}}}}}},{collection:"#user-webauthn",doc:{key:t.getCredential().getCredentialIdText(),data:{publicKey:t.getPublicKey().toRaw()}}}],satellite:{identity:e,satelliteId:r}});return o};var Ef=(i=>(i[i.RequestingUserCredential=0]="RequestingUserCredential",i[i.FinalizingCredential=1]="FinalizingCredential",i[i.Signing=2]="Signing",i[i.FinalizingSession=3]="FinalizingSession",i[i.RetrievingUser=4]="RetrievingUser",i))(Ef||{}),Rf=(s=>(s[s.CreatingUserCredential=0]="CreatingUserCredential",s[s.ValidatingUserCredential=1]="ValidatingUserCredential",s[s.FinalizingCredential=2]="FinalizingCredential",s[s.Signing=3]="Signing",s[s.FinalizingSession=4]="FinalizingSession",s[s.RegisteringUser=5]="RegisteringUser",s))(Rf||{});var Uo=class{async signUp({options:{onProgress:t,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:o}){let{satelliteId:i}=Ie.getInstance().get()??{satelliteId:void 0};if(U(i))throw new Lr("Satellite ID not set. Have you initialized the Satellite?");let s=({step:_,state:y})=>{switch(_){case ln.RequestingUserCredential:t?.({step:1,state:y});break;case ln.FinalizingCredential:t?.({step:2,state:y});break;case ln.Signing:t?.({step:3,state:y});break}},c=await Qt({fn:async()=>await il.createWithNewCredential({onProgress:s,passkeyOptions:n}),step:0,onProgress:t}),{delegationIdentity:l,sessionKey:d}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),u=await Qt({fn:async()=>await Of({delegationIdentity:l,passkeyIdentity:c,satelliteId:i}),step:5,onProgress:t});await Qt({fn:async()=>await this.#t({delegationIdentity:l,sessionKey:d}),step:4,onProgress:t}),await Qt({fn:async()=>await o({user:u}),step:5,onProgress:t})}async signIn({options:{onProgress:t,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:o}=Ie.getInstance().get()??{satelliteId:void 0};if(U(o))throw new Lr("Satellite ID not set. Have you initialized the Satellite?");let i=async({credentialId:p})=>{let u=await ma({collection:"#user-webauthn",key:Kr(p),options:{certified:!0},satellite:{identity:new at,satelliteId:o}});if(U(u))throw new da("No public key found for the selected passkey.");let{data:f}=u,{publicKey:h}=f;return oo(h,vi)},s=({step:p,state:u})=>{switch(p){case ln.RequestingUserCredential:t?.({step:0,state:u});break;case ln.FinalizingCredential:t?.({step:1,state:u});break;case ln.Signing:t?.({step:2,state:u});break}},a=await il.createWithExistingCredential({retrievePublicKey:i,onProgress:s}),{delegationIdentity:c,sessionKey:l}=await this.#e({identity:a,maxTimeToLiveInMilliseconds:r});await Qt({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:l}),step:3,onProgress:t}),await Qt({fn:n,step:4,onProgress:t})}async#e({identity:t,maxTimeToLiveInMilliseconds:r}){let n=await xt.generate({extractable:!1}),o=r??144e5,i=await Lt.create(t,n.getPublicKey(),new Date(Date.now()+o));return{delegationIdentity:qt.fromDelegation(n,i),sessionKey:n}}async#t({sessionKey:t,delegationIdentity:r}){let n=new Zt;await Promise.all([n.set(We,t.getKeyPair()),n.set(ke,JSON.stringify(r.getDelegation().toJSON()))])}};var vf=async({provider:e})=>{await Bi({fn:async()=>{let r=await Jp({provider:e});Ue.getInstance().set(r)},syncTabsOnSuccess:!0})},H0=async e=>{if("google"in e){let{google:{options:t}}=e;await Di({fn:()=>new Ia().signIn({options:t}),context:{windowGuard:!1}});return}if("github"in e){let{github:{options:t}}=e;await Di({fn:()=>new va().signIn({options:t}),context:{windowGuard:!1}});return}if("webauthn"in e){let{webauthn:{options:t,context:r}}=e;await Di({fn:()=>new Uo().signIn({options:t,loadAuth:()=>ya({syncTabsOnSuccess:!0})}),context:r});return}if("internet_identity"in e){let{internet_identity:{options:t,context:r}}=e,{domain:n,...o}=t??{};await Di({fn:()=>new Ta({domain:n}).signIn({options:o,authClient:Ce.getInstance().getAuthClient(),initAuth:vf}),context:r});return}if("dev"in e){let{dev:{options:t}}=e,{setAuthClientStorage:r}=Ce.getInstance();await Di({fn:()=>new Ra().signIn({options:t,initAuth:vf,setStorage:r}),context:{windowGuard:!1}});return}throw new ua("An unknown or unsupported provider was provided for sign-in.")},Di=async({fn:e,context:t})=>{if(t?.windowGuard===!1){await e();return}await Ea({fn:e})};var G0=async e=>{let t=async()=>await J0(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await t();return}await Ea({fn:t})},J0=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new Uo().signUp({options:t,loadAuthWithUser:ga});return}throw new pa("An unknown or unsupported provider was provided for sign-up.")};var w2=e=>e?.data?.provider==="webauthn",T2=e=>e?.data?.provider==="google",N2=e=>e?.data?.provider==="github";var v2=async({idlFactory:e,satellite:t})=>{let r=ue(t?.identity);return await Vp({idlFactory:e,...t,identity:r})};var If=async({asset:{data:e,headers:t,...r},actor:n,progress:o})=>{let{init_asset_upload:i,upload_asset_chunk:s,commit_asset_upload:a}=n,{batch_id:c}=await i(W0(r));o?.onInitiatedBatch();let{chunkIds:l}=await Z0({data:e,uploadFn:s,batchId:c});o?.onUploadedFileChunks(r.fullPath),await Y0({commitFn:a,batchId:c,data:e,headers:t,chunkIds:l}),o?.onCommittedBatch()};var W0=({filename:e,collection:t,token:r,fullPath:n,encoding:o,description:i})=>({collection:t,full_path:n,name:e,token:se(r),encoding_type:se(o),description:se(i)}),z0=({batchId:e,chunkIds:t,headers:r,data:n})=>{let o=r.find(([i,s])=>i.toLowerCase()==="content-type")===void 0&&n.type!==void 0&&n.type!==""?[["Content-Type",n.type]]:void 0;return{batch_id:e,chunk_ids:t.map(({chunk_id:i})=>i),headers:[...r,...o??[]]}},Y0=async({commitFn:e,...t})=>{let r=z0(t);await e(r)},Z0=async({data:e,uploadFn:t,batchId:r})=>{let n=[],o=ji()?new Blob([await e.arrayBuffer()]):e,i=0n;for(let a=0;a<o.size;a+=19e5){let c=o.slice(a,a+19e5);n.push({batchId:r,chunk:c,uploadFn:t,orderId:i}),i++}let s=[];for await(let a of X0({uploadChunks:n}))s=[...s,...a];return{chunkIds:s}};async function*X0({uploadChunks:e,limit:t=12}){for(let r=0;r<e.length;r=r+t){let n=e.slice(r,r+t);yield await Promise.all(n.map(o=>Q0(o)))}}var Q0=async({batchId:e,chunk:t,uploadFn:r,orderId:n})=>r({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:se(n)});var Af=async({asset:e,...t})=>{let r=await ge(t);await If({actor:r,asset:e})},Sf=async({collection:e,filter:t,...r})=>{let{list_assets:n}=await ge(r),{items:o,items_length:i,items_page:s,matches_length:a,matches_pages:c}=await n(e,dn(t));return{items:o.map(([l,d])=>d),items_length:i,items_page:me(s),matches_length:a,matches_pages:me(c)}},Cf=async({collection:e,filter:t,...r})=>{let{count_assets:n}=await ge(r);return n(e,dn(t))},Vf=async({collection:e,fullPath:t,...r})=>(await ge(r)).del_asset(e,t),Pf=async({assets:e,satellite:t})=>{let{del_many_assets:r}=await ge({satellite:t,options:{certified:!0}}),n=e.map(({collection:o,fullPath:i})=>[o,i]);await r(n)},Ff=async({collection:e,filter:t,...r})=>{let{del_filtered_assets:n}=await ge(r);return n(e,dn(t))},Bf=async({collection:e,fullPath:t,token:r,...n})=>{let{set_asset_token:o}=await ge(n);return o(e,t,se(r))},Df=async({collection:e,fullPath:t,...r})=>{let{get_asset:n}=await ge(r);return me(await n(e,t))},Uf=async({assets:e,...t})=>{let{get_many_assets:r}=await ge(t),n=e.map(({collection:i,fullPath:s})=>[i,s]);return(await r(n)).map(([i,s])=>me(s))};var kf=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var K2=e=>Lf(e),$2=e=>Lf({filename:e.data.name,...e}),Lf=async({filename:e,data:t,collection:r,headers:n=[],fullPath:o,token:i,satellite:s,encoding:a,description:c})=>{let l=ue(s?.identity),d=decodeURI(e),p=o??`/${r}/${d}`,u={...s,identity:l};return await Af({asset:{data:t,filename:d,collection:r,token:i,headers:n,fullPath:p,encoding:a,description:c},satellite:u,options:{certified:!0}}),{downloadUrl:qf({satellite:u,assetKey:{fullPath:p,token:i}}),fullPath:p,...J(i)&&{token:i},name:d}},H2=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:ue(r?.identity)},{items:i,...s}=await Sf({collection:e,filter:t??{},satellite:o,options:n??Xt}),a=i.map(({key:{full_path:c,token:l,name:d,owner:p,description:u},headers:f,encodings:h,created_at:_,updated_at:y})=>{let m=me(l);return{fullPath:c,description:me(u),name:d,downloadUrl:qf({satellite:o,assetKey:{fullPath:c,token:m}}),token:m,headers:f,encodings:h.reduce((b,[g,{modified:T,sha256:O,total_length:v}])=>({...b,[g]:{modified:T,sha256:kf(O),total_length:v}}),{}),owner:p.toText(),created_at:_,updated_at:y}});return{items:a,assets:a,...s}},G2=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:ue(r?.identity)};return await Cf({collection:e,satellite:o,filter:t??{},options:n??Xt})},J2=({collection:e,fullPath:t,satellite:r})=>Vf({collection:e,fullPath:t,satellite:{...r,identity:ue(r?.identity)},options:{certified:!0}}),W2=({collection:e,fullPath:t,token:r,satellite:n})=>Bf({collection:e,fullPath:t,token:r,satellite:{...n,identity:ue(n?.identity)},options:{certified:!0}}),z2=({assets:e,satellite:t})=>Pf({assets:e,satellite:{...t,identity:ue(t?.identity)},options:{certified:!0}}),Y2=async({collection:e,satellite:t,filter:r})=>{let n={...t,identity:ue(t?.identity)};return await Ff({collection:e,satellite:n,filter:r??{},options:{certified:!0}})},Z2=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Df({...r,satellite:{...e,identity:n},options:t??Xt})},X2=async({satellite:e,options:t,...r})=>{let n=ue(e?.identity);return await Uf({...r,satellite:{...e,identity:n},options:t??Xt})},qf=({assetKey:{fullPath:e,token:t},satellite:r})=>{let n={...r,identity:ue(r?.identity)};return`${Cp(n)}${e}${J(t)?`?token=${t}`:""}`};var eg=e=>{let t=e?.satelliteId??Zp();jo(t,"Satellite ID is not configured. Juno cannot be initialized.");let r=e?.container??Xp();return{satelliteId:t,internetIdentityId:e?.internetIdentityId,workers:e?.workers,syncTabs:e?.syncTabs,container:r}},cE=e=>tg(e),tg=async e=>{let t=eg(e);Ie.getInstance().set(t),await ya();let r=t.workers?.auth!==void 0?Ep(t.workers.auth):void 0,n=t.syncTabs===!1?void 0:Yp();return[...J(r)?[r]:[],...J(n)?[n]:[]]},rg=e=>Ue.getInstance().subscribe(e),lE=rg;export{cf as AuthClientSignInProgressStep,fa as InitError,Ta as InternetIdentityProvider,ha as ListError,ca as SignInError,Lr as SignInInitError,Do as SignInMissingClientIdError,ua as SignInProviderNotSupportedError,la as SignInUserInterruptError,pa as SignUpProviderNotSupportedError,Ef as WebAuthnSignInProgressStep,da as WebAuthnSignInRetrievePublicKeyError,Rf as WebAuthnSignUpProgressStep,lE as authSubscribe,G2 as countAssets,YO as countDocs,J2 as deleteAsset,GO as deleteDoc,Y2 as deleteFilteredAssets,WO as deleteFilteredDocs,z2 as deleteManyAssets,JO as deleteManyDocs,qf as downloadUrl,Z2 as getAsset,ma as getDoc,Zy as getIdentityOnce,X2 as getManyAssets,HO as getManyDocs,v2 as getSatelliteExtendedActor,D0 as handleRedirectCallback,cE as initJuno,tg as initSatellite,N2 as isGitHubUser,T2 as isGoogleUser,Ny as isWebAuthnAvailable,w2 as isWebAuthnUser,H2 as listAssets,zO as listDocs,rg as onAuthStateChange,W2 as setAssetToken,Hp as setDoc,Gp as setManyDocs,H0 as signIn,yl as signOut,G0 as signUp,Yy as unsafeIdentity,K2 as uploadBlob,$2 as uploadFile};
57
+ /*! Bundled license information:
58
+
59
+ @noble/hashes/esm/utils.js:
60
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
61
+ */
55
62
  /*! Bundled license information:
56
63
 
57
64
  @noble/hashes/esm/utils.js: