@junobuild/core-standalone 2.2.1 → 3.0.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.
Files changed (39) hide show
  1. package/dist/browser/index.js +28 -28
  2. package/dist/browser/index.js.map +4 -4
  3. package/dist/node/index.mjs +31 -108
  4. package/dist/node/index.mjs.map +4 -4
  5. package/dist/types/auth/providers/_auth-client.providers.d.ts +3 -12
  6. package/dist/types/auth/providers/_auth.providers.d.ts +11 -0
  7. package/dist/types/auth/providers/google.providers.d.ts +25 -0
  8. package/dist/types/auth/providers/webauthn.providers.d.ts +1 -1
  9. package/dist/types/auth/services/_auth-client.services.d.ts +17 -0
  10. package/dist/types/auth/services/identity.services.d.ts +22 -0
  11. package/dist/types/auth/services/load.services.d.ts +13 -0
  12. package/dist/types/auth/services/redirect.services.d.ts +1 -0
  13. package/dist/types/auth/services/sign-in.services.d.ts +19 -0
  14. package/dist/types/auth/services/sign-out.services.d.ts +10 -0
  15. package/dist/types/auth/services/sign-up.services.d.ts +8 -0
  16. package/dist/types/auth/services/user-webauthn.services.d.ts +1 -1
  17. package/dist/types/auth/stores/auth-client.store.d.ts +15 -0
  18. package/dist/types/auth/types/auth.d.ts +11 -12
  19. package/dist/types/auth/types/errors.d.ts +2 -0
  20. package/dist/types/auth/types/google.d.ts +50 -0
  21. package/dist/types/auth/types/provider.d.ts +7 -3
  22. package/dist/types/core/api/actor.api.d.ts +2 -2
  23. package/dist/types/core/services/{identity.services.d.ts → any-identity.services.d.ts} +1 -1
  24. package/dist/types/core/stores/_agent.factory.d.ts +1 -1
  25. package/dist/types/core/stores/actor.store.d.ts +2 -2
  26. package/dist/types/core/stores/agent.store.d.ts +1 -1
  27. package/dist/types/core/types/list.d.ts +1 -1
  28. package/dist/types/core/types/satellite.d.ts +1 -1
  29. package/dist/types/core/types/utility.d.ts +5 -3
  30. package/dist/types/core/utils/window.env.utils.d.ts +1 -0
  31. package/dist/types/functions/services/functions.services.d.ts +2 -2
  32. package/dist/types/index.d.ts +5 -3
  33. package/dist/workers/auth.worker.js +6 -6
  34. package/dist/workers/auth.worker.js.map +4 -4
  35. package/package.json +15 -16
  36. package/dist/types/auth/providers/nfid.providers.d.ts +0 -28
  37. package/dist/types/auth/services/auth.services.d.ts +0 -60
  38. package/dist/types/auth/types/nfid.d.ts +0 -22
  39. package/dist/types/auth/utils/auth.utils.d.ts +0 -3
@@ -1,141 +1,64 @@
1
1
  import { createRequire as topLevelCreateRequire } from 'module';
2
2
  const require = topLevelCreateRequire(import.meta.url);
3
- var k1=Object.create;var Nl=Object.defineProperty;var j1=Object.getOwnPropertyDescriptor;var H1=Object.getOwnPropertyNames;var $1=Object.getPrototypeOf,K1=Object.prototype.hasOwnProperty;var G1=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Y=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),z1=(t,e)=>{for(var r in e)Nl(t,r,{get:e[r],enumerable:!0})},Z1=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of H1(e))!K1.call(t,o)&&o!==r&&Nl(t,o,{get:()=>e[o],enumerable:!(n=j1(e,o))||n.enumerable});return t};var Fe=(t,e,r)=>(r=t!=null?k1($1(t)):{},Z1(e||!t||!t.__esModule?Nl(r,"default",{value:t,enumerable:!0}):r,t));var vl=Y(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.QueryResponseStatus=co.ReplicaRejectCode=void 0;co.isV2ResponseBody=Y1;co.isV3ResponseBody=W1;var hm;(function(t){t[t.SysFatal=1]="SysFatal",t[t.SysTransient=2]="SysTransient",t[t.DestinationInvalid=3]="DestinationInvalid",t[t.CanisterReject=4]="CanisterReject",t[t.CanisterError=5]="CanisterError"})(hm||(co.ReplicaRejectCode=hm={}));var mm;(function(t){t.Replied="replied",t.Rejected="rejected"})(mm||(co.QueryResponseStatus=mm={}));function Y1(t){return t!=null&&"reject_code"in t}function W1(t){return t!=null&&"certificate"in t}});var ym=Y(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});Fc.encode=X1;Fc.decode=J1;var Dc="abcdefghijklmnopqrstuvwxyz234567",Hs=Object.create(null);for(let t=0;t<Dc.length;t++)Hs[Dc[t]]=t;Hs[0]=Hs.o;Hs[1]=Hs.i;function X1(t){let e=0,r=0,n="";function o(s){return e<0?r|=s>>-e:r=s<<e&248,e>3?(e-=8,1):(e<4&&(n+=Dc[r>>3],e+=5),0)}for(let s=0;s<t.length;)s+=o(t[s]);return n+(e<0?Dc[r>>3]:"")}function J1(t){let e=0,r=0,n=new Uint8Array(t.length*4/3|0),o=0;function s(i){let a=Hs[i.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(i)}`);a<<=3,r|=a>>>e,e+=5,e>=8&&(n[o++]=r,e-=8,e>0?r=a<<5-e&255:r=0)}for(let i of t)s(i);return n.slice(0,o)}});var Il=Y(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});Rl.getCrc32=e2;var Q1=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 e2(t){let e=-1;for(let r=0;r<t.length;r++){let o=(t[r]^e)&255;e=Q1[o]^e>>>8}return(e^-1)>>>0}});var _m=Y(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.crypto=void 0;var uo=G1("node:crypto");Vc.crypto=uo&&typeof uo=="object"&&"webcrypto"in uo?uo.webcrypto:uo&&typeof uo=="object"&&"randomBytes"in uo?uo:void 0});var dt=Y(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.wrapXOFConstructorWithOpts=ee.wrapConstructorWithOpts=ee.wrapConstructor=ee.Hash=ee.nextTick=ee.swap32IfBE=ee.byteSwapIfBE=ee.swap8IfBE=ee.isLE=void 0;ee.isBytes=gm;ee.anumber=Sl;ee.abytes=Ks;ee.ahash=t2;ee.aexists=r2;ee.aoutput=n2;ee.u8=o2;ee.u32=s2;ee.clean=i2;ee.createView=a2;ee.rotr=c2;ee.rotl=u2;ee.byteSwap=Bl;ee.byteSwap32=xm;ee.bytesToHex=l2;ee.hexToBytes=f2;ee.asyncLoop=h2;ee.utf8ToBytes=Cl;ee.bytesToUtf8=m2;ee.toBytes=Uc;ee.kdfInputToBytes=y2;ee.concatBytes=_2;ee.checkOpts=b2;ee.createHasher=Em;ee.createOptHasher=Tm;ee.createXOFer=Om;ee.randomBytes=g2;var $s=_m();function gm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Sl(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ks(t,...e){if(!gm(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function t2(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Sl(t.outputLen),Sl(t.blockLen)}function r2(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function n2(t,e){Ks(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function o2(t){return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function s2(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function i2(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function a2(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function c2(t,e){return t<<32-e|t>>>e}function u2(t,e){return t<<e|t>>>32-e>>>0}ee.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Bl(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}ee.swap8IfBE=ee.isLE?t=>t:t=>Bl(t);ee.byteSwapIfBE=ee.swap8IfBE;function xm(t){for(let e=0;e<t.length;e++)t[e]=Bl(t[e]);return t}ee.swap32IfBE=ee.isLE?t=>t:xm;var wm=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",d2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function l2(t){if(Ks(t),wm)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=d2[t[r]];return e}var En={_0:48,_9:57,A:65,F:70,a:97,f:102};function bm(t){if(t>=En._0&&t<=En._9)return t-En._0;if(t>=En.A&&t<=En.F)return t-(En.A-10);if(t>=En.a&&t<=En.f)return t-(En.a-10)}function f2(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(wm)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=bm(t.charCodeAt(s)),a=bm(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}var p2=async()=>{};ee.nextTick=p2;async function h2(t,e,r){let n=Date.now();for(let o=0;o<t;o++){r(o);let s=Date.now()-n;s>=0&&s<e||(await(0,ee.nextTick)(),n+=s)}}function Cl(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function m2(t){return new TextDecoder().decode(t)}function Uc(t){return typeof t=="string"&&(t=Cl(t)),Ks(t),t}function y2(t){return typeof t=="string"&&(t=Cl(t)),Ks(t),t}function _2(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];Ks(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}function b2(t,e){if(e!==void 0&&{}.toString.call(e)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(t,e)}var Al=class{};ee.Hash=Al;function Em(t){let e=n=>t().update(Uc(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Tm(t){let e=(n,o)=>t(o).update(Uc(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function Om(t){let e=(n,o)=>t(o).update(Uc(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}ee.wrapConstructor=Em;ee.wrapConstructorWithOpts=Tm;ee.wrapXOFConstructorWithOpts=Om;function g2(t=32){if($s.crypto&&typeof $s.crypto.getRandomValues=="function")return $s.crypto.getRandomValues(new Uint8Array(t));if($s.crypto&&typeof $s.crypto.randomBytes=="function")return Uint8Array.from($s.crypto.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}});var vm=Y(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.SHA512_IV=Ut.SHA384_IV=Ut.SHA224_IV=Ut.SHA256_IV=Ut.HashMD=void 0;Ut.setBigUint64=Nm;Ut.Chi=x2;Ut.Maj=w2;var Hr=dt();function Nm(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,d=n?0:4;t.setUint32(e+c,i,n),t.setUint32(e+d,a,n)}function x2(t,e,r){return t&e^~t&r}function w2(t,e,r){return t&e^t&r^e&r}var Pl=class extends Hr.Hash{constructor(e,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=(0,Hr.createView)(this.buffer)}update(e){(0,Hr.aexists)(this),e=(0,Hr.toBytes)(e),(0,Hr.abytes)(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=(0,Hr.createView)(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){(0,Hr.aexists)(this),(0,Hr.aoutput)(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,(0,Hr.clean)(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)r[l]=0;Nm(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=(0,Hr.createView)(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,p=this.get();if(d>p.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<d;l++)a.setUint32(4*l,p[l],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}};Ut.HashMD=Pl;Ut.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);Ut.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);Ut.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]);Ut.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});var Zm=Y(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.toBig=ce.shrSL=ce.shrSH=ce.rotrSL=ce.rotrSH=ce.rotrBL=ce.rotrBH=ce.rotr32L=ce.rotr32H=ce.rotlSL=ce.rotlSH=ce.rotlBL=ce.rotlBH=ce.add5L=ce.add5H=ce.add4L=ce.add4H=ce.add3L=ce.add3H=void 0;ce.add=km;ce.fromBig=Fl;ce.split=Rm;var Lc=BigInt(2**32-1),Dl=BigInt(32);function Fl(t,e=!1){return e?{h:Number(t&Lc),l:Number(t>>Dl&Lc)}:{h:Number(t>>Dl&Lc)|0,l:Number(t&Lc)|0}}function Rm(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=Fl(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Im=(t,e)=>BigInt(t>>>0)<<Dl|BigInt(e>>>0);ce.toBig=Im;var Sm=(t,e,r)=>t>>>r;ce.shrSH=Sm;var Am=(t,e,r)=>t<<32-r|e>>>r;ce.shrSL=Am;var Bm=(t,e,r)=>t>>>r|e<<32-r;ce.rotrSH=Bm;var Cm=(t,e,r)=>t<<32-r|e>>>r;ce.rotrSL=Cm;var Pm=(t,e,r)=>t<<64-r|e>>>r-32;ce.rotrBH=Pm;var Dm=(t,e,r)=>t>>>r-32|e<<64-r;ce.rotrBL=Dm;var Fm=(t,e)=>e;ce.rotr32H=Fm;var Vm=(t,e)=>t;ce.rotr32L=Vm;var Um=(t,e,r)=>t<<r|e>>>32-r;ce.rotlSH=Um;var Lm=(t,e,r)=>e<<r|t>>>32-r;ce.rotlSL=Lm;var qm=(t,e,r)=>e<<r-32|t>>>64-r;ce.rotlBH=qm;var Mm=(t,e,r)=>t<<r-32|e>>>64-r;ce.rotlBL=Mm;function km(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var jm=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0);ce.add3L=jm;var Hm=(t,e,r,n)=>e+r+n+(t/2**32|0)|0;ce.add3H=Hm;var $m=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0);ce.add4L=$m;var Km=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0;ce.add4H=Km;var Gm=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0);ce.add5L=Gm;var zm=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;ce.add5H=zm;var E2={fromBig:Fl,split:Rm,toBig:Im,shrSH:Sm,shrSL:Am,rotrSH:Bm,rotrSL:Cm,rotrBH:Pm,rotrBL:Dm,rotr32H:Fm,rotr32L:Vm,rotlSH:Um,rotlSL:Lm,rotlBH:qm,rotlBL:Mm,add:km,add3L:jm,add3H:Hm,add4L:$m,add4H:Km,add5H:zm,add5L:Gm};ce.default=E2});var Gs=Y(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.sha512_224=Le.sha512_256=Le.sha384=Le.sha512=Le.sha224=Le.sha256=Le.SHA512_256=Le.SHA512_224=Le.SHA384=Le.SHA512=Le.SHA224=Le.SHA256=void 0;var Q=vm(),ye=Zm(),Qe=dt(),T2=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]),lo=new Uint32Array(64),ea=class extends Q.HashMD{constructor(e=32){super(64,e,8,!1),this.A=Q.SHA256_IV[0]|0,this.B=Q.SHA256_IV[1]|0,this.C=Q.SHA256_IV[2]|0,this.D=Q.SHA256_IV[3]|0,this.E=Q.SHA256_IV[4]|0,this.F=Q.SHA256_IV[5]|0,this.G=Q.SHA256_IV[6]|0,this.H=Q.SHA256_IV[7]|0}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let l=0;l<16;l++,r+=4)lo[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let u=lo[l-15],f=lo[l-2],h=(0,Qe.rotr)(u,7)^(0,Qe.rotr)(u,18)^u>>>3,m=(0,Qe.rotr)(f,17)^(0,Qe.rotr)(f,19)^f>>>10;lo[l]=m+lo[l-7]+h+lo[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:d,H:p}=this;for(let l=0;l<64;l++){let u=(0,Qe.rotr)(a,6)^(0,Qe.rotr)(a,11)^(0,Qe.rotr)(a,25),f=p+u+(0,Q.Chi)(a,c,d)+T2[l]+lo[l]|0,m=((0,Qe.rotr)(n,2)^(0,Qe.rotr)(n,13)^(0,Qe.rotr)(n,22))+(0,Q.Maj)(n,o,s)|0;p=d,d=c,c=a,a=i+f|0,i=s,s=o,o=n,n=f+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,p=p+this.H|0,this.set(n,o,s,i,a,c,d,p)}roundClean(){(0,Qe.clean)(lo)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,Qe.clean)(this.buffer)}};Le.SHA256=ea;var qc=class extends ea{constructor(){super(28),this.A=Q.SHA224_IV[0]|0,this.B=Q.SHA224_IV[1]|0,this.C=Q.SHA224_IV[2]|0,this.D=Q.SHA224_IV[3]|0,this.E=Q.SHA224_IV[4]|0,this.F=Q.SHA224_IV[5]|0,this.G=Q.SHA224_IV[6]|0,this.H=Q.SHA224_IV[7]|0}};Le.SHA224=qc;var Ym=ye.split(["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(t=>BigInt(t))),O2=Ym[0],N2=Ym[1],fo=new Uint32Array(80),po=new Uint32Array(80),zo=class extends Q.HashMD{constructor(e=64){super(128,e,16,!1),this.Ah=Q.SHA512_IV[0]|0,this.Al=Q.SHA512_IV[1]|0,this.Bh=Q.SHA512_IV[2]|0,this.Bl=Q.SHA512_IV[3]|0,this.Ch=Q.SHA512_IV[4]|0,this.Cl=Q.SHA512_IV[5]|0,this.Dh=Q.SHA512_IV[6]|0,this.Dl=Q.SHA512_IV[7]|0,this.Eh=Q.SHA512_IV[8]|0,this.El=Q.SHA512_IV[9]|0,this.Fh=Q.SHA512_IV[10]|0,this.Fl=Q.SHA512_IV[11]|0,this.Gh=Q.SHA512_IV[12]|0,this.Gl=Q.SHA512_IV[13]|0,this.Hh=Q.SHA512_IV[14]|0,this.Hl=Q.SHA512_IV[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:d,El:p,Fh:l,Fl:u,Gh:f,Gl:h,Hh:m,Hl:b}=this;return[e,r,n,o,s,i,a,c,d,p,l,u,f,h,m,b]}set(e,r,n,o,s,i,a,c,d,p,l,u,f,h,m,b){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=d|0,this.El=p|0,this.Fh=l|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=m|0,this.Hl=b|0}process(e,r){for(let _=0;_<16;_++,r+=4)fo[_]=e.getUint32(r),po[_]=e.getUint32(r+=4);for(let _=16;_<80;_++){let T=fo[_-15]|0,N=po[_-15]|0,v=ye.rotrSH(T,N,1)^ye.rotrSH(T,N,8)^ye.shrSH(T,N,7),R=ye.rotrSL(T,N,1)^ye.rotrSL(T,N,8)^ye.shrSL(T,N,7),A=fo[_-2]|0,E=po[_-2]|0,S=ye.rotrSH(A,E,19)^ye.rotrBH(A,E,61)^ye.shrSH(A,E,6),V=ye.rotrSL(A,E,19)^ye.rotrBL(A,E,61)^ye.shrSL(A,E,6),C=ye.add4L(R,V,po[_-7],po[_-16]),g=ye.add4H(C,v,S,fo[_-7],fo[_-16]);fo[_]=g|0,po[_]=C|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:d,Dl:p,Eh:l,El:u,Fh:f,Fl:h,Gh:m,Gl:b,Hh:y,Hl:x}=this;for(let _=0;_<80;_++){let T=ye.rotrSH(l,u,14)^ye.rotrSH(l,u,18)^ye.rotrBH(l,u,41),N=ye.rotrSL(l,u,14)^ye.rotrSL(l,u,18)^ye.rotrBL(l,u,41),v=l&f^~l&m,R=u&h^~u&b,A=ye.add5L(x,N,R,N2[_],po[_]),E=ye.add5H(A,y,T,v,O2[_],fo[_]),S=A|0,V=ye.rotrSH(n,o,28)^ye.rotrBH(n,o,34)^ye.rotrBH(n,o,39),C=ye.rotrSL(n,o,28)^ye.rotrBL(n,o,34)^ye.rotrBL(n,o,39),g=n&s^n&a^s&a,w=o&i^o&c^i&c;y=m|0,x=b|0,m=f|0,b=h|0,f=l|0,h=u|0,{h:l,l:u}=ye.add(d|0,p|0,E|0,S|0),d=a|0,p=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let O=ye.add3L(S,C,w);n=ye.add3H(O,E,V,g),o=O|0}({h:n,l:o}=ye.add(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=ye.add(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=ye.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:p}=ye.add(this.Dh|0,this.Dl|0,d|0,p|0),{h:l,l:u}=ye.add(this.Eh|0,this.El|0,l|0,u|0),{h:f,l:h}=ye.add(this.Fh|0,this.Fl|0,f|0,h|0),{h:m,l:b}=ye.add(this.Gh|0,this.Gl|0,m|0,b|0),{h:y,l:x}=ye.add(this.Hh|0,this.Hl|0,y|0,x|0),this.set(n,o,s,i,a,c,d,p,l,u,f,h,m,b,y,x)}roundClean(){(0,Qe.clean)(fo,po)}destroy(){(0,Qe.clean)(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};Le.SHA512=zo;var Mc=class extends zo{constructor(){super(48),this.Ah=Q.SHA384_IV[0]|0,this.Al=Q.SHA384_IV[1]|0,this.Bh=Q.SHA384_IV[2]|0,this.Bl=Q.SHA384_IV[3]|0,this.Ch=Q.SHA384_IV[4]|0,this.Cl=Q.SHA384_IV[5]|0,this.Dh=Q.SHA384_IV[6]|0,this.Dl=Q.SHA384_IV[7]|0,this.Eh=Q.SHA384_IV[8]|0,this.El=Q.SHA384_IV[9]|0,this.Fh=Q.SHA384_IV[10]|0,this.Fl=Q.SHA384_IV[11]|0,this.Gh=Q.SHA384_IV[12]|0,this.Gl=Q.SHA384_IV[13]|0,this.Hh=Q.SHA384_IV[14]|0,this.Hl=Q.SHA384_IV[15]|0}};Le.SHA384=Mc;var vt=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),Rt=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]),kc=class extends zo{constructor(){super(28),this.Ah=vt[0]|0,this.Al=vt[1]|0,this.Bh=vt[2]|0,this.Bl=vt[3]|0,this.Ch=vt[4]|0,this.Cl=vt[5]|0,this.Dh=vt[6]|0,this.Dl=vt[7]|0,this.Eh=vt[8]|0,this.El=vt[9]|0,this.Fh=vt[10]|0,this.Fl=vt[11]|0,this.Gh=vt[12]|0,this.Gl=vt[13]|0,this.Hh=vt[14]|0,this.Hl=vt[15]|0}};Le.SHA512_224=kc;var jc=class extends zo{constructor(){super(32),this.Ah=Rt[0]|0,this.Al=Rt[1]|0,this.Bh=Rt[2]|0,this.Bl=Rt[3]|0,this.Ch=Rt[4]|0,this.Cl=Rt[5]|0,this.Dh=Rt[6]|0,this.Dl=Rt[7]|0,this.Eh=Rt[8]|0,this.El=Rt[9]|0,this.Fh=Rt[10]|0,this.Fl=Rt[11]|0,this.Gh=Rt[12]|0,this.Gl=Rt[13]|0,this.Hh=Rt[14]|0,this.Hl=Rt[15]|0}};Le.SHA512_256=jc;Le.sha256=(0,Qe.createHasher)(()=>new ea);Le.sha224=(0,Qe.createHasher)(()=>new qc);Le.sha512=(0,Qe.createHasher)(()=>new zo);Le.sha384=(0,Qe.createHasher)(()=>new Mc);Le.sha512_256=(0,Qe.createHasher)(()=>new jc);Le.sha512_224=(0,Qe.createHasher)(()=>new kc)});var Qm=Y($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.Principal=$r.JSON_KEY_PRINCIPAL=void 0;var Wm=ym(),v2=Il(),R2=Gs(),Xm=dt();$r.JSON_KEY_PRINCIPAL="__principal__";var I2=2,Jm=4,S2="aaaaa-aa",Vl=class t{static anonymous(){return new this(new Uint8Array([Jm]))}static managementCanister(){return this.fromText(S2)}static selfAuthenticating(e){let r=(0,R2.sha224)(e);return new this(new Uint8Array([...r,I2]))}static from(e){if(typeof e=="string")return t.fromText(e);if(Object.getPrototypeOf(e)===Uint8Array.prototype)return new t(e);if(t.isPrincipal(e))return new t(e._arr);throw new Error(`Impossible to convert ${JSON.stringify(e)} to Principal.`)}static fromHex(e){return new this((0,Xm.hexToBytes)(e))}static fromText(e){let r=e;if(e.includes($r.JSON_KEY_PRINCIPAL)){let i=JSON.parse(e);$r.JSON_KEY_PRINCIPAL in i&&(r=i[$r.JSON_KEY_PRINCIPAL])}let n=r.toLowerCase().replace(/-/g,""),o=(0,Wm.decode)(n);o=o.slice(4,o.length);let s=new this(o);if(s.toText()!==r)throw new Error(`Principal "${s.toText()}" does not have a valid checksum (original value "${r}" may not be a valid Principal ID).`);return s}static fromUint8Array(e){return new this(e)}static isPrincipal(e){return e instanceof t||typeof e=="object"&&e!==null&&"_isPrincipal"in e&&e._isPrincipal===!0&&"_arr"in e&&e._arr instanceof Uint8Array}constructor(e){this._arr=e,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===Jm}toUint8Array(){return this._arr}toHex(){return(0,Xm.bytesToHex)(this._arr).toUpperCase()}toText(){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,(0,v2.getCrc32)(this._arr));let n=new Uint8Array(e),o=new Uint8Array([...n,...this._arr]),i=(0,Wm.encode)(o).match(/.{1,5}/g);if(!i)throw new Error;return i.join("-")}toString(){return this.toText()}toJSON(){return{[$r.JSON_KEY_PRINCIPAL]:this.toText()}}compareTo(e){for(let r=0;r<Math.min(this._arr.length,e._arr.length);r++){if(this._arr[r]<e._arr[r])return"lt";if(this._arr[r]>e._arr[r])return"gt"}return this._arr.length<e._arr.length?"lt":this._arr.length>e._arr.length?"gt":"eq"}ltEq(e){let r=this.compareTo(e);return r=="lt"||r=="eq"}gtEq(e){let r=this.compareTo(e);return r=="gt"||r=="eq"}};$r.Principal=Vl});var Rr=Y(Tn=>{"use strict";var A2=Tn&&Tn.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),B2=Tn&&Tn.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&A2(e,t,r)};Object.defineProperty(Tn,"__esModule",{value:!0});Tn.getCrc32=void 0;B2(Qm(),Tn);var C2=Il();Object.defineProperty(Tn,"getCrc32",{enumerable:!0,get:function(){return C2.getCrc32}})});var ar=Y(k=>{"use strict";Object.defineProperty(k,"__esModule",{value:!0});k.UNREACHABLE_ERROR=k.ExpiryJsonDeserializeErrorCode=k.InvalidReadStateRequestErrorCode=k.MissingCanisterIdErrorCode=k.HttpFetchErrorCode=k.HttpV3ApiNotSupportedErrorCode=k.HttpErrorCode=k.HashTreeDecodeErrorCode=k.UnexpectedErrorCode=k.QuerySignatureVerificationFailedErrorCode=k.MalformedPublicKeyErrorCode=k.MissingSignatureErrorCode=k.MalformedSignatureErrorCode=k.CreateHttpAgentErrorCode=k.IngressExpiryInvalidErrorCode=k.IdentityInvalidErrorCode=k.HttpDefaultFetchErrorCode=k.HashValueErrorCode=k.MissingRootKeyErrorCode=k.RequestStatusDoneNoReplyErrorCode=k.UncertifiedRejectUpdateErrorCode=k.UncertifiedRejectErrorCode=k.CertifiedRejectErrorCode=k.CertificateOutdatedErrorCode=k.TimeoutWaitingForResponseErrorCode=k.HexDecodeErrorCode=k.CborEncodeErrorCode=k.CborDecodeErrorCode=k.DerEncodeErrorCode=k.DerDecodeErrorCode=k.DerDecodeLengthMismatchErrorCode=k.DerPrefixMismatchErrorCode=k.DerKeyLengthMismatchErrorCode=k.MissingLookupValueErrorCode=k.MalformedLookupFoundValueErrorCode=k.LookupErrorCode=k.CertificateNotAuthorizedErrorCode=k.CertificateHasTooManyDelegationsErrorCode=k.CertificateTimeErrorCode=k.CertificateVerificationErrorCode=k.UnknownError=k.InputError=k.LimitError=k.ExternalError=k.TransportError=k.RejectError=k.ProtocolError=k.TrustError=k.AgentError=k.ErrorKindEnum=void 0;var hr=dt(),Kr;(function(t){t.Trust="Trust",t.Protocol="Protocol",t.Reject="Reject",t.Transport="Transport",t.External="External",t.Limit="Limit",t.Input="Input",t.Unknown="Unknown"})(Kr||(k.ErrorKindEnum=Kr={}));var pe=class{constructor(e=!1){this.isCertified=e}toString(){let e=this.toErrorMessage();return this.requestContext&&(e+=`
3
+ var Fp=Object.defineProperty;var Vp=(e,t)=>{for(var r in t)Fp(e,r,{get:t[r],enumerable:!0})};var qc;(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"})(qc||(qc={}));var hr;(function(e){e.Replied="replied",e.Rejected="rejected"})(hr||(hr={}));function Mc(e){return e!=null&&"reject_code"in e}function jc(e){return e!=null&&"certificate"in e}var li="abcdefghijklmnopqrstuvwxyz234567",Pn=Object.create(null);for(let e=0;e<li.length;e++)Pn[li[e]]=e;Pn[0]=Pn.o;Pn[1]=Pn.i;function Kc(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+=li[r>>3],t+=5),0)}for(let i=0;i<e.length;)i+=o(e[i]);return n+(t<0?li[r>>3]:"")}function Hc(e){let t=0,r=0,n=new Uint8Array(e.length*4/3|0),o=0;function i(s){let a=Pn[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 Cp=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 $c(e){let t=-1;for(let r=0;r<e.length;r++){let o=(e[r]^t)&255;t=Cp[o]^t>>>8}return(t^-1)>>>0}import*as jt from"node:crypto";var ln=jt&&typeof jt=="object"&&"webcrypto"in jt?jt.webcrypto:jt&&typeof jt=="object"&&"randomBytes"in jt?jt:void 0;function Ot(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Us(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function fe(e,...t){if(!Ot(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 ks(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 Jc(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 un(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function di(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ft(e,t){return e<<32-t|e>>>t}var zc=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Pp=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function H(e){if(fe(e),zc)return e.toHex();let t="";for(let r=0;r<e.length;r++)t+=Pp[e[r]];return t}var Kt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Gc(e){if(e>=Kt._0&&e<=Kt._9)return e-Kt._0;if(e>=Kt.A&&e<=Kt.F)return e-(Kt.A-10);if(e>=Kt.a&&e<=Kt.f)return e-(Kt.a-10)}function Ne(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(zc)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=Gc(e.charCodeAt(i)),a=Gc(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 ee(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function Ls(e){return typeof e=="string"&&(e=ee(e)),fe(e),e}function j(...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 ui=class{};function pi(e){let t=n=>e().update(Ls(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Bn(e=32){if(ln&&typeof ln.getRandomValues=="function")return ln.getRandomValues(new Uint8Array(e));if(ln&&typeof ln.randomBytes=="function")return Uint8Array.from(ln.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Bp(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 Wc(e,t,r){return e&t^~e&r}function Yc(e,t,r){return e&t^e&r^t&r}var mo=class extends ui{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=di(this.buffer)}update(t){ks(this),t=Ls(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=di(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){ks(this),Jc(t,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:i}=this,{pos:s}=this;r[s++]=128,un(this.buffer.subarray(s)),this.padOffset>o-s&&(this.process(n,0),s=0);for(let d=s;d<o;d++)r[d]=0;Bp(n,o-8,BigInt(this.length*8),i),this.process(n,0);let a=di(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()}},Ht=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),$t=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var ve=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var fi=BigInt(4294967295),Zc=BigInt(32);function Dp(e,t=!1){return t?{h:Number(e&fi),l:Number(e>>Zc&fi)}:{h:Number(e>>Zc&fi)|0,l:Number(e&fi)|0}}function Xc(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}=Dp(e[i],t);[n[i],o[i]]=[s,a]}return[n,o]}var qs=(e,t,r)=>e>>>r,Ms=(e,t,r)=>e<<32-r|t>>>r,dn=(e,t,r)=>e>>>r|t<<32-r,pn=(e,t,r)=>e<<32-r|t>>>r,_o=(e,t,r)=>e<<64-r|t>>>r-32,yo=(e,t,r)=>e>>>r-32|t<<64-r;function Et(e,t,r,n){let o=(t>>>0)+(n>>>0);return{h:e+r+(o/2**32|0)|0,l:o|0}}var Qc=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),el=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,tl=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),rl=(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 kp=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]),mr=new Uint32Array(64),hi=class extends mo{constructor(t=32){super(64,t,8,!1),this.A=Ht[0]|0,this.B=Ht[1]|0,this.C=Ht[2]|0,this.D=Ht[3]|0,this.E=Ht[4]|0,this.F=Ht[5]|0,this.G=Ht[6]|0,this.H=Ht[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)mr[d]=t.getUint32(r,!1);for(let d=16;d<64;d++){let l=mr[d-15],f=mr[d-2],h=ft(l,7)^ft(l,18)^l>>>3,m=ft(f,17)^ft(f,19)^f>>>10;mr[d]=m+mr[d-7]+h+mr[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=ft(a,6)^ft(a,11)^ft(a,25),f=p+l+Wc(a,c,u)+kp[d]+mr[d]|0,m=(ft(n,2)^ft(n,13)^ft(n,22))+Yc(n,o,i)|0;p=u,u=c,c=a,a=s+f|0,s=i,i=o,o=n,n=f+m|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(){un(mr)}destroy(){this.set(0,0,0,0,0,0,0,0),un(this.buffer)}},js=class extends hi{constructor(){super(28),this.A=$t[0]|0,this.B=$t[1]|0,this.C=$t[2]|0,this.D=$t[3]|0,this.E=$t[4]|0,this.F=$t[5]|0,this.G=$t[6]|0,this.H=$t[7]|0}},il=Xc(["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))),Lp=il[0],qp=il[1],_r=new Uint32Array(80),yr=new Uint32Array(80),Ks=class extends mo{constructor(t=64){super(128,t,16,!1),this.Ah=ve[0]|0,this.Al=ve[1]|0,this.Bh=ve[2]|0,this.Bl=ve[3]|0,this.Ch=ve[4]|0,this.Cl=ve[5]|0,this.Dh=ve[6]|0,this.Dl=ve[7]|0,this.Eh=ve[8]|0,this.El=ve[9]|0,this.Fh=ve[10]|0,this.Fl=ve[11]|0,this.Gh=ve[12]|0,this.Gl=ve[13]|0,this.Hh=ve[14]|0,this.Hl=ve[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:m,Hl:g}=this;return[t,r,n,o,i,s,a,c,u,p,d,l,f,h,m,g]}set(t,r,n,o,i,s,a,c,u,p,d,l,f,h,m,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=m|0,this.Hl=g|0}process(t,r){for(let y=0;y<16;y++,r+=4)_r[y]=t.getUint32(r),yr[y]=t.getUint32(r+=4);for(let y=16;y<80;y++){let T=_r[y-15]|0,E=yr[y-15]|0,O=dn(T,E,1)^dn(T,E,8)^qs(T,E,7),R=pn(T,E,1)^pn(T,E,8)^Ms(T,E,7),I=_r[y-2]|0,w=yr[y-2]|0,v=dn(I,w,19)^_o(I,w,61)^qs(I,w,6),V=pn(I,w,19)^yo(I,w,61)^Ms(I,w,6),S=tl(R,V,yr[y-7],yr[y-16]),b=rl(S,O,v,_r[y-7],_r[y-16]);_r[y]=b|0,yr[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:m,Gl:g,Hh:_,Hl:x}=this;for(let y=0;y<80;y++){let T=dn(d,l,14)^dn(d,l,18)^_o(d,l,41),E=pn(d,l,14)^pn(d,l,18)^yo(d,l,41),O=d&f^~d&m,R=l&h^~l&g,I=nl(x,E,R,qp[y],yr[y]),w=ol(I,_,T,O,Lp[y],_r[y]),v=I|0,V=dn(n,o,28)^_o(n,o,34)^_o(n,o,39),S=pn(n,o,28)^yo(n,o,34)^yo(n,o,39),b=n&i^n&a^i&a,N=o&s^o&c^s&c;_=m|0,x=g|0,m=f|0,g=h|0,f=d|0,h=l|0,{h:d,l}=Et(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=Qc(v,S,N);n=el(F,w,V,b),o=F|0}({h:n,l:o}=Et(this.Ah|0,this.Al|0,n|0,o|0)),{h:i,l:s}=Et(this.Bh|0,this.Bl|0,i|0,s|0),{h:a,l:c}=Et(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:p}=Et(this.Dh|0,this.Dl|0,u|0,p|0),{h:d,l}=Et(this.Eh|0,this.El|0,d|0,l|0),{h:f,l:h}=Et(this.Fh|0,this.Fl|0,f|0,h|0),{h:m,l:g}=Et(this.Gh|0,this.Gl|0,m|0,g|0),{h:_,l:x}=Et(this.Hh|0,this.Hl|0,_|0,x|0),this.set(n,o,i,s,a,c,u,p,d,l,f,h,m,g,_,x)}roundClean(){un(_r,yr)}destroy(){un(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Se=pi(()=>new hi),sl=pi(()=>new js),al=pi(()=>new Ks);var mi="__principal__",Mp=2,cl=4,jp="aaaaa-aa",M=class e{static anonymous(){return new this(new Uint8Array([cl]))}static managementCanister(){return this.fromText(jp)}static selfAuthenticating(t){let r=sl(t);return new this(new Uint8Array([...r,Mp]))}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(Ne(t))}static fromText(t){let r=t;if(t.includes(mi)){let s=JSON.parse(t);mi in s&&(r=s[mi])}let n=r.toLowerCase().replace(/-/g,""),o=Hc(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]===cl}toUint8Array(){return this._arr}toHex(){return H(this._arr).toUpperCase()}toText(){let t=new ArrayBuffer(4);new DataView(t).setUint32(0,$c(this._arr));let n=new Uint8Array(t),o=new Uint8Array([...n,...this._arr]),s=Kc(o).match(/.{1,5}/g);if(!s)throw new Error;return s.join("-")}toString(){return this.toText()}toJSON(){return{[mi]: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 Gt;(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"})(Gt||(Gt={}));var G=class{constructor(t=!1){this.isCertified=t}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`
4
4
  Request context:
5
- Request ID (hex): ${this.requestContext.requestId?(0,hr.bytesToHex)(this.requestContext.requestId):"undefined"}
6
- Sender pubkey (hex): ${(0,hr.bytesToHex)(this.requestContext.senderPubKey)}
7
- Sender signature (hex): ${(0,hr.bytesToHex)(this.requestContext.senderSignature)}
8
- Ingress expiry: ${this.requestContext.ingressExpiry.toString()}`),this.callContext&&(e+=`
5
+ Request ID (hex): ${this.requestContext.requestId?H(this.requestContext.requestId):"undefined"}
6
+ Sender pubkey (hex): ${H(this.requestContext.senderPubKey)}
7
+ Sender signature (hex): ${H(this.requestContext.senderSignature)}
8
+ Ingress expiry: ${this.requestContext.ingressExpiry.toString()}`),this.callContext&&(t+=`
9
9
  Call context:
10
10
  Canister ID: ${this.callContext.canisterId.toText()}
11
11
  Method name: ${this.callContext.methodName}
12
- HTTP details: ${JSON.stringify(this.callContext.httpDetails,null,2)}`),e}},Hc=class t extends Error{get code(){return this.cause.code}set code(e){this.cause.code=e}get kind(){return this.cause.kind}set kind(e){this.cause.kind=e}get isCertified(){return this.code.isCertified}constructor(e,r){super(e.toString()),this.name="AgentError",this.cause={code:e,kind:r},Object.setPrototypeOf(this,t.prototype)}hasCode(e){return this.code instanceof e}toString(){return`${this.name} (${this.kind}): ${this.message}`}};k.AgentError=Hc;var Gr=class extends Hc{static fromCode(e){return new this(e)}},Ul=class t extends Gr{constructor(e){super(e,Kr.Trust),this.name="TrustError",Object.setPrototypeOf(this,t.prototype)}};k.TrustError=Ul;var Ll=class t extends Gr{constructor(e){super(e,Kr.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,t.prototype)}};k.ProtocolError=Ll;var ql=class t extends Gr{constructor(e){super(e,Kr.Reject),this.name="RejectError",Object.setPrototypeOf(this,t.prototype)}};k.RejectError=ql;var Ml=class t extends Gr{constructor(e){super(e,Kr.Transport),this.name="TransportError",Object.setPrototypeOf(this,t.prototype)}};k.TransportError=Ml;var kl=class t extends Gr{constructor(e){super(e,Kr.External),this.name="ExternalError",Object.setPrototypeOf(this,t.prototype)}};k.ExternalError=kl;var jl=class t extends Gr{constructor(e){super(e,Kr.Limit),this.name="LimitError",Object.setPrototypeOf(this,t.prototype)}};k.LimitError=jl;var Hl=class t extends Gr{constructor(e){super(e,Kr.Input),this.name="InputError",Object.setPrototypeOf(this,t.prototype)}};k.InputError=Hl;var $l=class t extends Gr{constructor(e){super(e,Kr.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,t.prototype)}};k.UnknownError=$l;var Kl=class t extends pe{constructor(e,r){super(),this.reason=e,this.error=r,this.name="CertificateVerificationErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){let e=this.reason;return this.error&&(e+=`: ${ta(this.error)}`),`Certificate verification error: "${e}"`}};k.CertificateVerificationErrorCode=Kl;var Gl=class t extends pe{constructor(e,r,n,o,s){super(),this.maxAgeInMinutes=e,this.certificateTime=r,this.currentTime=n,this.timeDiffMsecs=o,this.ageType=s,this.name="CertificateTimeErrorCode",Object.setPrototypeOf(this,t.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`}};k.CertificateTimeErrorCode=Gl;var zl=class t extends pe{constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"Certificate has too many delegations"}};k.CertificateHasTooManyDelegationsErrorCode=zl;var Zl=class t extends pe{constructor(e,r){super(),this.canisterId=e,this.subnetId=r,this.name="CertificateNotAuthorizedErrorCode",Object.setPrototypeOf(this,t.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()}`}};k.CertificateNotAuthorizedErrorCode=Zl;var Yl=class t extends pe{constructor(e,r){super(),this.message=e,this.lookupStatus=r,this.name="LookupErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}};k.LookupErrorCode=Yl;var Wl=class t extends pe{constructor(e){super(),this.message=e,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return this.message}};k.MalformedLookupFoundValueErrorCode=Wl;var Xl=class t extends pe{constructor(e){super(),this.message=e,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return this.message}};k.MissingLookupValueErrorCode=Xl;var Jl=class t extends pe{constructor(e,r){super(),this.expectedLength=e,this.actualLength=r,this.name="DerKeyLengthMismatchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}};k.DerKeyLengthMismatchErrorCode=Jl;var Ql=class t extends pe{constructor(e,r){super(),this.expectedPrefix=e,this.actualPrefix=r,this.name="DerPrefixMismatchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${(0,hr.bytesToHex)(this.expectedPrefix)}, but got ${(0,hr.bytesToHex)(this.actualPrefix)}`}};k.DerPrefixMismatchErrorCode=Ql;var ef=class t extends pe{constructor(e,r){super(),this.expectedLength=e,this.actualLength=r,this.name="DerDecodeLengthMismatchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}};k.DerDecodeLengthMismatchErrorCode=ef;var tf=class t extends pe{constructor(e){super(),this.error=e,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}};k.DerDecodeErrorCode=tf;var rf=class t extends pe{constructor(e){super(),this.error=e,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}};k.DerEncodeErrorCode=rf;var nf=class t extends pe{constructor(e,r){super(),this.error=e,this.input=r,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${ta(this.error)}, input: ${(0,hr.bytesToHex)(this.input)}`}};k.CborDecodeErrorCode=nf;var of=class t extends pe{constructor(e,r){super(),this.error=e,this.value=r,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${ta(this.error)}, input: ${this.value}`}};k.CborEncodeErrorCode=of;var sf=class t extends pe{constructor(e){super(),this.error=e,this.name="HexDecodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to decode hex: ${this.error}`}};k.HexDecodeErrorCode=sf;var af=class t extends pe{constructor(e,r,n){super(),this.message=e,this.requestId=r,this.status=n,this.name="TimeoutWaitingForResponseErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){let e=`${this.message}
13
- `;return this.requestId&&(e+=` Request ID: ${(0,hr.bytesToHex)(this.requestId)}
14
- `),this.status&&(e+=` Request status: ${this.status}
15
- `),e}};k.TimeoutWaitingForResponseErrorCode=af;var cf=class t extends pe{constructor(e,r,n){super(),this.maxIngressExpiryInMinutes=e,this.requestId=r,this.retryTimes=n,this.name="CertificateOutdatedErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){let e=`Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?
16
- Request ID: ${(0,hr.bytesToHex)(this.requestId)}
17
- `;return this.retryTimes!==void 0&&(e+=` Retried ${this.retryTimes} times.`),e}};k.CertificateOutdatedErrorCode=cf;var uf=class t extends pe{constructor(e,r,n,o){super(!0),this.requestId=e,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="CertifiedRejectErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`The replica returned a rejection error:
18
- Request ID: ${(0,hr.bytesToHex)(this.requestId)}
12
+ HTTP details: ${JSON.stringify(this.callContext.httpDetails,null,2)}`),t}},ht=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}`}},Jt=class extends ht{static fromCode(t){return new this(t)}},Pe=class e extends Jt{constructor(t){super(t,Gt.Trust),this.name="TrustError",Object.setPrototypeOf(this,e.prototype)}},ne=class e extends Jt{constructor(t){super(t,Gt.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,e.prototype)}},gr=class e extends Jt{constructor(t){super(t,Gt.Reject),this.name="RejectError",Object.setPrototypeOf(this,e.prototype)}},go=class e extends Jt{constructor(t){super(t,Gt.Transport),this.name="TransportError",Object.setPrototypeOf(this,e.prototype)}},Oe=class e extends Jt{constructor(t){super(t,Gt.External),this.name="ExternalError",Object.setPrototypeOf(this,e.prototype)}};var z=class e extends Jt{constructor(t){super(t,Gt.Input),this.name="InputError",Object.setPrototypeOf(this,e.prototype)}},ge=class e extends Jt{constructor(t){super(t,Gt.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,e.prototype)}},xr=class e extends G{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+=`: ${Eo(this.error)}`),`Certificate verification error: "${t}"`}},fn=class e extends G{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`}},_i=class e extends G{constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Certificate has too many delegations"}},Dn=class e extends G{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()}`}},zt=class e extends G{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}`}},Un=class e extends G{constructor(t){super(),this.message=t,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},yi=class e extends G{constructor(t){super(),this.message=t,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.message}},kn=class e extends G{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`}},gi=class e extends G{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: ${H(this.expectedPrefix)}, but got ${H(this.actualPrefix)}`}},xi=class e extends G{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}`}},mt=class e extends G{constructor(t){super(),this.error=t,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},xo=class e extends G{constructor(t){super(),this.error=t,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},bi=class e extends G{constructor(t,r){super(),this.error=t,this.input=r,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${Eo(this.error)}, input: ${H(this.input)}`}},wi=class e extends G{constructor(t,r){super(),this.error=t,this.value=r,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${Eo(this.error)}, input: ${this.value}`}};var hn=class e extends G{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}
13
+ `;return this.requestId&&(t+=` Request ID: ${H(this.requestId)}
14
+ `),this.status&&(t+=` Request status: ${this.status}
15
+ `),t}},Ti=class e extends G{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?
16
+ Request ID: ${H(this.requestId)}
17
+ `;return this.retryTimes!==void 0&&(t+=` Retried ${this.retryTimes} times.`),t}},Ln=class e extends G{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:
18
+ Request ID: ${H(this.requestId)}
19
19
  Reject code: ${this.rejectCode}
20
20
  Reject text: ${this.rejectMessage}
21
21
  Error code: ${this.rejectErrorCode}
22
- `}};k.CertifiedRejectErrorCode=uf;var df=class t extends pe{constructor(e,r,n,o,s){super(),this.requestId=e,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.signatures=s,this.name="UncertifiedRejectErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`The replica returned a rejection error:
23
- Request ID: ${(0,hr.bytesToHex)(this.requestId)}
22
+ `}},Ni=class e extends G{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:
23
+ Request ID: ${H(this.requestId)}
24
24
  Reject code: ${this.rejectCode}
25
25
  Reject text: ${this.rejectMessage}
26
26
  Error code: ${this.rejectErrorCode}
27
- `}};k.UncertifiedRejectErrorCode=df;var lf=class t extends pe{constructor(e,r,n,o){super(),this.requestId=e,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="UncertifiedRejectUpdateErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`The replica returned a rejection error:
28
- Request ID: ${(0,hr.bytesToHex)(this.requestId)}
27
+ `}},Oi=class e extends G{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:
28
+ Request ID: ${H(this.requestId)}
29
29
  Reject code: ${this.rejectCode}
30
30
  Reject text: ${this.rejectMessage}
31
31
  Error code: ${this.rejectErrorCode}
32
- `}};k.UncertifiedRejectUpdateErrorCode=lf;var ff=class t extends pe{constructor(e){super(),this.requestId=e,this.name="RequestStatusDoneNoReplyErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Call was marked as done but we never saw the reply:
33
- Request ID: ${(0,hr.bytesToHex)(this.requestId)}
34
- `}};k.RequestStatusDoneNoReplyErrorCode=ff;var pf=class t extends pe{constructor(e){super(),this.shouldFetchRootKey=e,this.name="MissingRootKeyErrorCode",Object.setPrototypeOf(this,t.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.`}};k.MissingRootKeyErrorCode=pf;var hf=class t extends pe{constructor(e){super(),this.value=e,this.name="HashValueErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}};k.HashValueErrorCode=hf;var mf=class t extends pe{constructor(e){super(),this.error=e,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return this.error}};k.HttpDefaultFetchErrorCode=mf;var yf=class t extends pe{constructor(){super(),this.name="IdentityInvalidErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"This identity has expired due this application's security policy. Please refresh your authentication."}};k.IdentityInvalidErrorCode=yf;var _f=class t extends pe{constructor(e,r){super(),this.message=e,this.providedIngressExpiryInMinutes=r,this.name="IngressExpiryInvalidErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}};k.IngressExpiryInvalidErrorCode=_f;var bf=class t extends pe{constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}};k.CreateHttpAgentErrorCode=bf;var gf=class t extends pe{constructor(e){super(),this.error=e,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}};k.MalformedSignatureErrorCode=gf;var xf=class t extends pe{constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}};k.MissingSignatureErrorCode=xf;var wf=class t extends pe{constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}};k.MalformedPublicKeyErrorCode=wf;var Ef=class t extends pe{constructor(e){super(),this.nodeId=e,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}};k.QuerySignatureVerificationFailedErrorCode=Ef;var Tf=class t extends pe{constructor(e){super(),this.error=e,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Unexpected error: ${ta(this.error)}`}};k.UnexpectedErrorCode=Tf;var Of=class t extends pe{constructor(e){super(),this.error=e,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}};k.HashTreeDecodeErrorCode=Of;var Nf=class t extends pe{constructor(e,r,n,o){super(),this.status=e,this.statusText=r,this.headers=n,this.bodyText=o,this.name="HttpErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){let e=`HTTP request failed:
32
+ `}},Ei=class e extends G{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:
33
+ Request ID: ${H(this.requestId)}
34
+ `}},Rt=class e extends G{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.`}},Ri=class e extends G{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}`}},qn=class e extends G{constructor(t){super(),this.error=t,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return this.error}},br=class e extends G{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."}},mn=class e extends G{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.`}},vi=class e extends G{constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}},Ii=class e extends G{constructor(t){super(),this.error=t,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},Ai=class e extends G{constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}},Si=class e extends G{constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}},Fi=class e extends G{constructor(t){super(),this.nodeId=t,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},Be=class e extends G{constructor(t){super(),this.error=t,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Unexpected error: ${Eo(this.error)}`}},wr=class e extends G{constructor(t){super(),this.error=t,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},bo=class e extends G{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:
35
35
  Status: ${this.status} (${this.statusText})
36
36
  Headers: ${JSON.stringify(this.headers)}
37
- `;return this.bodyText&&(e+=` Body: ${this.bodyText}
38
- `),e}};k.HttpErrorCode=Nf;var vf=class t extends pe{constructor(){super(),this.name="HttpV3ApiNotSupportedErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"HTTP request failed: v3 API is not supported"}};k.HttpV3ApiNotSupportedErrorCode=vf;var Rf=class t extends pe{constructor(e){super(),this.error=e,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${ta(this.error)}`}};k.HttpFetchErrorCode=Rf;var If=class t extends pe{constructor(e){super(),this.receivedCanisterId=e,this.name="MissingCanisterIdErrorCode",Object.setPrototypeOf(this,t.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.`}};k.MissingCanisterIdErrorCode=If;var Sf=class t extends pe{constructor(e){super(),this.request=e,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}};k.InvalidReadStateRequestErrorCode=Sf;var Af=class t extends pe{constructor(e){super(),this.error=e,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};k.ExpiryJsonDeserializeErrorCode=Af;function ta(t){if(t instanceof Error)return t.stack??t.message;try{return JSON.stringify(t)}catch{return String(t)}}k.UNREACHABLE_ERROR=new Error("unreachable")});var $c=Y(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.PipeArrayBuffer=void 0;On.concat=P2;On.uint8FromBufLike=Cf;On.compare=ey;On.uint8Equals=D2;On.uint8ToDataView=F2;function P2(...t){let e=new Uint8Array(t.reduce((n,o)=>n+o.byteLength,0)),r=0;for(let n of t)e.set(n,r),r+=n.byteLength;return e}var Bf=class{save(){return this._view}restore(e){if(!(e instanceof Uint8Array))throw new Error("Checkpoint must be a Uint8Array");this._view=e}constructor(e,r=e?.byteLength||0){if(e&&!(e instanceof Uint8Array))try{e=Cf(e)}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(e&&r>e.byteLength)throw new Error("Length cannot exceed buffer length");this._buffer=e||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(e){let r=this._view.subarray(0,e);return this._view=this._view.subarray(e),r.slice()}readUint8(){if(this._view.byteLength===0)return;let e=this._view[0];return this._view=this._view.subarray(1),e}write(e){if(!(e instanceof Uint8Array))throw new Error("Buffer must be a Uint8Array");let r=this._view.byteLength;this._view.byteOffset+this._view.byteLength+e.byteLength>=this._buffer.byteLength?this.alloc(e.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+e.byteLength),this._view.set(e,r)}get end(){return this._view.byteLength===0}alloc(e){if(e<=0||!Number.isInteger(e))throw new Error("Amount must be a positive integer");let r=new Uint8Array((this._buffer.byteLength+e)*1.2|0),n=new Uint8Array(r.buffer,0,this._view.byteLength+e);n.set(this._view),this._buffer=r,this._view=n}};On.PipeArrayBuffer=Bf;function Cf(t){if(!t)throw new Error("Input cannot be null or undefined");return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):Array.isArray(t)?new Uint8Array(t):"buffer"in t?Cf(t.buffer):new Uint8Array(t)}function ey(t,e){if(t.byteLength!==e.byteLength)return t.byteLength-e.byteLength;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]-e[r];return 0}function D2(t,e){return ey(t,e)===0}function F2(t){if(!(t instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(t.buffer,t.byteOffset,t.byteLength)}});var Df=Y(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});Pf.idlLabelToId=U2;function V2(t){let r=new TextEncoder().encode(t),n=0;for(let o of r)n=(n*223+o)%2**32;return n}function U2(t){if(/^_\d+_$/.test(t)||/^_0x[0-9a-fA-F]+_$/.test(t)){let e=+t.slice(1,-1);if(Number.isSafeInteger(e)&&e>=0&&e<2**32)return e}return V2(t)}});var Ff=Y(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});Kc.ilog2=L2;Kc.iexp2=q2;function L2(t){let e=BigInt(t);if(t<=0)throw new RangeError("Input must be positive");return e.toString(2).length-1}function q2(t){let e=BigInt(t);if(t<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<e}});var Uf=Y(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.safeRead=ny;mr.safeReadUint8=Gc;mr.lebEncode=M2;mr.lebDecode=oy;mr.slebEncode=k2;mr.slebDecode=j2;mr.writeUIntLE=H2;mr.writeIntLE=sy;mr.readUIntLE=iy;mr.readIntLE=$2;var Vf=$c(),ty=Ff();function ry(){throw new Error("unexpected end of buffer")}function ny(t,e){return t.byteLength<e&&ry(),t.read(e)}function Gc(t){let e=t.readUint8();return e===void 0&&ry(),e}function M2(t){if(typeof t=="number"&&(t=BigInt(t)),t<BigInt(0))throw new Error("Cannot leb encode negative values.");let e=(t===BigInt(0)?0:(0,ty.ilog2)(t))+1,r=new Vf.PipeArrayBuffer(new Uint8Array(e),0);for(;;){let n=Number(t&BigInt(127));if(t/=BigInt(128),t===BigInt(0)){r.write(new Uint8Array([n]));break}else r.write(new Uint8Array([n|128]))}return r.buffer}function oy(t){let e=BigInt(1),r=BigInt(0),n;do n=Gc(t),r+=BigInt(n&127).valueOf()*e,e*=BigInt(128);while(n>=128);return r}function k2(t){typeof t=="number"&&(t=BigInt(t));let e=t<BigInt(0);e&&(t=-t-BigInt(1));let r=(t===BigInt(0)?0:(0,ty.ilog2)(t))+1,n=new Vf.PipeArrayBuffer(new Uint8Array(r),0);for(;;){let s=o(t);if(t/=BigInt(128),e&&t===BigInt(0)&&(s&64)!==0||!e&&t===BigInt(0)&&(s&64)===0){n.write(new Uint8Array([s]));break}else n.write(new Uint8Array([s|128]))}function o(s){let i=s%BigInt(128);return Number(e?BigInt(128)-i-BigInt(1):i)}return n.buffer}function j2(t){let e=new Uint8Array(t.buffer),r=0;for(;r<e.byteLength;r++)if(e[r]<128){if((e[r]&64)===0)return oy(t);break}let n=new Uint8Array(ny(t,r+1)),o=BigInt(0);for(let s=n.byteLength-1;s>=0;s--)o=o*BigInt(128)+BigInt(128-(n[s]&127)-1);return-o-BigInt(1)}function H2(t,e){if(BigInt(t)<BigInt(0))throw new Error("Cannot write negative values.");return sy(t,e)}function sy(t,e){t=BigInt(t);let r=new Vf.PipeArrayBuffer(new Uint8Array(Math.min(1,e)),0),n=0,o=BigInt(256),s=BigInt(0),i=Number(t%o);for(r.write(new Uint8Array([i]));++n<e;)t<0&&s===BigInt(0)&&i!==0&&(s=BigInt(1)),i=Number((t/o-s)%BigInt(256)),r.write(new Uint8Array([i])),o*=BigInt(256);return r.buffer}function iy(t,e){if(e<=0||!Number.isInteger(e))throw new Error("Byte length must be a positive integer");let r=BigInt(Gc(t)),n=BigInt(1),o=0;for(;++o<e;){n*=BigInt(256);let s=BigInt(Gc(t));r=r+n*s}return r}function $2(t,e){if(e<=0||!Number.isInteger(e))throw new Error("Byte length must be a positive integer");let r=iy(t,e),n=BigInt(2)**(BigInt(8)*BigInt(e-1)+BigInt(7));return r>=n&&(r-=n*BigInt(2)),r}});var Kf=Y(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.Principal=M.Nat64=M.Nat32=M.Nat16=M.Nat8=M.Int64=M.Int32=M.Int16=M.Int8=M.Float64=M.Float32=M.Nat=M.Int=M.Text=M.Null=M.Bool=M.Unknown=M.Reserved=M.Empty=M.ServiceClass=M.FuncClass=M.PrincipalClass=M.RecClass=M.VariantClass=M.TupleClass=M.RecordClass=M.OptClass=M.VecClass=M.FixedNatClass=M.FixedIntClass=M.FloatClass=M.NatClass=M.IntClass=M.TextClass=M.ReservedClass=M.NullClass=M.BoolClass=M.UnknownClass=M.EmptyClass=M.ConstructType=M.PrimitiveType=M.Type=M.Visitor=void 0;M.encode=G2;M.decode=z2;M.Tuple=cy;M.Vec=uy;M.Opt=dy;M.Record=ly;M.Variant=fy;M.Rec=py;M.Func=hy;M.Service=my;M.resetSubtypeCache=jf;M.subtype=$f;var K2=Rr(),Te=$c(),Wt=Df(),$=Uf(),qf=Ff(),Se;(function(t){t[t.Null=-1]="Null",t[t.Bool=-2]="Bool",t[t.Nat=-3]="Nat",t[t.Int=-4]="Int",t[t.Float32=-13]="Float32",t[t.Float64=-14]="Float64",t[t.Text=-15]="Text",t[t.Reserved=-16]="Reserved",t[t.Empty=-17]="Empty",t[t.Opt=-18]="Opt",t[t.Vector=-19]="Vector",t[t.Record=-20]="Record",t[t.Variant=-21]="Variant",t[t.Func=-22]="Func",t[t.Service=-23]="Service",t[t.Principal=-24]="Principal"})(Se||(Se={}));var zc="DIDL",ay=400;function ra(t,e,r){return t.map((n,o)=>r(n,e[o]))}var Mf=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(e){return this._idx.has(e.name)}add(e,r){let n=this._typs.length;this._idx.set(e.name,n),this._idxRefCount.set(n,1),this._typs.push(r)}merge(e,r){let n=this._idx.get(e.name),o=this._idx.get(r);if(n===void 0)throw new Error("Missing type index for "+e);if(o===void 0)throw new Error("Missing type index for "+r);this._typs[n]=this._typs[o];let s=this._getIdxRefCount(o);this._idxRefCount.set(o,s-1),this._idx.delete(r),this._compactFromEnd()}_getIdxRefCount(e){return this._idxRefCount.get(e)||0}_compactFromEnd(){for(;this._typs.length>0;){let e=this._typs.length-1;if(this._getIdxRefCount(e)>0)break;this._typs.pop(),this._idxRefCount.delete(e)}}encode(){let e=(0,$.lebEncode)(this._typs.length),r=(0,Te.concat)(...this._typs);return(0,Te.concat)(e,r)}indexOf(e){if(!this._idx.has(e))throw new Error("Missing type index for "+e);return(0,$.slebEncode)(this._idx.get(e)||0)}},kf=class{visitType(e,r){throw new Error("Not implemented")}visitPrimitive(e,r){return this.visitType(e,r)}visitEmpty(e,r){return this.visitPrimitive(e,r)}visitBool(e,r){return this.visitPrimitive(e,r)}visitNull(e,r){return this.visitPrimitive(e,r)}visitReserved(e,r){return this.visitPrimitive(e,r)}visitText(e,r){return this.visitPrimitive(e,r)}visitNumber(e,r){return this.visitPrimitive(e,r)}visitInt(e,r){return this.visitNumber(e,r)}visitNat(e,r){return this.visitNumber(e,r)}visitFloat(e,r){return this.visitPrimitive(e,r)}visitFixedInt(e,r){return this.visitNumber(e,r)}visitFixedNat(e,r){return this.visitNumber(e,r)}visitPrincipal(e,r){return this.visitPrimitive(e,r)}visitConstruct(e,r){return this.visitType(e,r)}visitVec(e,r,n){return this.visitConstruct(e,n)}visitOpt(e,r,n){return this.visitConstruct(e,n)}visitRecord(e,r,n){return this.visitConstruct(e,n)}visitTuple(e,r,n){let o=r.map((s,i)=>[`_${i}_`,s]);return this.visitRecord(e,o,n)}visitVariant(e,r,n){return this.visitConstruct(e,n)}visitRec(e,r,n){return this.visitConstruct(r,n)}visitFunc(e,r){return this.visitConstruct(e,r)}visitService(e,r){return this.visitConstruct(e,r)}};M.Visitor=kf;var de;(function(t){t.EmptyClass="__IDL_EmptyClass__",t.UnknownClass="__IDL_UnknownClass__",t.BoolClass="__IDL_BoolClass__",t.NullClass="__IDL_NullClass__",t.ReservedClass="__IDL_ReservedClass__",t.TextClass="__IDL_TextClass__",t.IntClass="__IDL_IntClass__",t.NatClass="__IDL_NatClass__",t.FloatClass="__IDL_FloatClass__",t.FixedIntClass="__IDL_FixedIntClass__",t.FixedNatClass="__IDL_FixedNatClass__",t.VecClass="__IDL_VecClass__",t.OptClass="__IDL_OptClass__",t.RecordClass="__IDL_RecordClass__",t.TupleClass="__IDL_TupleClass__",t.VariantClass="__IDL_VariantClass__",t.RecClass="__IDL_RecClass__",t.PrincipalClass="__IDL_PrincipalClass__",t.FuncClass="__IDL_FuncClass__",t.ServiceClass="__IDL_ServiceClass__"})(de||(de={}));var zs=class{display(){return this.name}valueToString(e){return We(e)}buildTypeTable(e){e.has(this)||this._buildTypeTableImpl(e)}};M.Type=zs;var Xt=class extends zs{checkType(e){if(this.name!==e.name)throw new Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`);return e}_buildTypeTableImpl(e){}};M.PrimitiveType=Xt;var Zr=class extends zs{checkType(e){if(e instanceof yr){let r=e.getType();if(typeof r>"u")throw new Error("type mismatch with uninitialized type");return r}throw new Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`)}encodeType(e){return e.indexOf(this.name)}};M.ConstructType=Zr;var na=class extends Xt{get typeName(){return de.EmptyClass}static[Symbol.hasInstance](e){return e.typeName===de.EmptyClass}accept(e,r){return e.visitEmpty(this,r)}covariant(e){throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return(0,$.slebEncode)(Se.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}};M.EmptyClass=na;var Yc=class extends zs{get typeName(){return de.UnknownClass}static[Symbol.hasInstance](e){return e.typeName===de.UnknownClass}checkType(e){throw new Error("Method not implemented for unknown.")}accept(e,r){throw e.visitType(this,r)}covariant(e){throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}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(e,r){let n=r.decodeValue(e,r);Object(n)!==n&&(n=Object(n));let o;return r instanceof yr?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"}};M.UnknownClass=Yc;var Wc=class extends Xt{get typeName(){return de.BoolClass}static[Symbol.hasInstance](e){return e.typeName===de.BoolClass}accept(e,r){return e.visitBool(this,r)}covariant(e){if(typeof e=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){return new Uint8Array([e?1:0])}encodeType(){return(0,$.slebEncode)(Se.Bool)}decodeValue(e,r){switch(this.checkType(r),(0,$.safeReadUint8)(e)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}};M.BoolClass=Wc;var Zo=class extends Xt{get typeName(){return de.NullClass}static[Symbol.hasInstance](e){return e.typeName===de.NullClass}accept(e,r){return e.visitNull(this,r)}covariant(e){if(e===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return(0,$.slebEncode)(Se.Null)}decodeValue(e,r){return this.checkType(r),null}get name(){return"null"}};M.NullClass=Zo;var Yr=class extends Xt{get typeName(){return de.ReservedClass}static[Symbol.hasInstance](e){return e.typeName===de.ReservedClass}accept(e,r){return e.visitReserved(this,r)}covariant(e){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return(0,$.slebEncode)(Se.Reserved)}decodeValue(e,r){return r.name!==this.name&&r.decodeValue(e,r),null}get name(){return"reserved"}};M.ReservedClass=Yr;var Xc=class extends Xt{get typeName(){return de.TextClass}static[Symbol.hasInstance](e){return e.typeName===de.TextClass}accept(e,r){return e.visitText(this,r)}covariant(e){if(typeof e=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){let r=new TextEncoder().encode(e),n=(0,$.lebEncode)(r.byteLength);return(0,Te.concat)(n,r)}encodeType(){return(0,$.slebEncode)(Se.Text)}decodeValue(e,r){this.checkType(r);let n=(0,$.lebDecode)(e),o=(0,$.safeRead)(e,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(o)}get name(){return"text"}valueToString(e){return'"'+e+'"'}};M.TextClass=Xc;var oa=class extends Xt{get typeName(){return de.IntClass}static[Symbol.hasInstance](e){return e.typeName===de.IntClass}accept(e,r){return e.visitInt(this,r)}covariant(e){if(typeof e=="bigint"||Number.isInteger(e))return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){return(0,$.slebEncode)(e)}encodeType(){return(0,$.slebEncode)(Se.Int)}decodeValue(e,r){return this.checkType(r),(0,$.slebDecode)(e)}get name(){return"int"}valueToString(e){return e.toString()}};M.IntClass=oa;var sa=class extends Xt{get typeName(){return de.NatClass}static[Symbol.hasInstance](e){return e.typeName===de.NatClass}accept(e,r){return e.visitNat(this,r)}covariant(e){if(typeof e=="bigint"&&e>=BigInt(0)||Number.isInteger(e)&&e>=0)return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){return(0,$.lebEncode)(e)}encodeType(){return(0,$.slebEncode)(Se.Nat)}decodeValue(e,r){return this.checkType(r),(0,$.lebDecode)(e)}get name(){return"nat"}valueToString(e){return e.toString()}};M.NatClass=sa;var ia=class extends Xt{get typeName(){return de.FloatClass}static[Symbol.hasInstance](e){return e.typeName===de.FloatClass}constructor(e){if(super(),this._bits=e,e!==32&&e!==64)throw new Error("not a valid float type")}accept(e,r){return e.visitFloat(this,r)}covariant(e){if(typeof e=="number"||e instanceof Number)return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){let r=new ArrayBuffer(this._bits/8),n=new DataView(r);return this._bits===32?n.setFloat32(0,e,!0):n.setFloat64(0,e,!0),new Uint8Array(r)}encodeType(){let e=this._bits===32?Se.Float32:Se.Float64;return(0,$.slebEncode)(e)}decodeValue(e,r){this.checkType(r);let n=(0,$.safeRead)(e,this._bits/8),o=(0,Te.uint8ToDataView)(n);return this._bits===32?o.getFloat32(0,!0):o.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(e){return e.toString()}};M.FloatClass=ia;var vn=class extends Xt{get typeName(){return de.FixedIntClass}static[Symbol.hasInstance](e){return e.typeName===de.FixedIntClass}constructor(e){super(),this._bits=e}accept(e,r){return e.visitFixedInt(this,r)}covariant(e){let r=(0,qf.iexp2)(this._bits-1)*BigInt(-1),n=(0,qf.iexp2)(this._bits-1)-BigInt(1),o=!1;if(typeof e=="bigint")o=e>=r&&e<=n;else if(Number.isInteger(e)){let s=BigInt(e);o=s>=r&&s<=n}else o=!1;if(o)return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){return(0,$.writeIntLE)(e,this._bits/8)}encodeType(){let e=Math.log2(this._bits)-3;return(0,$.slebEncode)(-9-e)}decodeValue(e,r){this.checkType(r);let n=(0,$.readIntLE)(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(e){return e.toString()}};M.FixedIntClass=vn;var zr=class extends Xt{get typeName(){return de.FixedNatClass}static[Symbol.hasInstance](e){return e.typeName===de.FixedNatClass}constructor(e){super(),this._bits=e}accept(e,r){return e.visitFixedNat(this,r)}covariant(e){let r=(0,qf.iexp2)(this._bits),n=!1;if(typeof e=="bigint"&&e>=BigInt(0)?n=e<r:Number.isInteger(e)&&e>=0?n=BigInt(e)<r:n=!1,n)return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){return(0,$.writeUIntLE)(e,this._bits/8)}encodeType(){let e=Math.log2(this._bits)-3;return(0,$.slebEncode)(-5-e)}decodeValue(e,r){this.checkType(r);let n=(0,$.readUIntLE)(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(e){return e.toString()}};M.FixedNatClass=zr;var Zs=class t extends Zr{get typeName(){return de.VecClass}static[Symbol.hasInstance](e){return e.typeName===de.VecClass}constructor(e){super(),this._type=e,this._blobOptimization=!1,e instanceof zr&&e._bits===8&&(this._blobOptimization=!0)}accept(e,r){return e.visitVec(this,this._type,r)}covariant(e){let r=this._type instanceof zr?this._type._bits:this._type instanceof vn?this._type._bits:0;if(ArrayBuffer.isView(e)&&r==e.BYTES_PER_ELEMENT*8||Array.isArray(e)&&e.every((n,o)=>{try{return this._type.covariant(n)}catch(s){throw new Error(`Invalid ${this.display()} argument:
37
+ `;return this.bodyText&&(t+=` Body: ${this.bodyText}
38
+ `),t}},wo=class e extends G{constructor(){super(),this.name="HttpV3ApiNotSupportedErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return"HTTP request failed: v3 API is not supported"}},To=class e extends G{constructor(t){super(),this.error=t,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${Eo(this.error)}`}},No=class e extends G{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.`}},Vi=class e extends G{constructor(t){super(),this.request=t,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},Oo=class e extends G{constructor(t){super(),this.error=t,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,e.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function Eo(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e)}catch{return String(e)}}var Tr=new Error("unreachable");var xn={};Vp(xn,{Bool:()=>yl,BoolClass:()=>Ui,ConstructType:()=>At,Empty:()=>ml,EmptyClass:()=>vo,FixedIntClass:()=>Zt,FixedNatClass:()=>It,Float32:()=>Tl,Float64:()=>Nl,FloatClass:()=>So,Func:()=>Ll,FuncClass:()=>gn,Int:()=>bl,Int16:()=>El,Int32:()=>Rl,Int64:()=>vl,Int8:()=>Ol,IntClass:()=>Io,Nat:()=>wl,Nat16:()=>Al,Nat32:()=>Sl,Nat64:()=>Fl,Nat8:()=>Il,NatClass:()=>Ao,Null:()=>gl,NullClass:()=>_n,Opt:()=>Bl,OptClass:()=>Er,PrimitiveType:()=>Ge,Principal:()=>Vl,PrincipalClass:()=>qi,Rec:()=>kl,RecClass:()=>tt,Record:()=>Dl,RecordClass:()=>yn,Reserved:()=>_l,ReservedClass:()=>St,Service:()=>ql,ServiceClass:()=>Hn,Text:()=>xl,TextClass:()=>ki,Tuple:()=>Cl,TupleClass:()=>Li,Type:()=>Mn,Unknown:()=>Gp,UnknownClass:()=>Di,Variant:()=>Ul,VariantClass:()=>Kn,Vec:()=>Pl,VecClass:()=>jn,Visitor:()=>Ys,decode:()=>$p,encode:()=>Hp,resetSubtypeCache:()=>Zs,subtype:()=>Qs});function W(...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 _t=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=vt(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 vt(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?vt(e.buffer):new Uint8Array(e)}function Hs(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 ll(e,t){return Hs(e,t)===0}function ul(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Kp(e){let r=new TextEncoder().encode(e),n=0;for(let o of r)n=(n*223+o)%2**32;return n}function De(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 Kp(e)}function $s(e){let t=BigInt(e);if(e<=0)throw new RangeError("Input must be positive");return t.toString(2).length-1}function Ci(e){let t=BigInt(e);if(e<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<t}function dl(){throw new Error("unexpected end of buffer")}function Or(e,t){return e.byteLength<t&&dl(),e.read(t)}function Nr(e){let t=e.readUint8();return t===void 0&&dl(),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:$s(e))+1,r=new _t(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 me(e){let t=BigInt(1),r=BigInt(0),n;do n=Nr(e),r+=BigInt(n&127).valueOf()*t,t*=BigInt(128);while(n>=128);return r}function _e(e){typeof e=="number"&&(e=BigInt(e));let t=e<BigInt(0);t&&(e=-e-BigInt(1));let r=(e===BigInt(0)?0:$s(e))+1,n=new _t(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 Wt(e){let t=new Uint8Array(e.buffer),r=0;for(;r<t.byteLength;r++)if(t[r]<128){if((t[r]&64)===0)return me(e);break}let n=new Uint8Array(Or(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 pl(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return Gs(e,t)}function Gs(e,t){e=BigInt(e);let r=new _t(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 Js(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=BigInt(Nr(e)),n=BigInt(1),o=0;for(;++o<t;){n*=BigInt(256);let i=BigInt(Nr(e));r=r+n*i}return r}function fl(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let r=Js(e,t),n=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return r>=n&&(r-=n*BigInt(2)),r}var Z;(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"})(Z||(Z={}));var Pi="DIDL",hl=400;function Ro(e,t,r){return e.map((n,o)=>r(n,t[o]))}var Ws=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=W(...this._typs);return W(t,r)}indexOf(t){if(!this._idx.has(t))throw new Error("Missing type index for "+t);return _e(this._idx.get(t)||0)}},Ys=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)}},K;(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__"})(K||(K={}));var Mn=class{display(){return this.name}valueToString(t){return he(t)}buildTypeTable(t){t.has(this)||this._buildTypeTableImpl(t)}},Ge=class extends Mn{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){}},At=class extends Mn{checkType(t){if(t instanceof tt){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)}},vo=class extends Ge{get typeName(){return K.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===K.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 _e(Z.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},Di=class extends Mn{get typeName(){return K.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===K.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 tt?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"}},Ui=class extends Ge{get typeName(){return K.BoolClass}static[Symbol.hasInstance](t){return t.typeName===K.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 _e(Z.Bool)}decodeValue(t,r){switch(this.checkType(r),Nr(t)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},_n=class extends Ge{get typeName(){return K.NullClass}static[Symbol.hasInstance](t){return t.typeName===K.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 _e(Z.Null)}decodeValue(t,r){return this.checkType(r),null}get name(){return"null"}},St=class extends Ge{get typeName(){return K.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===K.ReservedClass}accept(t,r){return t.visitReserved(this,r)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return _e(Z.Reserved)}decodeValue(t,r){return r.name!==this.name&&r.decodeValue(t,r),null}get name(){return"reserved"}},ki=class extends Ge{get typeName(){return K.TextClass}static[Symbol.hasInstance](t){return t.typeName===K.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 W(n,r)}encodeType(){return _e(Z.Text)}decodeValue(t,r){this.checkType(r);let n=me(t),o=Or(t,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(o)}get name(){return"text"}valueToString(t){return'"'+t+'"'}},Io=class extends Ge{get typeName(){return K.IntClass}static[Symbol.hasInstance](t){return t.typeName===K.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 _e(t)}encodeType(){return _e(Z.Int)}decodeValue(t,r){return this.checkType(r),Wt(t)}get name(){return"int"}valueToString(t){return t.toString()}},Ao=class extends Ge{get typeName(){return K.NatClass}static[Symbol.hasInstance](t){return t.typeName===K.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 _e(Z.Nat)}decodeValue(t,r){return this.checkType(r),me(t)}get name(){return"nat"}valueToString(t){return t.toString()}},So=class extends Ge{get typeName(){return K.FloatClass}static[Symbol.hasInstance](t){return t.typeName===K.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?Z.Float32:Z.Float64;return _e(t)}decodeValue(t,r){this.checkType(r);let n=Or(t,this._bits/8),o=ul(n);return this._bits===32?o.getFloat32(0,!0):o.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(t){return t.toString()}},Zt=class extends Ge{get typeName(){return K.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===K.FixedIntClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedInt(this,r)}covariant(t){let r=Ci(this._bits-1)*BigInt(-1),n=Ci(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 Gs(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return _e(-9-t)}decodeValue(t,r){this.checkType(r);let n=fl(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}},It=class extends Ge{get typeName(){return K.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===K.FixedNatClass}constructor(t){super(),this._bits=t}accept(t,r){return t.visitFixedNat(this,r)}covariant(t){let r=Ci(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 pl(t,this._bits/8)}encodeType(){let t=Math.log2(this._bits)-3;return _e(-5-t)}decodeValue(t,r){this.checkType(r);let n=Js(t,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(t){return t.toString()}},jn=class e extends At{get typeName(){return K.VecClass}static[Symbol.hasInstance](t){return t.typeName===K.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof It&&t._bits===8&&(this._blobOptimization=!0)}accept(t,r){return t.visitVec(this,this._type,r)}covariant(t){let r=this._type instanceof It?this._type._bits:this._type instanceof Zt?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:
39
39
 
40
- index ${o} -> ${s.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){let r=(0,$.lebEncode)(e.length);if(this._blobOptimization)return(0,Te.concat)(r,new Uint8Array(e));if(ArrayBuffer.isView(e))if(e instanceof Int16Array||e instanceof Uint16Array){let o=new DataView(new ArrayBuffer(e.length*2));for(let s=0;s<e.length;s++)e instanceof Int16Array?o.setInt16(s*2,e[s],!0):o.setUint16(s*2,e[s],!0);return(0,Te.concat)(r,new Uint8Array(o.buffer))}else if(e instanceof Int32Array||e instanceof Uint32Array){let o=new DataView(new ArrayBuffer(e.length*4));for(let s=0;s<e.length;s++)e instanceof Int32Array?o.setInt32(s*4,e[s],!0):o.setUint32(s*4,e[s],!0);return(0,Te.concat)(r,new Uint8Array(o.buffer))}else if(e instanceof BigInt64Array||e instanceof BigUint64Array){let o=new DataView(new ArrayBuffer(e.length*8));for(let s=0;s<e.length;s++)e instanceof BigInt64Array?o.setBigInt64(s*8,e[s],!0):o.setBigUint64(s*8,e[s],!0);return(0,Te.concat)(r,new Uint8Array(o.buffer))}else return(0,Te.concat)(r,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));let n=new Te.PipeArrayBuffer(new Uint8Array(r.byteLength+e.length),0);n.write(r);for(let o of e){let s=this._type.encodeValue(o);n.write(new Uint8Array(s))}return n.buffer}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let r=(0,$.slebEncode)(Se.Vector),n=this._type.encodeType(e);e.add(this,(0,Te.concat)(r,n))}decodeValue(e,r){let n=this.checkType(r);if(!(n instanceof t))throw new Error("Not a vector type");let o=Number((0,$.lebDecode)(e));if(this._type instanceof zr){if(this._type._bits==8)return new Uint8Array(e.read(o));if(this._type._bits==16){let i=e.read(o*2);return new Uint16Array(i.buffer,i.byteOffset,o)}if(this._type._bits==32){let i=e.read(o*4);return new Uint32Array(i.buffer,i.byteOffset,o)}if(this._type._bits==64)return new BigUint64Array(e.read(o*8).buffer)}if(this._type instanceof vn){if(this._type._bits==8)return new Int8Array(e.read(o));if(this._type._bits==16){let i=e.read(o*2),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new Int16Array(o);for(let d=0;d<o;d++)c[d]=a.getInt16(d*2,!0);return c}if(this._type._bits==32){let i=e.read(o*4),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new Int32Array(o);for(let d=0;d<o;d++)c[d]=a.getInt32(d*4,!0);return c}if(this._type._bits==64){let i=e.read(o*8),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new BigInt64Array(o);for(let d=0;d<o;d++)c[d]=a.getBigInt64(d*8,!0);return c}}let s=[];for(let i=0;i<o;i++)s.push(this._type.decodeValue(e,n._type));return s}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(e){return"vec {"+e.map(n=>this._type.valueToString(n)).join("; ")+"}"}};M.VecClass=Zs;var ho=class t extends Zr{get typeName(){return de.OptClass}static[Symbol.hasInstance](e){return e.typeName===de.OptClass}constructor(e){super(),this._type=e}accept(e,r){return e.visitOpt(this,this._type,r)}covariant(e){try{if(Array.isArray(e)&&(e.length===0||e.length===1&&this._type.covariant(e[0])))return!0}catch(r){throw new Error(`Invalid ${this.display()} argument: ${We(e)}
40
+ index ${o} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=oe(t.length);if(this._blobOptimization)return W(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 W(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 W(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 W(r,new Uint8Array(o.buffer))}else return W(r,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));let n=new _t(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=_e(Z.Vector),n=this._type.encodeType(t);t.add(this,W(r,n))}decodeValue(t,r){let n=this.checkType(r);if(!(n instanceof e))throw new Error("Not a vector type");let o=Number(me(t));if(this._type instanceof It){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 Zt){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("; ")+"}"}},Er=class e extends At{get typeName(){return K.OptClass}static[Symbol.hasInstance](t){return t.typeName===K.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)}
41
41
 
42
- -> ${r.message}`)}throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){return e.length===0?new Uint8Array([0]):(0,Te.concat)(new Uint8Array([1]),this._type.encodeValue(e[0]))}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let r=(0,$.slebEncode)(Se.Opt),n=this._type.encodeType(e);e.add(this,(0,Te.concat)(r,n))}decodeValue(e,r){if(r instanceof Zo)return[];if(r instanceof Yr)return[];let n=r;if(r instanceof yr){let o=r.getType();if(typeof o>"u")throw new Error("type mismatch with uninitialized type");n=o}if(n instanceof t)switch((0,$.safeReadUint8)(e)){case 0:return[];case 1:{let o=e.save();try{return[this._type.decodeValue(e,n._type)]}catch{return e.restore(o),n._type.decodeValue(e,n._type),[]}}default:throw new Error("Not an option value")}else{if(this._type instanceof Zo||this._type instanceof t||this._type instanceof Yr)return n.decodeValue(e,n),[];{let o=e.save();try{return[this._type.decodeValue(e,r)]}catch{return e.restore(o),n.decodeValue(e,r),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(e){return e.length===0?"null":`opt ${this._type.valueToString(e[0])}`}};M.OptClass=ho;var Yo=class t extends Zr{get typeName(){return de.RecordClass}static[Symbol.hasInstance](e){return e.typeName===de.RecordClass||e.typeName===de.TupleClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((r,n)=>(0,Wt.idlLabelToId)(r[0])-(0,Wt.idlLabelToId)(n[0]))}accept(e,r){return e.visitRecord(this,this._fields,r)}tryAsTuple(){let e=[];for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(n!==`_${r}_`)return null;e.push(o)}return e}covariant(e){if(typeof e=="object"&&this._fields.every(([r,n])=>{if(!e.hasOwnProperty(r))throw new Error(`Record is missing key "${r}".`);try{return n.covariant(e[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
42
+ -> ${r.message}`)}throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){return t.length===0?new Uint8Array([0]):W(new Uint8Array([1]),this._type.encodeValue(t[0]))}_buildTypeTableImpl(t){this._type.buildTypeTable(t);let r=_e(Z.Opt),n=this._type.encodeType(t);t.add(this,W(r,n))}decodeValue(t,r){if(r instanceof _n)return[];if(r instanceof St)return[];let n=r;if(r instanceof tt){let o=r.getType();if(typeof o>"u")throw new Error("type mismatch with uninitialized type");n=o}if(n instanceof e)switch(Nr(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 _n||this._type instanceof e||this._type instanceof St)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])}`}},yn=class e extends At{get typeName(){return K.RecordClass}static[Symbol.hasInstance](t){return t.typeName===K.RecordClass||t.typeName===K.TupleClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>De(r[0])-De(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:
43
43
 
44
- field ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){let r=this._fields.map(([o])=>e[o]),n=ra(this._fields,r,([,o],s)=>o.encodeValue(s));return(0,Te.concat)(...n)}_buildTypeTableImpl(e){this._fields.forEach(([s,i])=>i.buildTypeTable(e));let r=(0,$.slebEncode)(Se.Record),n=(0,$.lebEncode)(this._fields.length),o=this._fields.map(([s,i])=>(0,Te.concat)((0,$.lebEncode)((0,Wt.idlLabelToId)(s)),i.encodeType(e)));e.add(this,(0,Te.concat)(r,n,(0,Te.concat)(...o)))}decodeValue(e,r){let n=this.checkType(r);if(!(n instanceof t))throw new Error("Not a record type");let o={},s=0,i=0;for(;i<n._fields.length;){let[a,c]=n._fields[i];if(s>=this._fields.length){c.decodeValue(e,c),i++;continue}let[d,p]=this._fields[s],l=(0,Wt.idlLabelToId)(this._fields[s][0]),u=(0,Wt.idlLabelToId)(a);if(l===u)o[d]=p.decodeValue(e,c),s++,i++;else if(u>l)if(p instanceof ho||p instanceof Yr)o[d]=[],s++;else throw new Error("Cannot find required field "+d);else c.decodeValue(e,c),i++}for(let[a,c]of this._fields.slice(s))if(c instanceof ho||c instanceof Yr)o[a]=[];else throw new Error("Cannot find required field "+a);return o}get fieldsAsObject(){let e={};for(let[r,n]of this._fields)e[(0,Wt.idlLabelToId)(r)]=n;return e}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(e){let r=this._fields.map(([o])=>e[o]);return`record {${ra(this._fields,r,([o,s],i)=>o+"="+s.valueToString(i)).join("; ")}}`}};M.RecordClass=Yo;var Jc=class t extends Yo{get typeName(){return de.TupleClass}static[Symbol.hasInstance](e){return e.typeName===de.TupleClass}constructor(e){let r={};e.forEach((n,o)=>r["_"+o+"_"]=n),super(r),this._components=e}accept(e,r){return e.visitTuple(this,this._components,r)}covariant(e){if(Array.isArray(e)&&e.length>=this._fields.length&&this._components.every((r,n)=>{try{return r.covariant(e[n])}catch(o){throw new Error(`Invalid ${this.display()} argument:
44
+ 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=Ro(this._fields,r,([,o],i)=>o.encodeValue(i));return W(...n)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=_e(Z.Record),n=oe(this._fields.length),o=this._fields.map(([i,s])=>W(oe(De(i)),s.encodeType(t)));t.add(this,W(r,n,W(...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=De(this._fields[i][0]),l=De(a);if(d===l)o[u]=p.decodeValue(t,c),i++,s++;else if(l>d)if(p instanceof Er||p instanceof St)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 Er||c instanceof St)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[De(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 {${Ro(this._fields,r,([o,i],s)=>o+"="+i.valueToString(s)).join("; ")}}`}},Li=class e extends yn{get typeName(){return K.TupleClass}static[Symbol.hasInstance](t){return t.typeName===K.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:
45
45
 
46
- index ${n} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){let r=ra(this._components,e,(n,o)=>n.encodeValue(o));return(0,Te.concat)(...r)}decodeValue(e,r){let n=this.checkType(r);if(!(n instanceof t))throw new Error("not a tuple type");if(n._components.length<this._components.length)throw new Error("tuple mismatch");let o=[];for(let[s,i]of n._components.entries())s>=this._components.length?i.decodeValue(e,i):o.push(this._components[s].decodeValue(e,i));return o}display(){return`record {${this._components.map(r=>r.display()).join("; ")}}`}valueToString(e){return`record {${ra(this._components,e,(n,o)=>n.valueToString(o)).join("; ")}}`}};M.TupleClass=Jc;var Ys=class t extends Zr{get typeName(){return de.VariantClass}static[Symbol.hasInstance](e){return e.typeName===de.VariantClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((r,n)=>(0,Wt.idlLabelToId)(r[0])-(0,Wt.idlLabelToId)(n[0]))}accept(e,r){return e.visitVariant(this,this._fields,r)}covariant(e){if(typeof e=="object"&&Object.entries(e).length===1&&this._fields.every(([r,n])=>{try{return!e.hasOwnProperty(r)||n.covariant(e[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
46
+ index ${n} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${he(t)}`)}encodeValue(t){let r=Ro(this._components,t,(n,o)=>n.encodeValue(o));return W(...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 {${Ro(this._components,t,(n,o)=>n.valueToString(o)).join("; ")}}`}},Kn=class e extends At{get typeName(){return K.VariantClass}static[Symbol.hasInstance](t){return t.typeName===K.VariantClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((r,n)=>De(r[0])-De(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:
47
47
 
48
- variant ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(e.hasOwnProperty(n)){let s=(0,$.lebEncode)(r),i=o.encodeValue(e[n]);return(0,Te.concat)(s,i)}}throw Error("Variant has no data: "+e)}_buildTypeTableImpl(e){this._fields.forEach(([,s])=>{s.buildTypeTable(e)});let r=(0,$.slebEncode)(Se.Variant),n=(0,$.lebEncode)(this._fields.length),o=this._fields.map(([s,i])=>(0,Te.concat)((0,$.lebEncode)((0,Wt.idlLabelToId)(s)),i.encodeType(e)));e.add(this,(0,Te.concat)(r,n,...o))}decodeValue(e,r){let n=this.checkType(r);if(!(n instanceof t))throw new Error("Not a variant type");let o=Number((0,$.lebDecode)(e));if(o>=n._fields.length)throw Error("Invalid variant index: "+o);let[s,i]=n._fields[o];for(let[a,c]of this._fields)if((0,Wt.idlLabelToId)(s)===(0,Wt.idlLabelToId)(a)){let d=c.decodeValue(e,i);return{[a]:d}}throw new Error("Cannot find field hash "+s)}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(e){for(let[r,n]of this._fields)if(e.hasOwnProperty(r)){let o=n.valueToString(e[r]);return o==="null"?`variant {${r}}`:`variant {${r}=${o}}`}throw new Error("Variant has no data: "+e)}get alternativesAsObject(){let e={};for(let[r,n]of this._fields)e[(0,Wt.idlLabelToId)(r)]=n;return e}};M.VariantClass=Ys;var yr=class t extends Zr{constructor(){super(...arguments),this._id=t._counter++}get typeName(){return de.RecClass}static{this._counter=0}static[Symbol.hasInstance](e){return e.typeName===de.RecClass}accept(e,r){if(!this._type)throw Error("Recursive type uninitialized.");return e.visitRec(this,this._type,r)}fill(e){this._type=e}getType(){return this._type}covariant(e){if(this._type&&this._type.covariant(e))return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(e)}_buildTypeTableImpl(e){if(!this._type)throw Error("Recursive type uninitialized.");e.add(this,new Uint8Array([])),this._type.buildTypeTable(e),e.merge(this,this._type.name)}decodeValue(e,r){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(e,r)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`\u03BC${this.name}.${this._type.name}`}valueToString(e){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(e)}};M.RecClass=yr;function Hf(t){if((0,$.safeReadUint8)(t)!==1)throw new Error("Cannot decode principal");let r=Number((0,$.lebDecode)(t));return K2.Principal.fromUint8Array(new Uint8Array((0,$.safeRead)(t,r)))}var Qc=class extends Xt{get typeName(){return de.PrincipalClass}static[Symbol.hasInstance](e){return e.typeName===de.PrincipalClass}accept(e,r){return e.visitPrincipal(this,r)}covariant(e){if(e&&e._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){let r=e.toUint8Array(),n=(0,$.lebEncode)(r.byteLength);return(0,Te.concat)(new Uint8Array([1]),n,r)}encodeType(){return(0,$.slebEncode)(Se.Principal)}decodeValue(e,r){return this.checkType(r),Hf(e)}get name(){return"principal"}valueToString(e){return`${this.name} "${e.toText()}"`}};M.PrincipalClass=Qc;var Wo=class extends Zr{get typeName(){return de.FuncClass}static[Symbol.hasInstance](e){return e.typeName===de.FuncClass}static argsToString(e,r){if(e.length!==r.length)throw new Error("arity mismatch");return"("+e.map((n,o)=>n.valueToString(r[o])).join(", ")+")"}constructor(e,r,n=[]){super(),this.argTypes=e,this.retTypes=r,this.annotations=n}accept(e,r){return e.visitFunc(this,r)}covariant(e){if(Array.isArray(e)&&e.length===2&&e[0]&&e[0]._isPrincipal&&typeof e[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue([e,r]){let n=e.toUint8Array(),o=(0,$.lebEncode)(n.byteLength),s=(0,Te.concat)(new Uint8Array([1]),o,n),i=new TextEncoder().encode(r),a=(0,$.lebEncode)(i.byteLength);return(0,Te.concat)(new Uint8Array([1]),s,a,i)}_buildTypeTableImpl(e){this.argTypes.forEach(d=>d.buildTypeTable(e)),this.retTypes.forEach(d=>d.buildTypeTable(e));let r=(0,$.slebEncode)(Se.Func),n=(0,$.lebEncode)(this.argTypes.length),o=(0,Te.concat)(...this.argTypes.map(d=>d.encodeType(e))),s=(0,$.lebEncode)(this.retTypes.length),i=(0,Te.concat)(...this.retTypes.map(d=>d.encodeType(e))),a=(0,$.lebEncode)(this.annotations.length),c=(0,Te.concat)(...this.annotations.map(d=>this.encodeAnnotation(d)));e.add(this,(0,Te.concat)(r,n,o,s,i,a,c))}decodeValue(e,r){let n=r instanceof yr?r.getType()??r:r;if(!$f(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if((0,$.safeReadUint8)(e)!==1)throw new Error("Cannot decode function reference");let s=Hf(e),i=Number((0,$.lebDecode)(e)),a=(0,$.safeRead)(e,i),d=new TextDecoder("utf8",{fatal:!0}).decode(a);return[s,d]}get name(){let e=this.argTypes.map(o=>o.name).join(", "),r=this.retTypes.map(o=>o.name).join(", "),n=" "+this.annotations.join(" ");return`(${e}) -> (${r})${n}`}valueToString([e,r]){return`func "${e.toText()}".${r}`}display(){let e=this.argTypes.map(o=>o.display()).join(", "),r=this.retTypes.map(o=>o.display()).join(", "),n=" "+this.annotations.join(" ");return`(${e}) \u2192 (${r})${n}`}encodeAnnotation(e){if(e==="query")return new Uint8Array([1]);if(e==="oneway")return new Uint8Array([2]);if(e==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}};M.FuncClass=Wo;var Ws=class extends Zr{get typeName(){return de.ServiceClass}static[Symbol.hasInstance](e){return e.typeName===de.ServiceClass}constructor(e){super(),this._fields=Object.entries(e).sort((r,n)=>r[0]<n[0]?-1:r[0]>n[0]?1:0)}accept(e,r){return e.visitService(this,r)}covariant(e){if(e&&e._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${We(e)}`)}encodeValue(e){let r=e.toUint8Array(),n=(0,$.lebEncode)(r.length);return(0,Te.concat)(new Uint8Array([1]),n,r)}_buildTypeTableImpl(e){this._fields.forEach(([s,i])=>i.buildTypeTable(e));let r=(0,$.slebEncode)(Se.Service),n=(0,$.lebEncode)(this._fields.length),o=this._fields.map(([s,i])=>{let a=new TextEncoder().encode(s),c=(0,$.lebEncode)(a.length);return(0,Te.concat)(c,a,i.encodeType(e))});e.add(this,(0,Te.concat)(r,n,...o))}decodeValue(e,r){let n=r instanceof yr?r.getType()??r:r;if(!$f(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return Hf(e)}get name(){return`service {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}valueToString(e){return`service "${e.toText()}"`}fieldsAsObject(){let e={};for(let[r,n]of this._fields)e[r]=n;return e}};M.ServiceClass=Ws;function We(t){let e=JSON.stringify(t,(r,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return e&&e.length>ay?e.substring(0,ay-3)+"...":e}function G2(t,e){if(e.length<t.length)throw Error("Wrong number of message arguments");let r=new Mf;t.forEach(c=>c.buildTypeTable(r));let n=new TextEncoder().encode(zc),o=r.encode(),s=(0,$.lebEncode)(e.length),i=(0,Te.concat)(...t.map(c=>c.encodeType(r))),a=(0,Te.concat)(...ra(t,e,(c,d)=>{try{c.covariant(d)}catch(p){throw new Error(p.message+`
48
+ 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=oe(r),s=o.encodeValue(t[n]);return W(i,s)}}throw Error("Variant has no data: "+t)}_buildTypeTableImpl(t){this._fields.forEach(([,i])=>{i.buildTypeTable(t)});let r=_e(Z.Variant),n=oe(this._fields.length),o=this._fields.map(([i,s])=>W(oe(De(i)),s.encodeType(t)));t.add(this,W(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(me(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(De(i)===De(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[De(r)]=n;return t}},tt=class e extends At{constructor(){super(...arguments),this._id=e._counter++}get typeName(){return K.RecClass}static{this._counter=0}static[Symbol.hasInstance](t){return t.typeName===K.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 Xs(e){if(Nr(e)!==1)throw new Error("Cannot decode principal");let r=Number(me(e));return M.fromUint8Array(new Uint8Array(Or(e,r)))}var qi=class extends Ge{get typeName(){return K.PrincipalClass}static[Symbol.hasInstance](t){return t.typeName===K.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 W(new Uint8Array([1]),n,r)}encodeType(){return _e(Z.Principal)}decodeValue(t,r){return this.checkType(r),Xs(t)}get name(){return"principal"}valueToString(t){return`${this.name} "${t.toText()}"`}},gn=class extends At{get typeName(){return K.FuncClass}static[Symbol.hasInstance](t){return t.typeName===K.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=W(new Uint8Array([1]),o,n),s=new TextEncoder().encode(r),a=oe(s.byteLength);return W(new Uint8Array([1]),i,a,s)}_buildTypeTableImpl(t){this.argTypes.forEach(u=>u.buildTypeTable(t)),this.retTypes.forEach(u=>u.buildTypeTable(t));let r=_e(Z.Func),n=oe(this.argTypes.length),o=W(...this.argTypes.map(u=>u.encodeType(t))),i=oe(this.retTypes.length),s=W(...this.retTypes.map(u=>u.encodeType(t))),a=oe(this.annotations.length),c=W(...this.annotations.map(u=>this.encodeAnnotation(u)));t.add(this,W(r,n,o,i,s,a,c))}decodeValue(t,r){let n=r instanceof tt?r.getType()??r:r;if(!Qs(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(Nr(t)!==1)throw new Error("Cannot decode function reference");let i=Xs(t),s=Number(me(t)),a=Or(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")}},Hn=class extends At{get typeName(){return K.ServiceClass}static[Symbol.hasInstance](t){return t.typeName===K.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 W(new Uint8Array([1]),n,r)}_buildTypeTableImpl(t){this._fields.forEach(([i,s])=>s.buildTypeTable(t));let r=_e(Z.Service),n=oe(this._fields.length),o=this._fields.map(([i,s])=>{let a=new TextEncoder().encode(i),c=oe(a.length);return W(c,a,s.encodeType(t))});t.add(this,W(r,n,...o))}decodeValue(t,r){let n=r instanceof tt?r.getType()??r:r;if(!Qs(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return Xs(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>hl?t.substring(0,hl-3)+"...":t}function Hp(e,t){if(t.length<e.length)throw Error("Wrong number of message arguments");let r=new Ws;e.forEach(c=>c.buildTypeTable(r));let n=new TextEncoder().encode(Pi),o=r.encode(),i=oe(t.length),s=W(...e.map(c=>c.encodeType(r))),a=W(...Ro(e,t,(c,u)=>{try{c.covariant(u)}catch(p){throw new Error(p.message+`
49
49
 
50
- `)}return c.encodeValue(d)}));return(0,Te.concat)(n,o,s,i,a)}function z2(t,e){let r=new Te.PipeArrayBuffer(e);if(e.byteLength<zc.length)throw new Error("Message length smaller than magic number");let n=(0,$.safeRead)(r,zc.length),o=new TextDecoder().decode(n);if(o!==zc)throw new Error("Wrong magic number: "+JSON.stringify(o));function s(u){let f=[],h=Number((0,$.lebDecode)(u));for(let y=0;y<h;y++){let x=Number((0,$.slebDecode)(u));switch(x){case Se.Opt:case Se.Vector:{let _=Number((0,$.slebDecode)(u));f.push([x,_]);break}case Se.Record:case Se.Variant:{let _=[],T=Number((0,$.lebDecode)(u)),N;for(;T--;){let v=Number((0,$.lebDecode)(u));if(v>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof N=="number"&&N>=v)throw new Error("field id collision or not sorted");N=v;let R=Number((0,$.slebDecode)(u));_.push([v,R])}f.push([x,_]);break}case Se.Func:{let _=[],T=Number((0,$.lebDecode)(u));for(;T--;)_.push(Number((0,$.slebDecode)(u)));let N=[],v=Number((0,$.lebDecode)(u));for(;v--;)N.push(Number((0,$.slebDecode)(u)));let R=[],A=Number((0,$.lebDecode)(u));for(;A--;)switch(Number((0,$.lebDecode)(u))){case 1:{R.push("query");break}case 2:{R.push("oneway");break}case 3:{R.push("composite_query");break}default:throw new Error("unknown annotation")}f.push([x,[_,N,R]]);break}case Se.Service:{let _=Number((0,$.lebDecode)(u)),T=[];for(;_--;){let N=Number((0,$.lebDecode)(u)),v=new TextDecoder().decode((0,$.safeRead)(u,N)),R=(0,$.slebDecode)(u);T.push([v,R])}f.push([x,T]);break}default:throw new Error("Illegal op_code: "+x)}}let m=[],b=Number((0,$.lebDecode)(u));for(let y=0;y<b;y++)m.push(Number((0,$.slebDecode)(u)));return[f,m]}let[i,a]=s(r);if(a.length<t.length)throw new Error("Wrong number of return values");let c=i.map(u=>py());function d(u){if(u<-24)throw new Error("future value not supported");if(u<0)switch(u){case-1:return M.Null;case-2:return M.Bool;case-3:return M.Nat;case-4:return M.Int;case-5:return M.Nat8;case-6:return M.Nat16;case-7:return M.Nat32;case-8:return M.Nat64;case-9:return M.Int8;case-10:return M.Int16;case-11:return M.Int32;case-12:return M.Int64;case-13:return M.Float32;case-14:return M.Float64;case-15:return M.Text;case-16:return M.Reserved;case-17:return M.Empty;case-24:return M.Principal;default:throw new Error("Illegal op_code: "+u)}if(u>=i.length)throw new Error("type index out of range");return c[u]}function p(u){switch(u[0]){case Se.Vector:{let f=d(u[1]);return uy(f)}case Se.Opt:{let f=d(u[1]);return dy(f)}case Se.Record:{let f={};for(let[b,y]of u[1]){let x=`_${b}_`;f[x]=d(y)}let h=ly(f),m=h.tryAsTuple();return Array.isArray(m)?cy(...m):h}case Se.Variant:{let f={};for(let[h,m]of u[1]){let b=`_${h}_`;f[b]=d(m)}return fy(f)}case Se.Func:{let[f,h,m]=u[1];return hy(f.map(b=>d(b)),h.map(b=>d(b)),m)}case Se.Service:{let f={},h=u[1];for(let[m,b]of h){let y=d(b);if(y instanceof yr&&(y=y.getType()),!(y instanceof Wo))throw new Error("Illegal service definition: services can only contain functions");f[m]=y}return my(f)}default:throw new Error("Illegal op_code: "+u[0])}}i.forEach((u,f)=>{if(u[0]===Se.Func){let h=p(u);c[f].fill(h)}}),i.forEach((u,f)=>{if(u[0]!==Se.Func){let h=p(u);c[f].fill(h)}}),jf();let l=a.map(u=>d(u));try{let u=t.map((f,h)=>f.decodeValue(r,l[h]));for(let f=t.length;f<l.length;f++)l[f].decodeValue(r,l[f]);if(r.byteLength>0)throw new Error("decode: Left-over bytes");return u}finally{jf()}}M.Empty=new na;M.Reserved=new Yr;M.Unknown=new Yc;M.Bool=new Wc;M.Null=new Zo;M.Text=new Xc;M.Int=new oa;M.Nat=new sa;M.Float32=new ia(32);M.Float64=new ia(64);M.Int8=new vn(8);M.Int16=new vn(16);M.Int32=new vn(32);M.Int64=new vn(64);M.Nat8=new zr(8);M.Nat16=new zr(16);M.Nat32=new zr(32);M.Nat64=new zr(64);M.Principal=new Qc;function cy(...t){return new Jc(t)}function uy(t){return new Zs(t)}function dy(t){return new ho(t)}function ly(t){return new Yo(t)}function fy(t){return new Ys(t)}function py(){return new yr}function hy(t,e,r=[]){return new Wo(t,e,r)}function my(t){return new Ws(t)}var eu=class t{constructor(e=new Map){this.rels=e}copy(){let e=new Map;for(let[r,n]of this.rels.entries()){let o=new Map(n);e.set(r,o)}return new t(e)}known(e,r){return this.rels.get(e.name)?.get(r.name)}addNegative(e,r){this.addNames(e.name,r.name,!1)}add(e,r){this.addNames(e.name,r.name,!0)}display(){let e="";for(let[r,n]of this.rels)for(let[o,s]of n)e+=`${r} ${s?":<":"!<:"} ${o}
51
- `;return e}addNames(e,r,n){let o=this.rels.get(e);if(o==null){let s=new Map;s.set(r,n),this.rels.set(e,s)}else o.set(r,n)}},Zc=new eu;function jf(){Zc=new eu}function Z2(t,e){let r=new Set(t.annotations),n=new Set(e.annotations);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o))return!1;return!0}function Lf(t){return t instanceof ho||t instanceof Zo||t instanceof Yr}function $f(t,e){let r=Zc.copy(),n=Nn(r,t,e);return n?Zc.add(t,e):Zc.addNegative(t,e),n}function Nn(t,e,r){if(e.name===r.name)return!0;let n=t.known(e,r);if(n!==void 0)return n;if(t.add(e,r),r instanceof Yr||e instanceof na||e instanceof sa&&r instanceof oa)return!0;if(e instanceof Zs&&r instanceof Zs)return Nn(t,e._type,r._type);if(r instanceof ho)return!0;if(e instanceof Yo&&r instanceof Yo){let o=e.fieldsAsObject;for(let[s,i]of r._fields){let a=o[(0,Wt.idlLabelToId)(s)];if(a){if(!Nn(t,a,i))return!1}else if(!Lf(i))return!1}return!0}if(e instanceof Wo&&r instanceof Wo){if(!Z2(e,r))return!1;for(let o=0;o<e.argTypes.length;o++){let s=e.argTypes[o];if(o<r.argTypes.length){if(!Nn(t,r.argTypes[o],s))return!1}else if(!Lf(s))return!1}for(let o=0;o<r.retTypes.length;o++){let s=r.retTypes[o];if(o<e.retTypes.length){if(!Nn(t,e.retTypes[o],s))return!1}else if(!Lf(s))return!1}return!0}if(e instanceof Ys&&r instanceof Ys){let o=r.alternativesAsObject;for(let[s,i]of e._fields){let a=o[(0,Wt.idlLabelToId)(s)];if(!a||!Nn(t,i,a))return!1}return!0}if(e instanceof Ws&&r instanceof Ws){let o=e.fieldsAsObject();for(let[s,i]of r._fields){let a=o[s];if(!a||!Nn(t,a,i))return!1}return!0}return e instanceof yr?Nn(t,e.getType(),r):r instanceof yr?Nn(t,e,r.getType()):!1}});var Jf=Y(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.VecForm=It.OptionForm=It.VariantForm=It.TupleForm=It.RecordForm=It.InputForm=It.InputBox=void 0;var Gf=class{constructor(e,r){this.idl=e,this.ui=r,this.label=null,this.value=void 0;let n=document.createElement("span");n.className="status",this.status=n,r.input&&(r.input.addEventListener("blur",()=>{r.input.value!==""&&this.parse()}),r.input.addEventListener("input",()=>{n.style.display="none",r.input.classList.remove("reject")}))}isRejected(){return this.value===void 0}parse(e={}){if(this.ui.form){let r=this.ui.form.parse(e);return this.value=r,r}if(this.ui.input){let r=this.ui.input;try{let n=this.ui.parse(this.idl,e,r.value);if(!this.idl.covariant(n))throw new Error(`${r.value} is not of type ${this.idl.display()}`);return this.status.style.display="none",this.value=n,n}catch(n){r.classList.add("reject"),this.status.style.display="block",this.status.innerHTML="InputError: "+n.message,this.value=void 0;return}}return null}render(e){let r=document.createElement("span");if(this.label){let n=document.createElement("label");n.innerText=this.label,r.appendChild(n)}this.ui.input&&(r.appendChild(this.ui.input),r.appendChild(this.status)),this.ui.form&&this.ui.form.render(r),e.appendChild(r)}};It.InputBox=Gf;var mo=class{constructor(e){this.ui=e,this.form=[]}renderForm(e){this.ui.container?(this.form.forEach(r=>r.render(this.ui.container)),e.appendChild(this.ui.container)):this.form.forEach(r=>r.render(e))}render(e){if(this.ui.open&&this.ui.event){e.appendChild(this.ui.open);let r=this;r.ui.open.addEventListener(r.ui.event,()=>{if(r.ui.container)r.ui.container.innerHTML="";else{let n=r.ui.open.nextElementSibling;n&&n.parentNode.removeChild(n)}r.generateForm(),r.renderForm(e)})}else this.generateForm(),this.renderForm(e)}};It.InputForm=mo;var zf=class extends mo{constructor(e,r){super(r),this.fields=e,this.ui=r}generateForm(){this.form=this.fields.map(([e,r])=>{let n=this.ui.render(r);return this.ui.labelMap&&this.ui.labelMap.hasOwnProperty(e)?n.label=this.ui.labelMap[e]+" ":n.label=e+" ",n})}parse(e){let r={};if(this.fields.forEach(([n,o],s)=>{let i=this.form[s].parse(e);r[n]=i}),!this.form.some(n=>n.isRejected()))return r}};It.RecordForm=zf;var Zf=class extends mo{constructor(e,r){super(r),this.components=e,this.ui=r}generateForm(){this.form=this.components.map(e=>this.ui.render(e))}parse(e){let r=[];if(this.components.forEach((n,o)=>{let s=this.form[o].parse(e);r.push(s)}),!this.form.some(n=>n.isRejected()))return r}};It.TupleForm=Zf;var Yf=class extends mo{constructor(e,r){super(r),this.fields=e,this.ui=r}generateForm(){let e=this.ui.open.selectedIndex,[r,n]=this.fields[e],o=this.ui.render(n);this.form=[o]}parse(e){let r=this.ui.open,n=r.options[r.selectedIndex].value,o=this.form[0].parse(e);if(o===void 0)return;let s={};return s[n]=o,s}};It.VariantForm=Yf;var Wf=class extends mo{constructor(e,r){super(r),this.ty=e,this.ui=r}generateForm(){if(this.ui.open.checked){let e=this.ui.render(this.ty);this.form=[e]}else this.form=[]}parse(e){if(this.form.length===0)return[];{let r=this.form[0].parse(e);return r===void 0?void 0:[r]}}};It.OptionForm=Wf;var Xf=class extends mo{constructor(e,r){super(r),this.ty=e,this.ui=r}generateForm(){let e=+this.ui.open.value;this.form=[];for(let r=0;r<e;r++){let n=this.ui.render(this.ty);this.form.push(n)}}parse(e){let r=this.form.map(n=>n.parse(e));if(!this.form.some(n=>n.isRejected()))return r}};It.VecForm=Xf});var _y=Y(Ee=>{"use strict";var Y2=Ee&&Ee.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),W2=Ee&&Ee.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),yy=Ee&&Ee.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Y2(r,e,n[o]);return W2(r,e),r}})();Object.defineProperty(Ee,"__esModule",{value:!0});Ee.Render=Ee.vecForm=Ee.optForm=Ee.variantForm=Ee.tupleForm=Ee.recordForm=Ee.inputBox=void 0;Ee.renderInput=np;Ee.renderValue=Xo;var ru=yy(Kf()),Qf=Rr(),Xs=yy(Jf()),X2={parse:oE},aa={render:np},J2=(t,e)=>new Xs.InputBox(t,{...X2,...e});Ee.inputBox=J2;var Q2=(t,e)=>new Xs.RecordForm(t,{...aa,...e});Ee.recordForm=Q2;var eE=(t,e)=>new Xs.TupleForm(t,{...aa,...e});Ee.tupleForm=eE;var tE=(t,e)=>new Xs.VariantForm(t,{...aa,...e});Ee.variantForm=tE;var rE=(t,e)=>new Xs.OptionForm(t,{...aa,...e});Ee.optForm=rE;var nE=(t,e)=>new Xs.VecForm(t,{...aa,...e});Ee.vecForm=nE;var tu=class extends ru.Visitor{visitType(e,r){let n=document.createElement("input");return n.classList.add("argument"),n.placeholder=e.display(),(0,Ee.inputBox)(e,{input:n})}visitNull(e,r){return(0,Ee.inputBox)(e,{})}visitRecord(e,r,n){let o={};if(r.length>1){let i=document.createElement("div");i.classList.add("popup-form"),o={container:i}}let s=(0,Ee.recordForm)(r,o);return(0,Ee.inputBox)(e,{form:s})}visitTuple(e,r,n){let o={};if(r.length>1){let i=document.createElement("div");i.classList.add("popup-form"),o={container:i}}let s=(0,Ee.tupleForm)(r,o);return(0,Ee.inputBox)(e,{form:s})}visitVariant(e,r,n){let o=document.createElement("select");for(let[a,c]of r){let d=new Option(a);o.add(d)}o.selectedIndex=-1,o.classList.add("open");let s={open:o,event:"change"},i=(0,Ee.variantForm)(r,s);return(0,Ee.inputBox)(e,{form:i})}visitOpt(e,r,n){let o=document.createElement("input");o.type="checkbox",o.classList.add("open");let s=(0,Ee.optForm)(r,{open:o,event:"change"});return(0,Ee.inputBox)(e,{form:s})}visitVec(e,r,n){let o=document.createElement("input");o.type="number",o.min="0",o.max="100",o.style.width="8rem",o.placeholder="len",o.classList.add("open");let s=document.createElement("div");s.classList.add("popup-form");let i=(0,Ee.vecForm)(r,{open:o,event:"change",container:s});return(0,Ee.inputBox)(e,{form:i})}visitRec(e,r,n){return np(r)}};Ee.Render=tu;var ep=class extends ru.Visitor{visitNull(e,r){return null}visitBool(e,r){if(r==="true")return!0;if(r==="false")return!1;throw new Error(`Cannot parse ${r} as boolean`)}visitText(e,r){return r}visitFloat(e,r){return parseFloat(r)}visitFixedInt(e,r){return e._bits<=32?parseInt(r,10):BigInt(r)}visitFixedNat(e,r){return e._bits<=32?parseInt(r,10):BigInt(r)}visitNumber(e,r){return BigInt(r)}visitPrincipal(e,r){return Qf.Principal.fromText(r)}visitService(e,r){return Qf.Principal.fromText(r)}visitFunc(e,r){let n=r.split(".",2);return[Qf.Principal.fromText(n[0]),n[1]]}},tp=class extends ru.Visitor{visitNull(e,r){return null}visitBool(e,r){return Math.random()<.5}visitText(e,r){return Math.random().toString(36).substring(6)}visitFloat(e,r){return Math.random()}visitInt(e,r){return BigInt(this.generateNumber(!0))}visitNat(e,r){return BigInt(this.generateNumber(!1))}visitFixedInt(e,r){let n=this.generateNumber(!0);return e._bits<=32?n:BigInt(r)}visitFixedNat(e,r){let n=this.generateNumber(!1);return e._bits<=32?n:BigInt(r)}generateNumber(e){let r=Math.floor(Math.random()*100);return e&&Math.random()<.5?-r:r}};function oE(t,e,r){return e.random&&r===""?t.accept(new tp,r):t.accept(new ep,r)}function np(t){return t.accept(new tu,null)}function Xo(t,e,r){return t.accept(new rp,{input:e,value:r})}var rp=class extends ru.Visitor{visitType(e,r){r.input.ui.input.value=e.valueToString(r.value)}visitNull(e,r){}visitText(e,r){r.input.ui.input.value=r.value}visitRec(e,r,n){Xo(r,n.input,n.value)}visitOpt(e,r,n){if(n.value.length!==0){let o=n.input.ui.form,s=o.ui.open;s.checked=!0,s.dispatchEvent(new Event(o.ui.event)),Xo(r,o.form[0],n.value[0])}}visitRecord(e,r,n){let o=n.input.ui.form;r.forEach(([s,i],a)=>{Xo(i,o.form[a],n.value[s])})}visitTuple(e,r,n){let o=n.input.ui.form;r.forEach((s,i)=>{Xo(s,o.form[i],n.value[i])})}visitVariant(e,r,n){let o=n.input.ui.form,s=Object.entries(n.value)[0];r.forEach(([i,a],c)=>{if(i===s[0]){let d=o.ui.open;d.selectedIndex=c,d.dispatchEvent(new Event(o.ui.event)),Xo(a,o.form[0],s[1])}})}visitVec(e,r,n){let o=n.input.ui.form,s=n.value.length,i=o.ui.open;i.value=s,i.dispatchEvent(new Event(o.ui.event)),n.value.forEach((a,c)=>{Xo(r,o.form[c],a)})}}});var gy=Y(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0})});var ca=Y(lt=>{"use strict";var xy=lt&&lt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),sE=lt&&lt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Js=lt&&lt.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&xy(e,t,r)},iE=lt&&lt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&xy(r,e,n[o]);return sE(r,e),r}})();Object.defineProperty(lt,"__esModule",{value:!0});lt.IDL=void 0;Js(_y(),lt);Js(Jf(),lt);lt.IDL=iE(Kf());Js(Df(),lt);Js(Uf(),lt);Js($c(),lt);Js(gy(),lt)});var Qs=Y(ua=>{"use strict";Object.defineProperty(ua,"__esModule",{value:!0});ua.uint8FromBufLike=wy;ua.uint8ToBuf=aE;ua.uint8Equals=cE;function wy(t){if(!t)throw new Error("Input cannot be null or undefined");return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):Array.isArray(t)?new Uint8Array(t):"buffer"in t?wy(t.buffer):new Uint8Array(t)}function aE(t){let e=new ArrayBuffer(t.byteLength);return new Uint8Array(e).set(t),e}function cE(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}});var ou=Y(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0});da.hashValue=nu;da.requestIdOf=dE;da.hashOfMap=ip;var op=ca(),Ey=ar(),uE=Qs(),sp=dt(),Jo=Gs();function nu(t){if(typeof t=="string")return Ty(t);if(typeof t=="number")return(0,Jo.sha256)((0,op.lebEncode)(t));if(t instanceof Uint8Array||ArrayBuffer.isView(t))return(0,Jo.sha256)((0,uE.uint8FromBufLike)(t));if(Array.isArray(t)){let e=t.map(nu);return(0,Jo.sha256)((0,sp.concatBytes)(...e))}else{if(t&&typeof t=="object"&&t._isPrincipal)return(0,Jo.sha256)(t.toUint8Array());if(typeof t=="object"&&t!==null&&typeof t.toHash=="function")return nu(t.toHash());if(typeof t=="object")return ip(t);if(typeof t=="bigint")return(0,Jo.sha256)((0,op.lebEncode)(t))}throw Ey.InputError.fromCode(new Ey.HashValueErrorCode(t))}var Ty=t=>{let e=new TextEncoder().encode(t);return(0,Jo.sha256)(e)};function dE(t){return ip(t)}function ip(t){let n=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,a])=>{let c=Ty(i),d=nu(a);return[c,d]}).sort(([i],[a])=>(0,op.compare)(i,a)),o=(0,sp.concatBytes)(...n.map(i=>(0,sp.concatBytes)(...i)));return(0,Jo.sha256)(o)}});var su=Y(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR=Wr.IC_RESPONSE_DOMAIN_SEPARATOR=Wr.IC_REQUEST_DOMAIN_SEPARATOR=Wr.DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS=void 0;Wr.DEFAULT_INGRESS_EXPIRY_DELTA_IN_MSECS=300*1e3;Wr.IC_REQUEST_DOMAIN_SEPARATOR=new TextEncoder().encode(`
52
- ic-request`);Wr.IC_RESPONSE_DOMAIN_SEPARATOR=new TextEncoder().encode("\vic-response");Wr.IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR=new TextEncoder().encode("ic-request-auth-delegation")});var up=Y(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.AnonymousIdentity=Qo.SignIdentity=void 0;Qo.createIdentityDescriptor=pE;var Oy=Rr(),lE=ou(),Ny=dt(),fE=su(),ap=class{getPrincipal(){return this._principal||(this._principal=Oy.Principal.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(e){let{body:r,...n}=e,o=(0,lE.requestIdOf)(r);return{...n,body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign((0,Ny.concatBytes)(fE.IC_REQUEST_DOMAIN_SEPARATOR,o))}}}};Qo.SignIdentity=ap;var cp=class{getPrincipal(){return Oy.Principal.anonymous()}async transformRequest(e){return{...e,body:{content:e.body}}}};Qo.AnonymousIdentity=cp;function pE(t){return"getPublicKey"in t?{type:"PublicKeyIdentity",publicKey:(0,Ny.bytesToHex)(t.getPublicKey().toDer())}:{type:"AnonymousIdentity"}}});var Ry=Y((iu,vy)=>{(function(t,e){typeof iu=="object"&&typeof vy<"u"?e(iu):typeof define=="function"&&define.amd?define(["exports"],e):(t=typeof globalThis<"u"?globalThis:t||self,e(t.Cbor={}))})(iu,function(t){"use strict";class e extends Error{constructor(j){super(j),this.name="DecodingError"}}let r=55799,n=Symbol("CBOR_STOP_CODE");var o=(D=>(D[D.False=20]="False",D[D.True=21]="True",D[D.Null=22]="Null",D[D.Undefined=23]="Undefined",D[D.Break=31]="Break",D))(o||{}),s=(D=>(D[D.UnsignedInteger=0]="UnsignedInteger",D[D.NegativeInteger=1]="NegativeInteger",D[D.ByteString=2]="ByteString",D[D.TextString=3]="TextString",D[D.Array=4]="Array",D[D.Map=5]="Map",D[D.Tag=6]="Tag",D[D.Simple=7]="Simple",D))(s||{});let i=23,a=255,c=65535,d=4294967295,p=BigInt("0xffffffffffffffff");var l=(D=>(D[D.Value=23]="Value",D[D.OneByte=24]="OneByte",D[D.TwoBytes=25]="TwoBytes",D[D.FourBytes=26]="FourBytes",D[D.EightBytes=27]="EightBytes",D[D.Indefinite=31]="Indefinite",D))(l||{});let u=!1;function f(D){return D==null}function h(D,j){let ie=new Uint8Array(j);return ie.set(D),ie}let m=new TextDecoder;function b(D){return(D&224)>>5}function y(D){return D&31}let x=new Uint8Array,_,T=0;function N(D,j){x=D,T=0;let ie=v(j);return j?.(ie)??ie}function v(D){let[j,ie]=R();switch(j){case s.UnsignedInteger:return V(ie);case s.NegativeInteger:return C(ie);case s.ByteString:return g(ie);case s.TextString:return w(ie);case s.Array:return A(ie,D);case s.Map:return S(ie,D);case s.Tag:return O(ie,D);case s.Simple:return E(ie)}throw new e(`Unsupported major type: ${j}`)}function R(){let D=x.at(T);if(f(D))throw new e("Provided CBOR data is empty");let j=b(D),ie=y(D);return T++,[j,ie]}function A(D,j){let ie=V(D);if(ie===1/0){let Nt=[],bt=v(j);for(;bt!==n;)Nt.push(j?.(bt)??bt),bt=v(j);return Nt}let Ot=new Array(ie);for(let Nt=0;Nt<ie;Nt++){let bt=v(j);Ot[Nt]=j?.(bt)??bt}return Ot}function E(D){switch(D){case o.False:return!1;case o.True:return!0;case o.Null:return null;case o.Undefined:return;case o.Break:return n}throw new e(`Unrecognized simple type: ${D.toString(2)}`)}function S(D,j){let ie=V(D),Ot={};if(ie===1/0){let[Nt,bt]=R();for(;Nt!==s.Simple&&bt!==o.Break;){let io=w(bt),wn=v(j);Ot[io]=j?.(wn,io)??wn,[Nt,bt]=R()}return Ot}for(let Nt=0;Nt<ie;Nt++){let[bt,io]=R();if(bt!==s.TextString)throw new e("Map keys must be text strings");let wn=w(io),ao=v(j);Ot[wn]=j?.(ao,wn)??ao}return Ot}function V(D){if(D<=l.Value)return D;switch(_=new DataView(x.buffer,x.byteOffset+T),D){case l.OneByte:return T++,_.getUint8(0);case l.TwoBytes:return T+=2,_.getUint16(0,u);case l.FourBytes:return T+=4,_.getUint32(0,u);case l.EightBytes:return T+=8,_.getBigUint64(0,u);case l.Indefinite:return 1/0;default:throw new e(`Unsupported integer info: ${D.toString(2)}`)}}function C(D){let j=V(D);return typeof j=="number"?-1-j:-1n-j}function g(D){let j=V(D);if(j>Number.MAX_SAFE_INTEGER)throw new e("Byte length is too large");let ie=Number(j);return T+=ie,x.slice(T-ie,T)}function w(D){let j=g(D);return m.decode(j)}function O(D,j){let ie=V(D);if(ie===r)return v(j);throw new e(`Unsupported tag: ${ie}.`)}class P extends Error{constructor(j){super(j),this.name="SerializationError"}}let L=2*1024,I=100,B=new TextEncoder;function F(D){return D<<5}let U=new Uint8Array(L),q=new DataView(U.buffer),H=0,Z=[];function G(D,j){H=0;let ie=j?.(D)??D;return te(ie,j),U.slice(0,H)}function ae(D,j){H=0;let ie=j?.(D)??D;return Xi(r,ie,j),U.slice(0,H)}function te(D,j){if(H>U.length-I&&(U=h(U,U.length*2),q=new DataView(U.buffer)),D===!1||D===!0||D===null||D===void 0){Tt(D);return}if(typeof D=="number"||typeof D=="bigint"){Wi(D);return}if(typeof D=="string"){ks(D);return}if(D instanceof Uint8Array){js(D);return}if(D instanceof ArrayBuffer){js(new Uint8Array(D));return}if(Array.isArray(D)){Ce(D,j);return}if(typeof D=="object"){ne(D,j);return}throw new P(`Unsupported type: ${typeof D}`)}function Ce(D,j){me(s.Array,D.length),D.forEach((ie,Ot)=>{te(j?.(ie,Ot.toString())??ie,j)})}function ne(D,j){Z=Object.entries(D),me(s.Map,Z.length),Z.forEach(([ie,Ot])=>{ks(ie),te(j?.(Ot,ie)??Ot,j)})}function me(D,j){if(j<=i){q.setUint8(H++,F(D)|Number(j));return}if(j<=a){q.setUint8(H++,F(D)|l.OneByte),q.setUint8(H,Number(j)),H+=1;return}if(j<=c){q.setUint8(H++,F(D)|l.TwoBytes),q.setUint16(H,Number(j),u),H+=2;return}if(j<=d){q.setUint8(H++,F(D)|l.FourBytes),q.setUint32(H,Number(j),u),H+=4;return}if(j<=p){q.setUint8(H++,F(D)|l.EightBytes),q.setBigUint64(H,BigInt(j),u),H+=8;return}throw new P(`Value too large to encode: ${j}`)}function Tt(D){me(s.Simple,Vt(D))}function Vt(D){if(D===!1)return o.False;if(D===!0)return o.True;if(D===null)return o.Null;if(D===void 0)return o.Undefined;throw new P(`Unrecognized simple value: ${D.toString()}`)}function pr(D,j){me(D,j.length),H>U.length-j.length&&(U=h(U,U.length+j.length),q=new DataView(U.buffer)),U.set(j,H),H+=j.length}function xn(D,j){me(D,j)}function so(D){xn(s.UnsignedInteger,D)}function Yi(D){xn(s.NegativeInteger,typeof D=="bigint"?-1n-D:-1-D)}function Wi(D){D>=0?so(D):Yi(D)}function ks(D){pr(s.TextString,B.encode(D))}function js(D){pr(s.ByteString,D)}function Xi(D,j,ie){me(s.Tag,D),te(j,ie)}t.DecodingError=e,t.EncodingError=P,t.decode=N,t.encode=G,t.encodeWithSelfDescribedTag=ae,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})})});var la=Y(Jt=>{"use strict";var hE=Jt&&Jt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),mE=Jt&&Jt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),yE=Jt&&Jt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&hE(r,e,n[o]);return mE(r,e),r}})();Object.defineProperty(Jt,"__esModule",{value:!0});Jt.Cbor=Jt.ToCborValue=void 0;Jt.encode=Sy;Jt.decode=Ay;var _E=Rr(),Iy=yE(Ry()),au=ar(),bE=fa(),dp=class{};Jt.ToCborValue=dp;function gE(t){return typeof t=="object"&&t!==null&&"toCborValue"in t}function Sy(t){try{return Iy.encodeWithSelfDescribedTag(t,e=>_E.Principal.isPrincipal(e)?e.toUint8Array():bE.Expiry.isExpiry(e)?e.toBigInt():gE(e)?e.toCborValue():e)}catch(e){throw au.InputError.fromCode(new au.CborEncodeErrorCode(e,t))}}function Ay(t){try{return Iy.decode(t)}catch(e){throw au.InputError.fromCode(new au.CborDecodeErrorCode(e,t))}}Jt.Cbor={encode:Sy,decode:Ay}});var lp=Y(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});cu.randomNumber=void 0;var xE=()=>{if(typeof window<"u"&&window.crypto&&window.crypto.getRandomValues){let t=new Uint32Array(1);return window.crypto.getRandomValues(t),t[0]}if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]}return typeof crypto<"u"&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)};cu.randomNumber=xE});var ei=Y(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.ReadRequestType=Rn.SubmitRequestType=Rn.Endpoint=void 0;Rn.makeNonce=wE;var uu=lp(),By;(function(t){t.Query="read",t.ReadState="read_state",t.Call="call"})(By||(Rn.Endpoint=By={}));var Cy;(function(t){t.Call="call"})(Cy||(Rn.SubmitRequestType=Cy={}));var Py;(function(t){t.Query="query",t.ReadState="read_state"})(Py||(Rn.ReadRequestType=Py={}));function wE(){let t=new ArrayBuffer(16),e=new DataView(t),r=(0,uu.randomNumber)(),n=(0,uu.randomNumber)(),o=(0,uu.randomNumber)(),s=(0,uu.randomNumber)();return e.setUint32(0,r),e.setUint32(4,n),e.setUint32(8,o),e.setUint32(12,s),Object.assign(new Uint8Array(t),{__nonce__:void 0})}});var fu=Y(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.Expiry=cr.JSON_KEY_EXPIRY=void 0;cr.makeNonceTransform=vE;cr.makeExpiryTransform=RE;cr.httpHeadersTransform=IE;var EE=ca(),Dy=ei(),du=ar();cr.JSON_KEY_EXPIRY="__expiry__";var fp=BigInt(1e3),TE=BigInt(1e6),Fy=BigInt(60),OE=BigInt(90)*fp;function Vy(t){return t/fp}function NE(t){return Vy(t)/Fy}var lu=class t{constructor(e){this.__expiry__=e,this._isExpiry=!0}static fromDeltaInMilliseconds(e,r=0){let n=BigInt(e),o=BigInt(Date.now())+n+BigInt(r),s;return n<OE?s=Vy(o):s=NE(o)*Fy,new t(s*fp*TE)}toBigInt(){return this.__expiry__}toHash(){return(0,EE.lebEncode)(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[cr.JSON_KEY_EXPIRY]:this.toString()}}static fromJSON(e){let r=JSON.parse(e);if(r[cr.JSON_KEY_EXPIRY])try{let n=BigInt(r[cr.JSON_KEY_EXPIRY]);return new t(n)}catch(n){throw new du.InputError(new du.ExpiryJsonDeserializeErrorCode(`Not a valid BigInt: ${n}`))}throw new du.InputError(new du.ExpiryJsonDeserializeErrorCode(`The input does not contain the key ${cr.JSON_KEY_EXPIRY}`))}static isExpiry(e){return e instanceof t||typeof e=="object"&&e!==null&&"_isExpiry"in e&&e._isExpiry===!0&&"__expiry__"in e&&typeof e.__expiry__=="bigint"}};cr.Expiry=lu;function vE(t=Dy.makeNonce){return async e=>{let r=e.request.headers;e.request.headers=r,e.endpoint===Dy.Endpoint.Call&&(e.body.nonce=t())}}function RE(t){return async e=>{e.body.ingress_expiry=lu.fromDeltaInMilliseconds(t)}}function IE(t){let e=[];return t.forEach((r,n)=>{e.push([n,r])}),e}});var Ir=Y(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.notImplemented=re.bitMask=re.utf8ToBytes=re.randomBytes=re.isBytes=re.hexToBytes=re.concatBytes=re.bytesToUtf8=re.bytesToHex=re.anumber=re.abytes=void 0;re.abool=SE;re._abool2=AE;re._abytes2=BE;re.numberToHexUnpadded=Uy;re.hexToNumber=hp;re.bytesToNumberBE=CE;re.bytesToNumberLE=PE;re.numberToBytesBE=Ly;re.numberToBytesLE=DE;re.numberToVarBytesBE=FE;re.ensureBytes=VE;re.equalBytes=UE;re.copyBytes=LE;re.asciiToBytes=qE;re.inRange=qy;re.aInRange=ME;re.bitLen=kE;re.bitGet=jE;re.bitSet=HE;re.createHmacDrbg=KE;re.validateObject=zE;re.isHash=ZE;re._validateObject=YE;re.memoized=XE;var Xr=dt(),In=dt();Object.defineProperty(re,"abytes",{enumerable:!0,get:function(){return In.abytes}});Object.defineProperty(re,"anumber",{enumerable:!0,get:function(){return In.anumber}});Object.defineProperty(re,"bytesToHex",{enumerable:!0,get:function(){return In.bytesToHex}});Object.defineProperty(re,"bytesToUtf8",{enumerable:!0,get:function(){return In.bytesToUtf8}});Object.defineProperty(re,"concatBytes",{enumerable:!0,get:function(){return In.concatBytes}});Object.defineProperty(re,"hexToBytes",{enumerable:!0,get:function(){return In.hexToBytes}});Object.defineProperty(re,"isBytes",{enumerable:!0,get:function(){return In.isBytes}});Object.defineProperty(re,"randomBytes",{enumerable:!0,get:function(){return In.randomBytes}});Object.defineProperty(re,"utf8ToBytes",{enumerable:!0,get:function(){return In.utf8ToBytes}});var pu=BigInt(0),pa=BigInt(1);function SE(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function AE(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function BE(t,e,r=""){let n=(0,Xr.isBytes)(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function Uy(t){let e=t.toString(16);return e.length&1?"0"+e:e}function hp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?pu:BigInt("0x"+t)}function CE(t){return hp((0,Xr.bytesToHex)(t))}function PE(t){return(0,Xr.abytes)(t),hp((0,Xr.bytesToHex)(Uint8Array.from(t).reverse()))}function Ly(t,e){return(0,Xr.hexToBytes)(t.toString(16).padStart(e*2,"0"))}function DE(t,e){return Ly(t,e).reverse()}function FE(t){return(0,Xr.hexToBytes)(Uy(t))}function VE(t,e,r){let n;if(typeof e=="string")try{n=(0,Xr.hexToBytes)(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if((0,Xr.isBytes)(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(t+" of length "+r+" expected, got "+o);return n}function UE(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function LE(t){return Uint8Array.from(t)}function qE(t){return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new Error(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var pp=t=>typeof t=="bigint"&&pu<=t;function qy(t,e,r){return pp(t)&&pp(e)&&pp(r)&&e<=t&&t<r}function ME(t,e,r,n){if(!qy(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function kE(t){let e;for(e=0;t>pu;t>>=pa,e+=1);return e}function jE(t,e){return t>>BigInt(e)&pa}function HE(t,e,r){return t|(r?pa:pu)<<BigInt(e)}var $E=t=>(pa<<BigInt(t))-pa;re.bitMask=$E;function KE(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=f=>new Uint8Array(f),o=f=>Uint8Array.of(f),s=n(t),i=n(t),a=0,c=()=>{s.fill(1),i.fill(0),a=0},d=(...f)=>r(i,s,...f),p=(f=n(0))=>{i=d(o(0),f),s=d(),f.length!==0&&(i=d(o(1),f),s=d())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f<e;){s=d();let m=s.slice();h.push(m),f+=s.length}return(0,Xr.concatBytes)(...h)};return(f,h)=>{c(),p(f);let m;for(;!(m=h(l()));)p();return c(),m}}var GE={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||(0,Xr.isBytes)(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function zE(t,e,r={}){let n=(o,s,i)=>{let a=GE[s];if(typeof a!="function")throw new Error("invalid validator function");let c=t[o];if(!(i&&c===void 0)&&!a(c,t))throw new Error("param "+String(o)+" is invalid. Expected "+s+", got "+c)};for(let[o,s]of Object.entries(e))n(o,s,!1);for(let[o,s]of Object.entries(r))n(o,s,!0);return t}function ZE(t){return typeof t=="function"&&Number.isSafeInteger(t.outputLen)}function YE(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(o,s,i){let a=t[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}var WE=()=>{throw new Error("not implemented")};re.notImplemented=WE;function XE(t){let e=new WeakMap;return(r,...n)=>{let o=e.get(r);if(o!==void 0)return o;let s=t(r,...n);return e.set(r,s),s}}});var Jr=Y(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.isNegativeLE=void 0;je.mod=Qt;je.pow=eT;je.pow2=tT;je.invert=hu;je.tonelliShanks=yp;je.FpSqrt=Gy;je.validateField=iT;je.FpPow=_p;je.FpInvertBatch=zy;je.FpDiv=aT;je.FpLegendre=mu;je.FpIsSquare=cT;je.nLength=bp;je.Field=yu;je.FpSqrtOdd=uT;je.FpSqrtEven=dT;je.hashToPrivateScalar=lT;je.getFieldBytesLength=gp;je.getMinHashLength=Zy;je.mapHashToField=fT;var er=Ir(),Lt=BigInt(0),et=BigInt(1),es=BigInt(2),My=BigInt(3),ky=BigInt(4),jy=BigInt(5),JE=BigInt(7),Hy=BigInt(8),QE=BigInt(9),$y=BigInt(16);function Qt(t,e){let r=t%e;return r>=Lt?r:e+r}function eT(t,e,r){return _p(yu(r),t,e)}function tT(t,e,r){let n=t;for(;e-- >Lt;)n*=n,n%=r;return n}function hu(t,e){if(t===Lt)throw new Error("invert: expected non-zero number");if(e<=Lt)throw new Error("invert: expected positive modulus, got "+e);let r=Qt(t,e),n=e,o=Lt,s=et,i=et,a=Lt;for(;r!==Lt;){let d=n/r,p=n%r,l=o-i*d,u=s-a*d;n=r,r=p,o=i,s=a,i=l,a=u}if(n!==et)throw new Error("invert: does not exist");return Qt(o,e)}function mp(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Ky(t,e){let r=(t.ORDER+et)/ky,n=t.pow(e,r);return mp(t,n,e),n}function rT(t,e){let r=(t.ORDER-jy)/Hy,n=t.mul(e,es),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,es),o),a=t.mul(s,t.sub(i,t.ONE));return mp(t,a,e),a}function nT(t){let e=yu(t),r=yp(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+JE)/$y;return(a,c)=>{let d=a.pow(c,i),p=a.mul(d,n),l=a.mul(d,o),u=a.mul(d,s),f=a.eql(a.sqr(p),c),h=a.eql(a.sqr(l),c);d=a.cmov(d,p,f),p=a.cmov(u,l,h);let m=a.eql(a.sqr(p),c),b=a.cmov(d,p,m);return mp(a,b,c),b}}function yp(t){if(t<My)throw new Error("sqrt is not defined for small field");let e=t-et,r=0;for(;e%es===Lt;)e/=es,r++;let n=es,o=yu(t);for(;mu(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Ky;let s=o.pow(n,e),i=(e+et)/es;return function(c,d){if(c.is0(d))return d;if(mu(c,d)!==1)throw new Error("Cannot find square root");let p=r,l=c.mul(c.ONE,s),u=c.pow(d,e),f=c.pow(d,i);for(;!c.eql(u,c.ONE);){if(c.is0(u))return c.ZERO;let h=1,m=c.sqr(u);for(;!c.eql(m,c.ONE);)if(h++,m=c.sqr(m),h===p)throw new Error("Cannot find square root");let b=et<<BigInt(p-h-1),y=c.pow(l,b);p=h,l=c.sqr(y),u=c.mul(u,l),f=c.mul(f,y)}return f}}function Gy(t){return t%ky===My?Ky:t%Hy===jy?rT:t%$y===QE?nT(t):yp(t)}var oT=(t,e)=>(Qt(t,e)&et)===et;je.isNegativeLE=oT;var sT=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function iT(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=sT.reduce((n,o)=>(n[o]="function",n),e);return(0,er._validateObject)(t,r),t}function _p(t,e,r){if(r<Lt)throw new Error("invalid exponent, negatives unsupported");if(r===Lt)return t.ONE;if(r===et)return e;let n=t.ONE,o=e;for(;r>Lt;)r&et&&(n=t.mul(n,o)),o=t.sqr(o),r>>=et;return n}function zy(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function aT(t,e,r){return t.mul(e,typeof r=="bigint"?hu(r,t.ORDER):t.inv(r))}function mu(t,e){let r=(t.ORDER-et)/es,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function cT(t,e){return mu(t,e)===1}function bp(t,e){e!==void 0&&(0,er.anumber)(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function yu(t,e,r=!1,n={}){if(t<=Lt)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let u=e;u.BITS&&(o=u.BITS),u.sqrt&&(s=u.sqrt),typeof u.isLE=="boolean"&&(r=u.isLE),typeof u.modFromBytes=="boolean"&&(i=u.modFromBytes),a=u.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:d}=bp(t,o);if(d>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let p,l=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:d,MASK:(0,er.bitMask)(c),ZERO:Lt,ONE:et,allowedLengths:a,create:u=>Qt(u,t),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return Lt<=u&&u<t},is0:u=>u===Lt,isValidNot0:u=>!l.is0(u)&&l.isValid(u),isOdd:u=>(u&et)===et,neg:u=>Qt(-u,t),eql:(u,f)=>u===f,sqr:u=>Qt(u*u,t),add:(u,f)=>Qt(u+f,t),sub:(u,f)=>Qt(u-f,t),mul:(u,f)=>Qt(u*f,t),pow:(u,f)=>_p(l,u,f),div:(u,f)=>Qt(u*hu(f,t),t),sqrN:u=>u*u,addN:(u,f)=>u+f,subN:(u,f)=>u-f,mulN:(u,f)=>u*f,inv:u=>hu(u,t),sqrt:s||(u=>(p||(p=Gy(t)),p(l,u))),toBytes:u=>r?(0,er.numberToBytesLE)(u,d):(0,er.numberToBytesBE)(u,d),fromBytes:(u,f=!0)=>{if(a){if(!a.includes(u.length)||u.length>d)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);let m=new Uint8Array(d);m.set(u,r?0:m.length-u.length),u=m}if(u.length!==d)throw new Error("Field.fromBytes: expected "+d+" bytes, got "+u.length);let h=r?(0,er.bytesToNumberLE)(u):(0,er.bytesToNumberBE)(u);if(i&&(h=Qt(h,t)),!f&&!l.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:u=>zy(l,u),cmov:(u,f,h)=>h?f:u});return Object.freeze(l)}function uT(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?r:t.neg(r)}function dT(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function lT(t,e,r=!1){t=(0,er.ensureBytes)("privateHash",t);let n=t.length,o=bp(e).nByteLength+8;if(o<24||n<o||n>1024)throw new Error("hashToPrivateScalar: expected "+o+"-1024 bytes of input, got "+n);let s=r?(0,er.bytesToNumberLE)(t):(0,er.bytesToNumberBE)(t);return Qt(s,e-et)+et}function gp(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Zy(t){let e=gp(t);return e+Math.ceil(e/2)}function fT(t,e,r=!1){let n=t.length,o=gp(e),s=Zy(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?(0,er.bytesToNumberLE)(t):(0,er.bytesToNumberBE)(t),a=Qt(i,e-et)+et;return r?(0,er.numberToBytesLE)(a,o):(0,er.numberToBytesBE)(a,o)}});var ya=Y(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.wNAF=void 0;Sr.negateCt=Tp;Sr.normalizeZ=pT;Sr.mulEndoUnsafe=hT;Sr.pippenger=mT;Sr.precomputeMSMUnsafe=yT;Sr.validateBasic=_T;Sr._createCurveFields=bT;var ha=Ir(),ma=Jr(),ti=BigInt(0),ts=BigInt(1);function Tp(t,e){let r=e.negate();return t?r:e}function pT(t,e){let r=(0,ma.FpInvertBatch)(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function Np(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function xp(t,e){Np(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=(0,ha.bitMask)(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Yy(t,e,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=ts);let d=e*n,p=d+Math.abs(a)-1,l=a===0,u=a<0,f=e%2!==0;return{nextN:c,offset:p,isZero:l,isNeg:u,isNegF:f,offsetF:d}}function Jy(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function Qy(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}var wp=new WeakMap,e_=new WeakMap;function Ep(t){return e_.get(t)||1}function Wy(t){if(t!==ti)throw new Error("invalid wNAF")}var Op=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>ti;)r&ts&&(n=n.add(o)),o=o.double(),r>>=ts;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=xp(r,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let d=1;d<o;d++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=xp(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:d,isZero:p,isNeg:l,isNegF:u,offsetF:f}=Yy(n,a,i);n=c,p?s=s.add(Tp(u,r[f])):o=o.add(Tp(l,r[d]))}return Wy(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=xp(e,this.bits);for(let i=0;i<s.windows&&n!==ti;i++){let{nextN:a,offset:c,isZero:d,isNeg:p}=Yy(n,i,s);if(n=a,!d){let l=r[c];o=o.add(p?l.negate():l)}}return Wy(n),o}getPrecomputes(e,r,n){let o=wp.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),wp.set(r,o))),o}cached(e,r,n){let o=Ep(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=Ep(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){Np(r,this.bits),e_.set(e,r),wp.delete(e)}hasCache(e){return Ep(e)!==1}};Sr.wNAF=Op;function hT(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>ti||n>ti;)r&ts&&(s=s.add(o)),n&ts&&(i=i.add(o)),o=o.double(),r>>=ts,n>>=ts;return{p1:s,p2:i}}function mT(t,e,r,n){Jy(r,t),Qy(n,e);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=t.ZERO,a=(0,ha.bitLen)(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let d=(0,ha.bitMask)(c),p=new Array(Number(d)+1).fill(i),l=Math.floor((e.BITS-1)/c)*c,u=i;for(let f=l;f>=0;f-=c){p.fill(i);for(let m=0;m<s;m++){let b=n[m],y=Number(b>>BigInt(f)&d);p[y]=p[y].add(r[m])}let h=i;for(let m=p.length-1,b=i;m>0;m--)b=b.add(p[m]),h=h.add(b);if(u=u.add(h),f!==0)for(let m=0;m<c;m++)u=u.double()}return u}function yT(t,e,r,n){Np(n,e.BITS),Jy(r,t);let o=t.ZERO,s=2**n-1,i=Math.ceil(e.BITS/n),a=(0,ha.bitMask)(n),c=r.map(d=>{let p=[];for(let l=0,u=d;l<s;l++)p.push(u),u=u.add(d);return p});return d=>{if(Qy(d,e),d.length>r.length)throw new Error("array of scalars must be smaller than array of points");let p=o;for(let l=0;l<i;l++){if(p!==o)for(let f=0;f<n;f++)p=p.double();let u=BigInt(i*n-(l+1)*n);for(let f=0;f<d.length;f++){let h=d[f],m=Number(h>>u&a);m&&(p=p.add(c[f][m-1]))}}return p}}function _T(t){return(0,ma.validateField)(t.Fp),(0,ha.validateObject)(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...(0,ma.nLength)(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Xy(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return(0,ma.validateField)(e),e}else return(0,ma.Field)(t,{isLE:r})}function bT(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let d=e[c];if(!(typeof d=="bigint"&&d>ti))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Xy(e.p,r.Fp,n),s=Xy(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}});var bu=Y(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr._DST_scalar=void 0;Qr.expand_message_xmd=n_;Qr.expand_message_xof=o_;Qr.hash_to_field=_u;Qr.isogenyMap=wT;Qr.createHasher=ET;var gt=Ir(),t_=Jr(),gT=gt.bytesToNumberBE;function yo(t,e){if(_a(t),_a(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);let r=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)r[n]=t&255,t>>>=8;return new Uint8Array(r)}function xT(t,e){let r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]^e[n];return r}function _a(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function r_(t){if(!(0,gt.isBytes)(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or string");return typeof t=="string"?(0,gt.utf8ToBytes)(t):t}function n_(t,e,r,n){(0,gt.abytes)(t),_a(r),e=r_(e),e.length>255&&(e=n((0,gt.concatBytes)((0,gt.utf8ToBytes)("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=(0,gt.concatBytes)(e,yo(e.length,1)),c=yo(0,s),d=yo(r,2),p=new Array(i),l=n((0,gt.concatBytes)(c,t,d,yo(0,1),a));p[0]=n((0,gt.concatBytes)(l,yo(1,1),a));for(let f=1;f<=i;f++){let h=[xT(l,p[f-1]),yo(f+1,1),a];p[f]=n((0,gt.concatBytes)(...h))}return(0,gt.concatBytes)(...p).slice(0,r)}function o_(t,e,r,n,o){if((0,gt.abytes)(t),_a(r),e=r_(e),e.length>255){let s=Math.ceil(2*n/8);e=o.create({dkLen:s}).update((0,gt.utf8ToBytes)("H2C-OVERSIZE-DST-")).update(e).digest()}if(r>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(t).update(yo(r,2)).update(e).update(yo(e.length,1)).digest()}function _u(t,e,r){(0,gt._validateObject)(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:s,hash:i,expand:a,DST:c}=r;if(!(0,gt.isHash)(r.hash))throw new Error("expected valid hash");(0,gt.abytes)(t),_a(e);let d=n.toString(2).length,p=Math.ceil((d+o)/8),l=e*s*p,u;if(a==="xmd")u=n_(t,c,l,i);else if(a==="xof")u=o_(t,c,l,o,i);else if(a==="_internal_pass")u=t;else throw new Error('expand must be "xmd" or "xof"');let f=new Array(e);for(let h=0;h<e;h++){let m=new Array(s);for(let b=0;b<s;b++){let y=p*(b+h*s),x=u.subarray(y,y+p);m[b]=(0,t_.mod)(gT(x),n)}f[h]=m}return f}function wT(t,e){let r=e.map(n=>Array.from(n).reverse());return(n,o)=>{let[s,i,a,c]=r.map(l=>l.reduce((u,f)=>t.add(t.mul(u,n),f))),[d,p]=(0,t_.FpInvertBatch)(t,[i,c],!0);return n=t.mul(s,d),o=t.mul(o,t.mul(a,p)),{x:n,y:o}}}Qr._DST_scalar=(0,gt.utf8ToBytes)("HashToScalar-");function ET(t,e,r){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function n(s){return t.fromAffine(e(s))}function o(s){let i=s.clearCofactor();return i.equals(t.ZERO)?t.ZERO:(i.assertValidity(),i)}return{defaults:r,hashToCurve(s,i){let a=Object.assign({},r,i),c=_u(s,2,a),d=n(c[0]),p=n(c[1]);return o(d.add(p))},encodeToCurve(s,i){let a=r.encodeDST?{DST:r.encodeDST}:{},c=Object.assign({},r,a,i),d=_u(s,1,c),p=n(d[0]);return o(p)},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(let i of s)if(typeof i!="bigint")throw new Error("expected array of bigints");return o(n(s))},hashToScalar(s,i){let a=t.Fn.ORDER,c=Object.assign({},r,{p:a,m:1,DST:Qr._DST_scalar},i);return _u(s,1,c)[0][0]}}}});var s_=Y(ns=>{"use strict";Object.defineProperty(ns,"__esModule",{value:!0});ns.hmac=ns.HMAC=void 0;var rs=dt(),ba=class extends rs.Hash{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,(0,rs.ahash)(e);let n=(0,rs.toBytes)(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let o=this.blockLen,s=new Uint8Array(o);s.set(n.length>o?e.create().update(n).digest():n);for(let i=0;i<s.length;i++)s[i]^=54;this.iHash.update(s),this.oHash=e.create();for(let i=0;i<s.length;i++)s[i]^=106;this.oHash.update(s),(0,rs.clean)(s)}update(e){return(0,rs.aexists)(this),this.iHash.update(e),this}digestInto(e){(0,rs.aexists)(this),(0,rs.abytes)(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:o,destroyed:s,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};ns.HMAC=ba;var TT=(t,e,r)=>new ba(t,e).update(r).digest();ns.hmac=TT;ns.hmac.create=(t,e)=>new ba(t,e)});var Ap=Y(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.DER=qe.DERErr=void 0;qe._splitEndoScalar=a_;qe._normFnElement=_o;qe.weierstrassN=Sp;qe.SWUFpSqrtRatio=u_;qe.mapToCurveSimpleSWU=vT;qe.ecdh=l_;qe.ecdsa=f_;qe.weierstrassPoints=RT;qe._legacyHelperEquat=h_;qe.weierstrass=BT;var OT=s_(),NT=dt(),W=Ir(),Sn=ya(),ni=Jr(),i_=(t,e)=>(t+(t>=0?e:-e)/en)/e;function a_(t,e,r){let[[n,o],[s,i]]=e,a=i_(i*t,r),c=i_(-o*t,r),d=t-a*n-c*s,p=-a*o-c*i,l=d<Ar,u=p<Ar;l&&(d=-d),u&&(p=-p);let f=(0,W.bitMask)(Math.ceil((0,W.bitLen)(r)/2))+xt;if(d<Ar||d>=f||p<Ar||p>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:l,k1:d,k2neg:u,k2:p}}function Rp(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function vp(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return(0,W._abool2)(r.lowS,"lowS"),(0,W._abool2)(r.prehash,"prehash"),r.format!==void 0&&Rp(r.format),r}var gu=class extends Error{constructor(e=""){super(e)}};qe.DERErr=gu;qe.DER={Err:gu,_tlv:{encode:(t,e)=>{let{Err:r}=qe.DER;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,o=(0,W.numberToHexUnpadded)(n);if(o.length/2&128)throw new r("tlv.encode: long form length too big");let s=n>127?(0,W.numberToHexUnpadded)(o.length/2|128):"";return(0,W.numberToHexUnpadded)(t)+s+o+e},decode(t,e){let{Err:r}=qe.DER,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let o=e[n++],s=!!(o&128),i=0;if(!s)i=o;else{let c=o&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");let d=e.subarray(n,n+c);if(d.length!==c)throw new r("tlv.decode: length bytes not complete");if(d[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let p of d)i=i<<8|p;if(n+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}let a=e.subarray(n,n+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+i)}}},_int:{encode(t){let{Err:e}=qe.DER;if(t<Ar)throw new e("integer: negative integers are not allowed");let r=(0,W.numberToHexUnpadded)(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=qe.DER;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return(0,W.bytesToNumberBE)(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=qe.DER,o=(0,W.ensureBytes)("signature",t),{v:s,l:i}=n.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l:c}=n.decode(2,s),{v:d,l:p}=n.decode(2,c);if(p.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(d)}},hexFromSig(t){let{_tlv:e,_int:r}=qe.DER,n=e.encode(2,r.encode(t.r)),o=e.encode(2,r.encode(t.s)),s=n+o;return e.encode(48,s)}};var Ar=BigInt(0),xt=BigInt(1),en=BigInt(2),ri=BigInt(3),Ip=BigInt(4);function _o(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let o=(0,W.ensureBytes)("private key",e);try{n=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Sp(t,e={}){let r=(0,Sn._createCurveFields)("weierstrass",t,e),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;(0,W._validateObject)(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let d=d_(n,o);function p(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(C,g,w){let{x:O,y:P}=g.toAffine(),L=n.toBytes(O);if((0,W._abool2)(w,"isCompressed"),w){p();let I=!n.isOdd(P);return(0,W.concatBytes)(c_(I),L)}else return(0,W.concatBytes)(Uint8Array.of(4),L,n.toBytes(P))}function u(C){(0,W._abytes2)(C,void 0,"Point");let{publicKey:g,publicKeyUncompressed:w}=d,O=C.length,P=C[0],L=C.subarray(1);if(O===g&&(P===2||P===3)){let I=n.fromBytes(L);if(!n.isValid(I))throw new Error("bad point: is not on curve, wrong x");let B=m(I),F;try{F=n.sqrt(B)}catch(H){let Z=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+Z)}p();let U=n.isOdd(F);return(P&1)===1!==U&&(F=n.neg(F)),{x:I,y:F}}else if(O===w&&P===4){let I=n.BYTES,B=n.fromBytes(L.subarray(0,I)),F=n.fromBytes(L.subarray(I,I*2));if(!b(B,F))throw new Error("bad point: is not on curve");return{x:B,y:F}}else throw new Error(`bad point: got length ${O}, expected compressed=${g} or uncompressed=${w}`)}let f=e.toBytes||l,h=e.fromBytes||u;function m(C){let g=n.sqr(C),w=n.mul(g,C);return n.add(n.add(w,n.mul(C,s.a)),s.b)}function b(C,g){let w=n.sqr(g),O=m(C);return n.eql(w,O)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(s.a,ri),Ip),x=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(y,x)))throw new Error("bad curve params: a or b");function _(C,g,w=!1){if(!n.isValid(g)||w&&n.is0(g))throw new Error(`bad point coordinate ${C}`);return g}function T(C){if(!(C instanceof E))throw new Error("ProjectivePoint expected")}function N(C){if(!c||!c.basises)throw new Error("no endo");return a_(C,c.basises,o.ORDER)}let v=(0,W.memoized)((C,g)=>{let{X:w,Y:O,Z:P}=C;if(n.eql(P,n.ONE))return{x:w,y:O};let L=C.is0();g==null&&(g=L?n.ONE:n.inv(P));let I=n.mul(w,g),B=n.mul(O,g),F=n.mul(P,g);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:I,y:B}}),R=(0,W.memoized)(C=>{if(C.is0()){if(e.allowInfinityPoint&&!n.is0(C.Y))return;throw new Error("bad point: ZERO")}let{x:g,y:w}=C.toAffine();if(!n.isValid(g)||!n.isValid(w))throw new Error("bad point: x or y not field elements");if(!b(g,w))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(C,g,w,O,P){return w=new E(n.mul(w.X,C),w.Y,w.Z),g=(0,Sn.negateCt)(O,g),w=(0,Sn.negateCt)(P,w),g.add(w)}class E{constructor(g,w,O){this.X=_("x",g),this.Y=_("y",w,!0),this.Z=_("z",O),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){let{x:w,y:O}=g||{};if(!g||!n.isValid(w)||!n.isValid(O))throw new Error("invalid affine point");if(g instanceof E)throw new Error("projective point not allowed");return n.is0(w)&&n.is0(O)?E.ZERO:new E(w,O,n.ONE)}static fromBytes(g){let w=E.fromAffine(h((0,W._abytes2)(g,void 0,"point")));return w.assertValidity(),w}static fromHex(g){return E.fromBytes((0,W.ensureBytes)("pointHex",g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,w=!0){return V.createCache(this,g),w||this.multiply(ri),this}assertValidity(){R(this)}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){T(g);let{X:w,Y:O,Z:P}=this,{X:L,Y:I,Z:B}=g,F=n.eql(n.mul(w,B),n.mul(L,P)),U=n.eql(n.mul(O,B),n.mul(I,P));return F&&U}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b:w}=s,O=n.mul(w,ri),{X:P,Y:L,Z:I}=this,B=n.ZERO,F=n.ZERO,U=n.ZERO,q=n.mul(P,P),H=n.mul(L,L),Z=n.mul(I,I),G=n.mul(P,L);return G=n.add(G,G),U=n.mul(P,I),U=n.add(U,U),B=n.mul(g,U),F=n.mul(O,Z),F=n.add(B,F),B=n.sub(H,F),F=n.add(H,F),F=n.mul(B,F),B=n.mul(G,B),U=n.mul(O,U),Z=n.mul(g,Z),G=n.sub(q,Z),G=n.mul(g,G),G=n.add(G,U),U=n.add(q,q),q=n.add(U,q),q=n.add(q,Z),q=n.mul(q,G),F=n.add(F,q),Z=n.mul(L,I),Z=n.add(Z,Z),q=n.mul(Z,G),B=n.sub(B,q),U=n.mul(Z,H),U=n.add(U,U),U=n.add(U,U),new E(B,F,U)}add(g){T(g);let{X:w,Y:O,Z:P}=this,{X:L,Y:I,Z:B}=g,F=n.ZERO,U=n.ZERO,q=n.ZERO,H=s.a,Z=n.mul(s.b,ri),G=n.mul(w,L),ae=n.mul(O,I),te=n.mul(P,B),Ce=n.add(w,O),ne=n.add(L,I);Ce=n.mul(Ce,ne),ne=n.add(G,ae),Ce=n.sub(Ce,ne),ne=n.add(w,P);let me=n.add(L,B);return ne=n.mul(ne,me),me=n.add(G,te),ne=n.sub(ne,me),me=n.add(O,P),F=n.add(I,B),me=n.mul(me,F),F=n.add(ae,te),me=n.sub(me,F),q=n.mul(H,ne),F=n.mul(Z,te),q=n.add(F,q),F=n.sub(ae,q),q=n.add(ae,q),U=n.mul(F,q),ae=n.add(G,G),ae=n.add(ae,G),te=n.mul(H,te),ne=n.mul(Z,ne),ae=n.add(ae,te),te=n.sub(G,te),te=n.mul(H,te),ne=n.add(ne,te),G=n.mul(ae,ne),U=n.add(U,G),G=n.mul(me,ne),F=n.mul(Ce,F),F=n.sub(F,G),G=n.mul(Ce,ae),q=n.mul(me,q),q=n.add(q,G),new E(F,U,q)}subtract(g){return this.add(g.negate())}is0(){return this.equals(E.ZERO)}multiply(g){let{endo:w}=e;if(!o.isValidNot0(g))throw new Error("invalid scalar: out of range");let O,P,L=I=>V.cached(this,I,B=>(0,Sn.normalizeZ)(E,B));if(w){let{k1neg:I,k1:B,k2neg:F,k2:U}=N(g),{p:q,f:H}=L(B),{p:Z,f:G}=L(U);P=H.add(G),O=A(w.beta,q,Z,I,F)}else{let{p:I,f:B}=L(g);O=I,P=B}return(0,Sn.normalizeZ)(E,[O,P])[0]}multiplyUnsafe(g){let{endo:w}=e,O=this;if(!o.isValid(g))throw new Error("invalid scalar: out of range");if(g===Ar||O.is0())return E.ZERO;if(g===xt)return O;if(V.hasCache(this))return this.multiply(g);if(w){let{k1neg:P,k1:L,k2neg:I,k2:B}=N(g),{p1:F,p2:U}=(0,Sn.mulEndoUnsafe)(E,O,L,B);return A(w.beta,F,U,P,I)}else return V.unsafe(O,g)}multiplyAndAddUnsafe(g,w,O){let P=this.multiplyUnsafe(w).add(g.multiplyUnsafe(O));return P.is0()?void 0:P}toAffine(g){return v(this,g)}isTorsionFree(){let{isTorsionFree:g}=e;return i===xt?!0:g?g(E,this):V.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return i===xt?this:g?g(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return(0,W._abool2)(g,"isCompressed"),this.assertValidity(),f(E,this,g)}toHex(g=!0){return(0,W.bytesToHex)(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(g=!0){return this.toBytes(g)}_setWindowSize(g){this.precompute(g)}static normalizeZ(g){return(0,Sn.normalizeZ)(E,g)}static msm(g,w){return(0,Sn.pippenger)(E,o,g,w)}static fromPrivateKey(g){return E.BASE.multiply(_o(o,g))}}E.BASE=new E(s.Gx,s.Gy,n.ONE),E.ZERO=new E(n.ZERO,n.ONE,n.ZERO),E.Fp=n,E.Fn=o;let S=o.BITS,V=new Sn.wNAF(E,e.endo?Math.ceil(S/2):S);return E.BASE.precompute(8),E}function c_(t){return Uint8Array.of(t?2:3)}function u_(t,e){let r=t.ORDER,n=Ar;for(let h=r-xt;h%en===Ar;h/=en)n+=xt;let o=n,s=en<<o-xt-xt,i=s*en,a=(r-xt)/i,c=(a-xt)/en,d=i-xt,p=s,l=t.pow(e,a),u=t.pow(e,(a+xt)/en),f=(h,m)=>{let b=l,y=t.pow(m,d),x=t.sqr(y);x=t.mul(x,m);let _=t.mul(h,x);_=t.pow(_,c),_=t.mul(_,y),y=t.mul(_,m),x=t.mul(_,h);let T=t.mul(x,y);_=t.pow(T,p);let N=t.eql(_,t.ONE);y=t.mul(x,u),_=t.mul(T,b),x=t.cmov(y,x,N),T=t.cmov(_,T,N);for(let v=o;v>xt;v--){let R=v-en;R=en<<R-xt;let A=t.pow(T,R),E=t.eql(A,t.ONE);y=t.mul(x,b),b=t.mul(b,b),A=t.mul(T,b),x=t.cmov(y,x,E),T=t.cmov(A,T,E)}return{isValid:N,value:x}};if(t.ORDER%Ip===ri){let h=(t.ORDER-ri)/Ip,m=t.sqrt(t.neg(e));f=(b,y)=>{let x=t.sqr(y),_=t.mul(b,y);x=t.mul(x,_);let T=t.pow(x,h);T=t.mul(T,_);let N=t.mul(T,m),v=t.mul(t.sqr(T),y),R=t.eql(v,b),A=t.cmov(N,T,R);return{isValid:R,value:A}}}return f}function vT(t,e){(0,ni.validateField)(t);let{A:r,B:n,Z:o}=e;if(!t.isValid(r)||!t.isValid(n)||!t.isValid(o))throw new Error("mapToCurveSimpleSWU: invalid opts");let s=u_(t,o);if(!t.isOdd)throw new Error("Field does not have .isOdd()");return i=>{let a,c,d,p,l,u,f,h;a=t.sqr(i),a=t.mul(a,o),c=t.sqr(a),c=t.add(c,a),d=t.add(c,t.ONE),d=t.mul(d,n),p=t.cmov(o,t.neg(c),!t.eql(c,t.ZERO)),p=t.mul(p,r),c=t.sqr(d),u=t.sqr(p),l=t.mul(u,r),c=t.add(c,l),c=t.mul(c,d),u=t.mul(u,p),l=t.mul(u,n),c=t.add(c,l),f=t.mul(a,d);let{isValid:m,value:b}=s(c,u);h=t.mul(a,i),h=t.mul(h,b),f=t.cmov(f,d,m),h=t.cmov(h,b,m);let y=t.isOdd(i)===t.isOdd(h);h=t.cmov(t.neg(h),h,y);let x=(0,ni.FpInvertBatch)(t,[p],!0)[0];return f=t.mul(f,x),{x:f,y:h}}}function d_(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function l_(t,e={}){let{Fn:r}=t,n=e.randomBytes||W.randomBytes,o=Object.assign(d_(t.Fp,r),{seed:(0,ni.getMinHashLength)(r.ORDER)});function s(f){try{return!!_o(r,f)}catch{return!1}}function i(f,h){let{publicKey:m,publicKeyUncompressed:b}=o;try{let y=f.length;return h===!0&&y!==m||h===!1&&y!==b?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=n(o.seed)){return(0,ni.mapHashToField)((0,W._abytes2)(f,o.seed,"seed"),r.ORDER)}function c(f,h=!0){return t.BASE.multiply(_o(r,f)).toBytes(h)}function d(f){let h=a(f);return{secretKey:h,publicKey:c(h)}}function p(f){if(typeof f=="bigint")return!1;if(f instanceof t)return!0;let{secretKey:h,publicKey:m,publicKeyUncompressed:b}=o;if(r.allowedLengths||h===m)return;let y=(0,W.ensureBytes)("key",f).length;return y===m||y===b}function l(f,h,m=!0){if(p(f)===!0)throw new Error("first arg must be private key");if(p(h)===!1)throw new Error("second arg must be public key");let b=_o(r,f);return t.fromHex(h).multiply(b).toBytes(m)}return Object.freeze({getPublicKey:c,getSharedSecret:l,keygen:d,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:i,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:f=>_o(r,f),precompute(f=8,h=t.BASE){return h.precompute(f,!1)}},lengths:o})}function f_(t,e,r={}){(0,NT.ahash)(e),(0,W._validateObject)(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||W.randomBytes,o=r.hmac||((w,...O)=>(0,OT.hmac)(e,w,(0,W.concatBytes)(...O))),{Fp:s,Fn:i}=t,{ORDER:a,BITS:c}=i,{keygen:d,getPublicKey:p,getSharedSecret:l,utils:u,lengths:f}=l_(t,r),h={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},m="compact";function b(w){let O=a>>xt;return w>O}function y(w,O){if(!i.isValidNot0(O))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return O}function x(w,O){Rp(O);let P=f.signature,L=O==="compact"?P:O==="recovered"?P+1:void 0;return(0,W._abytes2)(w,L,`${O} signature`)}class _{constructor(O,P,L){this.r=y("r",O),this.s=y("s",P),L!=null&&(this.recovery=L),Object.freeze(this)}static fromBytes(O,P=m){x(O,P);let L;if(P==="der"){let{r:U,s:q}=qe.DER.toSig((0,W._abytes2)(O));return new _(U,q)}P==="recovered"&&(L=O[0],P="compact",O=O.subarray(1));let I=i.BYTES,B=O.subarray(0,I),F=O.subarray(I,I*2);return new _(i.fromBytes(B),i.fromBytes(F),L)}static fromHex(O,P){return this.fromBytes((0,W.hexToBytes)(O),P)}addRecoveryBit(O){return new _(this.r,this.s,O)}recoverPublicKey(O){let P=s.ORDER,{r:L,s:I,recovery:B}=this;if(B==null||![0,1,2,3].includes(B))throw new Error("recovery id invalid");if(a*en<P&&B>1)throw new Error("recovery id is ambiguous for h>1 curve");let U=B===2||B===3?L+a:L;if(!s.isValid(U))throw new Error("recovery id 2 or 3 invalid");let q=s.toBytes(U),H=t.fromBytes((0,W.concatBytes)(c_((B&1)===0),q)),Z=i.inv(U),G=N((0,W.ensureBytes)("msgHash",O)),ae=i.create(-G*Z),te=i.create(I*Z),Ce=t.BASE.multiplyUnsafe(ae).add(H.multiplyUnsafe(te));if(Ce.is0())throw new Error("point at infinify");return Ce.assertValidity(),Ce}hasHighS(){return b(this.s)}toBytes(O=m){if(Rp(O),O==="der")return(0,W.hexToBytes)(qe.DER.hexFromSig(this));let P=i.toBytes(this.r),L=i.toBytes(this.s);if(O==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return(0,W.concatBytes)(Uint8Array.of(this.recovery),P,L)}return(0,W.concatBytes)(P,L)}toHex(O){return(0,W.bytesToHex)(this.toBytes(O))}assertValidity(){}static fromCompact(O){return _.fromBytes((0,W.ensureBytes)("sig",O),"compact")}static fromDER(O){return _.fromBytes((0,W.ensureBytes)("sig",O),"der")}normalizeS(){return this.hasHighS()?new _(this.r,i.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return(0,W.bytesToHex)(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return(0,W.bytesToHex)(this.toBytes("compact"))}}let T=r.bits2int||function(O){if(O.length>8192)throw new Error("input is too large");let P=(0,W.bytesToNumberBE)(O),L=O.length*8-c;return L>0?P>>BigInt(L):P},N=r.bits2int_modN||function(O){return i.create(T(O))},v=(0,W.bitMask)(c);function R(w){return(0,W.aInRange)("num < 2^"+c,w,Ar,v),i.toBytes(w)}function A(w,O){return(0,W._abytes2)(w,void 0,"message"),O?(0,W._abytes2)(e(w),void 0,"prehashed message"):w}function E(w,O,P){if(["recovered","canonical"].some(ae=>ae in P))throw new Error("sign() legacy options not supported");let{lowS:L,prehash:I,extraEntropy:B}=vp(P,h);w=A(w,I);let F=N(w),U=_o(i,O),q=[R(U),R(F)];if(B!=null&&B!==!1){let ae=B===!0?n(f.secretKey):B;q.push((0,W.ensureBytes)("extraEntropy",ae))}let H=(0,W.concatBytes)(...q),Z=F;function G(ae){let te=T(ae);if(!i.isValidNot0(te))return;let Ce=i.inv(te),ne=t.BASE.multiply(te).toAffine(),me=i.create(ne.x);if(me===Ar)return;let Tt=i.create(Ce*i.create(Z+me*U));if(Tt===Ar)return;let Vt=(ne.x===me?0:2)|Number(ne.y&xt),pr=Tt;return L&&b(Tt)&&(pr=i.neg(Tt),Vt^=1),new _(me,pr,Vt)}return{seed:H,k2sig:G}}function S(w,O,P={}){w=(0,W.ensureBytes)("message",w);let{seed:L,k2sig:I}=E(w,O,P);return(0,W.createHmacDrbg)(e.outputLen,i.BYTES,o)(L,I)}function V(w){let O,P=typeof w=="string"||(0,W.isBytes)(w),L=!P&&w!==null&&typeof w=="object"&&typeof w.r=="bigint"&&typeof w.s=="bigint";if(!P&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(L)O=new _(w.r,w.s);else if(P){try{O=_.fromBytes((0,W.ensureBytes)("sig",w),"der")}catch(I){if(!(I instanceof qe.DER.Err))throw I}if(!O)try{O=_.fromBytes((0,W.ensureBytes)("sig",w),"compact")}catch{return!1}}return O||!1}function C(w,O,P,L={}){let{lowS:I,prehash:B,format:F}=vp(L,h);if(P=(0,W.ensureBytes)("publicKey",P),O=A((0,W.ensureBytes)("message",O),B),"strict"in L)throw new Error("options.strict was renamed to lowS");let U=F===void 0?V(w):_.fromBytes((0,W.ensureBytes)("sig",w),F);if(U===!1)return!1;try{let q=t.fromBytes(P);if(I&&U.hasHighS())return!1;let{r:H,s:Z}=U,G=N(O),ae=i.inv(Z),te=i.create(G*ae),Ce=i.create(H*ae),ne=t.BASE.multiplyUnsafe(te).add(q.multiplyUnsafe(Ce));return ne.is0()?!1:i.create(ne.x)===H}catch{return!1}}function g(w,O,P={}){let{prehash:L}=vp(P,h);return O=A(O,L),_.fromBytes(w,"recovered").recoverPublicKey(O).toBytes()}return Object.freeze({keygen:d,getPublicKey:p,getSharedSecret:l,utils:u,lengths:f,Point:t,sign:S,verify:C,recoverPublicKey:g,Signature:_,hash:e})}function RT(t){let{CURVE:e,curveOpts:r}=p_(t),n=Sp(e,r);return ST(t,n)}function p_(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=(0,ni.Field)(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function IT(t){let{CURVE:e,curveOpts:r}=p_(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function h_(t,e,r){function n(o){let s=t.sqr(o),i=t.mul(s,o);return t.add(t.add(i,t.mul(o,e)),r)}return n}function ST(t,e){let{Fp:r,Fn:n}=e;function o(i){return(0,W.inRange)(i,xt,n.ORDER)}let s=h_(r,t.a,t.b);return Object.assign({},{CURVE:t,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:i=>_o(n,i),weierstrassEquation:s,isWithinCurveOrder:o})}function AT(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,(0,ni.nLength)(r.Fn.ORDER,r.Fn.BITS))})}function BT(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:o}=IT(t),s=Sp(e,r),i=f_(s,n,o);return AT(t,i)}});var x_=Y(Cp=>{"use strict";Object.defineProperty(Cp,"__esModule",{value:!0});Cp.bls=FT;var ga=Ir(),m_=ya(),y_=bu(),__=Jr(),wu=Ap(),CT=BigInt(0),xu=BigInt(1),b_=BigInt(2),oi=BigInt(3);function PT(t){let e=[];for(;t>xu;t>>=xu)(t&xu)===CT?e.unshift(0):(t&oi)===oi?(e.unshift(-1),t+=xu):e.unshift(1);return e}function Bp(t){if(!Array.isArray(t)||t.length===0)throw new Error("expected non-empty array")}function DT(t,e,r,n){let{Fp2:o,Fp12:s}=t,{twistType:i,ateLoopSize:a,xNegative:c,postPrecompute:d}=n,p;if(i==="multiplicative")p=(_,T,N,v,R,A)=>s.mul014(v,_,o.mul(T,R),o.mul(N,A));else if(i==="divisive")p=(_,T,N,v,R,A)=>s.mul034(v,o.mul(N,A),o.mul(T,R),_);else throw new Error("bls: unknown twist type");let l=o.div(o.ONE,o.mul(o.ONE,b_));function u(_,T,N,v){let R=o.sqr(N),A=o.sqr(v),E=o.mulByB(o.mul(A,oi)),S=o.mul(E,oi),V=o.sub(o.sub(o.sqr(o.add(N,v)),A),R),C=o.sub(E,R),g=o.mul(o.sqr(T),oi),w=o.neg(V);return _.push([C,g,w]),T=o.mul(o.mul(o.mul(o.sub(R,S),T),N),l),N=o.sub(o.sqr(o.mul(o.add(R,S),l)),o.mul(o.sqr(E),oi)),v=o.mul(R,V),{Rx:T,Ry:N,Rz:v}}function f(_,T,N,v,R,A){let E=o.sub(N,o.mul(A,v)),S=o.sub(T,o.mul(R,v)),V=o.sub(o.mul(E,R),o.mul(S,A)),C=o.neg(E),g=S;_.push([V,C,g]);let w=o.sqr(S),O=o.mul(w,S),P=o.mul(w,T),L=o.add(o.sub(O,o.mul(P,b_)),o.mul(o.sqr(E),v));return T=o.mul(S,L),N=o.sub(o.mul(o.sub(P,L),E),o.mul(O,N)),v=o.mul(v,O),{Rx:T,Ry:N,Rz:v}}let h=PT(a),m=(0,ga.memoized)(_=>{let T=_,{x:N,y:v}=T.toAffine(),R=N,A=v,E=o.neg(v),S=R,V=A,C=o.ONE,g=[];for(let w of h){let O=[];({Rx:S,Ry:V,Rz:C}=u(O,S,V,C)),w&&({Rx:S,Ry:V,Rz:C}=f(O,S,V,C,R,w===-1?E:A)),g.push(O)}if(d){let w=g[g.length-1];d(S,V,C,R,A,f.bind(null,w))}return g});function b(_,T=!1){let N=s.ONE;if(_.length){let v=_[0][0].length;for(let R=0;R<v;R++){N=s.sqr(N);for(let[A,E,S]of _)for(let[V,C,g]of A[R])N=p(V,C,g,N,E,S)}}return c&&(N=s.conjugate(N)),T?s.finalExponentiate(N):N}function y(_,T=!0){let N=[];(0,m_.normalizeZ)(e,_.map(({g1:v})=>v)),(0,m_.normalizeZ)(r,_.map(({g2:v})=>v));for(let{g1:v,g2:R}of _){if(v.is0()||R.is0())throw new Error("pairing is not available for ZERO point");v.assertValidity(),R.assertValidity();let A=v.toAffine();N.push([m(R),A.x,A.y])}return b(N,T)}function x(_,T,N=!0){return y([{g1:_,g2:T}],N)}return{Fp12:s,millerLoopBatch:b,pairing:x,pairingBatch:y,calcPairingPrecomputes:m}}function g_(t,e,r,n,o){let{Fp12:s,pairingBatch:i}=t;function a(l){return l instanceof e.Point?l:e.Point.fromHex(l)}function c(l){return l instanceof r.Point?l:r.Point.fromHex(l)}function d(l){if(!(l instanceof r.Point))throw new Error(`expected valid message hashed to ${o?"G1":"G2"} curve`);return l}let p=o?(l,u)=>({g1:u,g2:l}):(l,u)=>({g1:l,g2:u});return{getPublicKey(l){let u=(0,wu._normFnElement)(e.Point.Fn,l);return e.Point.BASE.multiply(u)},sign(l,u,f){if(f!=null)throw new Error("sign() expects 2 arguments");let h=(0,wu._normFnElement)(e.Point.Fn,u);return d(l).assertValidity(),l.multiply(h)},verify(l,u,f,h){if(h!=null)throw new Error("verify() expects 3 arguments");l=c(l),f=a(f);let m=f.negate(),b=e.Point.BASE,y=d(u),x=l,_=i([p(m,y),p(b,x)]);return s.eql(_,s.ONE)},verifyBatch(l,u,f){if(Bp(u),f.length!==u.length)throw new Error("amount of public keys and messages should be equal");let h=c(l),m=u,b=f.map(a),y=new Map;for(let T=0;T<b.length;T++){let N=b[T],v=m[T],R=y.get(v);R===void 0&&(R=[],y.set(v,R)),R.push(N)}let x=[],_=e.Point.BASE;try{for(let[T,N]of y){let v=N.reduce((R,A)=>R.add(A));x.push(p(v,T))}return x.push(p(_.negate(),h)),s.eql(i(x),s.ONE)}catch{return!1}},aggregatePublicKeys(l){Bp(l),l=l.map(f=>a(f));let u=l.reduce((f,h)=>f.add(h),e.Point.ZERO);return u.assertValidity(),u},aggregateSignatures(l){Bp(l),l=l.map(f=>c(f));let u=l.reduce((f,h)=>f.add(h),r.Point.ZERO);return u.assertValidity(),u},hash(l,u){(0,ga.abytes)(l);let f=u?{DST:u}:void 0;return r.hashToCurve(l,f)},Signature:n}}function FT(t){let{Fp:e,Fr:r,Fp2:n,Fp6:o,Fp12:s}=t.fields,i=(0,wu.weierstrassPoints)(t.G1),a=Object.assign(i,(0,y_.createHasher)(i.Point,t.G1.mapToCurve,{...t.htfDefaults,...t.G1.htfDefaults})),c=(0,wu.weierstrassPoints)(t.G2),d=Object.assign(c,(0,y_.createHasher)(c.Point,t.G2.mapToCurve,{...t.htfDefaults,...t.G2.htfDefaults})),p=DT(t.fields,a.Point,d.Point,{...t.params,postPrecompute:t.postPrecompute}),{millerLoopBatch:l,pairing:u,pairingBatch:f,calcPairingPrecomputes:h}=p,m=g_(p,a,d,t.G2.Signature,!1),b=g_(p,d,a,t.G1.ShortSignature,!0),y=t.randomBytes||ga.randomBytes,x=()=>{let I=(0,__.getMinHashLength)(r.ORDER);return(0,__.mapHashToField)(y(I),r.ORDER)},_={randomSecretKey:x,randomPrivateKey:x,calcPairingPrecomputes:h},{ShortSignature:T}=t.G1,{Signature:N}=t.G2;function v(I,B){return I instanceof a.Point?I:b.hash((0,ga.ensureBytes)("point",I),B?.DST)}function R(I,B){return I instanceof d.Point?I:m.hash((0,ga.ensureBytes)("point",I),B?.DST)}function A(I){return m.getPublicKey(I).toBytes(!0)}function E(I){return b.getPublicKey(I).toBytes(!0)}function S(I,B,F){let U=R(I,F),q=m.sign(U,B);return I instanceof d.Point?q:N.toBytes(q)}function V(I,B,F){let U=v(I,F),q=b.sign(U,B);return I instanceof a.Point?q:T.toBytes(q)}function C(I,B,F,U){let q=R(B,U);return m.verify(I,q,F)}function g(I,B,F,U){let q=v(B,U);return b.verify(I,q,F)}function w(I){let B=m.aggregatePublicKeys(I);return I[0]instanceof a.Point?B:B.toBytes(!0)}function O(I){let B=m.aggregateSignatures(I);return I[0]instanceof d.Point?B:N.toBytes(B)}function P(I){let B=b.aggregateSignatures(I);return I[0]instanceof a.Point?B:T.toBytes(B)}function L(I,B,F,U){let q=B.map(H=>R(H,U));return m.verifyBatch(I,q,F)}return a.Point.BASE.precompute(4),{longSignatures:m,shortSignatures:b,millerLoopBatch:l,pairing:u,pairingBatch:f,verifyBatch:L,fields:{Fr:r,Fp:e,Fp2:n,Fp6:o,Fp12:s},params:{ateLoopSize:t.params.ateLoopSize,twistType:t.params.twistType,r:t.params.r,G1b:t.G1.b,G2b:t.G2.b},utils:_,getPublicKey:A,getPublicKeyForShortSignatures:E,sign:S,signShortSignature:V,verify:C,verifyShortSignature:g,aggregatePublicKeys:w,aggregateSignatures:O,aggregateShortSignatures:P,G1:a,G2:d,Signature:N,ShortSignature:T}}});var O_=Y(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});Eu.psiFrobenius=VT;Eu.tower12=UT;var bo=Ir(),An=Jr(),w_=BigInt(0),Bn=BigInt(1),qt=BigInt(2),E_=BigInt(3);function Vp(t,e,r,n,o=1,s){let i=BigInt(s===void 0?n:s),a=r**BigInt(n),c=[];for(let d=0;d<o;d++){let p=BigInt(d+1),l=[];for(let u=0,f=Bn;u<n;u++){let h=(p*f-p)/i%a;l.push(t.pow(e,h)),f*=r}c.push(l)}return c}function VT(t,e,r){let n=e.pow(r,(t.ORDER-Bn)/E_),o=e.pow(r,(t.ORDER-Bn)/qt);function s(u,f){let h=e.mul(e.frobeniusMap(u,1),n),m=e.mul(e.frobeniusMap(f,1),o);return[h,m]}let i=e.pow(r,(t.ORDER**qt-Bn)/E_),a=e.pow(r,(t.ORDER**qt-Bn)/qt);if(!e.eql(a,e.neg(e.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(u,f){return[e.mul(u,i),e.neg(f)]}let d=u=>(f,h)=>{let m=h.toAffine(),b=u(m.x,m.y);return f.fromAffine({x:b[0],y:b[1]})},p=d(s),l=d(c);return{psi:s,psi2:c,G2psi:p,G2psi2:l,PSI_X:n,PSI_Y:o,PSI2_X:i,PSI2_Y:a}}var T_=(t,e)=>{if(e.length!==2)throw new Error("invalid tuple");let r=e.map(n=>t.create(n));return{c0:r[0],c1:r[1]}},Pp=class{constructor(e,r={}){this.MASK=Bn;let n=e.ORDER,o=n*n;this.Fp=e,this.ORDER=o,this.BITS=(0,bo.bitLen)(o),this.BYTES=Math.ceil((0,bo.bitLen)(o)/8),this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO},this.Fp_NONRESIDUE=e.create(r.NONRESIDUE||BigInt(-1)),this.Fp_div2=e.div(e.ONE,qt),this.NONRESIDUE=T_(e,r.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=Vp(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=r.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return T_(this.Fp,e)}create(e){return e}isValid({c0:e,c1:r}){function n(o,s){return typeof o=="bigint"&&w_<=o&&o<s}return n(e,this.ORDER)&&n(r,this.ORDER)}is0({c0:e,c1:r}){return this.Fp.is0(e)&&this.Fp.is0(r)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}eql({c0:e,c1:r},{c0:n,c1:o}){return this.Fp.eql(e,n)&&this.Fp.eql(r,o)}neg({c0:e,c1:r}){return{c0:this.Fp.neg(e),c1:this.Fp.neg(r)}}pow(e,r){return An.FpPow(this,e,r)}invertBatch(e){return An.FpInvertBatch(this,e)}add(e,r){let{c0:n,c1:o}=e,{c0:s,c1:i}=r;return{c0:this.Fp.add(n,s),c1:this.Fp.add(o,i)}}sub({c0:e,c1:r},{c0:n,c1:o}){return{c0:this.Fp.sub(e,n),c1:this.Fp.sub(r,o)}}mul({c0:e,c1:r},n){let{Fp:o}=this;if(typeof n=="bigint")return{c0:o.mul(e,n),c1:o.mul(r,n)};let{c0:s,c1:i}=n,a=o.mul(e,s),c=o.mul(r,i),d=o.sub(a,c),p=o.sub(o.mul(o.add(e,r),o.add(s,i)),o.add(a,c));return{c0:d,c1:p}}sqr({c0:e,c1:r}){let{Fp:n}=this,o=n.add(e,r),s=n.sub(e,r),i=n.add(e,e);return{c0:n.mul(o,s),c1:n.mul(i,r)}}addN(e,r){return this.add(e,r)}subN(e,r){return this.sub(e,r)}mulN(e,r){return this.mul(e,r)}sqrN(e){return this.sqr(e)}div(e,r){let{Fp:n}=this;return this.mul(e,typeof r=="bigint"?n.inv(n.create(r)):this.inv(r))}inv({c0:e,c1:r}){let{Fp:n}=this,o=n.inv(n.create(e*e+r*r));return{c0:n.mul(o,n.create(e)),c1:n.mul(o,n.create(-r))}}sqrt(e){let{Fp:r}=this,n=this,{c0:o,c1:s}=e;if(r.is0(s))return An.FpLegendre(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 i=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(s),this.Fp_NONRESIDUE))),a=r.mul(r.add(i,o),this.Fp_div2);An.FpLegendre(r,a)===-1&&(a=r.sub(a,i));let d=r.sqrt(a),p=n.create({c0:d,c1:r.div(r.mul(s,this.Fp_div2),d)});if(!n.eql(n.sqr(p),e))throw new Error("Cannot find square root");let l=p,u=n.neg(l),{re:f,im:h}=n.reim(l),{re:m,im:b}=n.reim(u);return h>b||h===b&&f>m?l:u}isOdd(e){let{re:r,im:n}=this.reim(e),o=r%qt,s=r===w_,i=n%qt;return BigInt(o||s&&i)==Bn}fromBytes(e){let{Fp:r}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);return{c0:r.fromBytes(e.subarray(0,r.BYTES)),c1:r.fromBytes(e.subarray(r.BYTES))}}toBytes({c0:e,c1:r}){return(0,bo.concatBytes)(this.Fp.toBytes(e),this.Fp.toBytes(r))}cmov({c0:e,c1:r},{c0:n,c1:o},s){return{c0:this.Fp.cmov(e,n,s),c1:this.Fp.cmov(r,o,s)}}reim({c0:e,c1:r}){return{re:e,im:r}}Fp4Square(e,r){let n=this,o=n.sqr(e),s=n.sqr(r);return{first:n.add(n.mulByNonresidue(s),o),second:n.sub(n.sub(n.sqr(n.add(e,r)),o),s)}}mulByNonresidue({c0:e,c1:r}){return this.mul({c0:e,c1:r},this.NONRESIDUE)}frobeniusMap({c0:e,c1:r},n){return{c0:e,c1:this.Fp.mul(r,this.FROBENIUS_COEFFICIENTS[n%2])}}},Dp=class{constructor(e){this.MASK=Bn,this.Fp2=e,this.ORDER=e.ORDER,this.BITS=3*e.BITS,this.BYTES=3*e.BYTES,this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO,c2:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO,c2:e.ZERO};let{Fp:r}=e,n=Vp(e,e.NONRESIDUE,r.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=n[0],this.FROBENIUS_COEFFICIENTS_2=n[1],Object.seal(this)}add({c0:e,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return{c0:a.add(e,o),c1:a.add(r,s),c2:a.add(n,i)}}sub({c0:e,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return{c0:a.sub(e,o),c1:a.sub(r,s),c2:a.sub(n,i)}}mul({c0:e,c1:r,c2:n},o){let{Fp2:s}=this;if(typeof o=="bigint")return{c0:s.mul(e,o),c1:s.mul(r,o),c2:s.mul(n,o)};let{c0:i,c1:a,c2:c}=o,d=s.mul(e,i),p=s.mul(r,a),l=s.mul(n,c);return{c0:s.add(d,s.mulByNonresidue(s.sub(s.mul(s.add(r,n),s.add(a,c)),s.add(p,l)))),c1:s.add(s.sub(s.mul(s.add(e,r),s.add(i,a)),s.add(d,p)),s.mulByNonresidue(l)),c2:s.sub(s.add(p,s.mul(s.add(e,n),s.add(i,c))),s.add(d,l))}}sqr({c0:e,c1:r,c2:n}){let{Fp2:o}=this,s=o.sqr(e),i=o.mul(o.mul(e,r),qt),a=o.mul(o.mul(r,n),qt),c=o.sqr(n);return{c0:o.add(o.mulByNonresidue(a),s),c1:o.add(o.mulByNonresidue(c),i),c2:o.sub(o.sub(o.add(o.add(i,o.sqr(o.add(o.sub(e,r),n))),a),s),c)}}addN(e,r){return this.add(e,r)}subN(e,r){return this.sub(e,r)}mulN(e,r){return this.mul(e,r)}sqrN(e){return this.sqr(e)}create(e){return e}isValid({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return o.isValid(e)&&o.isValid(r)&&o.isValid(n)}is0({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return o.is0(e)&&o.is0(r)&&o.is0(n)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.neg(e),c1:o.neg(r),c2:o.neg(n)}}eql({c0:e,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return a.eql(e,o)&&a.eql(r,s)&&a.eql(n,i)}sqrt(e){return(0,bo.notImplemented)()}div(e,r){let{Fp2:n}=this,{Fp:o}=n;return this.mul(e,typeof r=="bigint"?o.inv(o.create(r)):this.inv(r))}pow(e,r){return An.FpPow(this,e,r)}invertBatch(e){return An.FpInvertBatch(this,e)}inv({c0:e,c1:r,c2:n}){let{Fp2:o}=this,s=o.sub(o.sqr(e),o.mulByNonresidue(o.mul(n,r))),i=o.sub(o.mulByNonresidue(o.sqr(n)),o.mul(e,r)),a=o.sub(o.sqr(r),o.mul(e,n)),c=o.inv(o.add(o.mulByNonresidue(o.add(o.mul(n,i),o.mul(r,a))),o.mul(e,s)));return{c0:o.mul(c,s),c1:o.mul(c,i),c2:o.mul(c,a)}}fromBytes(e){let{Fp2:r}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);let n=r.BYTES;return{c0:r.fromBytes(e.subarray(0,n)),c1:r.fromBytes(e.subarray(n,n*2)),c2:r.fromBytes(e.subarray(2*n))}}toBytes({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return(0,bo.concatBytes)(o.toBytes(e),o.toBytes(r),o.toBytes(n))}cmov({c0:e,c1:r,c2:n},{c0:o,c1:s,c2:i},a){let{Fp2:c}=this;return{c0:c.cmov(e,o,a),c1:c.cmov(r,s,a),c2:c.cmov(n,i,a)}}fromBigSix(e){let{Fp2:r}=this;if(!Array.isArray(e)||e.length!==6)throw new Error("invalid Fp6 usage");return{c0:r.fromBigTuple(e.slice(0,2)),c1:r.fromBigTuple(e.slice(2,4)),c2:r.fromBigTuple(e.slice(4,6))}}frobeniusMap({c0:e,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.frobeniusMap(e,o),c1:s.mul(s.frobeniusMap(r,o),this.FROBENIUS_COEFFICIENTS_1[o%6]),c2:s.mul(s.frobeniusMap(n,o),this.FROBENIUS_COEFFICIENTS_2[o%6])}}mulByFp2({c0:e,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.mul(e,o),c1:s.mul(r,o),c2:s.mul(n,o)}}mulByNonresidue({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.mulByNonresidue(n),c1:e,c2:r}}mul1({c0:e,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.mulByNonresidue(s.mul(n,o)),c1:s.mul(e,o),c2:s.mul(r,o)}}mul01({c0:e,c1:r,c2:n},o,s){let{Fp2:i}=this,a=i.mul(e,o),c=i.mul(r,s);return{c0:i.add(i.mulByNonresidue(i.sub(i.mul(i.add(r,n),s),c)),a),c1:i.sub(i.sub(i.mul(i.add(o,s),i.add(e,r)),a),c),c2:i.add(i.sub(i.mul(i.add(e,n),o),a),c)}}},Fp=class{constructor(e,r){this.MASK=Bn;let{Fp2:n}=e,{Fp:o}=n;this.Fp6=e,this.ORDER=n.ORDER,this.BITS=2*e.BITS,this.BYTES=2*e.BYTES,this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO},this.FROBENIUS_COEFFICIENTS=Vp(n,n.NONRESIDUE,o.ORDER,12,1,6)[0],this.X_LEN=r.X_LEN,this.finalExponentiate=r.Fp12finalExponentiate}create(e){return e}isValid({c0:e,c1:r}){let{Fp6:n}=this;return n.isValid(e)&&n.isValid(r)}is0({c0:e,c1:r}){let{Fp6:n}=this;return n.is0(e)&&n.is0(r)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:r}){let{Fp6:n}=this;return{c0:n.neg(e),c1:n.neg(r)}}eql({c0:e,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return s.eql(e,n)&&s.eql(r,o)}sqrt(e){(0,bo.notImplemented)()}inv({c0:e,c1:r}){let{Fp6:n}=this,o=n.inv(n.sub(n.sqr(e),n.mulByNonresidue(n.sqr(r))));return{c0:n.mul(e,o),c1:n.neg(n.mul(r,o))}}div(e,r){let{Fp6:n}=this,{Fp2:o}=n,{Fp:s}=o;return this.mul(e,typeof r=="bigint"?s.inv(s.create(r)):this.inv(r))}pow(e,r){return An.FpPow(this,e,r)}invertBatch(e){return An.FpInvertBatch(this,e)}add({c0:e,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return{c0:s.add(e,n),c1:s.add(r,o)}}sub({c0:e,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return{c0:s.sub(e,n),c1:s.sub(r,o)}}mul({c0:e,c1:r},n){let{Fp6:o}=this;if(typeof n=="bigint")return{c0:o.mul(e,n),c1:o.mul(r,n)};let{c0:s,c1:i}=n,a=o.mul(e,s),c=o.mul(r,i);return{c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(e,r),o.add(s,i)),o.add(a,c))}}sqr({c0:e,c1:r}){let{Fp6:n}=this,o=n.mul(e,r);return{c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(r),e),n.add(e,r)),o),n.mulByNonresidue(o)),c1:n.add(o,o)}}addN(e,r){return this.add(e,r)}subN(e,r){return this.sub(e,r)}mulN(e,r){return this.mul(e,r)}sqrN(e){return this.sqr(e)}fromBytes(e){let{Fp6:r}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);return{c0:r.fromBytes(e.subarray(0,r.BYTES)),c1:r.fromBytes(e.subarray(r.BYTES))}}toBytes({c0:e,c1:r}){let{Fp6:n}=this;return(0,bo.concatBytes)(n.toBytes(e),n.toBytes(r))}cmov({c0:e,c1:r},{c0:n,c1:o},s){let{Fp6:i}=this;return{c0:i.cmov(e,n,s),c1:i.cmov(r,o,s)}}fromBigTwelve(e){let{Fp6:r}=this;return{c0:r.fromBigSix(e.slice(0,6)),c1:r.fromBigSix(e.slice(6,12))}}frobeniusMap(e,r){let{Fp6:n}=this,{Fp2:o}=n,{c0:s,c1:i,c2:a}=n.frobeniusMap(e.c1,r),c=this.FROBENIUS_COEFFICIENTS[r%12];return{c0:n.frobeniusMap(e.c0,r),c1:n.create({c0:o.mul(s,c),c1:o.mul(i,c),c2:o.mul(a,c)})}}mulByFp2({c0:e,c1:r},n){let{Fp6:o}=this;return{c0:o.mulByFp2(e,n),c1:o.mulByFp2(r,n)}}conjugate({c0:e,c1:r}){return{c0:e,c1:this.Fp6.neg(r)}}mul014({c0:e,c1:r},n,o,s){let{Fp6:i}=this,{Fp2:a}=i,c=i.mul01(e,n,o),d=i.mul1(r,s);return{c0:i.add(i.mulByNonresidue(d),c),c1:i.sub(i.sub(i.mul01(i.add(r,e),n,a.add(o,s)),c),d)}}mul034({c0:e,c1:r},n,o,s){let{Fp6:i}=this,{Fp2:a}=i,c=i.create({c0:a.mul(e.c0,n),c1:a.mul(e.c1,n),c2:a.mul(e.c2,n)}),d=i.mul01(r,o,s),p=i.mul01(i.add(e,r),a.add(n,o),s);return{c0:i.add(i.mulByNonresidue(d),c),c1:i.sub(p,i.add(c,d))}}_cyclotomicSquare({c0:e,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:s,c1:i,c2:a}=e,{c0:c,c1:d,c2:p}=r,{first:l,second:u}=o.Fp4Square(s,d),{first:f,second:h}=o.Fp4Square(c,a),{first:m,second:b}=o.Fp4Square(i,p),y=o.mulByNonresidue(b);return{c0:n.create({c0:o.add(o.mul(o.sub(l,s),qt),l),c1:o.add(o.mul(o.sub(f,i),qt),f),c2:o.add(o.mul(o.sub(m,a),qt),m)}),c1:n.create({c0:o.add(o.mul(o.add(y,c),qt),y),c1:o.add(o.mul(o.add(u,d),qt),u),c2:o.add(o.mul(o.add(h,p),qt),h)})}}_cyclotomicExp(e,r){let n=this.ONE;for(let o=this.X_LEN-1;o>=0;o--)n=this._cyclotomicSquare(n),(0,bo.bitGet)(r,o)&&(n=this.mul(n,e));return n}};function UT(t){let e=An.Field(t.ORDER),r=new Pp(e,t),n=new Dp(r),o=new Fp(n,t);return{Fp:e,Fp2:r,Fp6:n,Fp12:o}}});var C_=Y(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.bls12_381=tn.bls12_381_Fr=void 0;var I_=Gs(),LT=x_(),qT=Jr(),ge=Ir(),S_=bu(),A_=O_(),B_=Ap(),St=BigInt(0),Tu=BigInt(1),_r=BigInt(2),Ou=BigInt(3),xa=BigInt(4),go=BigInt("0xd201000000010000"),MT=(0,ge.bitLen)(go),os={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:St,b:xa,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")};tn.bls12_381_Fr=(0,qT.Field)(os.n,{modFromBytes:!0,isLE:!0});var{Fp:X,Fp2:xe,Fp6:kT,Fp12:ve}=(0,A_.tower12)({ORDER:os.p,X_LEN:MT,FP2_NONRESIDUE:[Tu,Tu],Fp2mulByB:({c0:t,c1:e})=>{let r=X.mul(t,xa),n=X.mul(e,xa);return{c0:X.sub(r,n),c1:X.add(r,n)}},Fp12finalExponentiate:t=>{let e=go,r=ve.div(ve.frobeniusMap(t,6),t),n=ve.mul(ve.frobeniusMap(r,2),r),o=ve.conjugate(ve._cyclotomicExp(n,e)),s=ve.mul(ve.conjugate(ve._cyclotomicSquare(n)),o),i=ve.conjugate(ve._cyclotomicExp(s,e)),a=ve.conjugate(ve._cyclotomicExp(i,e)),c=ve.mul(ve.conjugate(ve._cyclotomicExp(a,e)),ve._cyclotomicSquare(o)),d=ve.conjugate(ve._cyclotomicExp(c,e)),p=ve.frobeniusMap(ve.mul(o,a),2),l=ve.frobeniusMap(ve.mul(i,n),3),u=ve.frobeniusMap(ve.mul(c,ve.conjugate(n)),1),f=ve.mul(ve.mul(d,ve.conjugate(s)),n);return ve.mul(ve.mul(ve.mul(p,l),u),f)}}),{G2psi:N_,G2psi2:jT}=(0,A_.psiFrobenius)(X,xe,xe.div(xe.ONE,xe.NONRESIDUE)),Up=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:X.ORDER,m:2,k:128,expand:"xmd",hash:I_.sha256}),Mp={p:xe.ORDER,n:os.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:xe.ZERO,b:xe.fromBigTuple([xa,xa]),Gx:xe.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:xe.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},Nu=wa(X.toBytes(St),{infinity:!0,compressed:!0});function vu(t){t=t.slice();let e=t[0]&224,r=!!(e>>7&1),n=!!(e>>6&1),o=!!(e>>5&1);return t[0]&=31,{compressed:r,infinity:n,sort:o,value:t}}function wa(t,e){if(t[0]&224)throw new Error("setMask: non-empty mask");return e.compressed&&(t[0]|=128),e.infinity&&(t[0]|=64),e.sort&&(t[0]|=32),t}function HT(t,e,r){let{BYTES:n,ORDER:o}=X,s=e.is0(),{x:i,y:a}=e.toAffine();if(r){if(s)return Nu.slice();let c=!!(a*_r/o);return wa((0,ge.numberToBytesBE)(i,n),{compressed:!0,sort:c})}else return s?(0,ge.concatBytes)(Uint8Array.of(64),new Uint8Array(2*n-1)):(0,ge.concatBytes)((0,ge.numberToBytesBE)(i,n),(0,ge.numberToBytesBE)(a,n))}function Lp(t){t.assertValidity();let{BYTES:e,ORDER:r}=X,{x:n,y:o}=t.toAffine();if(t.is0())return Nu.slice();let s=!!(o*_r/r);return wa((0,ge.numberToBytesBE)(n,e),{compressed:!0,sort:s})}function $T(t){let{compressed:e,infinity:r,sort:n,value:o}=vu(t),{BYTES:s,ORDER:i}=X;if(o.length===48&&e){let a=(0,ge.bytesToNumberBE)(o),c=X.create(a&(0,ge.bitMask)(X.BITS));if(r){if(c!==St)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:St,y:St}}let d=X.add(X.pow(c,Ou),X.create(os.b)),p=X.sqrt(d);if(!p)throw new Error("invalid G1 point: compressed point");return p*_r/i!==BigInt(n)&&(p=X.neg(p)),{x:X.create(c),y:X.create(p)}}else if(o.length===96&&!e){let a=(0,ge.bytesToNumberBE)(o.subarray(0,s)),c=(0,ge.bytesToNumberBE)(o.subarray(s));if(r){if(a!==St||c!==St)throw new Error("G1: non-empty point at infinity");return tn.bls12_381.G1.Point.ZERO.toAffine()}return{x:X.create(a),y:X.create(c)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function v_(t){let{infinity:e,sort:r,value:n}=vu((0,ge.ensureBytes)("signatureHex",t,48)),o=X.ORDER,s=tn.bls12_381.G1.Point,i=(0,ge.bytesToNumberBE)(n);if(e)return s.ZERO;let a=X.create(i&(0,ge.bitMask)(X.BITS)),c=X.add(X.pow(a,Ou),X.create(os.b)),d=X.sqrt(c);if(!d)throw new Error("invalid G1 point: compressed");let p=BigInt(r);d*_r/o!==p&&(d=X.neg(d));let l=s.fromAffine({x:a,y:d});return l.assertValidity(),l}function KT(t,e,r){let{BYTES:n,ORDER:o}=X,s=e.is0(),{x:i,y:a}=e.toAffine();if(r){if(s)return(0,ge.concatBytes)(Nu,(0,ge.numberToBytesBE)(St,n));let c=!!(a.c1===St?a.c0*_r/o:a.c1*_r/o);return(0,ge.concatBytes)(wa((0,ge.numberToBytesBE)(i.c1,n),{compressed:!0,sort:c}),(0,ge.numberToBytesBE)(i.c0,n))}else{if(s)return(0,ge.concatBytes)(Uint8Array.of(64),new Uint8Array(4*n-1));let{re:c,im:d}=xe.reim(i),{re:p,im:l}=xe.reim(a);return(0,ge.concatBytes)((0,ge.numberToBytesBE)(d,n),(0,ge.numberToBytesBE)(c,n),(0,ge.numberToBytesBE)(l,n),(0,ge.numberToBytesBE)(p,n))}}function qp(t){t.assertValidity();let{BYTES:e}=X;if(t.is0())return(0,ge.concatBytes)(Nu,(0,ge.numberToBytesBE)(St,e));let{x:r,y:n}=t.toAffine(),{re:o,im:s}=xe.reim(r),{re:i,im:a}=xe.reim(n),d=!!((a>St?a*_r:i*_r)/X.ORDER&Tu),p=o;return(0,ge.concatBytes)(wa((0,ge.numberToBytesBE)(s,e),{sort:d,compressed:!0}),(0,ge.numberToBytesBE)(p,e))}function GT(t){let{BYTES:e,ORDER:r}=X,{compressed:n,infinity:o,sort:s,value:i}=vu(t);if(!n&&!o&&s||!n&&o&&s||s&&o&&n)throw new Error("invalid encoding flag: "+(t[0]&224));let a=(c,d,p)=>(0,ge.bytesToNumberBE)(c.slice(d,p));if(i.length===96&&n){if(o){if(i.reduce((h,m)=>h!==0?m+1:m,0)>0)throw new Error("invalid G2 point: compressed");return{x:xe.ZERO,y:xe.ZERO}}let c=a(i,0,e),d=a(i,e,2*e),p=xe.create({c0:X.create(d),c1:X.create(c)}),l=xe.add(xe.pow(p,Ou),Mp.b),u=xe.sqrt(l),f=u.c1===St?u.c0*_r/r:u.c1*_r/r?Tu:St;return u=s&&f>0?u:xe.neg(u),{x:p,y:u}}else if(i.length===192&&!n){if(o){if(i.reduce((u,f)=>u!==0?f+1:f,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:xe.ZERO,y:xe.ZERO}}let c=a(i,0*e,1*e),d=a(i,1*e,2*e),p=a(i,2*e,3*e),l=a(i,3*e,4*e);return{x:xe.fromBigTuple([d,c]),y:xe.fromBigTuple([l,p])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function R_(t){let{ORDER:e}=X,{infinity:r,sort:n,value:o}=vu((0,ge.ensureBytes)("signatureHex",t)),s=tn.bls12_381.G2.Point,i=o.length/2;if(i!==48&&i!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");let a=(0,ge.bytesToNumberBE)(o.slice(0,i)),c=(0,ge.bytesToNumberBE)(o.slice(i));if(r)return s.ZERO;let d=X.create(a&(0,ge.bitMask)(X.BITS)),p=X.create(c),l=xe.create({c0:p,c1:d}),u=xe.add(xe.pow(l,Ou),Mp.b),f=xe.sqrt(u);if(!f)throw new Error("Failed to find a square root");let{re:h,im:m}=xe.reim(f),b=BigInt(n),y=m>St&&m*_r/e!==b,x=m===St&&h*_r/e!==b;(y||x)&&(f=xe.neg(f));let _=s.fromAffine({x:l,y:f});return _.assertValidity(),_}tn.bls12_381=(0,LT.bls)({fields:{Fp:X,Fp2:xe,Fp6:kT,Fp12:ve,Fr:tn.bls12_381_Fr},G1:{...os,Fp:X,htfDefaults:{...Up,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(t,e)=>{let r=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),n=new t(X.mul(e.X,r),e.Y,e.Z);return e.multiplyUnsafe(go).negate().multiplyUnsafe(go).equals(n)},clearCofactor:(t,e)=>e.multiplyUnsafe(go).add(e),mapToCurve:XT,fromBytes:$T,toBytes:HT,ShortSignature:{fromBytes(t){return(0,ge.abytes)(t),v_(t)},fromHex(t){return v_(t)},toBytes(t){return Lp(t)},toRawBytes(t){return Lp(t)},toHex(t){return(0,ge.bytesToHex)(Lp(t))}}},G2:{...Mp,Fp:xe,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...Up},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:JT,isTorsionFree:(t,e)=>e.multiplyUnsafe(go).negate().equals(N_(t,e)),clearCofactor:(t,e)=>{let r=go,n=e.multiplyUnsafe(r).negate(),o=N_(t,e),s=e.double();return s=jT(t,s),s=s.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),s=s.add(o),s=s.subtract(n),s.subtract(e)},fromBytes:GT,toBytes:KT,Signature:{fromBytes(t){return(0,ge.abytes)(t),R_(t)},fromHex(t){return R_(t)},toBytes(t){return qp(t)},toRawBytes(t){return qp(t)},toHex(t){return(0,ge.bytesToHex)(qp(t))}}},params:{ateLoopSize:go,r:os.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:Up,hash:I_.sha256});var zT=(0,S_.isogenyMap)(xe,[[["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(t=>t.map(e=>xe.fromBigTuple(e.map(BigInt))))),ZT=(0,S_.isogenyMap)(X,[["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(t=>t.map(e=>BigInt(e)))),YT=(0,B_.mapToCurveSimpleSWU)(X,{A:X.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:X.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:X.create(BigInt(11))}),WT=(0,B_.mapToCurveSimpleSWU)(xe,{A:xe.create({c0:X.create(St),c1:X.create(BigInt(240))}),B:xe.create({c0:X.create(BigInt(1012)),c1:X.create(BigInt(1012))}),Z:xe.create({c0:X.create(BigInt(-2)),c1:X.create(BigInt(-1))})});function XT(t){let{x:e,y:r}=YT(X.create(t[0]));return ZT(e,r)}function JT(t){let{x:e,y:r}=WT(xe.fromBigTuple(t));return zT(e,r)}});var jp=Y(Ru=>{"use strict";Object.defineProperty(Ru,"__esModule",{value:!0});Ru.verify=void 0;Ru.blsVerify=e6;var QT=C_(),kp=dt();function e6(t,e,r){let n=typeof t=="string"?t:(0,kp.bytesToHex)(t),o=typeof e=="string"?e:(0,kp.bytesToHex)(e),s=typeof r=="string"?r:(0,kp.bytesToHex)(r);return QT.bls12_381.verifyShortSignature(o,s,n)}});var Iu=Y(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.decodeTime=ss.decodeLeb128=void 0;var P_=ca(),t6=BigInt(1e6),r6=t=>(0,P_.lebDecode)(new P_.PipeArrayBuffer(t));ss.decodeLeb128=r6;var n6=t=>{let r=(0,ss.decodeLeb128)(t)/t6;return new Date(Number(r))};ss.decodeTime=n6});var ai=Y(Ue=>{"use strict";var o6=Ue&&Ue.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),s6=Ue&&Ue.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),F_=Ue&&Ue.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&o6(r,e,n[o]);return s6(r,e),r}})();Object.defineProperty(Ue,"__esModule",{value:!0});Ue.LookupLabelStatus=Ue.LookupSubtreeStatus=Ue.LookupPathStatus=Ue.Certificate=Ue.NodeType=void 0;Ue.hashTreeToString=Au;Ue.lookupResultToBuffer=Kp;Ue.reconstruct=Ta;Ue.domain_sep=si;Ue.lookup_path=Bu;Ue.lookup_subtree=zp;Ue.flatten_forks=Gp;Ue.find_label=ii;Ue.check_canister_ranges=q_;var V_=F_(la()),he=ar(),Hp=Rr(),i6=F_(jp()),a6=Iu(),xo=dt(),U_=Qs(),Su=Gs(),D_=60*1e3,c6=60,u6=24,d6=u6*c6,l6=5,f6=5,p6=30*d6,ze;(function(t){t[t.Empty=0]="Empty",t[t.Fork=1]="Fork",t[t.Labeled=2]="Labeled",t[t.Leaf=3]="Leaf",t[t.Pruned=4]="Pruned"})(ze||(Ue.NodeType=ze={}));function Au(t){let e=n=>n.split(`
53
- `).map(o=>" "+o).join(`
54
- `);function r(n){let o=new TextDecoder(void 0,{fatal:!0});try{return JSON.stringify(o.decode(n))}catch{return`data(...${n.byteLength} bytes)`}}switch(t[0]){case ze.Empty:return"()";case ze.Fork:if(t[1]instanceof Array&&t[2]instanceof Uint8Array){let n=Au(t[1]),o=Au(t[2]);return`sub(
55
- left:
56
- ${e(n)}
57
- ---
58
- right:
59
- ${e(o)}
60
- )`}else throw he.UnknownError.fromCode(new he.HashTreeDecodeErrorCode("Invalid tree structure for fork"));case ze.Labeled:if(t[1]instanceof Uint8Array&&t[2]instanceof Uint8Array){let n=r(t[1]),o=Au(t[2]);return`label(
61
- label:
62
- ${e(n)}
63
- sub:
64
- ${e(o)}
65
- )`}else throw he.UnknownError.fromCode(new he.HashTreeDecodeErrorCode("Invalid tree structure for labeled"));case ze.Leaf:{if(t[1]){if(Array.isArray(t[1]))return JSON.stringify(t[1])}else throw he.UnknownError.fromCode(new he.HashTreeDecodeErrorCode("Invalid tree structure for leaf"));return`leaf(...${t[1].byteLength} bytes)`}case ze.Pruned:{if(t[1]){if(Array.isArray(t[1]))return JSON.stringify(t[1])}else throw he.UnknownError.fromCode(new he.HashTreeDecodeErrorCode("Invalid tree structure for pruned"));return`pruned(${(0,xo.bytesToHex)(new Uint8Array(t[1]))}`}default:return`unknown(${JSON.stringify(t[0])})`}}function h6(t,e){for(let r=0;r<t.length;r++)if(t[r]>e[r])return!0;return!1}var $p=class t{#e=!1;#t=void 0;static async create(e){let r=t.createUnverified(e);return await r.verify(),r}static createUnverified(e){return new t(e.certificate,e.rootKey,e.canisterId,e.blsVerify??i6.blsVerify,e.maxAgeInMinutes,e.disableTimeVerification,e.agent)}constructor(e,r,n,o,s=l6,i=!1,a){this._rootKey=r,this._canisterId=n,this._blsVerify=o,this._maxAgeInMinutes=s,this.#e=i,this.cert=V_.decode(e),a&&"getTimeDiffMsecs"in a&&"hasSyncedTime"in a&&"syncTime"in a&&(this.#t=a)}lookup_path(e){return Bu(e,this.cert.tree)}lookup_subtree(e){return zp(e,this.cert.tree)}async verify(){let e=await Ta(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,o=y6(r),s=(0,xo.concatBytes)(si("ic-state-root"),e),i=Kp(this.lookup_path(["time"]));if(!i)throw he.ProtocolError.fromCode(new he.CertificateVerificationErrorCode("Certificate does not contain a time"));if(!this.#e){let a=this.#t?.getTimeDiffMsecs()??0,c=this._maxAgeInMinutes*D_,d=new Date,p=d.getTime()+a,l=p-c,u=p+f6*D_,f=(0,a6.decodeTime)(i),h=f.getTime()<l,m=f.getTime()>u;if((h||m)&&this.#t&&!this.#t.hasSyncedTime())return await this.#t.syncTime(this._canisterId),await this.verify();if(h)throw he.TrustError.fromCode(new he.CertificateTimeErrorCode(this._maxAgeInMinutes,f,d,a,"past"));if(m)throw this.#t?.hasSyncedTime()?he.UnknownError.fromCode(new he.UnexpectedErrorCode("System time has been synced with the IC network, but certificate is still too far in the future.")):he.TrustError.fromCode(new he.CertificateTimeErrorCode(5,f,d,a,"future"))}try{if(!await this._blsVerify(o,n,s))throw he.TrustError.fromCode(new he.CertificateVerificationErrorCode("Invalid signature"))}catch(a){throw he.TrustError.fromCode(new he.CertificateVerificationErrorCode("Signature verification failed",a))}}async _checkDelegationAndGetKey(e){if(!e)return this._rootKey;let r=t.createUnverified({certificate:e.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:p6,agent:this.#t});if(r.cert.delegation)throw he.ProtocolError.fromCode(new he.CertificateHasTooManyDelegationsErrorCode);await r.verify();let n=e.subnet_id,o=Hp.Principal.fromUint8Array(n);if(!q_({canisterId:this._canisterId,subnetId:o,tree:r.cert.tree}))throw he.TrustError.fromCode(new he.CertificateNotAuthorizedErrorCode(this._canisterId,o));let i=Kp(r.lookup_path(["subnet",n,"public_key"]));if(!i)throw he.TrustError.fromCode(new he.MissingLookupValueErrorCode(`Could not find subnet key for subnet ID ${o.toText()}`));return i}};Ue.Certificate=$p;var Ea=(0,xo.hexToBytes)("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),m6=96;function y6(t){let e=Ea.byteLength+m6;if(t.byteLength!==e)throw he.ProtocolError.fromCode(new he.DerKeyLengthMismatchErrorCode(e,t.byteLength));let r=t.slice(0,Ea.byteLength);if(!(0,U_.uint8Equals)(r,Ea))throw he.ProtocolError.fromCode(new he.DerPrefixMismatchErrorCode(Ea,r));return t.slice(Ea.byteLength)}function Kp(t){if(t.status===rn.Found&&t.value instanceof Uint8Array)return t.value}async function Ta(t){switch(t[0]){case ze.Empty:return(0,Su.sha256)(si("ic-hashtree-empty"));case ze.Pruned:return t[1];case ze.Leaf:return(0,Su.sha256)((0,xo.concatBytes)(si("ic-hashtree-leaf"),t[1]));case ze.Labeled:return(0,Su.sha256)((0,xo.concatBytes)(si("ic-hashtree-labeled"),t[1],await Ta(t[2])));case ze.Fork:return(0,Su.sha256)((0,xo.concatBytes)(si("ic-hashtree-fork"),await Ta(t[1]),await Ta(t[2])));default:throw he.UNREACHABLE_ERROR}}function si(t){let e=new Uint8Array([t.length]),r=new TextEncoder().encode(t);return(0,xo.concatBytes)(e,r)}function L_(t){return typeof t[0]=="string"?(0,xo.utf8ToBytes)(t[0]):t[0]}var rn;(function(t){t.Unknown="Unknown",t.Absent="Absent",t.Found="Found",t.Error="Error"})(rn||(Ue.LookupPathStatus=rn={}));var Oa;(function(t){t.Absent="Absent",t.Unknown="Unknown",t.Found="Found"})(Oa||(Ue.LookupSubtreeStatus=Oa={}));var He;(function(t){t.Absent="Absent",t.Unknown="Unknown",t.Found="Found",t.Less="Less",t.Greater="Greater"})(He||(Ue.LookupLabelStatus=He={}));function Bu(t,e){if(t.length===0)switch(e[0]){case ze.Empty:return{status:rn.Absent};case ze.Leaf:{if(!e[1])throw he.UnknownError.fromCode(new he.HashTreeDecodeErrorCode("Invalid tree structure for leaf"));if(e[1]instanceof Uint8Array)return{status:rn.Found,value:e[1].slice(e[1].byteOffset,e[1].byteLength+e[1].byteOffset)};throw he.UNREACHABLE_ERROR}case ze.Pruned:return{status:rn.Unknown};case ze.Labeled:case ze.Fork:return{status:rn.Error};default:throw he.UNREACHABLE_ERROR}let r=L_(t),n=ii(r,e);switch(n.status){case He.Found:return Bu(t.slice(1),n.value);case He.Absent:case He.Greater:case He.Less:return{status:rn.Absent};case He.Unknown:return{status:rn.Unknown};default:throw he.UNREACHABLE_ERROR}}function zp(t,e){if(t.length===0)return{status:Oa.Found,value:e};let r=L_(t),n=ii(r,e);switch(n.status){case He.Found:return zp(t.slice(1),n.value);case He.Unknown:return{status:Oa.Unknown};case He.Absent:case He.Greater:case He.Less:return{status:Oa.Absent};default:throw he.UNREACHABLE_ERROR}}function Gp(t){switch(t[0]){case ze.Empty:return[];case ze.Fork:return Gp(t[1]).concat(Gp(t[2]));default:return[t]}}function ii(t,e){switch(e[0]){case ze.Labeled:return h6(t,e[1])?{status:He.Greater}:(0,U_.uint8Equals)(t,e[1])?{status:He.Found,value:e[2]}:{status:He.Less};case ze.Fork:{let r=ii(t,e[1]);switch(r.status){case He.Greater:{let n=ii(t,e[2]);return n.status===He.Less?{status:He.Absent}:n}case He.Unknown:{let n=ii(t,e[2]);return n.status===He.Less?{status:He.Unknown}:n}default:return r}}case ze.Pruned:return{status:He.Unknown};default:return{status:He.Absent}}}function q_(t){let{canisterId:e,subnetId:r,tree:n}=t,o=Bu(["subnet",r.toUint8Array(),"canister_ranges"],n);if(o.status!==rn.Found)throw he.ProtocolError.fromCode(new he.LookupErrorCode(`Could not find canister ranges for subnet ${r.toText()}`,o.status));if(!(o.value instanceof Uint8Array))throw he.ProtocolError.fromCode(new he.MalformedLookupFoundValueErrorCode(`Could not find canister ranges for subnet ${r.toText()}`));return V_.decode(o.value).map(c=>[Hp.Principal.fromUint8Array(c[0]),Hp.Principal.fromUint8Array(c[1])]).some(c=>c[0].ltEq(e)&&c[1].gtEq(e))}});var Cu=Y(ft=>{"use strict";var _6=ft&&ft.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),b6=ft&&ft.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),g6=ft&&ft.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&_6(r,e,n[o]);return b6(r,e),r}})();Object.defineProperty(ft,"__esModule",{value:!0});ft.encodePath=ft.fetchNodeKeys=ft.request=ft.CustomPath=void 0;var wo=Rr(),ot=ar(),Eo=ai(),Yp=g6(la()),M_=Iu(),tr=dt(),Zp=class{constructor(e,r,n){this.key=e,this.path=r,this.decodeStrategy=n}};ft.CustomPath=Zp;var x6=async t=>{let{agent:e,paths:r,disableCertificateTimeVerification:n=!1}=t,o=wo.Principal.from(t.canisterId),s=[...new Set(r)],i=new Map,a=s.map((c,d)=>{let p=(0,ft.encodePath)(c,o);return(async()=>{try{if(e.rootKey===null)throw ot.ExternalError.fromCode(new ot.MissingRootKeyErrorCode);let l=e.rootKey,u=await e.readState(o,{paths:[p]}),f=await Eo.Certificate.create({certificate:u.certificate,rootKey:l,canisterId:o,disableTimeVerification:n,agent:e}),h=(y,x)=>{if(x==="subnet"){let _=(0,ft.fetchNodeKeys)(u.certificate,o,l);return{path:x,data:_}}else return{path:x,data:(0,Eo.lookupResultToBuffer)(y.lookup_path(p))}},{path:m,data:b}=h(f,s[d]);if(!b)console.warn(`Expected to find result for path ${m}, but instead found nothing.`),typeof m=="string"?i.set(m,null):i.set(m.key,null);else switch(m){case"time":{i.set(m,(0,M_.decodeTime)(b));break}case"controllers":{i.set(m,T6(b));break}case"module_hash":{i.set(m,(0,tr.bytesToHex)(b));break}case"subnet":{i.set(m,b);break}case"candid":{i.set(m,new TextDecoder().decode(b));break}default:if(typeof m!="string"&&"key"in m&&"path"in m)switch(m.decodeStrategy){case"raw":i.set(m.key,b);break;case"leb128":{i.set(m.key,(0,M_.decodeLeb128)(b));break}case"cbor":{i.set(m.key,Yp.decode(b));break}case"hex":{i.set(m.key,(0,tr.bytesToHex)(b));break}case"utf-8":i.set(m.key,new TextDecoder().decode(b))}}}catch(l){if(l instanceof ot.AgentError&&(l.hasCode(ot.CertificateVerificationErrorCode)||l.hasCode(ot.CertificateTimeErrorCode)))throw l;typeof c!="string"&&"key"in c&&"path"in c?i.set(c.key,null):i.set(c,null),console.group(),console.warn(`Expected to find result for path ${c}, but instead found nothing.`),console.warn(l),console.groupEnd()}})()});return await Promise.all(a),i};ft.request=x6;var w6=(t,e,r)=>{if(!e._isPrincipal)throw ot.InputError.fromCode(new ot.UnexpectedErrorCode("Invalid canisterId"));let n=Yp.decode(t),o=n.tree,s=n.delegation,i;if(s&&s.subnet_id?i=wo.Principal.fromUint8Array(new Uint8Array(s.subnet_id)):!s&&typeof r<"u"?(i=wo.Principal.selfAuthenticating(new Uint8Array(r)),s={subnet_id:i.toUint8Array(),certificate:new Uint8Array(0)}):(i=wo.Principal.selfAuthenticating(wo.Principal.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),s={subnet_id:i.toUint8Array(),certificate:new Uint8Array(0)}),!(0,Eo.check_canister_ranges)({canisterId:e,subnetId:i,tree:o}))throw ot.TrustError.fromCode(new ot.CertificateNotAuthorizedErrorCode(e,i));let c=(0,Eo.lookup_subtree)(["subnet",s.subnet_id,"node"],o);if(c.status!==Eo.LookupSubtreeStatus.Found)throw ot.ProtocolError.fromCode(new ot.LookupErrorCode("Node not found",c.status));if(c.value instanceof Uint8Array)throw ot.UnknownError.fromCode(new ot.HashTreeDecodeErrorCode("Invalid node tree"));let d=(0,Eo.flatten_forks)(c.value),p=new Map;return d.forEach(l=>{let u=wo.Principal.from(l[1]).toText(),f=(0,Eo.lookup_path)(["public_key"],l[2]);if(f.status!==Eo.LookupPathStatus.Found)throw ot.ProtocolError.fromCode(new ot.LookupErrorCode("Public key not found",f.status));let h=f.value;if(h.byteLength!==44)throw ot.ProtocolError.fromCode(new ot.DerKeyLengthMismatchErrorCode(44,h.byteLength));p.set(u,h)}),{subnetId:wo.Principal.fromUint8Array(new Uint8Array(s.subnet_id)).toText(),nodeKeys:p}};ft.fetchNodeKeys=w6;var E6=(t,e)=>{let r=e.toUint8Array();switch(t){case"time":return[(0,tr.utf8ToBytes)("time")];case"controllers":return[(0,tr.utf8ToBytes)("canister"),r,(0,tr.utf8ToBytes)("controllers")];case"module_hash":return[(0,tr.utf8ToBytes)("canister"),r,(0,tr.utf8ToBytes)("module_hash")];case"subnet":return[(0,tr.utf8ToBytes)("subnet")];case"candid":return[(0,tr.utf8ToBytes)("canister"),r,(0,tr.utf8ToBytes)("metadata"),(0,tr.utf8ToBytes)("candid:service")];default:if("key"in t&&"path"in t)if(typeof t.path=="string"||t.path instanceof Uint8Array){let n=t.path,o=typeof n=="string"?(0,tr.utf8ToBytes)(n):n;return[(0,tr.utf8ToBytes)("canister"),r,(0,tr.utf8ToBytes)("metadata"),o]}else return t.path}throw ot.UnknownError.fromCode(new ot.UnexpectedErrorCode(`Error while encoding your path for canister status. Please ensure that your path ${t} was formatted correctly.`))};ft.encodePath=E6;var T6=t=>Yp.decode(t).map(r=>wo.Principal.fromUint8Array(r))});var H_=Y(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.PrimeEdwardsPoint=void 0;as.edwards=k_;as.eddsa=j_;as.twistedEdwards=S6;var Oe=Ir(),is=ya(),O6=Jr(),To=BigInt(0),pt=BigInt(1),Wp=BigInt(2),N6=BigInt(8);function v6(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function k_(t,e={}){let r=(0,is._createCurveFields)("edwards",t,e,e.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;(0,Oe._validateObject)(e,{},{uvRatio:"function"});let a=Wp<<BigInt(o.BYTES*8)-pt,c=b=>n.create(b),d=e.uvRatio||((b,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(b,y))}}catch{return{isValid:!1,value:To}}});if(!v6(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function p(b,y,x=!1){let _=x?pt:To;return(0,Oe.aInRange)("coordinate "+b,y,_,a),y}function l(b){if(!(b instanceof h))throw new Error("ExtendedPoint expected")}let u=(0,Oe.memoized)((b,y)=>{let{X:x,Y:_,Z:T}=b,N=b.is0();y==null&&(y=N?N6:n.inv(T));let v=c(x*y),R=c(_*y),A=n.mul(T,y);if(N)return{x:To,y:pt};if(A!==pt)throw new Error("invZ was invalid");return{x:v,y:R}}),f=(0,Oe.memoized)(b=>{let{a:y,d:x}=s;if(b.is0())throw new Error("bad point: ZERO");let{X:_,Y:T,Z:N,T:v}=b,R=c(_*_),A=c(T*T),E=c(N*N),S=c(E*E),V=c(R*y),C=c(E*c(V+A)),g=c(S+c(x*c(R*A)));if(C!==g)throw new Error("bad point: equation left != right (1)");let w=c(_*T),O=c(N*v);if(w!==O)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(y,x,_,T){this.X=p("x",y),this.Y=p("y",x),this.Z=p("z",_,!0),this.T=p("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw new Error("extended point not allowed");let{x,y:_}=y||{};return p("x",x),p("y",_),new h(x,_,pt,c(x*_))}static fromBytes(y,x=!1){let _=n.BYTES,{a:T,d:N}=s;y=(0,Oe.copyBytes)((0,Oe._abytes2)(y,_,"point")),(0,Oe._abool2)(x,"zip215");let v=(0,Oe.copyBytes)(y),R=y[_-1];v[_-1]=R&-129;let A=(0,Oe.bytesToNumberLE)(v),E=x?a:n.ORDER;(0,Oe.aInRange)("point.y",A,To,E);let S=c(A*A),V=c(S-pt),C=c(N*S-T),{isValid:g,value:w}=d(V,C);if(!g)throw new Error("bad point: invalid y coordinate");let O=(w&pt)===pt,P=(R&128)!==0;if(!x&&w===To&&P)throw new Error("bad point: x=0 and x_0=1");return P!==O&&(w=c(-w)),h.fromAffine({x:w,y:A})}static fromHex(y,x=!1){return h.fromBytes((0,Oe.ensureBytes)("point",y),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,x=!0){return m.createCache(this,y),x||this.multiply(Wp),this}assertValidity(){f(this)}equals(y){l(y);let{X:x,Y:_,Z:T}=this,{X:N,Y:v,Z:R}=y,A=c(x*R),E=c(N*T),S=c(_*R),V=c(v*T);return A===E&&S===V}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=s,{X:x,Y:_,Z:T}=this,N=c(x*x),v=c(_*_),R=c(Wp*c(T*T)),A=c(y*N),E=x+_,S=c(c(E*E)-N-v),V=A+v,C=V-R,g=A-v,w=c(S*C),O=c(V*g),P=c(S*g),L=c(C*V);return new h(w,O,L,P)}add(y){l(y);let{a:x,d:_}=s,{X:T,Y:N,Z:v,T:R}=this,{X:A,Y:E,Z:S,T:V}=y,C=c(T*A),g=c(N*E),w=c(R*_*V),O=c(v*S),P=c((T+N)*(A+E)-C-g),L=O-w,I=O+w,B=c(g-x*C),F=c(P*L),U=c(I*B),q=c(P*B),H=c(L*I);return new h(F,U,H,q)}subtract(y){return this.add(y.negate())}multiply(y){if(!o.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:_}=m.cached(this,y,T=>(0,is.normalizeZ)(h,T));return(0,is.normalizeZ)(h,[x,_])[0]}multiplyUnsafe(y,x=h.ZERO){if(!o.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===To?h.ZERO:this.is0()||y===pt?this:m.unsafe(this,y,_=>(0,is.normalizeZ)(h,_),x)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(y){return u(this,y)}clearCofactor(){return i===pt?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:x}=this.toAffine(),_=n.toBytes(x);return _[_.length-1]|=y&pt?128:0,_}toHex(){return(0,Oe.bytesToHex)(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(y){return(0,is.normalizeZ)(h,y)}static msm(y,x){return(0,is.pippenger)(h,o,y,x)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}h.BASE=new h(s.Gx,s.Gy,pt,c(s.Gx*s.Gy)),h.ZERO=new h(To,pt,pt,To),h.Fp=n,h.Fn=o;let m=new is.wNAF(h,o.BITS);return h.BASE.precompute(8),h}var Xp=class{constructor(e){this.ep=e}static fromBytes(e){(0,Oe.notImplemented)()}static fromHex(e){(0,Oe.notImplemented)()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return(0,Oe.bytesToHex)(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,r){return this.init(this.ep.precompute(e,r))}toRawBytes(){return this.toBytes()}};as.PrimeEdwardsPoint=Xp;function j_(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');(0,Oe._validateObject)(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=t,a=r.randomBytes||Oe.randomBytes,c=r.adjustScalarBytes||(E=>E),d=r.domain||((E,S,V)=>{if((0,Oe._abool2)(V,"phflag"),S.length||V)throw new Error("Contexts/pre-hash are not supported");return E});function p(E){return i.create((0,Oe.bytesToNumberLE)(E))}function l(E){let S=_.secretKey;E=(0,Oe.ensureBytes)("private key",E,S);let V=(0,Oe.ensureBytes)("hashed private key",e(E),2*S),C=c(V.slice(0,S)),g=V.slice(S,2*S),w=p(C);return{head:C,prefix:g,scalar:w}}function u(E){let{head:S,prefix:V,scalar:C}=l(E),g=o.multiply(C),w=g.toBytes();return{head:S,prefix:V,scalar:C,point:g,pointBytes:w}}function f(E){return u(E).pointBytes}function h(E=Uint8Array.of(),...S){let V=(0,Oe.concatBytes)(...S);return p(e(d(V,(0,Oe.ensureBytes)("context",E),!!n)))}function m(E,S,V={}){E=(0,Oe.ensureBytes)("message",E),n&&(E=n(E));let{prefix:C,scalar:g,pointBytes:w}=u(S),O=h(V.context,C,E),P=o.multiply(O).toBytes(),L=h(V.context,P,w,E),I=i.create(O+L*g);if(!i.isValid(I))throw new Error("sign failed: invalid s");let B=(0,Oe.concatBytes)(P,i.toBytes(I));return(0,Oe._abytes2)(B,_.signature,"result")}let b={zip215:!0};function y(E,S,V,C=b){let{context:g,zip215:w}=C,O=_.signature;E=(0,Oe.ensureBytes)("signature",E,O),S=(0,Oe.ensureBytes)("message",S),V=(0,Oe.ensureBytes)("publicKey",V,_.publicKey),w!==void 0&&(0,Oe._abool2)(w,"zip215"),n&&(S=n(S));let P=O/2,L=E.subarray(0,P),I=(0,Oe.bytesToNumberLE)(E.subarray(P,O)),B,F,U;try{B=t.fromBytes(V,w),F=t.fromBytes(L,w),U=o.multiplyUnsafe(I)}catch{return!1}if(!w&&B.isSmallOrder())return!1;let q=h(g,F.toBytes(),B.toBytes(),S);return F.add(B.multiplyUnsafe(q)).subtract(U).clearCofactor().is0()}let x=s.BYTES,_={secretKey:x,publicKey:x,signature:2*x,seed:x};function T(E=a(_.seed)){return(0,Oe._abytes2)(E,_.seed,"seed")}function N(E){let S=A.randomSecretKey(E);return{secretKey:S,publicKey:f(S)}}function v(E){return(0,Oe.isBytes)(E)&&E.length===i.BYTES}function R(E,S){try{return!!t.fromBytes(E,S)}catch{return!1}}let A={getExtendedPublicKey:u,randomSecretKey:T,isValidSecretKey:v,isValidPublicKey:R,toMontgomery(E){let{y:S}=t.fromBytes(E),V=_.publicKey,C=V===32;if(!C&&V!==57)throw new Error("only defined for 25519 and 448");let g=C?s.div(pt+S,pt-S):s.div(S-pt,S+pt);return s.toBytes(g)},toMontgomerySecret(E){let S=_.secretKey;(0,Oe._abytes2)(E,S);let V=e(E.subarray(0,S));return c(V).subarray(0,S)},randomPrivateKey:T,precompute(E=8,S=t.BASE){return S.precompute(E,!1)}};return Object.freeze({keygen:N,getPublicKey:f,sign:m,verify:y,utils:A,Point:t,lengths:_})}function R6(t){let e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=(0,O6.Field)(e.n,t.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function I6(t,e){let r=e.Point;return Object.assign({},e,{ExtendedPoint:r,CURVE:t,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function S6(t){let{CURVE:e,curveOpts:r,hash:n,eddsaOpts:o}=R6(t),s=k_(e,r),i=j_(s,n,o);return I6(t,i)}});var $_=Y(Jp=>{"use strict";Object.defineProperty(Jp,"__esModule",{value:!0});Jp.montgomery=C6;var nn=Ir(),A6=Jr(),Na=BigInt(0),ci=BigInt(1),Pu=BigInt(2);function B6(t){return(0,nn._validateObject)(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function C6(t){let e=B6(t),{P:r,type:n,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let c=i||nn.randomBytes,d=a?255:448,p=a?32:56,l=BigInt(a?9:5),u=BigInt(a?121665:39081),f=a?Pu**BigInt(254):Pu**BigInt(447),h=a?BigInt(8)*Pu**BigInt(251)-ci:BigInt(4)*Pu**BigInt(445)-ci,m=f+h+ci,b=g=>(0,A6.mod)(g,r),y=x(l);function x(g){return(0,nn.numberToBytesLE)(b(g),p)}function _(g){let w=(0,nn.ensureBytes)("u coordinate",g,p);return a&&(w[31]&=127),b((0,nn.bytesToNumberLE)(w))}function T(g){return(0,nn.bytesToNumberLE)(o((0,nn.ensureBytes)("scalar",g,p)))}function N(g,w){let O=A(_(w),T(g));if(O===Na)throw new Error("invalid private or public key received");return x(O)}function v(g){return N(g,y)}function R(g,w,O){let P=b(g*(w-O));return w=b(w-P),O=b(O+P),{x_2:w,x_3:O}}function A(g,w){(0,nn.aInRange)("u",g,Na,r),(0,nn.aInRange)("scalar",w,f,m);let O=w,P=g,L=ci,I=Na,B=g,F=ci,U=Na;for(let H=BigInt(d-1);H>=Na;H--){let Z=O>>H&ci;U^=Z,{x_2:L,x_3:B}=R(U,L,B),{x_2:I,x_3:F}=R(U,I,F),U=Z;let G=L+I,ae=b(G*G),te=L-I,Ce=b(te*te),ne=ae-Ce,me=B+F,Tt=B-F,Vt=b(Tt*G),pr=b(me*te),xn=Vt+pr,so=Vt-pr;B=b(xn*xn),F=b(P*b(so*so)),L=b(ae*Ce),I=b(ne*(ae+b(u*ne)))}({x_2:L,x_3:B}=R(U,L,B)),{x_2:I,x_3:F}=R(U,I,F);let q=s(I);return b(L*q)}let E={secretKey:p,publicKey:p,seed:p},S=(g=c(p))=>((0,nn.abytes)(g,E.seed),g);function V(g){let w=S(g);return{secretKey:w,publicKey:v(w)}}return{keygen:V,getSharedSecret:(g,w)=>N(g,w),getPublicKey:g=>v(g),scalarMult:N,scalarMultBase:v,utils:{randomSecretKey:S,randomPrivateKey:S},GuBytes:y.slice(),lengths:E}}});var rb=Y(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.hash_to_ristretto255=oe.hashToRistretto255=oe.encodeToCurve=oe.hashToCurve=oe.RistrettoPoint=oe.edwardsToMontgomery=oe.ED25519_TORSION_SUBGROUP=oe.ristretto255_hasher=oe.ristretto255=oe.ed25519_hasher=oe.x25519=oe.ed25519ph=oe.ed25519ctx=oe.ed25519=void 0;oe.edwardsToMontgomeryPub=tb;oe.edwardsToMontgomeryPriv=G6;var va=Gs(),Fu=dt(),P6=ya(),Uu=H_(),Du=bu(),Ae=Jr(),D6=$_(),cs=Ir(),F6=BigInt(0),on=BigInt(1),Vu=BigInt(2),Z_=BigInt(3),Y_=BigInt(5),rh=BigInt(8),Cn=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Ra={p:Cn,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:rh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function W_(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Cn,a=t*t%s*t%s,c=(0,Ae.pow2)(a,Vu,s)*a%s,d=(0,Ae.pow2)(c,on,s)*t%s,p=(0,Ae.pow2)(d,Y_,s)*d%s,l=(0,Ae.pow2)(p,e,s)*p%s,u=(0,Ae.pow2)(l,r,s)*l%s,f=(0,Ae.pow2)(u,n,s)*u%s,h=(0,Ae.pow2)(f,o,s)*f%s,m=(0,Ae.pow2)(h,o,s)*f%s,b=(0,Ae.pow2)(m,e,s)*p%s;return{pow_p_5_8:(0,Ae.pow2)(b,Vu,s)*t%s,b2:a}}function X_(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var Qp=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function nh(t,e){let r=Cn,n=(0,Ae.mod)(e*e*e,r),o=(0,Ae.mod)(n*n*e,r),s=W_(t*o).pow_p_5_8,i=(0,Ae.mod)(t*n*s,r),a=(0,Ae.mod)(e*i*i,r),c=i,d=(0,Ae.mod)(i*Qp,r),p=a===t,l=a===(0,Ae.mod)(-t,r),u=a===(0,Ae.mod)(-t*Qp,r);return p&&(i=c),(l||u)&&(i=d),(0,Ae.isNegativeLE)(i,r)&&(i=(0,Ae.mod)(-i,r)),{isValid:p||l,value:i}}var K=(0,Ae.Field)(Ra.p,{isLE:!0}),J_=(0,Ae.Field)(Ra.n,{isLE:!0}),oh={...Ra,Fp:K,hash:va.sha512,adjustScalarBytes:X_,uvRatio:nh};oe.ed25519=(0,Uu.twistedEdwards)(oh);function Q_(t,e,r){if(e.length>255)throw new Error("Context is too big");return(0,Fu.concatBytes)((0,Fu.utf8ToBytes)("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}oe.ed25519ctx=(0,Uu.twistedEdwards)({...oh,domain:Q_});oe.ed25519ph=(0,Uu.twistedEdwards)(Object.assign({},oh,{domain:Q_,prehash:va.sha512}));oe.x25519=(()=>{let t=K.ORDER;return(0,D6.montgomery)({P:t,type:"x25519",powPminus2:e=>{let{pow_p_5_8:r,b2:n}=W_(e);return(0,Ae.mod)((0,Ae.pow2)(r,Z_,t)*n,t)},adjustScalarBytes:X_})})();var V6=(Cn+Z_)/rh,U6=K.pow(Vu,V6),K_=K.sqrt(K.neg(K.ONE));function L6(t){let e=(Cn-Y_)/rh,r=BigInt(486662),n=K.sqr(t);n=K.mul(n,Vu);let o=K.add(n,K.ONE),s=K.neg(r),i=K.sqr(o),a=K.mul(i,o),c=K.mul(n,r);c=K.mul(c,s),c=K.add(c,i),c=K.mul(c,s);let d=K.sqr(a);i=K.sqr(d),d=K.mul(d,a),d=K.mul(d,c),i=K.mul(i,d);let p=K.pow(i,e);p=K.mul(p,d);let l=K.mul(p,K_);i=K.sqr(p),i=K.mul(i,a);let u=K.eql(i,c),f=K.cmov(l,p,u),h=K.mul(s,n),m=K.mul(p,t);m=K.mul(m,U6);let b=K.mul(m,K_),y=K.mul(c,n);i=K.sqr(m),i=K.mul(i,a);let x=K.eql(i,y),_=K.cmov(b,m,x);i=K.sqr(f),i=K.mul(i,a);let T=K.eql(i,c),N=K.cmov(h,s,T),v=K.cmov(_,f,T),R=K.isOdd(v);return v=K.cmov(v,K.neg(v),T!==R),{xMn:N,xMd:o,yMn:v,yMd:on}}var q6=(0,Ae.FpSqrtEven)(K,K.neg(BigInt(486664)));function M6(t){let{xMn:e,xMd:r,yMn:n,yMd:o}=L6(t),s=K.mul(e,o);s=K.mul(s,q6);let i=K.mul(r,n),a=K.sub(e,r),c=K.add(e,r),d=K.mul(i,c),p=K.eql(d,K.ZERO);s=K.cmov(s,K.ZERO,p),i=K.cmov(i,K.ONE,p),a=K.cmov(a,K.ONE,p),c=K.cmov(c,K.ONE,p);let[l,u]=(0,Ae.FpInvertBatch)(K,[i,c],!0);return{x:K.mul(s,l),y:K.mul(a,u)}}oe.ed25519_hasher=(0,Du.createHasher)(oe.ed25519.Point,t=>M6(t[0]),{DST:"edwards25519_XMD:SHA-512_ELL2_RO_",encodeDST:"edwards25519_XMD:SHA-512_ELL2_NU_",p:Cn,m:1,k:128,expand:"xmd",hash:va.sha512});var eh=Qp,k6=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),j6=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),H6=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),$6=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),G_=t=>nh(on,t),K6=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),th=t=>oe.ed25519.Point.Fp.create((0,cs.bytesToNumberLE)(t)&K6);function z_(t){let{d:e}=Ra,r=Cn,n=y=>K.create(y),o=n(eh*t*t),s=n((o+on)*H6),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:d}=nh(s,a),p=n(d*t);(0,Ae.isNegativeLE)(p,r)||(p=n(-p)),c||(d=p),c||(i=o);let l=n(i*(o-on)*$6-a),u=d*d,f=n((d+d)*a),h=n(l*k6),m=n(on-u),b=n(on+u);return new oe.ed25519.Point(n(f*b),n(m*h),n(h*b),n(f*m))}function eb(t){(0,Fu.abytes)(t,64);let e=th(t.subarray(0,32)),r=z_(e),n=th(t.subarray(32,64)),o=z_(n);return new Br(r.add(o))}var Br=class t extends Uu.PrimeEdwardsPoint{constructor(e){super(e)}static fromAffine(e){return new t(oe.ed25519.Point.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static hashToCurve(e){return eb((0,cs.ensureBytes)("ristrettoHash",e,64))}static fromBytes(e){(0,Fu.abytes)(e,32);let{a:r,d:n}=Ra,o=Cn,s=T=>K.create(T),i=th(e);if(!(0,cs.equalBytes)(K.toBytes(i),e)||(0,Ae.isNegativeLE)(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(on+r*a),d=s(on-r*a),p=s(c*c),l=s(d*d),u=s(r*n*p-l),{isValid:f,value:h}=G_(s(u*l)),m=s(h*d),b=s(h*m*u),y=s((i+i)*m);(0,Ae.isNegativeLE)(y,o)&&(y=s(-y));let x=s(c*b),_=s(y*x);if(!f||(0,Ae.isNegativeLE)(_,o)||x===F6)throw new Error("invalid ristretto255 encoding 2");return new t(new oe.ed25519.Point(y,x,on,_))}static fromHex(e){return t.fromBytes((0,cs.ensureBytes)("ristrettoHex",e,32))}static msm(e,r){return(0,P6.pippenger)(t,oe.ed25519.Point.Fn,e,r)}toBytes(){let{X:e,Y:r,Z:n,T:o}=this.ep,s=Cn,i=b=>K.create(b),a=i(i(n+r)*i(n-r)),c=i(e*r),d=i(c*c),{value:p}=G_(i(a*d)),l=i(p*a),u=i(p*c),f=i(l*u*o),h;if((0,Ae.isNegativeLE)(o*f,s)){let b=i(r*eh),y=i(e*eh);e=b,r=y,h=i(l*j6)}else h=u;(0,Ae.isNegativeLE)(e*f,s)&&(r=i(-r));let m=i((n-r)*h);return(0,Ae.isNegativeLE)(m,s)&&(m=i(-m)),K.toBytes(m)}equals(e){this.assertSame(e);let{X:r,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=d=>K.create(d),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(t.ZERO)}};Br.BASE=new Br(oe.ed25519.Point.BASE);Br.ZERO=new Br(oe.ed25519.Point.ZERO);Br.Fp=K;Br.Fn=J_;oe.ristretto255={Point:Br};oe.ristretto255_hasher={hashToCurve(t,e){let r=e?.DST||"ristretto255_XMD:SHA-512_R255MAP_RO_",n=(0,Du.expand_message_xmd)(t,r,64,va.sha512);return eb(n)},hashToScalar(t,e={DST:Du._DST_scalar}){let r=(0,Du.expand_message_xmd)(t,e.DST,64,va.sha512);return J_.create((0,cs.bytesToNumberLE)(r))}};oe.ED25519_TORSION_SUBGROUP=["0100000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a","0000000000000000000000000000000000000000000000000000000000000080","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05","ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f","26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85","0000000000000000000000000000000000000000000000000000000000000000","c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa"];function tb(t){return oe.ed25519.utils.toMontgomery((0,cs.ensureBytes)("pub",t))}oe.edwardsToMontgomery=tb;function G6(t){return oe.ed25519.utils.toMontgomerySecret((0,cs.ensureBytes)("pub",t))}oe.RistrettoPoint=Br;oe.hashToCurve=oe.ed25519_hasher.hashToCurve;oe.encodeToCurve=oe.ed25519_hasher.encodeToCurve;oe.hashToRistretto255=oe.ristretto255_hasher.hashToCurve;oe.hash_to_ristretto255=oe.ristretto255_hasher.hashToCurve});var sb=Y(Lu=>{"use strict";var nb,ob;Object.defineProperty(Lu,"__esModule",{value:!0});Lu.ExpirableMap=void 0;var sh=class{static{nb=Symbol.iterator,ob=Symbol.toStringTag}#e;#t;constructor(e={}){this[nb]=this.entries.bind(this),this[ob]="ExpirableMap";let{source:r=[],expirationTime:n=600*1e3}=e,o=Date.now();this.#e=new Map([...r].map(([s,i])=>[s,{value:i,timestamp:o}])),this.#t=n}prune(){let e=Date.now();for(let[r,n]of this.#e.entries())e-n.timestamp>this.#t&&this.#e.delete(r);return this}set(e,r){this.prune();let n={value:r,timestamp:Date.now()};return this.#e.set(e,n),this}get(e){let r=this.#e.get(e);if(r!==void 0){if(Date.now()-r.timestamp>this.#t){this.#e.delete(e);return}return r.value}}clear(){this.#e.clear()}entries(){let e=this.#e.entries();return function*(){for(let[n,o]of e)yield[n,o.value]}()}values(){let e=this.#e.values();return function*(){for(let n of e)yield n.value}()}keys(){return this.#e.keys()}forEach(e,r){for(let[n,o]of this.#e.entries())e.call(r,o.value,n,this)}has(e){return this.#e.has(e)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}};Lu.ExpirableMap=sh});var ih=Y(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.unwrapDER=Pe.BLS12_381_G2_OID=Pe.SECP256K1_OID=Pe.ED25519_OID=Pe.DER_COSE_OID=Pe.decodeLen=Pe.decodeLenBytes=Pe.encodeLen=Pe.encodeLenBytes=void 0;Pe.wrapDER=J6;var At=ar(),z6=Qs(),Z6=t=>{if(t<=127)return 1;if(t<=255)return 2;if(t<=65535)return 3;if(t<=16777215)return 4;throw At.InputError.fromCode(new At.DerEncodeErrorCode("Length too long (> 4 bytes)"))};Pe.encodeLenBytes=Z6;var Y6=(t,e,r)=>{if(r<=127)return t[e]=r,1;if(r<=255)return t[e]=129,t[e+1]=r,2;if(r<=65535)return t[e]=130,t[e+1]=r>>8,t[e+2]=r,3;if(r<=16777215)return t[e]=131,t[e+1]=r>>16,t[e+2]=r>>8,t[e+3]=r,4;throw At.InputError.fromCode(new At.DerEncodeErrorCode("Length too long (> 4 bytes)"))};Pe.encodeLen=Y6;var W6=(t,e)=>{if(t[e]<128)return 1;if(t[e]===128)throw At.InputError.fromCode(new At.DerDecodeErrorCode("Invalid length 0"));if(t[e]===129)return 2;if(t[e]===130)return 3;if(t[e]===131)return 4;throw At.InputError.fromCode(new At.DerDecodeErrorCode("Length too long (> 4 bytes)"))};Pe.decodeLenBytes=W6;var X6=(t,e)=>{let r=(0,Pe.decodeLenBytes)(t,e);if(r===1)return t[e];if(r===2)return t[e+1];if(r===3)return(t[e+1]<<8)+t[e+2];if(r===4)return(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];throw At.InputError.fromCode(new At.DerDecodeErrorCode("Length too long (> 4 bytes)"))};Pe.decodeLen=X6;Pe.DER_COSE_OID=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]);Pe.ED25519_OID=Uint8Array.from([48,5,6,3,43,101,112]);Pe.SECP256K1_OID=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]);Pe.BLS12_381_G2_OID=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 J6(t,e){let r=2+(0,Pe.encodeLenBytes)(t.byteLength+1),n=e.byteLength+r+t.byteLength,o=0,s=new Uint8Array(1+(0,Pe.encodeLenBytes)(n)+n);return s[o++]=48,o+=(0,Pe.encodeLen)(s,o,n),s.set(e,o),o+=e.byteLength,s[o++]=3,o+=(0,Pe.encodeLen)(s,o,t.byteLength+1),s[o++]=0,s.set(new Uint8Array(t),o),s}var Q6=(t,e)=>{let r=0,n=(a,c)=>{if(o[r++]!==a)throw At.InputError.fromCode(new At.DerDecodeErrorCode(`Expected ${c} at offset ${r}`))},o=new Uint8Array(t);if(n(48,"sequence"),r+=(0,Pe.decodeLenBytes)(o,r),!(0,z6.uint8Equals)(o.slice(r,r+e.byteLength),e))throw At.InputError.fromCode(new At.DerDecodeErrorCode("Not the expected OID."));r+=e.byteLength,n(3,"bit string");let s=(0,Pe.decodeLen)(o,r)-1;r+=(0,Pe.decodeLenBytes)(o,r),n(0,"0 padding");let i=o.slice(r);if(s!==i.length)throw At.InputError.fromCode(new At.DerDecodeLengthMismatchErrorCode(s,i.length));return i};Pe.unwrapDER=Q6});var ch=Y(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});ku.Ed25519PublicKey=void 0;var qu=ih(),Mu=ar(),ah=class t{static from(e){return this.fromDer(e.toDer())}static fromRaw(e){return new t(e)}static fromDer(e){return new t(this.derDecode(e))}static{this.RAW_KEY_LENGTH=32}static derEncode(e){return(0,qu.wrapDER)(e,qu.ED25519_OID)}static derDecode(e){let r=(0,qu.unwrapDER)(e,qu.ED25519_OID);if(r.length!==this.RAW_KEY_LENGTH)throw Mu.InputError.fromCode(new Mu.DerDecodeErrorCode("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(e){if(e.byteLength!==t.RAW_KEY_LENGTH)throw Mu.InputError.fromCode(new Mu.DerDecodeErrorCode("An Ed25519 public key must be exactly 32 bytes long"));this.#e=e,this.#t=t.derEncode(e)}toDer(){return this.derKey}toRaw(){return this.rawKey}};ku.Ed25519PublicKey=ah});var dh=Y(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.ObservableLog=ui.Observable=void 0;var ju=class{constructor(){this.observers=[]}subscribe(e){this.observers.push(e)}unsubscribe(e){this.observers=this.observers.filter(r=>r!==e)}notify(e,...r){this.observers.forEach(n=>n(e,...r))}};ui.Observable=ju;var uh=class extends ju{constructor(){super()}print(e,...r){this.notify({message:e,level:"info"},...r)}warn(e,...r){this.notify({message:e,level:"warn"},...r)}error(e,r,...n){this.notify({message:e,level:"error",error:r},...n)}};ui.ObservableLog=uh});var fb=Y(Sa=>{"use strict";Object.defineProperty(Sa,"__esModule",{value:!0});Sa.ExponentialBackoff=void 0;Sa.exponentialBackoff=e4;var ib=.5,ab=1.5,cb=500,ub=6e4,db=9e5,lb=10,Ia=class t{#e;#t;#r;#c;#i;#d;#n;#o;#a=0;static{this.default={initialInterval:cb,randomizationFactor:ib,multiplier:ab,maxInterval:ub,maxElapsedTime:db,maxIterations:lb,date:Date}}constructor(e=t.default){let{initialInterval:r=cb,randomizationFactor:n=ib,multiplier:o=ab,maxInterval:s=ub,maxElapsedTime:i=db,maxIterations:a=lb,date:c=Date}=e;this.#e=r,this.#t=n,this.#r=o,this.#c=s,this.#o=c,this.#i=c.now(),this.#d=i,this.#n=a}get ellapsedTimeInMsec(){return this.#o.now()-this.#i}get currentInterval(){return this.#e}get count(){return this.#a}get randomValueFromInterval(){let e=this.#t*this.#e,r=this.#e-e,n=this.#e+e;return Math.random()*(n-r)+r}incrementCurrentInterval(){return this.#e=Math.min(this.#e*this.#r,this.#c),this.#a++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#d||this.#a>=this.#n?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};Sa.ExponentialBackoff=Ia;function*e4(t=Ia.default){let e=new Ia(t),r=e.next();for(;r;)yield r,r=e.next()}});var $u=Y($e=>{"use strict";var gb=$e&&$e.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),t4=$e&&$e.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),r4=$e&&$e.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&gb(r,e,n[o]);return t4(r,e),r}})(),n4=$e&&$e.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&gb(e,t,r)};Object.defineProperty($e,"__esModule",{value:!0});$e.HttpAgent=$e.MANAGEMENT_CANISTER_ID=$e.IC_ROOT_KEY=$e.RequestStatusResponseStatus=$e.makeNonce=void 0;$e.calculateIngressExpiry=Hu;var Pn=Rr(),z=ar(),pb=up(),Oo=r4(la()),Aa=ou(),hb=vl(),di=fu(),Dn=ei(),mb=Cu(),yb=ai(),o4=rb(),s4=sb(),i4=ch(),a4=dh(),c4=fb(),u4=Iu(),_b=dt(),lh=Qs(),d4=su();n4(fu(),$e);var l4=ei();Object.defineProperty($e,"makeNonce",{enumerable:!0,get:function(){return l4.makeNonce}});var bb;(function(t){t.Received="received",t.Processing="processing",t.Replied="replied",t.Rejected="rejected",t.Unknown="unknown",t.Done="done"})(bb||($e.RequestStatusResponseStatus=bb={}));var ph=60*1e3,f4=1e6,p4=0;$e.IC_ROOT_KEY="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";$e.MANAGEMENT_CANISTER_ID="aaaaa-aa";var h4="ic0.app",m4=".ic0.app",y4="icp0.io",_4=".icp0.io",b4="icp-api.io",g4=".icp-api.io",fh=200,x4=202,w4=404;function E4(){let t;if(typeof window<"u")if(window.fetch)t=window.fetch.bind(window);else throw z.ExternalError.fromCode(new z.HttpDefaultFetchErrorCode("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)t=global.fetch.bind(global);else throw z.ExternalError.fromCode(new z.HttpDefaultFetchErrorCode("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&&(t=self.fetch.bind(self));if(t)return t;throw z.ExternalError.fromCode(new z.HttpDefaultFetchErrorCode("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function T4(t){let e;if(t!==void 0)!t.match(/^[a-z]+:/)&&typeof window<"u"?e=new URL(window.location.protocol+"//"+t):e=new URL(t);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,s=o?.hostname,i;s&&typeof s=="string"&&(n.some(a=>s.endsWith(a))?i=s:i=r.find(a=>s.endsWith(a))),o&&i?e=new URL(`${o.protocol}//${i}${o.port?":"+o.port:""}`):e=new URL("https://icp-api.io")}return e.toString()}var hh=class t{#e;#t;#r;#c;#i;#d;#n;#o;#a;#g;#s;#l;#f;#u;get#T(){return this.#u*ph}#p;#h;#m;#y;constructor(e={}){this.#e=null,this.#t=!1,this.#r=p4,this.#c=!1,this.#i=null,this.#d=!1,this._isAgent=!0,this.config={},this.log=new a4.ObservableLog,this.#p=[],this.#h=[],this.#m=new s4.ExpirableMap({expirationTime:5*ph}),this.#y=!0,this.#w=(o,s)=>{if(this.#y===!1)return o;let{status:i,signatures:a=[],requestId:c}=o;for(let d of a){let{timestamp:p,identity:l}=d,u=Pn.Principal.fromUint8Array(l).toText(),f;if(i===hb.QueryResponseStatus.Replied){let{reply:x}=o;f=(0,Aa.hashOfMap)({status:i,reply:x,timestamp:BigInt(p),request_id:c})}else if(i===hb.QueryResponseStatus.Rejected){let{reject_code:x,reject_message:_,error_code:T}=o;f=(0,Aa.hashOfMap)({status:i,reject_code:x,reject_message:_,error_code:T,timestamp:BigInt(p),request_id:c})}else throw z.UnknownError.fromCode(new z.UnexpectedErrorCode(`Unknown status: ${i}`));let h=(0,_b.concatBytes)(d4.IC_RESPONSE_DOMAIN_SEPARATOR,f),m=s.nodeKeys.get(u);if(!m)throw z.ProtocolError.fromCode(new z.MalformedPublicKeyErrorCode);let b=i4.Ed25519PublicKey.fromDer(m).rawKey;if(o4.ed25519.verify(d.signature,h,b))return o;throw z.TrustError.fromCode(new z.QuerySignatureVerificationFailedErrorCode(u))}return o},this.config=e,this.#o=e.fetch||E4()||fetch.bind(global),this.#a=e.fetchOptions,this.#g=e.callOptions,this.#t=e.shouldFetchRootKey??!1,this.#d=e.shouldSyncTime??!1,e.rootKey?this.rootKey=e.rootKey:this.#t?this.rootKey=null:this.rootKey=(0,_b.hexToBytes)($e.IC_ROOT_KEY);let r=T4(e.host);this.host=new URL(r),e.verifyQuerySignatures!==void 0&&(this.#y=e.verifyQuerySignatures),this.#l=e.retryTimes??3;let n=()=>new c4.ExponentialBackoff({maxIterations:this.#l});if(this.#f=e.backoffStrategy||n,this.host.hostname.endsWith(m4)?this.host.hostname=h4:this.host.hostname.endsWith(_4)?this.host.hostname=y4:this.host.hostname.endsWith(g4)&&(this.host.hostname=b4),e.credentials){let{name:o,password:s}=e.credentials;this.#s=`${o}${s?":"+s:""}`}if(this.#n=Promise.resolve(e.identity||new pb.AnonymousIdentity),e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes>5)throw z.InputError.fromCode(new z.IngressExpiryInvalidErrorCode("The maximum ingress expiry time is 5 minutes.",e.ingressExpiryInMinutes));if(e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes<=0)throw z.InputError.fromCode(new z.IngressExpiryInvalidErrorCode("Ingress expiry time must be greater than 0.",e.ingressExpiryInMinutes));this.#u=e.ingressExpiryInMinutes||5,this.addTransform("update",(0,di.makeNonceTransform)(Dn.makeNonce)),e.useQueryNonces&&this.addTransform("query",(0,di.makeNonceTransform)(Dn.makeNonce)),e.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(e={}){return new this({...e})}static async create(e={}){let r=t.createSync(e);return await r.#b(),r}static async from(e){try{return"config"in e?await t.create(e.config):await t.create({fetch:e._fetch,fetchOptions:e._fetchOptions,callOptions:e._callOptions,host:e._host.toString(),identity:e._identity??void 0})}catch{throw z.InputError.fromCode(new z.CreateHttpAgentErrorCode)}}isLocal(){let e=this.host.hostname;return e==="127.0.0.1"||e.endsWith("127.0.0.1")}addTransform(e,r,n=r.priority||0){if(e==="update"){let o=this.#h.findIndex(s=>(s.priority||0)<n);this.#h.splice(o>=0?o:this.#h.length,0,Object.assign(r,{priority:n}))}else if(e==="query"){let o=this.#p.findIndex(s=>(s.priority||0)<n);this.#p.splice(o>=0?o:this.#p.length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this.#n)throw z.ExternalError.fromCode(new z.IdentityInvalidErrorCode);return(await this.#n).getPrincipal()}async call(e,r,n){let o=r.callSync??!0,s=await(n??this.#n);if(!s)throw z.ExternalError.fromCode(new z.IdentityInvalidErrorCode);let i=Pn.Principal.from(e),a=r.effectiveCanisterId?Pn.Principal.from(r.effectiveCanisterId):i;await this.#b(a);let c=s.getPrincipal(),d=Hu(this.#u,this.#r),p={request_type:Dn.SubmitRequestType.Call,canister_id:i,method_name:r.methodName,arg:r.arg,sender:c,ingress_expiry:d},l=await this._transform({request:{body:null,method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:Dn.Endpoint.Call,body:p}),u;r?.nonce?u=f(r.nonce):l.body.nonce?u=f(l.body.nonce):u=void 0,p.nonce=u;function f(y){return Object.assign(y,{__nonce__:void 0})}l=await s.transformRequest(l);let h=Oo.encode(l.body),m=this.#f(),b=(0,Aa.requestIdOf)(p);try{let _=o?()=>(this.log.print(`fetching "/api/v3/canister/${a.toText()}/call" with request:`,l),this.#o(""+new URL(`/api/v3/canister/${a.toText()}/call`,this.host),{...this.#g,...l.request,body:h})):()=>(this.log.print(`fetching "/api/v2/canister/${a.toText()}/call" with request:`,l),this.#o(""+new URL(`/api/v2/canister/${a.toText()}/call`,this.host),{...this.#g,...l.request,body:h})),{responseBodyBytes:T,...N}=await this.#_({requestFn:_,backoff:m,tries:0}),v=T.byteLength>0?Oo.decode(T):null;return{requestId:b,response:{...N,body:v},requestDetails:p}}catch(y){let x;if(y instanceof z.AgentError){if(y.hasCode(z.HttpV3ApiNotSupportedErrorCode))return this.log.warn("v3 api not supported. Fall back to v2"),this.call(e,{...r,callSync:!1},n);if(y.hasCode(z.IngressExpiryInvalidErrorCode)&&!this.#c)return await this.syncTime(i),this.call(i,r,n);y.code.requestContext={requestId:b,senderPubKey:l.body.sender_pubkey,senderSignature:l.body.sender_sig,ingressExpiry:l.body.content.ingress_expiry},x=y}else x=z.UnknownError.fromCode(new z.UnexpectedErrorCode(y));throw this.log.error(`Error while making call: ${x.message}`,x),x}}async#x(e){let{ecid:r,transformedRequest:n,body:o,requestId:s,backoff:i,tries:a}=e,c=a===0?0:i.next();if(this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with tries:`,{tries:a,backoff:i,delay:c}),c===null)throw z.UnknownError.fromCode(new z.TimeoutWaitingForResponseErrorCode(`Backoff strategy exhausted after ${a} attempts.`,s));c>0&&await new Promise(f=>setTimeout(f,c));let d;try{this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with request:`,n);let f=await this.#o(""+new URL(`/api/v2/canister/${r.toString()}/query`,this.host),{...this.#a,...n.request,body:o});if(f.status===fh)d={...Oo.decode((0,lh.uint8FromBufLike)(await f.arrayBuffer())),httpDetails:{ok:f.ok,status:f.status,statusText:f.statusText,headers:(0,di.httpHeadersTransform)(f.headers)},requestId:s};else throw z.ProtocolError.fromCode(new z.HttpErrorCode(f.status,f.statusText,(0,di.httpHeadersTransform)(f.headers),await f.text()))}catch(f){if(a<this.#l)return this.log.warn(`Caught exception while attempting to make query:
50
+ `)}return c.encodeValue(u)}));return W(n,o,i,s,a)}function $p(e,t){let r=new _t(t);if(t.byteLength<Pi.length)throw new Error("Message length smaller than magic number");let n=Or(r,Pi.length),o=new TextDecoder().decode(n);if(o!==Pi)throw new Error("Wrong magic number: "+JSON.stringify(o));function i(l){let f=[],h=Number(me(l));for(let _=0;_<h;_++){let x=Number(Wt(l));switch(x){case Z.Opt:case Z.Vector:{let y=Number(Wt(l));f.push([x,y]);break}case Z.Record:case Z.Variant:{let y=[],T=Number(me(l)),E;for(;T--;){let O=Number(me(l));if(O>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof E=="number"&&E>=O)throw new Error("field id collision or not sorted");E=O;let R=Number(Wt(l));y.push([O,R])}f.push([x,y]);break}case Z.Func:{let y=[],T=Number(me(l));for(;T--;)y.push(Number(Wt(l)));let E=[],O=Number(me(l));for(;O--;)E.push(Number(Wt(l)));let R=[],I=Number(me(l));for(;I--;)switch(Number(me(l))){case 1:{R.push("query");break}case 2:{R.push("oneway");break}case 3:{R.push("composite_query");break}default:throw new Error("unknown annotation")}f.push([x,[y,E,R]]);break}case Z.Service:{let y=Number(me(l)),T=[];for(;y--;){let E=Number(me(l)),O=new TextDecoder().decode(Or(l,E)),R=Wt(l);T.push([O,R])}f.push([x,T]);break}default:throw new Error("Illegal op_code: "+x)}}let m=[],g=Number(me(l));for(let _=0;_<g;_++)m.push(Number(Wt(l)));return[f,m]}let[s,a]=i(r);if(a.length<e.length)throw new Error("Wrong number of return values");let c=s.map(l=>kl());function u(l){if(l<-24)throw new Error("future value not supported");if(l<0)switch(l){case-1:return gl;case-2:return yl;case-3:return wl;case-4:return bl;case-5:return Il;case-6:return Al;case-7:return Sl;case-8:return Fl;case-9:return Ol;case-10:return El;case-11:return Rl;case-12:return vl;case-13:return Tl;case-14:return Nl;case-15:return xl;case-16:return _l;case-17:return ml;case-24:return Vl;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 Z.Vector:{let f=u(l[1]);return Pl(f)}case Z.Opt:{let f=u(l[1]);return Bl(f)}case Z.Record:{let f={};for(let[g,_]of l[1]){let x=`_${g}_`;f[x]=u(_)}let h=Dl(f),m=h.tryAsTuple();return Array.isArray(m)?Cl(...m):h}case Z.Variant:{let f={};for(let[h,m]of l[1]){let g=`_${h}_`;f[g]=u(m)}return Ul(f)}case Z.Func:{let[f,h,m]=l[1];return Ll(f.map(g=>u(g)),h.map(g=>u(g)),m)}case Z.Service:{let f={},h=l[1];for(let[m,g]of h){let _=u(g);if(_ instanceof tt&&(_=_.getType()),!(_ instanceof gn))throw new Error("Illegal service definition: services can only contain functions");f[m]=_}return ql(f)}default:throw new Error("Illegal op_code: "+l[0])}}s.forEach((l,f)=>{if(l[0]===Z.Func){let h=p(l);c[f].fill(h)}}),s.forEach((l,f)=>{if(l[0]!==Z.Func){let h=p(l);c[f].fill(h)}}),Zs();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{Zs()}}var ml=new vo,_l=new St,Gp=new Di,yl=new Ui,gl=new _n,xl=new ki,bl=new Io,wl=new Ao,Tl=new So(32),Nl=new So(64),Ol=new Zt(8),El=new Zt(16),Rl=new Zt(32),vl=new Zt(64),Il=new It(8),Al=new It(16),Sl=new It(32),Fl=new It(64),Vl=new qi;function Cl(...e){return new Li(e)}function Pl(e){return new jn(e)}function Bl(e){return new Er(e)}function Dl(e){return new yn(e)}function Ul(e){return new Kn(e)}function kl(){return new tt}function Ll(e,t,r=[]){return new gn(e,t,r)}function ql(e){return new Hn(e)}var Mi=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)}},Bi=new Mi;function Zs(){Bi=new Mi}function Jp(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 zs(e){return e instanceof Er||e instanceof _n||e instanceof St}function Qs(e,t){let r=Bi.copy(),n=Yt(r,e,t);return n?Bi.add(e,t):Bi.addNegative(e,t),n}function Yt(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 St||t instanceof vo||t instanceof Ao&&r instanceof Io)return!0;if(t instanceof jn&&r instanceof jn)return Yt(e,t._type,r._type);if(r instanceof Er)return!0;if(t instanceof yn&&r instanceof yn){let o=t.fieldsAsObject;for(let[i,s]of r._fields){let a=o[De(i)];if(a){if(!Yt(e,a,s))return!1}else if(!zs(s))return!1}return!0}if(t instanceof gn&&r instanceof gn){if(!Jp(t,r))return!1;for(let o=0;o<t.argTypes.length;o++){let i=t.argTypes[o];if(o<r.argTypes.length){if(!Yt(e,r.argTypes[o],i))return!1}else if(!zs(i))return!1}for(let o=0;o<r.retTypes.length;o++){let i=r.retTypes[o];if(o<t.retTypes.length){if(!Yt(e,t.retTypes[o],i))return!1}else if(!zs(i))return!1}return!0}if(t instanceof Kn&&r instanceof Kn){let o=r.alternativesAsObject;for(let[i,s]of t._fields){let a=o[De(i)];if(!a||!Yt(e,s,a))return!1}return!0}if(t instanceof Hn&&r instanceof Hn){let o=t.fieldsAsObject();for(let[i,s]of r._fields){let a=o[i];if(!a||!Yt(e,a,s))return!1}return!0}return t instanceof tt?Yt(e,t.getType(),r):r instanceof tt?Yt(e,t,r.getType()):!1}function $n(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?$n(e.buffer):new Uint8Array(e)}function bn(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 ea(e){if(typeof e=="string")return Ml(e);if(typeof e=="number")return Se(oe(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return Se($n(e));if(Array.isArray(e)){let t=e.map(ea);return Se(j(...t))}else{if(e&&typeof e=="object"&&e._isPrincipal)return Se(e.toUint8Array());if(typeof e=="object"&&e!==null&&typeof e.toHash=="function")return ea(e.toHash());if(typeof e=="object")return Fo(e);if(typeof e=="bigint")return Se(oe(e))}throw z.fromCode(new Ri(e))}var Ml=e=>{let t=new TextEncoder().encode(e);return Se(t)};function Xt(e){return Fo(e)}function Fo(e){let n=Object.entries(e).filter(([,s])=>s!==void 0).map(([s,a])=>{let c=Ml(s),u=ea(a);return[c,u]}).sort(([s],[a])=>Hs(s,a)),o=j(...n.map(s=>j(...s)));return Se(o)}var Vo=new TextEncoder().encode(`
52
+ ic-request`),ta=new TextEncoder().encode("\vic-response"),ra=new TextEncoder().encode("ic-request-auth-delegation");var Ft=class{getPrincipal(){return this._principal||(this._principal=M.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(t){let{body:r,...n}=t,o=Xt(r);return{...n,body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign(j(Vo,o))}}}},rt=class{getPrincipal(){return M.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}};var Qt=class extends Error{constructor(t){super(t),this.name="DecodingError"}},Kl=55799,Hl=Symbol("CBOR_STOP_CODE"),xt=(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))(xt||{}),be=(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))(be||{}),zp=23,Wp=255,Yp=65535,Zp=4294967295,Xp=BigInt("0xffffffffffffffff"),gt=(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))(gt||{}),Gn=!1;function Qp(e){return e==null}function $l(e,t){let r=new Uint8Array(t);return r.set(e),r}var ef=new TextDecoder;function tf(e){return(e&224)>>5}function rf(e){return e&31}var Bo=new Uint8Array,Co,bt=0;function Gl(e,t){Bo=e,bt=0;let r=wn(t);return t?.(r)??r}function wn(e){let[t,r]=ji();switch(t){case be.UnsignedInteger:return Jn(r);case be.NegativeInteger:return af(r);case be.ByteString:return Jl(r);case be.TextString:return oa(r);case be.Array:return nf(r,e);case be.Map:return sf(r,e);case be.Tag:return cf(r,e);case be.Simple:return of(r)}throw new Qt(`Unsupported major type: ${t}`)}function ji(){let e=Bo.at(bt);if(Qp(e))throw new Qt("Provided CBOR data is empty");let t=tf(e),r=rf(e);return bt++,[t,r]}function nf(e,t){let r=Jn(e);if(r===1/0){let o=[],i=wn(t);for(;i!==Hl;)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 of(e){switch(e){case xt.False:return!1;case xt.True:return!0;case xt.Null:return null;case xt.Undefined:return;case xt.Break:return Hl}throw new Qt(`Unrecognized simple type: ${e.toString(2)}`)}function sf(e,t){let r=Jn(e),n={};if(r===1/0){let[o,i]=ji();for(;o!==be.Simple&&i!==xt.Break;){let s=oa(i),a=wn(t);n[s]=t?.(a,s)??a,[o,i]=ji()}return n}for(let o=0;o<r;o++){let[i,s]=ji();if(i!==be.TextString)throw new Qt("Map keys must be text strings");let a=oa(s),c=wn(t);n[a]=t?.(c,a)??c}return n}function Jn(e){if(e<=gt.Value)return e;switch(Co=new DataView(Bo.buffer,Bo.byteOffset+bt),e){case gt.OneByte:return bt++,Co.getUint8(0);case gt.TwoBytes:return bt+=2,Co.getUint16(0,Gn);case gt.FourBytes:return bt+=4,Co.getUint32(0,Gn);case gt.EightBytes:return bt+=8,Co.getBigUint64(0,Gn);case gt.Indefinite:return 1/0;default:throw new Qt(`Unsupported integer info: ${e.toString(2)}`)}}function af(e){let t=Jn(e);return typeof t=="number"?-1-t:-1n-t}function Jl(e){let t=Jn(e);if(t>Number.MAX_SAFE_INTEGER)throw new Qt("Byte length is too large");let r=Number(t);return bt+=r,Bo.slice(bt-r,bt)}function oa(e){let t=Jl(e);return ef.decode(t)}function cf(e,t){let r=Jn(e);if(r===Kl)return wn(t);throw new Qt(`Unsupported tag: ${r}.`)}var Do=class extends Error{constructor(t){super(t),this.name="SerializationError"}},lf=2*1024,uf=100,df=new TextEncoder;function Po(e){return e<<5}var et=new Uint8Array(lf),yt=new DataView(et.buffer),xe=0,na=[];function zl(e,t){xe=0;let r=t?.(e)??e;return xf(Kl,r,t),et.slice(0,xe)}function ia(e,t){if(xe>et.length-uf&&(et=$l(et,et.length*2),yt=new DataView(et.buffer)),e===!1||e===!0||e===null||e===void 0){hf(e);return}if(typeof e=="number"||typeof e=="bigint"){gf(e);return}if(typeof e=="string"){Zl(e);return}if(e instanceof Uint8Array){jl(e);return}if(e instanceof ArrayBuffer){jl(new Uint8Array(e));return}if(Array.isArray(e)){pf(e,t);return}if(typeof e=="object"){ff(e,t);return}throw new Do(`Unsupported type: ${typeof e}`)}function pf(e,t){zn(be.Array,e.length),e.forEach((r,n)=>{ia(t?.(r,n.toString())??r,t)})}function ff(e,t){na=Object.entries(e),zn(be.Map,na.length),na.forEach(([r,n])=>{Zl(r),ia(t?.(n,r)??n,t)})}function zn(e,t){if(t<=zp){yt.setUint8(xe++,Po(e)|Number(t));return}if(t<=Wp){yt.setUint8(xe++,Po(e)|gt.OneByte),yt.setUint8(xe,Number(t)),xe+=1;return}if(t<=Yp){yt.setUint8(xe++,Po(e)|gt.TwoBytes),yt.setUint16(xe,Number(t),Gn),xe+=2;return}if(t<=Zp){yt.setUint8(xe++,Po(e)|gt.FourBytes),yt.setUint32(xe,Number(t),Gn),xe+=4;return}if(t<=Xp){yt.setUint8(xe++,Po(e)|gt.EightBytes),yt.setBigUint64(xe,BigInt(t),Gn),xe+=8;return}throw new Do(`Value too large to encode: ${t}`)}function hf(e){zn(be.Simple,mf(e))}function mf(e){if(e===!1)return xt.False;if(e===!0)return xt.True;if(e===null)return xt.Null;if(e===void 0)return xt.Undefined;throw new Do(`Unrecognized simple value: ${e.toString()}`)}function Wl(e,t){zn(e,t.length),xe>et.length-t.length&&(et=$l(et,et.length+t.length),yt=new DataView(et.buffer)),et.set(t,xe),xe+=t.length}function Yl(e,t){zn(e,t)}function _f(e){Yl(be.UnsignedInteger,e)}function yf(e){Yl(be.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function gf(e){e>=0?_f(e):yf(e)}function Zl(e){Wl(be.TextString,df.encode(e))}function jl(e){Wl(be.ByteString,e)}function xf(e,t,r){zn(be.Tag,e),ia(t,r)}function wf(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function Uo(e){try{return zl(e,t=>M.isPrincipal(t)?t.toUint8Array():Wn.isExpiry(t)?t.toBigInt():wf(t)?t.toCborValue():t)}catch(t){throw z.fromCode(new wi(t,e))}}function Je(e){try{return Gl(e)}catch(t){throw z.fromCode(new bi(t,e))}}var Ki={encode:Uo,decode:Je};var ko=()=>{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 er;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(er||(er={}));var Hi;(function(e){e.Call="call"})(Hi||(Hi={}));var Tn;(function(e){e.Query="query",e.ReadState="read_state"})(Tn||(Tn={}));function Lo(){let e=new ArrayBuffer(16),t=new DataView(e),r=ko(),n=ko(),o=ko(),i=ko();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 $i="__expiry__",aa=BigInt(1e3),Tf=BigInt(1e6),Xl=BigInt(60),Nf=BigInt(90)*aa;function Ql(e){return e/aa}function Of(e){return Ql(e)/Xl}var Wn=class e{constructor(t){this.__expiry__=t,this._isExpiry=!0}static fromDeltaInMilliseconds(t,r=0){let n=BigInt(t),o=BigInt(Date.now())+n+BigInt(r),i;return n<Nf?i=Ql(o):i=Of(o)*Xl,new e(i*aa*Tf)}toBigInt(){return this.__expiry__}toHash(){return oe(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[$i]:this.toString()}}static fromJSON(t){let r=JSON.parse(t);if(r[$i])try{let n=BigInt(r[$i]);return new e(n)}catch(n){throw new z(new Oo(`Not a valid BigInt: ${n}`))}throw new z(new Oo(`The input does not contain the key ${$i}`))}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 ca(e=Lo){return async t=>{let r=t.request.headers;t.request.headers=r,t.endpoint===er.Call&&(t.body.nonce=e())}}function Gi(e){let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t}var ua=BigInt(0),Ji=BigInt(1);function Nn(e,t=""){if(typeof e!="boolean"){let r=t&&`"${t}"`;throw new Error(r+"expected boolean, got type="+typeof e)}return e}function Rr(e,t,r=""){let n=Ot(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 eu(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?ua:BigInt("0x"+e)}function ze(e){return eu(H(e))}function tr(e){return fe(e),eu(H(Uint8Array.from(e).reverse()))}function we(e,t){return Ne(e.toString(16).padStart(t*2,"0"))}function da(e,t){return we(e,t).reverse()}function le(e,t,r){let n;if(typeof t=="string")try{n=Ne(t)}catch(i){throw new Error(e+" must be hex string or Uint8Array, cause: "+i)}else if(Ot(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 tu(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 pa(e){return Uint8Array.from(e)}var la=e=>typeof e=="bigint"&&ua<=e;function fa(e,t,r){return la(e)&&la(t)&&la(r)&&t<=e&&e<r}function zi(e,t,r,n){if(!fa(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}function rr(e){let t;for(t=0;e>ua;e>>=Ji,t+=1);return t}function ru(e,t){return e>>BigInt(t)&Ji}var wt=e=>(Ji<<BigInt(e))-Ji;function nu(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 Yn=()=>{throw new Error("not implemented")};function vr(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 Ue=BigInt(0),Ee=BigInt(1),On=BigInt(2),iu=BigInt(3),su=BigInt(4),au=BigInt(5),Ef=BigInt(7),cu=BigInt(8),Rf=BigInt(9),lu=BigInt(16);function se(e,t){let r=e%t;return r>=Ue?r:t+r}function Tt(e,t,r){let n=e;for(;t-- >Ue;)n*=n,n%=r;return n}function ou(e,t){if(e===Ue)throw new Error("invert: expected non-zero number");if(t<=Ue)throw new Error("invert: expected positive modulus, got "+t);let r=se(e,t),n=t,o=Ue,i=Ee,s=Ee,a=Ue;for(;r!==Ue;){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!==Ee)throw new Error("invert: does not exist");return se(o,t)}function ha(e,t,r){if(!e.eql(e.sqr(t),r))throw new Error("Cannot find square root")}function uu(e,t){let r=(e.ORDER+Ee)/su,n=e.pow(t,r);return ha(e,n,t),n}function vf(e,t){let r=(e.ORDER-au)/cu,n=e.mul(t,On),o=e.pow(n,r),i=e.mul(t,o),s=e.mul(e.mul(i,On),o),a=e.mul(i,e.sub(s,e.ONE));return ha(e,a,t),a}function If(e){let t=ke(e),r=du(e),n=r(t,t.neg(t.ONE)),o=r(t,n),i=r(t,t.neg(n)),s=(e+Ef)/lu;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 m=a.eql(a.sqr(p),c),g=a.cmov(u,p,m);return ha(a,g,c),g}}function du(e){if(e<iu)throw new Error("sqrt is not defined for small field");let t=e-Ee,r=0;for(;t%On===Ue;)t/=On,r++;let n=On,o=ke(e);for(;qo(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return uu;let i=o.pow(n,t),s=(t+Ee)/On;return function(c,u){if(c.is0(u))return u;if(qo(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,m=c.sqr(l);for(;!c.eql(m,c.ONE);)if(h++,m=c.sqr(m),h===p)throw new Error("Cannot find square root");let g=Ee<<BigInt(p-h-1),_=c.pow(d,g);p=h,d=c.sqr(_),l=c.mul(l,d),f=c.mul(f,_)}return f}}function Af(e){return e%su===iu?uu:e%cu===au?vf:e%lu===Rf?If(e):du(e)}var or=(e,t)=>(se(e,t)&Ee)===Ee,Sf=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Wi(e){let t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=Sf.reduce((n,o)=>(n[o]="function",n),t);return nr(e,r),e}function Mo(e,t,r){if(r<Ue)throw new Error("invalid exponent, negatives unsupported");if(r===Ue)return e.ONE;if(r===Ee)return t;let n=e.ONE,o=t;for(;r>Ue;)r&Ee&&(n=e.mul(n,o)),o=e.sqr(o),r>>=Ee;return n}function nt(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 qo(e,t){let r=(e.ORDER-Ee)/On,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 ma(e,t){t!==void 0&&Us(t);let r=t!==void 0?t:e.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function ke(e,t,r=!1,n={}){if(e<=Ue)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}=ma(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:wt(c),ZERO:Ue,ONE:Ee,allowedLengths:a,create:l=>se(l,e),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return Ue<=l&&l<e},is0:l=>l===Ue,isValidNot0:l=>!d.is0(l)&&d.isValid(l),isOdd:l=>(l&Ee)===Ee,neg:l=>se(-l,e),eql:(l,f)=>l===f,sqr:l=>se(l*l,e),add:(l,f)=>se(l+f,e),sub:(l,f)=>se(l-f,e),mul:(l,f)=>se(l*f,e),pow:(l,f)=>Mo(d,l,f),div:(l,f)=>se(l*ou(f,e),e),sqrN:l=>l*l,addN:(l,f)=>l+f,subN:(l,f)=>l-f,mulN:(l,f)=>l*f,inv:l=>ou(l,e),sqrt:i||(l=>(p||(p=Af(e)),p(d,l))),toBytes:l=>r?da(l,u):we(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 m=new Uint8Array(u);m.set(l,r?0:m.length-l.length),l=m}if(l.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+l.length);let h=r?tr(l):ze(l);if(s&&(h=se(h,e)),!f&&!d.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:l=>nt(d,l),cmov:(l,f,h)=>h?f:l});return Object.freeze(d)}function pu(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 Yi(e){let t=pu(e);return t+Math.ceil(t/2)}function _a(e,t,r=!1){let n=e.length,o=pu(t),i=Yi(t);if(n<16||n<i||n>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+n);let s=r?tr(e):ze(e),a=se(s,t-Ee)+Ee;return r?da(a,o):we(a,o)}var Zn=BigInt(0),En=BigInt(1);function jo(e,t){let r=t.negate();return e?r:t}function ot(e,t){let r=nt(e.Fp,t.map(n=>n.Z));return t.map((n,o)=>e.fromAffine(n.toAffine(r[o])))}function _u(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ya(e,t){_u(e,t);let r=Math.ceil(t/e)+1,n=2**(e-1),o=2**e,i=wt(e),s=BigInt(e);return{windows:r,windowSize:n,mask:i,maxNumber:o,shiftBy:s}}function fu(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+=En);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 Vf(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 Cf(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 ga=new WeakMap,yu=new WeakMap;function xa(e){return yu.get(e)||1}function hu(e){if(e!==Zn)throw new Error("invalid wNAF")}var Xn=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>Zn;)r&En&&(n=n.add(o)),o=o.double(),r>>=En;return n}precomputeWindow(t,r){let{windows:n,windowSize:o}=ya(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=ya(t,this.bits);for(let a=0;a<s.windows;a++){let{nextN:c,offset:u,isZero:p,isNeg:d,isNegF:l,offsetF:f}=fu(n,a,s);n=c,p?i=i.add(jo(l,r[f])):o=o.add(jo(d,r[u]))}return hu(n),{p:o,f:i}}wNAFUnsafe(t,r,n,o=this.ZERO){let i=ya(t,this.bits);for(let s=0;s<i.windows&&n!==Zn;s++){let{nextN:a,offset:c,isZero:u,isNeg:p}=fu(n,s,i);if(n=a,!u){let d=r[c];o=o.add(p?d.negate():d)}}return hu(n),o}getPrecomputes(t,r,n){let o=ga.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof n=="function"&&(o=n(o)),ga.set(r,o))),o}cached(t,r,n){let o=xa(t);return this.wNAF(o,this.getPrecomputes(o,t,n),r)}unsafe(t,r,n,o){let i=xa(t);return i===1?this._unsafeLadder(t,r,o):this.wNAFUnsafe(i,this.getPrecomputes(i,t,n),r,o)}createCache(t,r){_u(r,this.bits),yu.set(t,r),ga.delete(t)}hasCache(t){return xa(t)!==1}};function gu(e,t,r,n){let o=t,i=e.ZERO,s=e.ZERO;for(;r>Zn||n>Zn;)r&En&&(i=i.add(o)),n&En&&(s=s.add(o)),o=o.double(),r>>=En,n>>=En;return{p1:i,p2:s}}function Qn(e,t,r,n){Vf(r,e),Cf(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=rr(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let u=wt(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 m=0;m<i;m++){let g=n[m],_=Number(g>>BigInt(f)&u);p[_]=p[_].add(r[m])}let h=s;for(let m=p.length-1,g=s;m>0;m--)g=g.add(p[m]),h=h.add(g);if(l=l.add(h),f!==0)for(let m=0;m<c;m++)l=l.double()}return l}function mu(e,t,r){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Wi(t),t}else return ke(e,{isLE:r})}function Zi(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>Zn))throw new Error(`CURVE.${c} must be positive bigint`)}let o=mu(t.p,r.Fp,n),i=mu(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 Pf=ze;function Ir(e,t){if(Ko(e),Ko(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 Bf(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 Ko(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function xu(e){if(!Ot(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?ee(e):e}function Df(e,t,r,n){fe(e),Ko(r),t=xu(t),t.length>255&&(t=n(j(ee("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=j(t,Ir(t.length,1)),c=Ir(0,i),u=Ir(r,2),p=new Array(s),d=n(j(c,e,u,Ir(0,1),a));p[0]=n(j(d,Ir(1,1),a));for(let f=1;f<=s;f++){let h=[Bf(d,p[f-1]),Ir(f+1,1),a];p[f]=n(j(...h))}return j(...p).slice(0,r)}function Uf(e,t,r,n,o){if(fe(e),Ko(r),t=xu(t),t.length>255){let i=Math.ceil(2*n/8);t=o.create({dkLen:i}).update(ee("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(Ir(r,2)).update(t).update(Ir(t.length,1)).digest()}function ba(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(!nu(r.hash))throw new Error("expected valid hash");fe(e),Ko(t);let u=n.toString(2).length,p=Math.ceil((u+o)/8),d=t*i*p,l;if(a==="xmd")l=Df(e,c,d,s);else if(a==="xof")l=Uf(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 m=new Array(i);for(let g=0;g<i;g++){let _=p*(g+h*i),x=l.subarray(_,_+p);m[g]=se(Pf(x),n)}f[h]=m}return f}function wa(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]=nt(e,[s,c],!0);return n=e.mul(i,u),o=e.mul(o,e.mul(a,p)),{x:n,y:o}}}var kf=ee("HashToScalar-");function Ta(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=ba(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=ba(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:kf},s);return ba(i,1,c)[0][0]}}}var bu=(e,t)=>(e+(e>=0?t:-t)/ir)/t;function Lf(e,t,r){let[[n,o],[i,s]]=t,a=bu(s*e,r),c=bu(-o*e,r),u=e-a*n-c*i,p=-a*o-c*s,d=u<Rn,l=p<Rn;d&&(u=-u),l&&(p=-p);let f=wt(Math.ceil(rr(r)/2))+Le;if(u<Rn||u>=f||p<Rn||p>=f)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:d,k1:u,k2neg:l,k2:p}}var Rn=BigInt(0),Le=BigInt(1),ir=BigInt(2),eo=BigInt(3),Na=BigInt(4);function Ho(e,t){let{BYTES:r}=e,n;if(typeof t=="bigint")n=t;else{let o=le("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 qf(e,t={}){let r=Zi("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=Kf(n,o);function p(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function d(S,b,N){let{x:F,y:B}=b.toAffine(),k=n.toBytes(F);if(Nn(N,"isCompressed"),N){p();let A=!n.isOdd(B);return j(Mf(A),k)}else return j(Uint8Array.of(4),k,n.toBytes(B))}function l(S){Rr(S,void 0,"Point");let{publicKey:b,publicKeyUncompressed:N}=u,F=S.length,B=S[0],k=S.subarray(1);if(F===b&&(B===2||B===3)){let A=n.fromBytes(k);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");let C=m(A),P;try{P=n.sqrt(C)}catch(te){let Q=te instanceof Error?": "+te.message:"";throw new Error("bad point: is not on curve, sqrt error"+Q)}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(k.subarray(0,A)),P=n.fromBytes(k.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=${b} or uncompressed=${N}`)}let f=t.toBytes||d,h=t.fromBytes||l;function m(S){let b=n.sqr(S),N=n.mul(b,S);return n.add(n.add(N,n.mul(S,i.a)),i.b)}function g(S,b){let N=n.sqr(b),F=m(S);return n.eql(N,F)}if(!g(i.Gx,i.Gy))throw new Error("bad curve params: generator point");let _=n.mul(n.pow(i.a,eo),Na),x=n.mul(n.sqr(i.b),BigInt(27));if(n.is0(n.add(_,x)))throw new Error("bad curve params: a or b");function y(S,b,N=!1){if(!n.isValid(b)||N&&n.is0(b))throw new Error(`bad point coordinate ${S}`);return b}function T(S){if(!(S instanceof w))throw new Error("ProjectivePoint expected")}function E(S){if(!c||!c.basises)throw new Error("no endo");return Lf(S,c.basises,o.ORDER)}let O=vr((S,b)=>{let{X:N,Y:F,Z:B}=S;if(n.eql(B,n.ONE))return{x:N,y:F};let k=S.is0();b==null&&(b=k?n.ONE:n.inv(B));let A=n.mul(N,b),C=n.mul(F,b),P=n.mul(B,b);if(k)return{x:n.ZERO,y:n.ZERO};if(!n.eql(P,n.ONE))throw new Error("invZ was invalid");return{x:A,y:C}}),R=vr(S=>{if(S.is0()){if(t.allowInfinityPoint&&!n.is0(S.Y))return;throw new Error("bad point: ZERO")}let{x:b,y:N}=S.toAffine();if(!n.isValid(b)||!n.isValid(N))throw new Error("bad point: x or y not field elements");if(!g(b,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,b,N,F,B){return N=new w(n.mul(N.X,S),N.Y,N.Z),b=jo(F,b),N=jo(B,N),b.add(N)}class w{constructor(b,N,F){this.X=y("x",b),this.Y=y("y",N,!0),this.Z=y("z",F),Object.freeze(this)}static CURVE(){return i}static fromAffine(b){let{x:N,y:F}=b||{};if(!b||!n.isValid(N)||!n.isValid(F))throw new Error("invalid affine point");if(b 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(b){let N=w.fromAffine(h(Rr(b,void 0,"point")));return N.assertValidity(),N}static fromHex(b){return w.fromBytes(le("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,N=!0){return V.createCache(this,b),N||this.multiply(eo),this}assertValidity(){R(this)}hasEvenY(){let{y:b}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(b)}equals(b){T(b);let{X:N,Y:F,Z:B}=this,{X:k,Y:A,Z:C}=b,P=n.eql(n.mul(N,C),n.mul(k,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:b,b:N}=i,F=n.mul(N,eo),{X:B,Y:k,Z:A}=this,C=n.ZERO,P=n.ZERO,D=n.ZERO,U=n.mul(B,B),te=n.mul(k,k),Q=n.mul(A,A),$=n.mul(B,k);return $=n.add($,$),D=n.mul(B,A),D=n.add(D,D),C=n.mul(b,D),P=n.mul(F,Q),P=n.add(C,P),C=n.sub(te,P),P=n.add(te,P),P=n.mul(C,P),C=n.mul($,C),D=n.mul(F,D),Q=n.mul(b,Q),$=n.sub(U,Q),$=n.mul(b,$),$=n.add($,D),D=n.add(U,U),U=n.add(D,U),U=n.add(U,Q),U=n.mul(U,$),P=n.add(P,U),Q=n.mul(k,A),Q=n.add(Q,Q),U=n.mul(Q,$),C=n.sub(C,U),D=n.mul(Q,te),D=n.add(D,D),D=n.add(D,D),new w(C,P,D)}add(b){T(b);let{X:N,Y:F,Z:B}=this,{X:k,Y:A,Z:C}=b,P=n.ZERO,D=n.ZERO,U=n.ZERO,te=i.a,Q=n.mul(i.b,eo),$=n.mul(N,k),ie=n.mul(F,A),pe=n.mul(B,C),Ae=n.add(N,F),re=n.add(k,A);Ae=n.mul(Ae,re),re=n.add($,ie),Ae=n.sub(Ae,re),re=n.add(N,B);let ce=n.add(k,C);return re=n.mul(re,ce),ce=n.add($,pe),re=n.sub(re,ce),ce=n.add(F,B),P=n.add(A,C),ce=n.mul(ce,P),P=n.add(ie,pe),ce=n.sub(ce,P),U=n.mul(te,re),P=n.mul(Q,pe),U=n.add(P,U),P=n.sub(ie,U),U=n.add(ie,U),D=n.mul(P,U),ie=n.add($,$),ie=n.add(ie,$),pe=n.mul(te,pe),re=n.mul(Q,re),ie=n.add(ie,pe),pe=n.sub($,pe),pe=n.mul(te,pe),re=n.add(re,pe),$=n.mul(ie,re),D=n.add(D,$),$=n.mul(ce,re),P=n.mul(Ae,P),P=n.sub(P,$),$=n.mul(Ae,ie),U=n.mul(ce,U),U=n.add(U,$),new w(P,D,U)}subtract(b){return this.add(b.negate())}is0(){return this.equals(w.ZERO)}multiply(b){let{endo:N}=t;if(!o.isValidNot0(b))throw new Error("invalid scalar: out of range");let F,B,k=A=>V.cached(this,A,C=>ot(w,C));if(N){let{k1neg:A,k1:C,k2neg:P,k2:D}=E(b),{p:U,f:te}=k(C),{p:Q,f:$}=k(D);B=te.add($),F=I(N.beta,U,Q,A,P)}else{let{p:A,f:C}=k(b);F=A,B=C}return ot(w,[F,B])[0]}multiplyUnsafe(b){let{endo:N}=t,F=this;if(!o.isValid(b))throw new Error("invalid scalar: out of range");if(b===Rn||F.is0())return w.ZERO;if(b===Le)return F;if(V.hasCache(this))return this.multiply(b);if(N){let{k1neg:B,k1:k,k2neg:A,k2:C}=E(b),{p1:P,p2:D}=gu(w,F,k,C);return I(N.beta,P,D,B,A)}else return V.unsafe(F,b)}multiplyAndAddUnsafe(b,N,F){let B=this.multiplyUnsafe(N).add(b.multiplyUnsafe(F));return B.is0()?void 0:B}toAffine(b){return O(this,b)}isTorsionFree(){let{isTorsionFree:b}=t;return s===Le?!0:b?b(w,this):V.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:b}=t;return s===Le?this:b?b(w,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(b=!0){return Nn(b,"isCompressed"),this.assertValidity(),f(w,this,b)}toHex(b=!0){return H(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return ot(w,b)}static msm(b,N){return Qn(w,o,b,N)}static fromPrivateKey(b){return w.BASE.multiply(Ho(o,b))}}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 Xn(w,t.endo?Math.ceil(v/2):v);return w.BASE.precompute(8),w}function Mf(e){return Uint8Array.of(e?2:3)}function jf(e,t){let r=e.ORDER,n=Rn;for(let h=r-Le;h%ir===Rn;h/=ir)n+=Le;let o=n,i=ir<<o-Le-Le,s=i*ir,a=(r-Le)/s,c=(a-Le)/ir,u=s-Le,p=i,d=e.pow(t,a),l=e.pow(t,(a+Le)/ir),f=(h,m)=>{let g=d,_=e.pow(m,u),x=e.sqr(_);x=e.mul(x,m);let y=e.mul(h,x);y=e.pow(y,c),y=e.mul(y,_),_=e.mul(y,m),x=e.mul(y,h);let T=e.mul(x,_);y=e.pow(T,p);let E=e.eql(y,e.ONE);_=e.mul(x,l),y=e.mul(T,g),x=e.cmov(_,x,E),T=e.cmov(y,T,E);for(let O=o;O>Le;O--){let R=O-ir;R=ir<<R-Le;let I=e.pow(T,R),w=e.eql(I,e.ONE);_=e.mul(x,g),g=e.mul(g,g),I=e.mul(T,g),x=e.cmov(_,x,w),T=e.cmov(I,T,w)}return{isValid:E,value:x}};if(e.ORDER%Na===eo){let h=(e.ORDER-eo)/Na,m=e.sqrt(e.neg(t));f=(g,_)=>{let x=e.sqr(_),y=e.mul(g,_);x=e.mul(x,y);let T=e.pow(x,h);T=e.mul(T,y);let E=e.mul(T,m),O=e.mul(e.sqr(T),_),R=e.eql(O,g),I=e.cmov(E,T,R);return{isValid:R,value:I}}}return f}function Oa(e,t){Wi(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=jf(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:m,value:g}=i(c,l);h=e.mul(a,s),h=e.mul(h,g),f=e.cmov(f,u,m),h=e.cmov(h,g,m);let _=e.isOdd(s)===e.isOdd(h);h=e.cmov(e.neg(h),h,_);let x=nt(e,[p],!0)[0];return f=e.mul(f,x),{x:f,y:h}}}function Kf(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function Ea(e){let{CURVE:t,curveOpts:r}=Hf(e),n=qf(t,r);return Gf(e,n)}function Hf(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=ke(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 $f(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 Gf(e,t){let{Fp:r,Fn:n}=t;function o(s){return fa(s,Le,n.ORDER)}let i=$f(r,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:s=>Ho(n,s),weierstrassEquation:i,isWithinCurveOrder:o})}var Jf=BigInt(0),Xi=BigInt(1),wu=BigInt(2),to=BigInt(3);function zf(e){let t=[];for(;e>Xi;e>>=Xi)(e&Xi)===Jf?t.unshift(0):(e&to)===to?(t.unshift(-1),e+=Xi):t.unshift(1);return t}function Ra(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function Wf(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,E,O,R,I)=>i.mul014(O,y,o.mul(T,R),o.mul(E,I));else if(s==="divisive")p=(y,T,E,O,R,I)=>i.mul034(O,o.mul(E,I),o.mul(T,R),y);else throw new Error("bls: unknown twist type");let d=o.div(o.ONE,o.mul(o.ONE,wu));function l(y,T,E,O){let R=o.sqr(E),I=o.sqr(O),w=o.mulByB(o.mul(I,to)),v=o.mul(w,to),V=o.sub(o.sub(o.sqr(o.add(E,O)),I),R),S=o.sub(w,R),b=o.mul(o.sqr(T),to),N=o.neg(V);return y.push([S,b,N]),T=o.mul(o.mul(o.mul(o.sub(R,v),T),E),d),E=o.sub(o.sqr(o.mul(o.add(R,v),d)),o.mul(o.sqr(w),to)),O=o.mul(R,V),{Rx:T,Ry:E,Rz:O}}function f(y,T,E,O,R,I){let w=o.sub(E,o.mul(I,O)),v=o.sub(T,o.mul(R,O)),V=o.sub(o.mul(w,R),o.mul(v,I)),S=o.neg(w),b=v;y.push([V,S,b]);let N=o.sqr(v),F=o.mul(N,v),B=o.mul(N,T),k=o.add(o.sub(F,o.mul(B,wu)),o.mul(o.sqr(w),O));return T=o.mul(v,k),E=o.sub(o.mul(o.sub(B,k),w),o.mul(F,E)),O=o.mul(O,F),{Rx:T,Ry:E,Rz:O}}let h=zf(a),m=vr(y=>{let T=y,{x:E,y:O}=T.toAffine(),R=E,I=O,w=o.neg(O),v=R,V=I,S=o.ONE,b=[];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,R,N===-1?w:I)),b.push(F)}if(u){let N=b[b.length-1];u(v,V,S,R,I,f.bind(null,N))}return b});function g(y,T=!1){let E=i.ONE;if(y.length){let O=y[0][0].length;for(let R=0;R<O;R++){E=i.sqr(E);for(let[I,w,v]of y)for(let[V,S,b]of I[R])E=p(V,S,b,E,w,v)}}return c&&(E=i.conjugate(E)),T?i.finalExponentiate(E):E}function _(y,T=!0){let E=[];ot(t,y.map(({g1:O})=>O)),ot(r,y.map(({g2:O})=>O));for(let{g1:O,g2:R}of y){if(O.is0()||R.is0())throw new Error("pairing is not available for ZERO point");O.assertValidity(),R.assertValidity();let I=O.toAffine();E.push([m(R),I.x,I.y])}return g(E,T)}function x(y,T,E=!0){return _([{g1:y,g2:T}],E)}return{Fp12:i,millerLoopBatch:g,pairing:x,pairingBatch:_,calcPairingPrecomputes:m}}function Tu(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=Ho(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=Ho(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 m=f.negate(),g=t.Point.BASE,_=u(l),x=d,y=s([p(m,_),p(g,x)]);return i.eql(y,i.ONE)},verifyBatch(d,l,f){if(Ra(l),f.length!==l.length)throw new Error("amount of public keys and messages should be equal");let h=c(d),m=l,g=f.map(a),_=new Map;for(let T=0;T<g.length;T++){let E=g[T],O=m[T],R=_.get(O);R===void 0&&(R=[],_.set(O,R)),R.push(E)}let x=[],y=t.Point.BASE;try{for(let[T,E]of _){let O=E.reduce((R,I)=>R.add(I));x.push(p(O,T))}return x.push(p(y.negate(),h)),i.eql(s(x),i.ONE)}catch{return!1}},aggregatePublicKeys(d){Ra(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){Ra(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 Nu(e){let{Fp:t,Fr:r,Fp2:n,Fp6:o,Fp12:i}=e.fields,s=Ea(e.G1),a=Object.assign(s,Ta(s.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),c=Ea(e.G2),u=Object.assign(c,Ta(c.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),p=Wf(e.fields,a.Point,u.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:d,pairing:l,pairingBatch:f,calcPairingPrecomputes:h}=p,m=Tu(p,a,u,e.G2.Signature,!1),g=Tu(p,u,a,e.G1.ShortSignature,!0),_=e.randomBytes||Bn,x=()=>{let A=Yi(r.ORDER);return _a(_(A),r.ORDER)},y={randomSecretKey:x,randomPrivateKey:x,calcPairingPrecomputes:h},{ShortSignature:T}=e.G1,{Signature:E}=e.G2;function O(A,C){return A instanceof a.Point?A:g.hash(le("point",A),C?.DST)}function R(A,C){return A instanceof u.Point?A:m.hash(le("point",A),C?.DST)}function I(A){return m.getPublicKey(A).toBytes(!0)}function w(A){return g.getPublicKey(A).toBytes(!0)}function v(A,C,P){let D=R(A,P),U=m.sign(D,C);return A instanceof u.Point?U:E.toBytes(U)}function V(A,C,P){let D=O(A,P),U=g.sign(D,C);return A instanceof a.Point?U:T.toBytes(U)}function S(A,C,P,D){let U=R(C,D);return m.verify(A,U,P)}function b(A,C,P,D){let U=O(C,D);return g.verify(A,U,P)}function N(A){let C=m.aggregatePublicKeys(A);return A[0]instanceof a.Point?C:C.toBytes(!0)}function F(A){let C=m.aggregateSignatures(A);return A[0]instanceof u.Point?C:E.toBytes(C)}function B(A){let C=g.aggregateSignatures(A);return A[0]instanceof a.Point?C:T.toBytes(C)}function k(A,C,P,D){let U=C.map(te=>R(te,D));return m.verifyBatch(A,U,P)}return a.Point.BASE.precompute(4),{longSignatures:m,shortSignatures:g,millerLoopBatch:d,pairing:l,pairingBatch:f,verifyBatch:k,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:b,aggregatePublicKeys:N,aggregateSignatures:F,aggregateShortSignatures:B,G1:a,G2:u,Signature:E,ShortSignature:T}}var Ou=BigInt(0),sr=BigInt(1),qe=BigInt(2),Eu=BigInt(3);function Sa(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=sr;l<n;l++){let h=(p*f-p)/s%a;d.push(e.pow(t,h)),f*=r}c.push(d)}return c}function vu(e,t,r){let n=t.pow(r,(e.ORDER-sr)/Eu),o=t.pow(r,(e.ORDER-sr)/qe);function i(l,f){let h=t.mul(t.frobeniusMap(l,1),n),m=t.mul(t.frobeniusMap(f,1),o);return[h,m]}let s=t.pow(r,(e.ORDER**qe-sr)/Eu),a=t.pow(r,(e.ORDER**qe-sr)/qe);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 m=h.toAffine(),g=l(m.x,m.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 Ru=(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]}},va=class{constructor(t,r={}){this.MASK=sr;let n=t.ORDER,o=n*n;this.Fp=t,this.ORDER=o,this.BITS=rr(o),this.BYTES=Math.ceil(rr(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,qe),this.NONRESIDUE=Ru(t,r.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=Sa(t,this.Fp_NONRESIDUE,t.ORDER,2)[0],this.mulByB=r.Fp2mulByB,Object.seal(this)}fromBigTuple(t){return Ru(this.Fp,t)}create(t){return t}isValid({c0:t,c1:r}){function n(o,i){return typeof o=="bigint"&&Ou<=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 Mo(this,t,r)}invertBatch(t){return nt(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 qo(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);qo(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:m,im:g}=n.reim(l);return h>g||h===g&&f>m?d:l}isOdd(t){let{re:r,im:n}=this.reim(t),o=r%qe,i=r===Ou,s=n%qe;return BigInt(o||i&&s)==sr}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 j(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])}}},Ia=class{constructor(t){this.MASK=sr,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=Sa(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),qe),a=o.mul(o.mul(r,n),qe),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 Yn()}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 Mo(this,t,r)}invertBatch(t){return nt(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 j(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)}}},Aa=class{constructor(t,r){this.MASK=sr;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=Sa(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){Yn()}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 Mo(this,t,r)}invertBatch(t){return nt(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 j(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:m,second:g}=o.Fp4Square(s,p),_=o.mulByNonresidue(g);return{c0:n.create({c0:o.add(o.mul(o.sub(d,i),qe),d),c1:o.add(o.mul(o.sub(f,s),qe),f),c2:o.add(o.mul(o.sub(m,a),qe),m)}),c1:n.create({c0:o.add(o.mul(o.add(_,c),qe),_),c1:o.add(o.mul(o.add(l,u),qe),l),c2:o.add(o.mul(o.add(h,p),qe),h)})}}_cyclotomicExp(t,r){let n=this.ONE;for(let o=this.X_LEN-1;o>=0;o--)n=this._cyclotomicSquare(n),ru(r,o)&&(n=this.mul(n,t));return n}};function Iu(e){let t=ke(e.ORDER),r=new va(t,e),n=new Ia(r),o=new Aa(n,e);return{Fp:t,Fp2:r,Fp6:n,Fp12:o}}var Fe=BigInt(0),Qi=BigInt(1),it=BigInt(2),es=BigInt(3),$o=BigInt(4),Ar=BigInt("0xd201000000010000"),Yf=rr(Ar),vn={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Fe,b:$o,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},Zf=ke(vn.n,{modFromBytes:!0,isLE:!0}),{Fp:L,Fp2:J,Fp6:Xf,Fp12:Y}=Iu({ORDER:vn.p,X_LEN:Yf,FP2_NONRESIDUE:[Qi,Qi],Fp2mulByB:({c0:e,c1:t})=>{let r=L.mul(e,$o),n=L.mul(t,$o);return{c0:L.sub(r,n),c1:L.add(r,n)}},Fp12finalExponentiate:e=>{let t=Ar,r=Y.div(Y.frobeniusMap(e,6),e),n=Y.mul(Y.frobeniusMap(r,2),r),o=Y.conjugate(Y._cyclotomicExp(n,t)),i=Y.mul(Y.conjugate(Y._cyclotomicSquare(n)),o),s=Y.conjugate(Y._cyclotomicExp(i,t)),a=Y.conjugate(Y._cyclotomicExp(s,t)),c=Y.mul(Y.conjugate(Y._cyclotomicExp(a,t)),Y._cyclotomicSquare(o)),u=Y.conjugate(Y._cyclotomicExp(c,t)),p=Y.frobeniusMap(Y.mul(o,a),2),d=Y.frobeniusMap(Y.mul(s,n),3),l=Y.frobeniusMap(Y.mul(c,Y.conjugate(n)),1),f=Y.mul(Y.mul(u,Y.conjugate(i)),n);return Y.mul(Y.mul(Y.mul(p,d),l),f)}}),{G2psi:Au,G2psi2:Qf}=vu(L,J,J.div(J.ONE,J.NONRESIDUE)),Fa=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:Se}),Pa={p:J.ORDER,n:vn.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:J.ZERO,b:J.fromBigTuple([$o,$o]),Gx:J.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:J.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},ts=Go(L.toBytes(Fe),{infinity:!0,compressed:!0});function rs(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 Go(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 eh(e,t,r){let{BYTES:n,ORDER:o}=L,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return ts.slice();let c=!!(a*it/o);return Go(we(s,n),{compressed:!0,sort:c})}else return i?j(Uint8Array.of(64),new Uint8Array(2*n-1)):j(we(s,n),we(a,n))}function Va(e){e.assertValidity();let{BYTES:t,ORDER:r}=L,{x:n,y:o}=e.toAffine();if(e.is0())return ts.slice();let i=!!(o*it/r);return Go(we(n,t),{compressed:!0,sort:i})}function th(e){let{compressed:t,infinity:r,sort:n,value:o}=rs(e),{BYTES:i,ORDER:s}=L;if(o.length===48&&t){let a=ze(o),c=L.create(a&wt(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 u=L.add(L.pow(c,es),L.create(vn.b)),p=L.sqrt(u);if(!p)throw new Error("invalid G1 point: compressed point");return p*it/s!==BigInt(n)&&(p=L.neg(p)),{x:L.create(c),y:L.create(p)}}else if(o.length===96&&!t){let a=ze(o.subarray(0,i)),c=ze(o.subarray(i));if(r){if(a!==Fe||c!==Fe)throw new Error("G1: non-empty point at infinity");return Jo.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 Su(e){let{infinity:t,sort:r,value:n}=rs(le("signatureHex",e,48)),o=L.ORDER,i=Jo.G1.Point,s=ze(n);if(t)return i.ZERO;let a=L.create(s&wt(L.BITS)),c=L.add(L.pow(a,es),L.create(vn.b)),u=L.sqrt(c);if(!u)throw new Error("invalid G1 point: compressed");let p=BigInt(r);u*it/o!==p&&(u=L.neg(u));let d=i.fromAffine({x:a,y:u});return d.assertValidity(),d}function rh(e,t,r){let{BYTES:n,ORDER:o}=L,i=t.is0(),{x:s,y:a}=t.toAffine();if(r){if(i)return j(ts,we(Fe,n));let c=!!(a.c1===Fe?a.c0*it/o:a.c1*it/o);return j(Go(we(s.c1,n),{compressed:!0,sort:c}),we(s.c0,n))}else{if(i)return j(Uint8Array.of(64),new Uint8Array(4*n-1));let{re:c,im:u}=J.reim(s),{re:p,im:d}=J.reim(a);return j(we(u,n),we(c,n),we(d,n),we(p,n))}}function Ca(e){e.assertValidity();let{BYTES:t}=L;if(e.is0())return j(ts,we(Fe,t));let{x:r,y:n}=e.toAffine(),{re:o,im:i}=J.reim(r),{re:s,im:a}=J.reim(n),u=!!((a>Fe?a*it:s*it)/L.ORDER&Qi),p=o;return j(Go(we(i,t),{sort:u,compressed:!0}),we(p,t))}function nh(e){let{BYTES:t,ORDER:r}=L,{compressed:n,infinity:o,sort:i,value:s}=rs(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)=>ze(c.slice(u,p));if(s.length===96&&n){if(o){if(s.reduce((h,m)=>h!==0?m+1:m,0)>0)throw new Error("invalid G2 point: compressed");return{x:J.ZERO,y:J.ZERO}}let c=a(s,0,t),u=a(s,t,2*t),p=J.create({c0:L.create(u),c1:L.create(c)}),d=J.add(J.pow(p,es),Pa.b),l=J.sqrt(d),f=l.c1===Fe?l.c0*it/r:l.c1*it/r?Qi:Fe;return l=i&&f>0?l:J.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:J.ZERO,y:J.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:J.fromBigTuple([u,c]),y:J.fromBigTuple([d,p])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function Fu(e){let{ORDER:t}=L,{infinity:r,sort:n,value:o}=rs(le("signatureHex",e)),i=Jo.G2.Point,s=o.length/2;if(s!==48&&s!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");let a=ze(o.slice(0,s)),c=ze(o.slice(s));if(r)return i.ZERO;let u=L.create(a&wt(L.BITS)),p=L.create(c),d=J.create({c0:p,c1:u}),l=J.add(J.pow(d,es),Pa.b),f=J.sqrt(l);if(!f)throw new Error("Failed to find a square root");let{re:h,im:m}=J.reim(f),g=BigInt(n),_=m>Fe&&m*it/t!==g,x=m===Fe&&h*it/t!==g;(_||x)&&(f=J.neg(f));let y=i.fromAffine({x:d,y:f});return y.assertValidity(),y}var Jo=Nu({fields:{Fp:L,Fp2:J,Fp6:Xf,Fp12:Y,Fr:Zf},G1:{...vn,Fp:L,htfDefaults:{...Fa,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(Ar).negate().multiplyUnsafe(Ar).equals(n)},clearCofactor:(e,t)=>t.multiplyUnsafe(Ar).add(t),mapToCurve:ch,fromBytes:th,toBytes:eh,ShortSignature:{fromBytes(e){return fe(e),Su(e)},fromHex(e){return Su(e)},toBytes(e){return Va(e)},toRawBytes(e){return Va(e)},toHex(e){return H(Va(e))}}},G2:{...Pa,Fp:J,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...Fa},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:lh,isTorsionFree:(e,t)=>t.multiplyUnsafe(Ar).negate().equals(Au(e,t)),clearCofactor:(e,t)=>{let r=Ar,n=t.multiplyUnsafe(r).negate(),o=Au(e,t),i=t.double();return i=Qf(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:nh,toBytes:rh,Signature:{fromBytes(e){return fe(e),Fu(e)},fromHex(e){return Fu(e)},toBytes(e){return Ca(e)},toRawBytes(e){return Ca(e)},toHex(e){return H(Ca(e))}}},params:{ateLoopSize:Ar,r:vn.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:Fa,hash:Se}),oh=wa(J,[[["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=>J.fromBigTuple(t.map(BigInt))))),ih=wa(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)))),sh=Oa(L,{A:L.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:L.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:L.create(BigInt(11))}),ah=Oa(J,{A:J.create({c0:L.create(Fe),c1:L.create(BigInt(240))}),B:J.create({c0:L.create(BigInt(1012)),c1:L.create(BigInt(1012))}),Z:J.create({c0:L.create(BigInt(-2)),c1:L.create(BigInt(-1))})});function ch(e){let{x:t,y:r}=sh(L.create(e[0]));return ih(t,r)}function lh(e){let{x:t,y:r}=ah(J.fromBigTuple(e));return oh(t,r)}function Vu(e,t,r){let n=typeof e=="string"?e:H(e),o=typeof t=="string"?t:H(t),i=typeof r=="string"?r:H(r);return Jo.verifyShortSignature(o,i,n)}var dh=BigInt(1e6),Ba=e=>me(new _t(e)),ro=e=>{let r=Ba(e)/dh;return new Date(Number(r))};var Cu=60*1e3,ph=60,fh=24,hh=fh*ph,mh=5,_h=5,yh=30*hh,Ie;(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"})(Ie||(Ie={}));function gh(e,t){for(let r=0;r<e.length;r++)if(e[r]>t[r])return!0;return!1}var Sr=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.canisterId,t.blsVerify??Vu,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,r,n,o,i=mh,s=!1,a){this._rootKey=r,this._canisterId=n,this._blsVerify=o,this._maxAgeInMinutes=i,this.#e=s,this.cert=Je(t),a&&"getTimeDiffMsecs"in a&&"hasSyncedTime"in a&&"syncTime"in a&&(this.#t=a)}lookup_path(t){return An(t,this.cert.tree)}lookup_subtree(t){return is(t,this.cert.tree)}async verify(){let t=await ns(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,o=bh(r),i=j(Wo("ic-state-root"),t),s=Ve(this.lookup_path(["time"]));if(!s)throw ne.fromCode(new xr("Certificate does not contain a time"));if(!this.#e){let a=this.#t?.getTimeDiffMsecs()??0,c=this._maxAgeInMinutes*Cu,u=new Date,p=u.getTime()+a,d=p-c,l=p+_h*Cu,f=ro(s),h=f.getTime()<d,m=f.getTime()>l;if((h||m)&&this.#t&&!this.#t.hasSyncedTime())return await this.#t.syncTime(this._canisterId),await this.verify();if(h)throw Pe.fromCode(new fn(this._maxAgeInMinutes,f,u,a,"past"));if(m)throw this.#t?.hasSyncedTime()?ge.fromCode(new Be("System time has been synced with the IC network, but certificate is still too far in the future.")):Pe.fromCode(new fn(5,f,u,a,"future"))}try{if(!await this._blsVerify(o,n,i))throw Pe.fromCode(new xr("Invalid signature"))}catch(a){throw Pe.fromCode(new xr("Signature verification failed",a))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;let r=e.createUnverified({certificate:t.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:yh,agent:this.#t});if(r.cert.delegation)throw ne.fromCode(new _i);await r.verify();let n=t.subnet_id,o=M.fromUint8Array(n);if(!Da({canisterId:this._canisterId,subnetId:o,tree:r.cert.tree}))throw Pe.fromCode(new Dn(this._canisterId,o));let s=Ve(r.lookup_path(["subnet",n,"public_key"]));if(!s)throw Pe.fromCode(new yi(`Could not find subnet key for subnet ID ${o.toText()}`));return s}},zo=Ne("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),xh=96;function bh(e){let t=zo.byteLength+xh;if(e.byteLength!==t)throw ne.fromCode(new kn(t,e.byteLength));let r=e.slice(0,zo.byteLength);if(!bn(r,zo))throw ne.fromCode(new gi(zo,r));return e.slice(zo.byteLength)}function Ve(e){if(e.status===We.Found&&e.value instanceof Uint8Array)return e.value}async function ns(e){switch(e[0]){case Ie.Empty:return Se(Wo("ic-hashtree-empty"));case Ie.Pruned:return e[1];case Ie.Leaf:return Se(j(Wo("ic-hashtree-leaf"),e[1]));case Ie.Labeled:return Se(j(Wo("ic-hashtree-labeled"),e[1],await ns(e[2])));case Ie.Fork:return Se(j(Wo("ic-hashtree-fork"),await ns(e[1]),await ns(e[2])));default:throw Tr}}function Wo(e){let t=new Uint8Array([e.length]),r=new TextEncoder().encode(e);return j(t,r)}function Pu(e){return typeof e[0]=="string"?ee(e[0]):e[0]}var We;(function(e){e.Unknown="Unknown",e.Absent="Absent",e.Found="Found",e.Error="Error"})(We||(We={}));var In;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(In||(In={}));var ae;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(ae||(ae={}));function An(e,t){if(e.length===0)switch(t[0]){case Ie.Empty:return{status:We.Absent};case Ie.Leaf:{if(!t[1])throw ge.fromCode(new wr("Invalid tree structure for leaf"));if(t[1]instanceof Uint8Array)return{status:We.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw Tr}case Ie.Pruned:return{status:We.Unknown};case Ie.Labeled:case Ie.Fork:return{status:We.Error};default:throw Tr}let r=Pu(e),n=Yo(r,t);switch(n.status){case ae.Found:return An(e.slice(1),n.value);case ae.Absent:case ae.Greater:case ae.Less:return{status:We.Absent};case ae.Unknown:return{status:We.Unknown};default:throw Tr}}function is(e,t){if(e.length===0)return{status:In.Found,value:t};let r=Pu(e),n=Yo(r,t);switch(n.status){case ae.Found:return is(e.slice(1),n.value);case ae.Unknown:return{status:In.Unknown};case ae.Absent:case ae.Greater:case ae.Less:return{status:In.Absent};default:throw Tr}}function os(e){switch(e[0]){case Ie.Empty:return[];case Ie.Fork:return os(e[1]).concat(os(e[2]));default:return[e]}}function Yo(e,t){switch(t[0]){case Ie.Labeled:return gh(e,t[1])?{status:ae.Greater}:bn(e,t[1])?{status:ae.Found,value:t[2]}:{status:ae.Less};case Ie.Fork:{let r=Yo(e,t[1]);switch(r.status){case ae.Greater:{let n=Yo(e,t[2]);return n.status===ae.Less?{status:ae.Absent}:n}case ae.Unknown:{let n=Yo(e,t[2]);return n.status===ae.Less?{status:ae.Unknown}:n}default:return r}}case Ie.Pruned:return{status:ae.Unknown};default:return{status:ae.Absent}}}function Da(e){let{canisterId:t,subnetId:r,tree:n}=e,o=An(["subnet",r.toUint8Array(),"canister_ranges"],n);if(o.status!==We.Found)throw ne.fromCode(new zt(`Could not find canister ranges for subnet ${r.toText()}`,o.status));if(!(o.value instanceof Uint8Array))throw ne.fromCode(new Un(`Could not find canister ranges for subnet ${r.toText()}`));return Je(o.value).map(c=>[M.fromUint8Array(c[0]),M.fromUint8Array(c[1])]).some(c=>c[0].ltEq(t)&&c[1].gtEq(t))}var Ua=async e=>{let{agent:t,paths:r,disableCertificateTimeVerification:n=!1}=e,o=M.from(e.canisterId),i=[...new Set(r)],s=new Map,a=i.map((c,u)=>{let p=Th(c,o);return(async()=>{try{if(t.rootKey===null)throw Oe.fromCode(new Rt);let d=t.rootKey,l=await t.readState(o,{paths:[p]}),f=await Sr.create({certificate:l.certificate,rootKey:d,canisterId:o,disableTimeVerification:n,agent:t}),h=(_,x)=>{if(x==="subnet"){let y=wh(l.certificate,o,d);return{path:x,data:y}}else return{path:x,data:Ve(_.lookup_path(p))}},{path:m,data:g}=h(f,i[u]);if(!g)console.warn(`Expected to find result for path ${m}, but instead found nothing.`),typeof m=="string"?s.set(m,null):s.set(m.key,null);else switch(m){case"time":{s.set(m,ro(g));break}case"controllers":{s.set(m,Nh(g));break}case"module_hash":{s.set(m,H(g));break}case"subnet":{s.set(m,g);break}case"candid":{s.set(m,new TextDecoder().decode(g));break}default:if(typeof m!="string"&&"key"in m&&"path"in m)switch(m.decodeStrategy){case"raw":s.set(m.key,g);break;case"leb128":{s.set(m.key,Ba(g));break}case"cbor":{s.set(m.key,Je(g));break}case"hex":{s.set(m.key,H(g));break}case"utf-8":s.set(m.key,new TextDecoder().decode(g))}}}catch(d){if(d instanceof ht&&(d.hasCode(xr)||d.hasCode(fn)))throw d;typeof c!="string"&&"key"in c&&"path"in c?s.set(c.key,null):s.set(c,null),console.group(),console.warn(`Expected to find result for path ${c}, but instead found nothing.`),console.warn(d),console.groupEnd()}})()});return await Promise.all(a),s},wh=(e,t,r)=>{if(!t._isPrincipal)throw z.fromCode(new Be("Invalid canisterId"));let n=Je(e),o=n.tree,i=n.delegation,s;if(i&&i.subnet_id?s=M.fromUint8Array(new Uint8Array(i.subnet_id)):!i&&typeof r<"u"?(s=M.selfAuthenticating(new Uint8Array(r)),i={subnet_id:s.toUint8Array(),certificate:new Uint8Array(0)}):(s=M.selfAuthenticating(M.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),i={subnet_id:s.toUint8Array(),certificate:new Uint8Array(0)}),!Da({canisterId:t,subnetId:s,tree:o}))throw Pe.fromCode(new Dn(t,s));let c=is(["subnet",i.subnet_id,"node"],o);if(c.status!==In.Found)throw ne.fromCode(new zt("Node not found",c.status));if(c.value instanceof Uint8Array)throw ge.fromCode(new wr("Invalid node tree"));let u=os(c.value),p=new Map;return u.forEach(d=>{let l=M.from(d[1]).toText(),f=An(["public_key"],d[2]);if(f.status!==We.Found)throw ne.fromCode(new zt("Public key not found",f.status));let h=f.value;if(h.byteLength!==44)throw ne.fromCode(new kn(44,h.byteLength));p.set(l,h)}),{subnetId:M.fromUint8Array(new Uint8Array(i.subnet_id)).toText(),nodeKeys:p}},Th=(e,t)=>{let r=t.toUint8Array();switch(e){case"time":return[ee("time")];case"controllers":return[ee("canister"),r,ee("controllers")];case"module_hash":return[ee("canister"),r,ee("module_hash")];case"subnet":return[ee("subnet")];case"candid":return[ee("canister"),r,ee("metadata"),ee("candid:service")];default:if("key"in e&&"path"in e)if(typeof e.path=="string"||e.path instanceof Uint8Array){let n=e.path,o=typeof n=="string"?ee(n):n;return[ee("canister"),r,ee("metadata"),o]}else return e.path}throw ge.fromCode(new Be(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))},Nh=e=>Je(e).map(r=>M.fromUint8Array(r));var Fr=BigInt(0),Re=BigInt(1),ka=BigInt(2),Oh=BigInt(8);function Eh(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 Rh(e,t={}){let r=Zi("edwards",e,t,t.FpFnLE),{Fp:n,Fn:o}=r,i=r.CURVE,{h:s}=i;nr(t,{},{uvRatio:"function"});let a=ka<<BigInt(o.BYTES*8)-Re,c=g=>n.create(g),u=t.uvRatio||((g,_)=>{try{return{isValid:!0,value:n.sqrt(n.div(g,_))}}catch{return{isValid:!1,value:Fr}}});if(!Eh(n,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");function p(g,_,x=!1){let y=x?Re:Fr;return zi("coordinate "+g,_,y,a),_}function d(g){if(!(g instanceof h))throw new Error("ExtendedPoint expected")}let l=vr((g,_)=>{let{X:x,Y:y,Z:T}=g,E=g.is0();_==null&&(_=E?Oh:n.inv(T));let O=c(x*_),R=c(y*_),I=n.mul(T,_);if(E)return{x:Fr,y:Re};if(I!==Re)throw new Error("invZ was invalid");return{x:O,y:R}}),f=vr(g=>{let{a:_,d:x}=i;if(g.is0())throw new Error("bad point: ZERO");let{X:y,Y:T,Z:E,T:O}=g,R=c(y*y),I=c(T*T),w=c(E*E),v=c(w*w),V=c(R*_),S=c(w*c(V+I)),b=c(v+c(x*c(R*I)));if(S!==b)throw new Error("bad point: equation left != right (1)");let N=c(y*T),F=c(E*O);if(N!==F)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(_,x,y,T){this.X=p("x",_),this.Y=p("y",x),this.Z=p("z",y,!0),this.T=p("t",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(_){if(_ instanceof h)throw new Error("extended point not allowed");let{x,y}=_||{};return p("x",x),p("y",y),new h(x,y,Re,c(x*y))}static fromBytes(_,x=!1){let y=n.BYTES,{a:T,d:E}=i;_=pa(Rr(_,y,"point")),Nn(x,"zip215");let O=pa(_),R=_[y-1];O[y-1]=R&-129;let I=tr(O),w=x?a:n.ORDER;zi("point.y",I,Fr,w);let v=c(I*I),V=c(v-Re),S=c(E*v-T),{isValid:b,value:N}=u(V,S);if(!b)throw new Error("bad point: invalid y coordinate");let F=(N&Re)===Re,B=(R&128)!==0;if(!x&&N===Fr&&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(_,x=!1){return h.fromBytes(le("point",_),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,x=!0){return m.createCache(this,_),x||this.multiply(ka),this}assertValidity(){f(this)}equals(_){d(_);let{X:x,Y:y,Z:T}=this,{X:E,Y:O,Z:R}=_,I=c(x*R),w=c(E*T),v=c(y*R),V=c(O*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:_}=i,{X:x,Y:y,Z:T}=this,E=c(x*x),O=c(y*y),R=c(ka*c(T*T)),I=c(_*E),w=x+y,v=c(c(w*w)-E-O),V=I+O,S=V-R,b=I-O,N=c(v*S),F=c(V*b),B=c(v*b),k=c(S*V);return new h(N,F,k,B)}add(_){d(_);let{a:x,d:y}=i,{X:T,Y:E,Z:O,T:R}=this,{X:I,Y:w,Z:v,T:V}=_,S=c(T*I),b=c(E*w),N=c(R*y*V),F=c(O*v),B=c((T+E)*(I+w)-S-b),k=F-N,A=F+N,C=c(b-x*S),P=c(B*k),D=c(A*C),U=c(B*C),te=c(k*A);return new h(P,D,te,U)}subtract(_){return this.add(_.negate())}multiply(_){if(!o.isValidNot0(_))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:y}=m.cached(this,_,T=>ot(h,T));return ot(h,[x,y])[0]}multiplyUnsafe(_,x=h.ZERO){if(!o.isValid(_))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return _===Fr?h.ZERO:this.is0()||_===Re?this:m.unsafe(this,_,y=>ot(h,y),x)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}isTorsionFree(){return m.unsafe(this,i.n).is0()}toAffine(_){return l(this,_)}clearCofactor(){return s===Re?this:this.multiplyUnsafe(s)}toBytes(){let{x:_,y:x}=this.toAffine(),y=n.toBytes(x);return y[y.length-1]|=_&Re?128:0,y}toHex(){return H(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(_){return ot(h,_)}static msm(_,x){return Qn(h,o,_,x)}_setWindowSize(_){this.precompute(_)}toRawBytes(){return this.toBytes()}}h.BASE=new h(i.Gx,i.Gy,Re,c(i.Gx*i.Gy)),h.ZERO=new h(Fr,Re,Re,Fr),h.Fp=n,h.Fn=o;let m=new Xn(h,o.BITS);return h.BASE.precompute(8),h}var ss=class{constructor(t){this.ep=t}static fromBytes(t){Yn()}static fromHex(t){Yn()}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 H(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 vh(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||Bn,c=r.adjustScalarBytes||(w=>w),u=r.domain||((w,v,V)=>{if(Nn(V,"phflag"),v.length||V)throw new Error("Contexts/pre-hash are not supported");return w});function p(w){return s.create(tr(w))}function d(w){let v=y.secretKey;w=le("private key",w,v);let V=le("hashed private key",t(w),2*v),S=c(V.slice(0,v)),b=V.slice(v,2*v),N=p(S);return{head:S,prefix:b,scalar:N}}function l(w){let{head:v,prefix:V,scalar:S}=d(w),b=o.multiply(S),N=b.toBytes();return{head:v,prefix:V,scalar:S,point:b,pointBytes:N}}function f(w){return l(w).pointBytes}function h(w=Uint8Array.of(),...v){let V=j(...v);return p(t(u(V,le("context",w),!!n)))}function m(w,v,V={}){w=le("message",w),n&&(w=n(w));let{prefix:S,scalar:b,pointBytes:N}=l(v),F=h(V.context,S,w),B=o.multiply(F).toBytes(),k=h(V.context,B,N,w),A=s.create(F+k*b);if(!s.isValid(A))throw new Error("sign failed: invalid s");let C=j(B,s.toBytes(A));return Rr(C,y.signature,"result")}let g={zip215:!0};function _(w,v,V,S=g){let{context:b,zip215:N}=S,F=y.signature;w=le("signature",w,F),v=le("message",v),V=le("publicKey",V,y.publicKey),N!==void 0&&Nn(N,"zip215"),n&&(v=n(v));let B=F/2,k=w.subarray(0,B),A=tr(w.subarray(B,F)),C,P,D;try{C=e.fromBytes(V,N),P=e.fromBytes(k,N),D=o.multiplyUnsafe(A)}catch{return!1}if(!N&&C.isSmallOrder())return!1;let U=h(b,P.toBytes(),C.toBytes(),v);return P.add(C.multiplyUnsafe(U)).subtract(D).clearCofactor().is0()}let x=i.BYTES,y={secretKey:x,publicKey:x,signature:2*x,seed:x};function T(w=a(y.seed)){return Rr(w,y.seed,"seed")}function E(w){let v=I.randomSecretKey(w);return{secretKey:v,publicKey:f(v)}}function O(w){return Ot(w)&&w.length===s.BYTES}function R(w,v){try{return!!e.fromBytes(w,v)}catch{return!1}}let I={getExtendedPublicKey:l,randomSecretKey:T,isValidSecretKey:O,isValidPublicKey:R,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 b=S?i.div(Re+v,Re-v):i.div(v-Re,v+Re);return i.toBytes(b)},toMontgomerySecret(w){let v=y.secretKey;Rr(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:E,getPublicKey:f,sign:m,verify:_,utils:I,Point:e,lengths:y})}function Ih(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=ke(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 Ah(e,t){let r=t.Point;return Object.assign({},t,{ExtendedPoint:r,CURVE:e,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function Bu(e){let{CURVE:t,curveOpts:r,hash:n,eddsaOpts:o}=Ih(e),i=Rh(t,r),s=vh(i,n,o);return Ah(e,s)}var Sh=BigInt(0),ar=BigInt(1),Du=BigInt(2),cg=BigInt(3),Fh=BigInt(5),Vh=BigInt(8),no=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Zo={p:no,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Vh,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Ch(e){let t=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),i=no,a=e*e%i*e%i,c=Tt(a,Du,i)*a%i,u=Tt(c,ar,i)*e%i,p=Tt(u,Fh,i)*u%i,d=Tt(p,t,i)*p%i,l=Tt(d,r,i)*d%i,f=Tt(l,n,i)*l%i,h=Tt(f,o,i)*f%i,m=Tt(h,o,i)*f%i,g=Tt(m,t,i)*p%i;return{pow_p_5_8:Tt(g,Du,i)*e%i,b2:a}}function Ph(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var La=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ja(e,t){let r=no,n=se(t*t*t,r),o=se(n*n*t,r),i=Ch(e*o).pow_p_5_8,s=se(e*n*i,r),a=se(t*s*s,r),c=s,u=se(s*La,r),p=a===e,d=a===se(-e,r),l=a===se(-e*La,r);return p&&(s=c),(d||l)&&(s=u),or(s,r)&&(s=se(-s,r)),{isValid:p||d,value:s}}var Vr=ke(Zo.p,{isLE:!0}),Bh=ke(Zo.n,{isLE:!0}),Dh={...Zo,Fp:Vr,hash:al,adjustScalarBytes:Ph,uvRatio:ja},Me=Bu(Dh);var qa=La,Uh=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),kh=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Lh=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),qh=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Uu=e=>ja(ar,e),Mh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ma=e=>Me.Point.Fp.create(tr(e)&Mh);function ku(e){let{d:t}=Zo,r=no,n=_=>Vr.create(_),o=n(qa*e*e),i=n((o+ar)*Lh),s=BigInt(-1),a=n((s-t*o)*n(o+t)),{isValid:c,value:u}=ja(i,a),p=n(u*e);or(p,r)||(p=n(-p)),c||(u=p),c||(s=o);let d=n(s*(o-ar)*qh-a),l=u*u,f=n((u+u)*a),h=n(d*Uh),m=n(ar-l),g=n(ar+l);return new Me.Point(n(f*g),n(m*h),n(h*g),n(f*m))}function jh(e){fe(e,64);let t=Ma(e.subarray(0,32)),r=ku(t),n=Ma(e.subarray(32,64)),o=ku(n);return new cr(r.add(o))}var cr=class e extends ss{constructor(t){super(t)}static fromAffine(t){return new e(Me.Point.fromAffine(t))}assertSame(t){if(!(t instanceof e))throw new Error("RistrettoPoint expected")}init(t){return new e(t)}static hashToCurve(t){return jh(le("ristrettoHash",t,64))}static fromBytes(t){fe(t,32);let{a:r,d:n}=Zo,o=no,i=T=>Vr.create(T),s=Ma(t);if(!tu(Vr.toBytes(s),t)||or(s,o))throw new Error("invalid ristretto255 encoding 1");let a=i(s*s),c=i(ar+r*a),u=i(ar-r*a),p=i(c*c),d=i(u*u),l=i(r*n*p-d),{isValid:f,value:h}=Uu(i(l*d)),m=i(h*u),g=i(h*m*l),_=i((s+s)*m);or(_,o)&&(_=i(-_));let x=i(c*g),y=i(_*x);if(!f||or(y,o)||x===Sh)throw new Error("invalid ristretto255 encoding 2");return new e(new Me.Point(_,x,ar,y))}static fromHex(t){return e.fromBytes(le("ristrettoHex",t,32))}static msm(t,r){return Qn(e,Me.Point.Fn,t,r)}toBytes(){let{X:t,Y:r,Z:n,T:o}=this.ep,i=no,s=g=>Vr.create(g),a=s(s(n+r)*s(n-r)),c=s(t*r),u=s(c*c),{value:p}=Uu(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*qa),_=s(t*qa);t=g,r=_,h=s(d*kh)}else h=l;or(t*f,i)&&(r=s(-r));let m=s((n-r)*h);return or(m,i)&&(m=s(-m)),Vr.toBytes(m)}equals(t){this.assertSame(t);let{X:r,Y:n}=this.ep,{X:o,Y:i}=t.ep,s=u=>Vr.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)}};cr.BASE=new cr(Me.Point.BASE);cr.ZERO=new cr(Me.Point.ZERO);cr.Fp=Vr;cr.Fn=Bh;var Lu,qu,as=class{static{Lu=Symbol.iterator,qu=Symbol.toStringTag}#e;#t;constructor(t={}){this[Lu]=this.entries.bind(this),this[qu]="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 Mu=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 xo("Length too long (> 4 bytes)"))},ju=(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 xo("Length too long (> 4 bytes)"))},Ka=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw z.fromCode(new mt("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 mt("Length too long (> 4 bytes)"))},Kh=(e,t)=>{let r=Ka(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 mt("Length too long (> 4 bytes)"))},Xo=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),Sn=Uint8Array.from([48,5,6,3,43,101,112]),fg=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),hg=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 Fn(e,t){let r=2+Mu(e.byteLength+1),n=t.byteLength+r+e.byteLength,o=0,i=new Uint8Array(1+Mu(n)+n);return i[o++]=48,o+=ju(i,o,n),i.set(t,o),o+=t.byteLength,i[o++]=3,o+=ju(i,o,e.byteLength+1),i[o++]=0,i.set(new Uint8Array(e),o),i}var Vn=(e,t)=>{let r=0,n=(a,c)=>{if(o[r++]!==a)throw z.fromCode(new mt(`Expected ${c} at offset ${r}`))},o=new Uint8Array(e);if(n(48,"sequence"),r+=Ka(o,r),!bn(o.slice(r,r+t.byteLength),t))throw z.fromCode(new mt("Not the expected OID."));r+=t.byteLength,n(3,"bit string");let i=Kh(o,r)-1;r+=Ka(o,r),n(0,"0 padding");let s=o.slice(r);if(i!==s.length)throw z.fromCode(new xi(i,s.length));return s};var cs=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 Fn(t,Sn)}static derDecode(t){let r=Vn(t,Sn);if(r.length!==this.RAW_KEY_LENGTH)throw z.fromCode(new mt("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 mt("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 Ha=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))}},ls=class extends Ha{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 us=class e{#e;#t;#r;#c;#s;#u;#n;#o;#a=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.#c=i,this.#o=c,this.#s=c.now(),this.#u=s,this.#n=a}get ellapsedTimeInMsec(){return this.#o.now()-this.#s}get currentInterval(){return this.#e}get count(){return this.#a}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.#c),this.#a++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#u||this.#a>=this.#n?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};var Vt;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(Vt||(Vt={}));var Ja=60*1e3,Hh=1e6,$h=0,Gh="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";var Jh="ic0.app",zh=".ic0.app",Wh="icp0.io",Yh=".icp0.io",Zh="icp-api.io",Xh=".icp-api.io",$a=200,Qh=202,em=404;function tm(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw Oe.fromCode(new qn("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 Oe.fromCode(new qn("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 Oe.fromCode(new qn("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function rm(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 lr=class e{#e;#t;#r;#c;#s;#u;#n;#o;#a;#x;#i;#d;#p;#l;get#N(){return this.#l*Ja}#f;#h;#m;#_;constructor(t={}){this.#e=null,this.#t=!1,this.#r=$h,this.#c=!1,this.#s=null,this.#u=!1,this._isAgent=!0,this.config={},this.log=new ls,this.#f=[],this.#h=[],this.#m=new as({expirationTime:5*Ja}),this.#_=!0,this.#w=(o,i)=>{if(this.#_===!1)return o;let{status:s,signatures:a=[],requestId:c}=o;for(let u of a){let{timestamp:p,identity:d}=u,l=M.fromUint8Array(d).toText(),f;if(s===hr.Replied){let{reply:x}=o;f=Fo({status:s,reply:x,timestamp:BigInt(p),request_id:c})}else if(s===hr.Rejected){let{reject_code:x,reject_message:y,error_code:T}=o;f=Fo({status:s,reject_code:x,reject_message:y,error_code:T,timestamp:BigInt(p),request_id:c})}else throw ge.fromCode(new Be(`Unknown status: ${s}`));let h=j(ta,f),m=i.nodeKeys.get(l);if(!m)throw ne.fromCode(new Si);let g=cs.fromDer(m).rawKey;if(Me.verify(u.signature,h,g))return o;throw Pe.fromCode(new Fi(l))}return o},this.config=t,this.#o=t.fetch||tm()||fetch.bind(global),this.#a=t.fetchOptions,this.#x=t.callOptions,this.#t=t.shouldFetchRootKey??!1,this.#u=t.shouldSyncTime??!1,t.rootKey?this.rootKey=t.rootKey:this.#t?this.rootKey=null:this.rootKey=Ne(Gh);let r=rm(t.host);this.host=new URL(r),t.verifyQuerySignatures!==void 0&&(this.#_=t.verifyQuerySignatures),this.#d=t.retryTimes??3;let n=()=>new us({maxIterations:this.#d});if(this.#p=t.backoffStrategy||n,this.host.hostname.endsWith(zh)?this.host.hostname=Jh:this.host.hostname.endsWith(Yh)?this.host.hostname=Wh:this.host.hostname.endsWith(Xh)&&(this.host.hostname=Zh),t.credentials){let{name:o,password:i}=t.credentials;this.#i=`${o}${i?":"+i:""}`}if(this.#n=Promise.resolve(t.identity||new rt),t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes>5)throw z.fromCode(new mn("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw z.fromCode(new mn("Ingress expiry time must be greater than 0.",t.ingressExpiryInMinutes));this.#l=t.ingressExpiryInMinutes||5,this.addTransform("update",ca(Lo)),t.useQueryNonces&&this.addTransform("query",ca(Lo)),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.#g(),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 vi)}}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.#h.findIndex(i=>(i.priority||0)<n);this.#h.splice(o>=0?o:this.#h.length,0,Object.assign(r,{priority:n}))}else if(t==="query"){let o=this.#f.findIndex(i=>(i.priority||0)<n);this.#f.splice(o>=0?o:this.#f.length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this.#n)throw Oe.fromCode(new br);return(await this.#n).getPrincipal()}async call(t,r,n){let o=r.callSync??!0,i=await(n??this.#n);if(!i)throw Oe.fromCode(new br);let s=M.from(t),a=r.effectiveCanisterId?M.from(r.effectiveCanisterId):s;await this.#g(a);let c=i.getPrincipal(),u=Ga(this.#l,this.#r),p={request_type:Hi.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.#i?{Authorization:"Basic "+btoa(this.#i)}:{}}},endpoint:er.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(_){return Object.assign(_,{__nonce__:void 0})}d=await i.transformRequest(d);let h=Uo(d.body),m=this.#p(),g=Xt(p);try{let y=o?()=>(this.log.print(`fetching "/api/v3/canister/${a.toText()}/call" with request:`,d),this.#o(""+new URL(`/api/v3/canister/${a.toText()}/call`,this.host),{...this.#x,...d.request,body:h})):()=>(this.log.print(`fetching "/api/v2/canister/${a.toText()}/call" with request:`,d),this.#o(""+new URL(`/api/v2/canister/${a.toText()}/call`,this.host),{...this.#x,...d.request,body:h})),{responseBodyBytes:T,...E}=await this.#y({requestFn:y,backoff:m,tries:0}),O=T.byteLength>0?Je(T):null;return{requestId:g,response:{...E,body:O},requestDetails:p}}catch(_){let x;if(_ instanceof ht){if(_.hasCode(wo))return this.log.warn("v3 api not supported. Fall back to v2"),this.call(t,{...r,callSync:!1},n);if(_.hasCode(mn)&&!this.#c)return await this.syncTime(s),this.call(s,r,n);_.code.requestContext={requestId:g,senderPubKey:d.body.sender_pubkey,senderSignature:d.body.sender_sig,ingressExpiry:d.body.content.ingress_expiry},x=_}else x=ge.fromCode(new Be(_));throw this.log.error(`Error while making call: ${x.message}`,x),x}}async#b(t){let{ecid:r,transformedRequest:n,body:o,requestId:i,backoff:s,tries:a}=t,c=a===0?0:s.next();if(this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with tries:`,{tries:a,backoff:s,delay:c}),c===null)throw ge.fromCode(new hn(`Backoff strategy exhausted after ${a} attempts.`,i));c>0&&await new Promise(f=>setTimeout(f,c));let u;try{this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with request:`,n);let f=await this.#o(""+new URL(`/api/v2/canister/${r.toString()}/query`,this.host),{...this.#a,...n.request,body:o});if(f.status===$a)u={...Je($n(await f.arrayBuffer())),httpDetails:{ok:f.ok,status:f.status,statusText:f.statusText,headers:Gi(f.headers)},requestId:i};else throw ne.fromCode(new bo(f.status,f.statusText,Gi(f.headers),await f.text()))}catch(f){if(a<this.#d)return this.log.warn(`Caught exception while attempting to make query:
66
53
  ${f}
67
- Retrying query.`),await this.#x({...e,tries:a+1});throw f instanceof z.AgentError?f:z.TransportError.fromCode(new z.HttpFetchErrorCode(f))}if(!this.#y)return d;let p=d.signatures?.[0]?.timestamp;if(!p)throw z.ProtocolError.fromCode(new z.MalformedSignatureErrorCode("Timestamp not found in query response. This suggests a malformed or malicious response."));let l=Number(BigInt(p)/BigInt(f4));if(Date.now()+this.#r-l>this.#T){if(a<this.#l)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:s,signatureTimestampMs:l}),await this.#x({...e,tries:a+1});throw z.TrustError.fromCode(new z.CertificateOutdatedErrorCode(this.#u,s,a))}return d}async#_(e){let{requestFn:r,backoff:n,tries:o}=e,s=o===0?0:n.next();if(s===null)throw z.ProtocolError.fromCode(new z.TimeoutWaitingForResponseErrorCode(`Retry strategy exhausted after ${o} attempts.`));s>0&&await new Promise(p=>setTimeout(p,s));let i,a=new Uint8Array;try{i=await r(),i.status===fh&&(a=(0,lh.uint8FromBufLike)(await i.clone().arrayBuffer()))}catch(p){if(o<this.#l)return this.log.warn(`Caught exception while attempting to make request:
54
+ Retrying query.`),await this.#b({...t,tries:a+1});throw f instanceof ht?f:go.fromCode(new To(f))}if(!this.#_)return u;let p=u.signatures?.[0]?.timestamp;if(!p)throw ne.fromCode(new Ii("Timestamp not found in query response. This suggests a malformed or malicious response."));let d=Number(BigInt(p)/BigInt(Hh));if(Date.now()+this.#r-d>this.#N){if(a<this.#d)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:i,signatureTimestampMs:d}),await this.#b({...t,tries:a+1});throw Pe.fromCode(new Ti(this.#l,i,a))}return u}async#y(t){let{requestFn:r,backoff:n,tries:o}=t,i=o===0?0:n.next();if(i===null)throw ne.fromCode(new hn(`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===$a&&(a=$n(await s.clone().arrayBuffer()))}catch(p){if(o<this.#d)return this.log.warn(`Caught exception while attempting to make request:
68
55
  ${p}
69
- Retrying request.`),await this.#_({requestFn:r,backoff:n,tries:o+1});throw z.TransportError.fromCode(new z.HttpFetchErrorCode(p))}let c=(0,di.httpHeadersTransform)(i.headers);if(i.status===fh||i.status===x4)return{ok:i.ok,status:i.status,statusText:i.statusText,responseBodyBytes:a,headers:c};let d=await i.text();if(i.status===w4&&i.url.includes("api/v3"))throw z.ProtocolError.fromCode(new z.HttpV3ApiNotSupportedErrorCode);if(d.startsWith("Invalid request expiry: "))throw z.InputError.fromCode(new z.IngressExpiryInvalidErrorCode(d,this.#u));if(o<this.#l)return await this.#_({requestFn:r,backoff:n,tries:o+1});throw z.ProtocolError.fromCode(new z.HttpErrorCode(i.status,i.statusText,c,d))}async query(e,r,n){let o=this.#f(),s=r.effectiveCanisterId?Pn.Principal.from(r.effectiveCanisterId):Pn.Principal.from(e);await this.#b(s),this.log.print(`ecid ${s.toString()}`),this.log.print(`canisterId ${e.toString()}`);let i,a=await(n??this.#n);if(!a)throw z.ExternalError.fromCode(new z.IdentityInvalidErrorCode);let c=Pn.Principal.from(e),d=a.getPrincipal(),p=Hu(this.#u,this.#r),l={request_type:Dn.ReadRequestType.Query,canister_id:c,method_name:r.methodName,arg:r.arg,sender:d,ingress_expiry:p},u=(0,Aa.requestIdOf)(l);i=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:Dn.Endpoint.Query,body:l}),i=await a.transformRequest(i);let f=Oo.encode(i.body),h={canister:c.toText(),ecid:s,transformedRequest:i,body:f,requestId:u,backoff:o,tries:0},m=async()=>{let y=await this.#x(h);return{requestDetails:l,...y}},b=async()=>{let y=this.#m.get(s.toString());if(y)return y;await this.fetchSubnetKeys(s.toString());let x=this.#m.get(s.toString());if(!x)throw z.TrustError.fromCode(new z.MissingSignatureErrorCode);return x};try{if(!this.#y)return await m();let[y,x]=await Promise.all([m(),b()]);try{return this.#w(y,x)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#m.delete(s.toString());let _=await b();return this.#w(y,_)}}catch(y){let x;throw y instanceof z.AgentError?(y.code.requestContext={requestId:u,senderPubKey:i.body.sender_pubkey,senderSignature:i.body.sender_sig,ingressExpiry:i.body.content.ingress_expiry},x=y):x=z.UnknownError.fromCode(new z.UnexpectedErrorCode(y)),this.log.error(`Error while making query: ${x.message}`,x),x}}#w;async createReadStateRequest(e,r){await this.#b();let n=await(r??this.#n);if(!n)throw z.ExternalError.fromCode(new z.IdentityInvalidErrorCode);let o=n.getPrincipal(),s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:Dn.Endpoint.ReadState,body:{request_type:Dn.ReadRequestType.ReadState,paths:e.paths,sender:o,ingress_expiry:Hu(this.#u,this.#r)}});return n.transformRequest(s)}async readState(e,r,n,o){await this.#E();let s=Pn.Principal.from(e);function i(p){for(let l of p.paths){let[u,f]=l,h=new TextEncoder().encode("request_status");if((0,lh.uint8Equals)(u,h))return f}}let a,c;if(o)a=o,c=(0,Aa.requestIdOf)(a);else{c=i(r);let p=await this.#n;if(!p)throw z.ExternalError.fromCode(new z.IdentityInvalidErrorCode);a=await this.createReadStateRequest(r,p)}this.log.print(`fetching "/api/v2/canister/${s}/read_state" with request:`,a);let d=this.#f();try{let{responseBodyBytes:p}=await this.#_({requestFn:()=>this.#o(""+new URL(`/api/v2/canister/${s.toString()}/read_state`,this.host),{...this.#a,...a.request,body:Oo.encode(a.body)}),backoff:d,tries:0}),l=Oo.decode(p);return this.log.print("Read state response:",l),l}catch(p){let l;throw p instanceof z.AgentError?(p.code.requestContext={requestId:c,senderPubKey:a.body.sender_pubkey,senderSignature:a.body.sender_sig,ingressExpiry:a.body.content.ingress_expiry},l=p):l=z.UnknownError.fromCode(new z.UnexpectedErrorCode(p)),this.log.error(`Error while making read state: ${l.message}`,l),l}}parseTimeFromResponse(e){let r;if(e.certificate){let n=Oo.decode(e.certificate);if(n&&"tree"in n)r=n.tree;else throw z.ProtocolError.fromCode(new z.HashTreeDecodeErrorCode("Could not decode time from response"));let o=(0,yb.lookup_path)(["time"],r);if(o.status!==yb.LookupPathStatus.Found)throw z.ProtocolError.fromCode(new z.LookupErrorCode("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 z.ProtocolError.fromCode(new z.MalformedLookupFoundValueErrorCode("Time was not in its expected format."));let s=(0,u4.decodeTime)(o.value);return this.log.print("Time from response:",s),this.log.print("Time from response in milliseconds:",s.getTime()),s.getTime()}else this.log.warn("No certificate found in response");return 0}async syncTime(e){this.#i=this.#i??(async()=>{await this.#E();let r=Date.now();try{e||this.log.print("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");let n=e??Pn.Principal.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),o=t.createSync({identity:new pb.AnonymousIdentity,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 c=(await(0,mb.request)({canisterId:n,agent:o,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(c instanceof Date)return c.getTime()},[]))).reduce((a,c)=>typeof c=="number"&&c>a?c:a,0);i>0&&(this.#r=i-r,this.#c=!0,this.log.notify({message:`Syncing time: offset of ${this.#r}`,level:"info"}))}catch(n){let o=n instanceof z.AgentError?n:z.UnknownError.fromCode(new z.UnexpectedErrorCode(n));throw this.log.error("Caught exception while attempting to sync time",o),o}})(),await this.#i.finally(()=>{this.#i=null})}async status(){let e=this.#s?{Authorization:"Basic "+btoa(this.#s)}:{};this.log.print('fetching "/api/v2/status"');let r=this.#f(),{responseBodyBytes:n}=await this.#_({backoff:r,requestFn:()=>this.#o(""+new URL("/api/v2/status",this.host),{headers:e,...this.#a}),tries:0});return Oo.decode(n)}async fetchRootKey(){return this.#e=this.#e??(async()=>{let e=await this.status();return this.rootKey=e.root_key,this.rootKey})(),await this.#e.finally(()=>{this.#e=null})}async#b(e){await Promise.all([this.#E(),this.#O(e)])}async#E(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#t)await this.fetchRootKey();else throw z.ExternalError.fromCode(new z.MissingRootKeyErrorCode(this.#t))}async#O(e){this.#d&&!this.hasSyncedTime()&&await this.syncTime(e)}invalidateIdentity(){this.#n=null}replaceIdentity(e){this.#n=Promise.resolve(e)}async fetchSubnetKeys(e){let r=Pn.Principal.from(e);await this.#b(r);let o=(await(0,mb.request)({canisterId:r,paths:["subnet"],agent:this})).get("subnet");if(o&&typeof o=="object"&&"nodeKeys"in o)return this.#m.set(r.toText(),o),o}_transform(e){let r=Promise.resolve(e);if(e.endpoint===Dn.Endpoint.Call)for(let n of this.#h)r=r.then(o=>n(o).then(s=>s||o));else for(let n of this.#p)r=r.then(o=>n(o).then(s=>s||o));return r}getTimeDiffMsecs(){return this.#r}hasSyncedTime(){return this.#c}};$e.HttpAgent=hh;function Hu(t,e){let r=t*ph;return di.Expiry.fromDeltaInMilliseconds(r,e)}});var fa=Y(No=>{"use strict";var O4=No&&No.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),xb=No&&No.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&O4(e,t,r)};Object.defineProperty(No,"__esModule",{value:!0});xb(vl(),No);xb($u(),No)});var Gu=Y(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.defaultStrategy=v4;sn.once=wb;sn.conditionalDelay=Eb;sn.maxAttempts=R4;sn.throttle=I4;sn.timeout=Tb;sn.backoff=Ob;sn.chain=Nb;var Ku=ar(),N4=300*1e3;function v4(){return Nb(Eb(wb(),1e3),Ob(1e3,1.2),Tb(N4))}function wb(){let t=!0;return async()=>t?(t=!1,!0):!1}function Eb(t,e){return async(r,n,o)=>{if(await t(r,n,o))return new Promise(s=>setTimeout(s,e))}}function R4(t){let e=t;return async(r,n,o)=>{if(--e<=0)throw Ku.ProtocolError.fromCode(new Ku.TimeoutWaitingForResponseErrorCode(`Failed to retrieve a reply for request after ${t} attempts`,n,o))}}function I4(t){return()=>new Promise(e=>setTimeout(e,t))}function Tb(t){let e=Date.now()+t;return async(r,n,o)=>{if(Date.now()>e)throw Ku.ProtocolError.fromCode(new Ku.TimeoutWaitingForResponseErrorCode(`Request timed out after ${t} msec`,n,o))}}function Ob(t,e){let r=t;return()=>new Promise(n=>setTimeout(()=>{r*=e,n()},r))}function Nb(...t){return async(e,r,n)=>{for(let o of t)await o(e,r,n)}}});var zu=Y(Bt=>{"use strict";var S4=Bt&&Bt.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),A4=Bt&&Bt.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),B4=Bt&&Bt.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&S4(r,e,n[o]);return A4(r,e),r}})();Object.defineProperty(Bt,"__esModule",{value:!0});Bt.DEFAULT_POLLING_OPTIONS=Bt.defaultStrategy=Bt.strategy=void 0;Bt.pollForResponse=Sb;Bt.constructRequest=Ab;var li=ai(),Fn=ar();Bt.strategy=B4(Gu());var C4=Gu(),P4=ei(),us=fa(),vb=dt(),D4=Gu();Object.defineProperty(Bt,"defaultStrategy",{enumerable:!0,get:function(){return D4.defaultStrategy}});Bt.DEFAULT_POLLING_OPTIONS={preSignReadStateRequest:!1};function Ib(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function mh(t,e){return t!==null&&typeof t=="object"&&Ib(t,e)}function F4(t,e){return Ib(t,e)&&typeof t[e]=="function"}function Rb(t){return mh(t,"body")&&mh(t.body,"content")&&t.body.content.request_type===P4.ReadRequestType.ReadState&&mh(t.body.content,"ingress_expiry")&&typeof t.body.content.ingress_expiry=="object"&&t.body.content.ingress_expiry!==null&&F4(t.body.content.ingress_expiry,"toHash")}async function Sb(t,e,r,n={}){let o=[(0,vb.utf8ToBytes)("request_status"),r],s,i;if(n.preSignReadStateRequest??!1?(i=await Ab({paths:[o],agent:t,pollingOptions:n}),s=await t.readState(e,{paths:[o]},void 0,i)):s=await t.readState(e,{paths:[o]}),t.rootKey==null)throw Fn.ExternalError.fromCode(new Fn.MissingRootKeyErrorCode);let c=await li.Certificate.create({certificate:s.certificate,rootKey:t.rootKey,canisterId:e,blsVerify:n.blsVerify,agent:t}),d=(0,li.lookupResultToBuffer)(c.lookup_path([...o,(0,vb.utf8ToBytes)("status")])),p;switch(typeof d>"u"?p=us.RequestStatusResponseStatus.Unknown:p=new TextDecoder().decode(d),p){case us.RequestStatusResponseStatus.Replied:return{reply:(0,li.lookupResultToBuffer)(c.lookup_path([...o,"reply"])),certificate:c};case us.RequestStatusResponseStatus.Received:case us.RequestStatusResponseStatus.Unknown:case us.RequestStatusResponseStatus.Processing:{let l=n.strategy??(0,C4.defaultStrategy)();return await l(e,r,p),Sb(t,e,r,{...n,strategy:l,request:i})}case us.RequestStatusResponseStatus.Rejected:{let l=new Uint8Array((0,li.lookupResultToBuffer)(c.lookup_path([...o,"reject_code"])))[0],u=new TextDecoder().decode((0,li.lookupResultToBuffer)(c.lookup_path([...o,"reject_message"]))),f=(0,li.lookupResultToBuffer)(c.lookup_path([...o,"error_code"])),h=f?new TextDecoder().decode(f):void 0;throw Fn.RejectError.fromCode(new Fn.CertifiedRejectErrorCode(r,l,u,h))}case us.RequestStatusResponseStatus.Done:throw Fn.UnknownError.fromCode(new Fn.RequestStatusDoneNoReplyErrorCode(r))}throw Fn.UNREACHABLE_ERROR}async function Ab(t){let{paths:e,agent:r,pollingOptions:n}=t;if(n.request&&Rb(n.request))return n.request;let o=await r.createReadStateRequest?.({paths:e},void 0);if(!Rb(o))throw Fn.InputError.fromCode(new Fn.InvalidReadStateRequestErrorCode(o));return o}});var _h=Y(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.ACTOR_METHOD_WITH_CERTIFICATE=ur.ACTOR_METHOD_WITH_HTTP_DETAILS=ur.Actor=void 0;var Zu=fa(),rr=ar(),Yu=ca(),Cb=zu(),Ba=Rr(),fi=ai(),Bb=$u(),V4=dt(),br=Symbol.for("ic-agent-metadata"),yh=class t{static agentOf(e){return e[br].config.agent}static interfaceOf(e){return e[br].service}static canisterIdOf(e){return Ba.Principal.from(e[br].config.canisterId)}static createActorClass(e,r){let n=e({IDL:Yu.IDL});class o extends t{constructor(i){if(!i.canisterId)throw rr.InputError.fromCode(new rr.MissingCanisterIdErrorCode(i.canisterId));let a=typeof i.canisterId=="string"?Ba.Principal.fromText(i.canisterId):i.canisterId;super({config:{...Pb,...i,canisterId:a},service:n});for(let[c,d]of n._fields)r?.httpDetails&&d.annotations.push(ur.ACTOR_METHOD_WITH_HTTP_DETAILS),r?.certificate&&d.annotations.push(ur.ACTOR_METHOD_WITH_CERTIFICATE),this[c]=U4(this,c,d,i.blsVerify)}}return o}static createActor(e,r){if(!r.canisterId)throw rr.InputError.fromCode(new rr.MissingCanisterIdErrorCode(r.canisterId));return new(this.createActorClass(e))(r)}static createActorWithHttpDetails(e,r){return new(this.createActorClass(e,{httpDetails:!0}))(r)}static createActorWithExtendedDetails(e,r,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(e,n))(r)}constructor(e){this[br]=Object.freeze(e)}};ur.Actor=yh;function pi(t,e){let r=Yu.IDL.decode(t,e);switch(r.length){case 0:return;case 1:return r[0];default:return r}}var Pb={pollingOptions:Cb.DEFAULT_POLLING_OPTIONS};ur.ACTOR_METHOD_WITH_HTTP_DETAILS="http-details";ur.ACTOR_METHOD_WITH_CERTIFICATE="certificate";function U4(t,e,r,n){let o;r.annotations.includes("query")||r.annotations.includes("composite_query")?o=async(i,...a)=>{i={...i,...t[br].config.queryTransform?.(e,a,{...t[br].config,...i})};let c=i.agent||t[br].config.agent||new Bb.HttpAgent,d=Ba.Principal.from(i.canisterId||t[br].config.canisterId),p=Yu.IDL.encode(r.argTypes,a),l=await c.query(d,{methodName:e,arg:p,effectiveCanisterId:i.effectiveCanisterId}),u={...l.httpDetails,requestDetails:l.requestDetails};switch(l.status){case Zu.QueryResponseStatus.Rejected:{let f=new rr.UncertifiedRejectErrorCode(l.requestId,l.reject_code,l.reject_message,l.error_code,l.signatures);throw f.callContext={canisterId:d,methodName:e,httpDetails:u},rr.RejectError.fromCode(f)}case Zu.QueryResponseStatus.Replied:return r.annotations.includes(ur.ACTOR_METHOD_WITH_HTTP_DETAILS)?{httpDetails:u,result:pi(r.retTypes,l.reply.arg)}:pi(r.retTypes,l.reply.arg)}}:o=async(i,...a)=>{i={...i,...t[br].config.callTransform?.(e,a,{...t[br].config,...i})};let c=i.agent||t[br].config.agent||Bb.HttpAgent.createSync(),{canisterId:d,effectiveCanisterId:p,pollingOptions:l}={...Pb,...t[br].config,...i},u=Ba.Principal.from(d),f=p!==void 0?Ba.Principal.from(p):u,h=Yu.IDL.encode(r.argTypes,a),{requestId:m,response:b,requestDetails:y}=await c.call(u,{methodName:e,arg:h,effectiveCanisterId:f,nonce:i.nonce}),x,_;if((0,Zu.isV3ResponseBody)(b.body)){if(c.rootKey==null)throw rr.ExternalError.fromCode(new rr.MissingRootKeyErrorCode);let R=b.body.certificate;_=await fi.Certificate.create({certificate:R,rootKey:c.rootKey,canisterId:f,blsVerify:n,agent:c});let A=[(0,V4.utf8ToBytes)("request_status"),m];switch(new TextDecoder().decode((0,fi.lookupResultToBuffer)(_.lookup_path([...A,"status"])))){case"replied":x=(0,fi.lookupResultToBuffer)(_.lookup_path([...A,"reply"]));break;case"rejected":{let S=new Uint8Array((0,fi.lookupResultToBuffer)(_.lookup_path([...A,"reject_code"])))[0],V=new TextDecoder().decode((0,fi.lookupResultToBuffer)(_.lookup_path([...A,"reject_message"]))),C=(0,fi.lookupResultToBuffer)(_.lookup_path([...A,"error_code"])),g=C?new TextDecoder().decode(C):void 0,w=new rr.CertifiedRejectErrorCode(m,S,V,g);throw w.callContext={canisterId:u,methodName:e,httpDetails:b},rr.RejectError.fromCode(w)}}}else if((0,Zu.isV2ResponseBody)(b.body)){let{reject_code:R,reject_message:A,error_code:E}=b.body,S=new rr.UncertifiedRejectUpdateErrorCode(m,R,A,E);throw S.callContext={canisterId:u,methodName:e,httpDetails:b},rr.RejectError.fromCode(S)}if(b.status===202){let R={...l,blsVerify:n},A=await(0,Cb.pollForResponse)(c,f,m,R);_=A.certificate,x=A.reply}let T=r.annotations.includes(ur.ACTOR_METHOD_WITH_HTTP_DETAILS),N=r.annotations.includes(ur.ACTOR_METHOD_WITH_CERTIFICATE),v={...b,requestDetails:y};if(x!==void 0)return T&&N?{httpDetails:v,certificate:_,result:pi(r.retTypes,x)}:N?{certificate:_,result:pi(r.retTypes,x)}:T?{httpDetails:v,result:pi(r.retTypes,x)}:pi(r.retTypes,x);{let R=new rr.UnexpectedErrorCode(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${r.retTypes.map(A=>A.display()).join(",")}].`);throw R.callContext={canisterId:u,methodName:e,httpDetails:v},rr.UnknownError.fromCode(R)}};let s=(...i)=>o({},...i);return s.withOptions=i=>(...a)=>o(i,...a),s}});var Db=Y(Vn=>{"use strict";var L4=Vn&&Vn.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),q4=Vn&&Vn.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),M4=Vn&&Vn.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&L4(r,e,n[o]);return q4(r,e),r}})();Object.defineProperty(Vn,"__esModule",{value:!0});Vn.fetchCandid=K4;var k4=Rr(),j4=M4(Cu()),H4=$u(),$4=_h();async function K4(t,e){e||(e=await H4.HttpAgent.create());let n=(await j4.request({agent:e,canisterId:k4.Principal.fromText(t),paths:["candid"]})).get("candid");if(n)return n;let o=({IDL:i})=>i.Service({__get_candid_interface_tmp_hack:i.Func([],[i.Text],["query"])});return await $4.Actor.createActor(o,{agent:e,canisterId:t}).__get_candid_interface_tmp_hack()}});var gh=Y(_e=>{"use strict";var Fb=_e&&_e.__createBinding||(Object.create?(function(t,e,r,n){n===void 0&&(n=r);var o=Object.getOwnPropertyDescriptor(e,r);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[r]}}),Object.defineProperty(t,n,o)}):(function(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]})),G4=_e&&_e.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),Ct=_e&&_e.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Fb(e,t,r)},Vb=_e&&_e.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(r){var n=[];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[n.length]=o);return n},t(e)};return function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var n=t(e),o=0;o<n.length;o++)n[o]!=="default"&&Fb(r,e,n[o]);return G4(r,e),r}})();Object.defineProperty(_e,"__esModule",{value:!0});_e.ToCborValue=_e.Cbor=_e.CanisterStatus=_e.polling=_e.IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR=_e.IC_RESPONSE_DOMAIN_SEPARATOR=_e.IC_REQUEST_DOMAIN_SEPARATOR=void 0;Ct(_h(),_e);Ct(fa(),_e);Ct(fu(),_e);Ct(ei(),_e);Ct(up(),_e);Ct(ai(),_e);var bh=su();Object.defineProperty(_e,"IC_REQUEST_DOMAIN_SEPARATOR",{enumerable:!0,get:function(){return bh.IC_REQUEST_DOMAIN_SEPARATOR}});Object.defineProperty(_e,"IC_RESPONSE_DOMAIN_SEPARATOR",{enumerable:!0,get:function(){return bh.IC_RESPONSE_DOMAIN_SEPARATOR}});Object.defineProperty(_e,"IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR",{enumerable:!0,get:function(){return bh.IC_REQUEST_AUTH_DELEGATION_DOMAIN_SEPARATOR}});Ct(ih(),_e);Ct(ar(),_e);Ct(Db(),_e);Ct(dh(),_e);Ct(ch(),_e);Ct(ou(),_e);Ct(jp(),_e);Ct(Qs(),_e);Ct(lp(),_e);_e.polling=Vb(zu());var z4=Vb(Cu());_e.CanisterStatus=z4;var Ub=la();Object.defineProperty(_e,"Cbor",{enumerable:!0,get:function(){return Ub.Cbor}});Object.defineProperty(_e,"ToCborValue",{enumerable:!0,get:function(){return Ub.ToCborValue}});Ct(zu(),_e)});var De=Y((M5,tg)=>{"use strict";var Nh=Object.defineProperty,Z4=Object.getOwnPropertyDescriptor,Y4=Object.getOwnPropertyNames,W4=Object.prototype.hasOwnProperty,X4=(t,e)=>{for(var r in e)Nh(t,r,{get:e[r],enumerable:!0})},J4=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Y4(e))!W4.call(t,o)&&o!==r&&Nh(t,o,{get:()=>e[o],enumerable:!(n=Z4(e,o))||n.enumerable});return t},Q4=t=>J4(Nh({},"__esModule",{value:!0}),t),kb={};X4(kb,{AgentManager:()=>uO,Canister:()=>iO,FromStringToTokenError:()=>jb,ICPToken:()=>nO,InvalidPercentageError:()=>Zb,NullishError:()=>Yb,TokenAmount:()=>oO,TokenAmountV2:()=>sO,arrayBufferToUint8Array:()=>yO,arrayOfNumberToUint8Array:()=>bO,asNonNullish:()=>lO,asciiStringToByteArray:()=>gO,assertNonNullish:()=>Va,assertPercentageNumber:()=>fO,base64ToUint8Array:()=>vO,bigEndianCrc32:()=>SO,bigIntToUint8Array:()=>hO,candidNumberArrayToBigInt:()=>EO,convertStringToE8s:()=>Hb,createAgent:()=>Gb,createServices:()=>dO,debounce:()=>UO,decodeBase32:()=>OO,defaultAgent:()=>Kb,encodeBase32:()=>TO,fromDefinedNullable:()=>qO,fromNullable:()=>vh,fromNullishNullable:()=>MO,hashObject:()=>BO,hashText:()=>Jb,hexStringToUint8Array:()=>xO,isEmptyString:()=>aO,isNullish:()=>Fa,jsonReplacer:()=>Xb,jsonReviver:()=>AO,nonNullish:()=>an,notEmptyString:()=>$b,nowInBigIntNanoSeconds:()=>FO,numberToUint8Array:()=>mO,principalToSubAccount:()=>kO,queryAndUpdate:()=>cO,secondsToDuration:()=>PO,smallerVersion:()=>jO,toBigIntNanoSeconds:()=>VO,toNullable:()=>LO,uint8ArrayToArrayOfNumber:()=>_O,uint8ArrayToBase64:()=>NO,uint8ArrayToBigInt:()=>pO,uint8ArrayToHexString:()=>Wb,uint8ArraysEqual:()=>wO});tg.exports=Q4(kb);var jb=(t=>(t[t.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",t[t.InvalidFormat=1]="InvalidFormat",t[t.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",t))(jb||{}),eO=BigInt(1e8),tO=8,Hb=t=>{let e=t.includes("e")?Number(t).toLocaleString("en",{useGrouping:!1,maximumFractionDigits:20}):t;e=e.trim().replace(/[,']/g,"");let r=e.match(/\d*(\.\d*)?/);if(!r||r[0]!==e)return 1;let[n,o]=e.split("."),s=BigInt(0);if(n)try{s+=BigInt(n)*eO}catch{return 1}if(o){if(o.length>8)return 0;try{s+=BigInt(o.padEnd(8,"0"))}catch{return 1}}return s},rO=({amount:t,decimals:e})=>{t=t.trim().replace(/[,']/g,"");let r=t.match(/\d*(\.\d*)?/);if(!r||r[0]!==t)return 1;let[n,o]=t.split("."),s=0n,i=10n**BigInt(e);if(n)try{s+=BigInt(n)*i}catch{return 1}if(o){if(o.length>e)return 2;try{s+=BigInt(o.padEnd(e,"0"))}catch{return 1}}return s},nO={symbol:"ICP",name:"Internet Computer",decimals:8},oO=class Pa{constructor(e,r){if(this.e8s=e,this.token=r,r.decimals!==8)throw new Error("Use TokenAmountV2 for number of decimals other than 8")}static fromE8s({amount:e,token:r}){return new Pa(e,r)}static fromString({amount:e,token:r}){if(r.decimals!==8)throw new Error("Use TokenAmountV2 for number of decimals other than 8");let n=Hb(e);return typeof n=="bigint"?new Pa(n,r):n}static fromNumber({amount:e,token:r}){let n=Pa.fromString({amount:e.toString(),token:r});if(n instanceof Pa)return n;throw n===0?new Error(`Number ${e} has more than 8 decimals`):new Error(`Invalid number ${e}`)}toE8s(){return this.e8s}},sO=class Da{constructor(e,r){this.ulps=e,this.token=r}static fromUlps({amount:e,token:r}){return new Da(e,r)}static fromString({amount:e,token:r}){let n=rO({amount:e,decimals:r.decimals});return typeof n=="bigint"?new Da(n,r):n}static fromNumber({amount:e,token:r}){let n=Da.fromString({amount:e.toFixed(Math.min(tO,r.decimals)),token:r});if(n instanceof Da)return n;throw n===2?new Error(`Number ${e} has more than ${r.decimals} decimals`):new Error(`Invalid number ${e}`)}toUlps(){return this.ulps}toE8s(){return this.token.decimals<8?this.ulps*10n**BigInt(8-this.token.decimals):this.token.decimals===8?this.ulps:this.ulps/10n**BigInt(this.token.decimals-8)}},iO=class{constructor(t,e,r){this.id=t,this.service=e,this.certifiedService=r}get canisterId(){return this.id}caller=({certified:t=!0})=>t?this.certifiedService:this.service},Fa=t=>t==null,an=t=>!Fa(t),$b=t=>an(t)&&t!=="",aO=t=>!$b(t),cO=async({request:t,onLoad:e,onQueryError:r,onUpdateError:n,strategy:o="query_and_update",identity:s,resolution:i="race"})=>{let a=!1,c=p=>t({certified:p,identity:s}).then(l=>{a||e({certified:p,response:l})}).catch(l=>{p||r==null||r({error:l,identity:s}),!a&&(Fa(n)||(console.error(l),p&&n({error:l,identity:s})))}).finally(()=>a=a||p),d=o==="query"?[c(!1)]:o==="update"?[c(!0)]:[c(!1),c(!0)];await(i==="all_settled"?Promise.allSettled(d):Promise.race(d))},Lb=gh(),xh=gh(),Kb=()=>xh.HttpAgent.createSync({host:"https://icp-api.io",identity:new xh.AnonymousIdentity}),Gb=async({identity:t,host:e,fetchRootKey:r=!1,verifyQuerySignatures:n=!1,retryTimes:o})=>await xh.HttpAgent.create({identity:t,...an(e)&&{host:e},verifyQuerySignatures:n,...an(o)&&{retryTimes:o},shouldFetchRootKey:r}),uO=class zb{constructor(e){this.config=e}agents=void 0;static create(e){return new zb(e)}getAgent=async({identity:e})=>{let r=e.getPrincipal().toText();if(Fa(this.agents)||Fa(this.agents[r])){let n=await Gb({identity:e,fetchRootKey:this.config.fetchRootKey,host:this.config.host,verifyQuerySignatures:!0});return this.agents={...this.agents??{},[r]:n},n}return this.agents[r]};clearAgents=()=>{this.agents=null}},dO=({options:{canisterId:t,serviceOverride:e,certifiedServiceOverride:r,agent:n,callTransform:o,queryTransform:s},idlFactory:i,certifiedIdlFactory:a})=>{let c=n??Kb(),d=e??Lb.Actor.createActor(i,{agent:c,canisterId:t,callTransform:o,queryTransform:s}),p=r??Lb.Actor.createActor(a,{agent:c,canisterId:t,callTransform:o,queryTransform:s});return{service:d,certifiedService:p,agent:c,canisterId:t}},Zb=class extends Error{},Yb=class extends Error{},Va=(t,e)=>{if(t==null)throw new Yb(e)},lO=(t,e)=>(Va(t,e),t),fO=t=>{if(t<0||t>100)throw new Zb(`${t} is not a valid percentage number.`)},pO=t=>{let e=new DataView(t.buffer,t.byteOffset,t.byteLength);if(typeof e.getBigUint64=="function")return e.getBigUint64(0);let r=BigInt(e.getUint32(0)),n=BigInt(e.getUint32(4));return(r<<BigInt(32))+n},hO=t=>{let e=new ArrayBuffer(8),r=new DataView(e);if(typeof r.setBigUint64=="function")r.setBigUint64(0,t);else{let n=Number(t>>BigInt(32)),o=Number(t&BigInt(4294967295));r.setUint32(0,n),r.setUint32(4,o)}return new Uint8Array(e)},mO=t=>{let e=new DataView(new ArrayBuffer(8));for(let r=7;r>=0;--r)e.setUint8(r,t%256),t=t>>8;return new Uint8Array(e.buffer)},yO=t=>new Uint8Array(t),_O=t=>Array.from(t),bO=t=>new Uint8Array(t),gO=t=>Array.from(t).map(e=>e.charCodeAt(0)),xO=t=>{let e=t.match(/.{1,2}/g);return Va(e,"Invalid hex string."),Uint8Array.from(e.map(r=>parseInt(r,16)))},wO=({a:t,b:e})=>t.length===e.length&&t.every((r,n)=>r===e[n]),Wb=t=>(t instanceof Uint8Array||(t=Uint8Array.from(t)),t.reduce((e,r)=>e+r.toString(16).padStart(2,"0"),"")),EO=t=>{let e=0n;for(let r=t.length-1;r>=0;r--)e=(e<<32n)+BigInt(t[r]);return e},Wu="abcdefghijklmnopqrstuvwxyz234567",hi=Object.create(null);for(let t=0;t<Wu.length;t++)hi[Wu[t]]=t;hi[0]=hi.o;hi[1]=hi.i;var TO=t=>{let e=0,r=0,n="",o=s=>(e<0?r|=s>>-e:r=s<<e&248,e>3?(e-=8,1):(e<4&&(n+=Wu[r>>3],e+=5),0));for(let s=0;s<t.length;)s+=o(t[s]);return n+(e<0?Wu[r>>3]:"")},OO=t=>{let e=0,r=0,n=new Uint8Array(t.length*4/3|0),o=0,s=i=>{let a=hi[i.toLowerCase()];Va(a,`Invalid character: ${JSON.stringify(i)}`),a<<=3,r|=a>>>e,e+=5,e>=8&&(n[o++]=r,e-=8,e>0?r=a<<5-e&255:r=0)};for(let i of t)s(i);return n.slice(0,o)},NO=t=>btoa(String.fromCharCode(...new Uint8Array(t))),vO=t=>Uint8Array.from(atob(t),e=>e.charCodeAt(0)),RO=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]),IO=t=>{let e=-1;for(let r=0;r<t.length;r++){let n=(t[r]^e)&255;e=RO[n]^e>>>8}return(e^-1)>>>0},SO=t=>{let e=new ArrayBuffer(4);return new DataView(e).setUint32(0,IO(t),!1),new Uint8Array(e)},wh=Rr(),Eh="__bigint__",Th="__principal__",Oh="__uint8array__",Xb=(t,e)=>typeof e=="bigint"?{[Eh]:`${e}`}:an(e)&&wh.Principal.isPrincipal(e)?{[Th]:wh.Principal.from(e).toText()}:an(e)&&e instanceof Uint8Array?{[Oh]:Array.from(e)}:e,AO=(t,e)=>{let r=n=>e[n];return an(e)&&typeof e=="object"&&Eh in e?BigInt(r(Eh)):an(e)&&typeof e=="object"&&Th in e?wh.Principal.fromText(r(Th)):an(e)&&typeof e=="object"&&Oh in e?Uint8Array.from(r(Oh)):e},BO=async t=>{let e=JSON.stringify(t,Xb);return await Jb(e)},Jb=async t=>{let e=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",e);return Wb(new Uint8Array(r))},CO={year:"year",year_plural:"years",month:"month",month_plural:"months",day:"day",day_plural:"days",hour:"hour",hour_plural:"hours",minute:"minute",minute_plural:"minutes",second:"second",second_plural:"seconds"},PO=({seconds:t,i18n:e=CO})=>{let r=t/BigInt(60),n=r/BigInt(60);r-=n*BigInt(60);let o=n/BigInt(24);n-=o*BigInt(24);let s=DO(o);return o-=Qb(s),[Ca({labelKey:"year",amount:s}),Ca({labelKey:"day",amount:o}),Ca({labelKey:"hour",amount:n}),Ca({labelKey:"minute",amount:r}),...t>BigInt(0)&&t<BigInt(60)?[Ca({labelKey:"second",amount:t})]:[]].filter(({amount:i})=>i>0).slice(0,2).map(i=>`${i.amount} ${i.amount===1?e[i.labelKey]:e[`${i.labelKey}_plural`]}`).join(", ")},DO=t=>{let e=t/BigInt(365);for(;Qb(e)>t;)e--;return e},Qb=t=>{let e=t/BigInt(4);return t*BigInt(365)+e},Ca=({labelKey:t,amount:e})=>({labelKey:t,amount:Number(e)}),eg=1000000n,FO=()=>BigInt(Date.now())*eg,VO=t=>BigInt(t.getTime())*eg,UO=(t,e)=>{let r;return(...n)=>{let o=()=>t(...n);r&&clearTimeout(r),r=setTimeout(o,e!==void 0&&e>0?e:300)}},LO=t=>an(t)?[t]:[],vh=t=>t?.[0],qO=t=>{let e=vh(t);return Va(e),e},MO=t=>vh(t??[]),kO=t=>{let e=t.toUint8Array(),r=new Uint8Array(32);return r[0]=e.length,r.set(e,1),r},qb=({nums:t,amountZeros:e})=>e>t.length?[...t,...[...Array(e-t.length).keys()].map(()=>0)]:t,Mb=t=>{if(!Number.isNaN(Number(t)))return Number(t);let e=t.split("").reduce((r,n)=>Number.isNaN(Number(n))?r:r+n,"");return Number(e)},jO=({minVersion:t,currentVersion:e})=>{let r=qb({nums:t.split(".").map(Mb),amountZeros:3}).join(".");return qb({nums:e.split(".").map(Mb),amountZeros:3}).join(".").localeCompare(r,void 0,{numeric:!0,sensitivity:"base"})<0}});var M1=Fe(De(),1);var mw=Fe(De(),1);var rg;(function(t){t[t.SysFatal=1]="SysFatal",t[t.SysTransient=2]="SysTransient",t[t.DestinationInvalid=3]="DestinationInvalid",t[t.CanisterReject=4]="CanisterReject",t[t.CanisterError=5]="CanisterError"})(rg||(rg={}));var vo;(function(t){t.Replied="replied",t.Rejected="rejected"})(vo||(vo={}));function ng(t){return t!=null&&"reject_code"in t}function og(t){return t!=null&&"certificate"in t}var Xu="abcdefghijklmnopqrstuvwxyz234567",mi=Object.create(null);for(let t=0;t<Xu.length;t++)mi[Xu[t]]=t;mi[0]=mi.o;mi[1]=mi.i;function sg(t){let e=0,r=0,n="";function o(s){return e<0?r|=s>>-e:r=s<<e&248,e>3?(e-=8,1):(e<4&&(n+=Xu[r>>3],e+=5),0)}for(let s=0;s<t.length;)s+=o(t[s]);return n+(e<0?Xu[r>>3]:"")}function ig(t){let e=0,r=0,n=new Uint8Array(t.length*4/3|0),o=0;function s(i){let a=mi[i.toLowerCase()];if(a===void 0)throw new Error(`Invalid character: ${JSON.stringify(i)}`);a<<=3,r|=a>>>e,e+=5,e>=8&&(n[o++]=r,e-=8,e>0?r=a<<5-e&255:r=0)}for(let i of t)s(i);return n.slice(0,o)}var HO=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 ag(t){let e=-1;for(let r=0;r<t.length;r++){let o=(t[r]^e)&255;e=HO[o]^e>>>8}return(e^-1)>>>0}import*as Un from"node:crypto";var ds=Un&&typeof Un=="object"&&"webcrypto"in Un?Un.webcrypto:Un&&typeof Un=="object"&&"randomBytes"in Un?Un:void 0;function cn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Rh(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Xe(t,...e){if(!cn(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Ih(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ug(t,e){Xe(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function ls(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Qu(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Cr(t,e){return t<<32-e|t>>>e}var dg=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",$O=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ue(t){if(Xe(t),dg)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=$O[t[r]];return e}var Ln={_0:48,_9:57,A:65,F:70,a:97,f:102};function cg(t){if(t>=Ln._0&&t<=Ln._9)return t-Ln._0;if(t>=Ln.A&&t<=Ln.F)return t-(Ln.A-10);if(t>=Ln.a&&t<=Ln.f)return t-(Ln.a-10)}function ht(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(dg)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let o=0,s=0;o<r;o++,s+=2){let i=cg(t.charCodeAt(s)),a=cg(t.charCodeAt(s+1));if(i===void 0||a===void 0){let c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[o]=i*16+a}return n}function Ve(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Sh(t){return typeof t=="string"&&(t=Ve(t)),Xe(t),t}function le(...t){let e=0;for(let n=0;n<t.length;n++){let o=t[n];Xe(o),e+=o.length}let r=new Uint8Array(e);for(let n=0,o=0;n<t.length;n++){let s=t[n];r.set(s,o),o+=s.length}return r}var Ju=class{};function ed(t){let e=n=>t().update(Sh(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function yi(t=32){if(ds&&typeof ds.getRandomValues=="function")return ds.getRandomValues(new Uint8Array(t));if(ds&&typeof ds.randomBytes=="function")return Uint8Array.from(ds.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function KO(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let o=BigInt(32),s=BigInt(4294967295),i=Number(r>>o&s),a=Number(r&s),c=n?4:0,d=n?0:4;t.setUint32(e+c,i,n),t.setUint32(e+d,a,n)}function lg(t,e,r){return t&e^~t&r}function fg(t,e,r){return t&e^t&r^e&r}var Ua=class extends Ju{constructor(e,r,n,o){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Qu(this.buffer)}update(e){Ih(this),e=Sh(e),Xe(e);let{view:r,buffer:n,blockLen:o}=this,s=e.length;for(let i=0;i<s;){let a=Math.min(o-this.pos,s-i);if(a===o){let c=Qu(e);for(;o<=s-i;i+=o)this.process(c,i);continue}n.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ih(this),ug(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:o,isLE:s}=this,{pos:i}=this;r[i++]=128,ls(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(n,0),i=0);for(let l=i;l<o;l++)r[l]=0;KO(n,o-8,BigInt(this.length*8),s),this.process(n,0);let a=Qu(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let d=c/4,p=this.get();if(d>p.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<d;l++)a.setUint32(4*l,p[l],s)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:o,finished:s,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=s,e.length=o,e.pos=a,o%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},qn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Mn=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]);var wt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var td=BigInt(4294967295),pg=BigInt(32);function GO(t,e=!1){return e?{h:Number(t&td),l:Number(t>>pg&td)}:{h:Number(t>>pg&td)|0,l:Number(t&td)|0}}function hg(t,e=!1){let r=t.length,n=new Uint32Array(r),o=new Uint32Array(r);for(let s=0;s<r;s++){let{h:i,l:a}=GO(t[s],e);[n[s],o[s]]=[i,a]}return[n,o]}var Ah=(t,e,r)=>t>>>r,Bh=(t,e,r)=>t<<32-r|e>>>r,fs=(t,e,r)=>t>>>r|e<<32-r,ps=(t,e,r)=>t<<32-r|e>>>r,La=(t,e,r)=>t<<64-r|e>>>r-32,qa=(t,e,r)=>t>>>r-32|e<<64-r;function un(t,e,r,n){let o=(e>>>0)+(n>>>0);return{h:t+r+(o/2**32|0)|0,l:o|0}}var mg=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),yg=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,_g=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),bg=(t,e,r,n,o)=>e+r+n+o+(t/2**32|0)|0,gg=(t,e,r,n,o)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(o>>>0),xg=(t,e,r,n,o,s)=>e+r+n+o+s+(t/2**32|0)|0;var ZO=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]),Ro=new Uint32Array(64),rd=class extends Ua{constructor(e=32){super(64,e,8,!1),this.A=qn[0]|0,this.B=qn[1]|0,this.C=qn[2]|0,this.D=qn[3]|0,this.E=qn[4]|0,this.F=qn[5]|0,this.G=qn[6]|0,this.H=qn[7]|0}get(){let{A:e,B:r,C:n,D:o,E:s,F:i,G:a,H:c}=this;return[e,r,n,o,s,i,a,c]}set(e,r,n,o,s,i,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=o|0,this.E=s|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let l=0;l<16;l++,r+=4)Ro[l]=e.getUint32(r,!1);for(let l=16;l<64;l++){let u=Ro[l-15],f=Ro[l-2],h=Cr(u,7)^Cr(u,18)^u>>>3,m=Cr(f,17)^Cr(f,19)^f>>>10;Ro[l]=m+Ro[l-7]+h+Ro[l-16]|0}let{A:n,B:o,C:s,D:i,E:a,F:c,G:d,H:p}=this;for(let l=0;l<64;l++){let u=Cr(a,6)^Cr(a,11)^Cr(a,25),f=p+u+lg(a,c,d)+ZO[l]+Ro[l]|0,m=(Cr(n,2)^Cr(n,13)^Cr(n,22))+fg(n,o,s)|0;p=d,d=c,c=a,a=i+f|0,i=s,s=o,o=n,n=f+m|0}n=n+this.A|0,o=o+this.B|0,s=s+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,d=d+this.G|0,p=p+this.H|0,this.set(n,o,s,i,a,c,d,p)}roundClean(){ls(Ro)}destroy(){this.set(0,0,0,0,0,0,0,0),ls(this.buffer)}},Ch=class extends rd{constructor(){super(28),this.A=Mn[0]|0,this.B=Mn[1]|0,this.C=Mn[2]|0,this.D=Mn[3]|0,this.E=Mn[4]|0,this.F=Mn[5]|0,this.G=Mn[6]|0,this.H=Mn[7]|0}},wg=hg(["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(t=>BigInt(t))),YO=wg[0],WO=wg[1],Io=new Uint32Array(80),So=new Uint32Array(80),Ph=class extends Ua{constructor(e=64){super(128,e,16,!1),this.Ah=wt[0]|0,this.Al=wt[1]|0,this.Bh=wt[2]|0,this.Bl=wt[3]|0,this.Ch=wt[4]|0,this.Cl=wt[5]|0,this.Dh=wt[6]|0,this.Dl=wt[7]|0,this.Eh=wt[8]|0,this.El=wt[9]|0,this.Fh=wt[10]|0,this.Fl=wt[11]|0,this.Gh=wt[12]|0,this.Gl=wt[13]|0,this.Hh=wt[14]|0,this.Hl=wt[15]|0}get(){let{Ah:e,Al:r,Bh:n,Bl:o,Ch:s,Cl:i,Dh:a,Dl:c,Eh:d,El:p,Fh:l,Fl:u,Gh:f,Gl:h,Hh:m,Hl:b}=this;return[e,r,n,o,s,i,a,c,d,p,l,u,f,h,m,b]}set(e,r,n,o,s,i,a,c,d,p,l,u,f,h,m,b){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=o|0,this.Ch=s|0,this.Cl=i|0,this.Dh=a|0,this.Dl=c|0,this.Eh=d|0,this.El=p|0,this.Fh=l|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=m|0,this.Hl=b|0}process(e,r){for(let _=0;_<16;_++,r+=4)Io[_]=e.getUint32(r),So[_]=e.getUint32(r+=4);for(let _=16;_<80;_++){let T=Io[_-15]|0,N=So[_-15]|0,v=fs(T,N,1)^fs(T,N,8)^Ah(T,N,7),R=ps(T,N,1)^ps(T,N,8)^Bh(T,N,7),A=Io[_-2]|0,E=So[_-2]|0,S=fs(A,E,19)^La(A,E,61)^Ah(A,E,6),V=ps(A,E,19)^qa(A,E,61)^Bh(A,E,6),C=_g(R,V,So[_-7],So[_-16]),g=bg(C,v,S,Io[_-7],Io[_-16]);Io[_]=g|0,So[_]=C|0}let{Ah:n,Al:o,Bh:s,Bl:i,Ch:a,Cl:c,Dh:d,Dl:p,Eh:l,El:u,Fh:f,Fl:h,Gh:m,Gl:b,Hh:y,Hl:x}=this;for(let _=0;_<80;_++){let T=fs(l,u,14)^fs(l,u,18)^La(l,u,41),N=ps(l,u,14)^ps(l,u,18)^qa(l,u,41),v=l&f^~l&m,R=u&h^~u&b,A=gg(x,N,R,WO[_],So[_]),E=xg(A,y,T,v,YO[_],Io[_]),S=A|0,V=fs(n,o,28)^La(n,o,34)^La(n,o,39),C=ps(n,o,28)^qa(n,o,34)^qa(n,o,39),g=n&s^n&a^s&a,w=o&i^o&c^i&c;y=m|0,x=b|0,m=f|0,b=h|0,f=l|0,h=u|0,{h:l,l:u}=un(d|0,p|0,E|0,S|0),d=a|0,p=c|0,a=s|0,c=i|0,s=n|0,i=o|0;let O=mg(S,C,w);n=yg(O,E,V,g),o=O|0}({h:n,l:o}=un(this.Ah|0,this.Al|0,n|0,o|0)),{h:s,l:i}=un(this.Bh|0,this.Bl|0,s|0,i|0),{h:a,l:c}=un(this.Ch|0,this.Cl|0,a|0,c|0),{h:d,l:p}=un(this.Dh|0,this.Dl|0,d|0,p|0),{h:l,l:u}=un(this.Eh|0,this.El|0,l|0,u|0),{h:f,l:h}=un(this.Fh|0,this.Fl|0,f|0,h|0),{h:m,l:b}=un(this.Gh|0,this.Gl|0,m|0,b|0),{h:y,l:x}=un(this.Hh|0,this.Hl|0,y|0,x|0),this.set(n,o,s,i,a,c,d,p,l,u,f,h,m,b,y,x)}roundClean(){ls(Io,So)}destroy(){ls(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Pt=ed(()=>new rd),Eg=ed(()=>new Ch),Tg=ed(()=>new Ph);var nd="__principal__",XO=2,Og=4,JO="aaaaa-aa",se=class t{static anonymous(){return new this(new Uint8Array([Og]))}static managementCanister(){return this.fromText(JO)}static selfAuthenticating(e){let r=Eg(e);return new this(new Uint8Array([...r,XO]))}static from(e){if(typeof e=="string")return t.fromText(e);if(Object.getPrototypeOf(e)===Uint8Array.prototype)return new t(e);if(t.isPrincipal(e))return new t(e._arr);throw new Error(`Impossible to convert ${JSON.stringify(e)} to Principal.`)}static fromHex(e){return new this(ht(e))}static fromText(e){let r=e;if(e.includes(nd)){let i=JSON.parse(e);nd in i&&(r=i[nd])}let n=r.toLowerCase().replace(/-/g,""),o=ig(n);o=o.slice(4,o.length);let s=new this(o);if(s.toText()!==r)throw new Error(`Principal "${s.toText()}" does not have a valid checksum (original value "${r}" may not be a valid Principal ID).`);return s}static fromUint8Array(e){return new this(e)}static isPrincipal(e){return e instanceof t||typeof e=="object"&&e!==null&&"_isPrincipal"in e&&e._isPrincipal===!0&&"_arr"in e&&e._arr instanceof Uint8Array}constructor(e){this._arr=e,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===Og}toUint8Array(){return this._arr}toHex(){return ue(this._arr).toUpperCase()}toText(){let e=new ArrayBuffer(4);new DataView(e).setUint32(0,ag(this._arr));let n=new Uint8Array(e),o=new Uint8Array([...n,...this._arr]),i=sg(o).match(/.{1,5}/g);if(!i)throw new Error;return i.join("-")}toString(){return this.toText()}toJSON(){return{[nd]:this.toText()}}compareTo(e){for(let r=0;r<Math.min(this._arr.length,e._arr.length);r++){if(this._arr[r]<e._arr[r])return"lt";if(this._arr[r]>e._arr[r])return"gt"}return this._arr.length<e._arr.length?"lt":this._arr.length>e._arr.length?"gt":"eq"}ltEq(e){let r=this.compareTo(e);return r=="lt"||r=="eq"}gtEq(e){let r=this.compareTo(e);return r=="gt"||r=="eq"}};var kn;(function(t){t.Trust="Trust",t.Protocol="Protocol",t.Reject="Reject",t.Transport="Transport",t.External="External",t.Limit="Limit",t.Input="Input",t.Unknown="Unknown"})(kn||(kn={}));var be=class{constructor(e=!1){this.isCertified=e}toString(){let e=this.toErrorMessage();return this.requestContext&&(e+=`
70
- Request context:
71
- Request ID (hex): ${this.requestContext.requestId?ue(this.requestContext.requestId):"undefined"}
72
- Sender pubkey (hex): ${ue(this.requestContext.senderPubKey)}
73
- Sender signature (hex): ${ue(this.requestContext.senderSignature)}
74
- Ingress expiry: ${this.requestContext.ingressExpiry.toString()}`),this.callContext&&(e+=`
75
- Call context:
76
- Canister ID: ${this.callContext.canisterId.toText()}
77
- Method name: ${this.callContext.methodName}
78
- HTTP details: ${JSON.stringify(this.callContext.httpDetails,null,2)}`),e}},Pr=class t extends Error{get code(){return this.cause.code}set code(e){this.cause.code=e}get kind(){return this.cause.kind}set kind(e){this.cause.kind=e}get isCertified(){return this.code.isCertified}constructor(e,r){super(e.toString()),this.name="AgentError",this.cause={code:e,kind:r},Object.setPrototypeOf(this,t.prototype)}hasCode(e){return this.code instanceof e}toString(){return`${this.name} (${this.kind}): ${this.message}`}},jn=class extends Pr{static fromCode(e){return new this(e)}},Mt=class t extends jn{constructor(e){super(e,kn.Trust),this.name="TrustError",Object.setPrototypeOf(this,t.prototype)}},Me=class t extends jn{constructor(e){super(e,kn.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,t.prototype)}},Ao=class t extends jn{constructor(e){super(e,kn.Reject),this.name="RejectError",Object.setPrototypeOf(this,t.prototype)}},Ma=class t extends jn{constructor(e){super(e,kn.Transport),this.name="TransportError",Object.setPrototypeOf(this,t.prototype)}},mt=class t extends jn{constructor(e){super(e,kn.External),this.name="ExternalError",Object.setPrototypeOf(this,t.prototype)}};var Ne=class t extends jn{constructor(e){super(e,kn.Input),this.name="InputError",Object.setPrototypeOf(this,t.prototype)}},st=class t extends jn{constructor(e){super(e,kn.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,t.prototype)}},Bo=class t extends be{constructor(e,r){super(),this.reason=e,this.error=r,this.name="CertificateVerificationErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){let e=this.reason;return this.error&&(e+=`: ${za(this.error)}`),`Certificate verification error: "${e}"`}},hs=class t extends be{constructor(e,r,n,o,s){super(),this.maxAgeInMinutes=e,this.certificateTime=r,this.currentTime=n,this.timeDiffMsecs=o,this.ageType=s,this.name="CertificateTimeErrorCode",Object.setPrototypeOf(this,t.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`}},od=class t extends be{constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"Certificate has too many delegations"}},_i=class t extends be{constructor(e,r){super(),this.canisterId=e,this.subnetId=r,this.name="CertificateNotAuthorizedErrorCode",Object.setPrototypeOf(this,t.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()}`}},Hn=class t extends be{constructor(e,r){super(),this.message=e,this.lookupStatus=r,this.name="LookupErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}},bi=class t extends be{constructor(e){super(),this.message=e,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return this.message}},sd=class t extends be{constructor(e){super(),this.message=e,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return this.message}},gi=class t extends be{constructor(e,r){super(),this.expectedLength=e,this.actualLength=r,this.name="DerKeyLengthMismatchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}},id=class t extends be{constructor(e,r){super(),this.expectedPrefix=e,this.actualPrefix=r,this.name="DerPrefixMismatchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${ue(this.expectedPrefix)}, but got ${ue(this.actualPrefix)}`}},ad=class t extends be{constructor(e,r){super(),this.expectedLength=e,this.actualLength=r,this.name="DerDecodeLengthMismatchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}},Dr=class t extends be{constructor(e){super(),this.error=e,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}},ka=class t extends be{constructor(e){super(),this.error=e,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}},cd=class t extends be{constructor(e,r){super(),this.error=e,this.input=r,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${za(this.error)}, input: ${ue(this.input)}`}},ud=class t extends be{constructor(e,r){super(),this.error=e,this.value=r,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${za(this.error)}, input: ${this.value}`}};var ms=class t extends be{constructor(e,r,n){super(),this.message=e,this.requestId=r,this.status=n,this.name="TimeoutWaitingForResponseErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){let e=`${this.message}
79
- `;return this.requestId&&(e+=` Request ID: ${ue(this.requestId)}
80
- `),this.status&&(e+=` Request status: ${this.status}
81
- `),e}},dd=class t extends be{constructor(e,r,n){super(),this.maxIngressExpiryInMinutes=e,this.requestId=r,this.retryTimes=n,this.name="CertificateOutdatedErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){let e=`Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?
82
- Request ID: ${ue(this.requestId)}
83
- `;return this.retryTimes!==void 0&&(e+=` Retried ${this.retryTimes} times.`),e}},xi=class t extends be{constructor(e,r,n,o){super(!0),this.requestId=e,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="CertifiedRejectErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`The replica returned a rejection error:
84
- Request ID: ${ue(this.requestId)}
85
- Reject code: ${this.rejectCode}
86
- Reject text: ${this.rejectMessage}
87
- Error code: ${this.rejectErrorCode}
88
- `}},ld=class t extends be{constructor(e,r,n,o,s){super(),this.requestId=e,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.signatures=s,this.name="UncertifiedRejectErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`The replica returned a rejection error:
89
- Request ID: ${ue(this.requestId)}
90
- Reject code: ${this.rejectCode}
91
- Reject text: ${this.rejectMessage}
92
- Error code: ${this.rejectErrorCode}
93
- `}},fd=class t extends be{constructor(e,r,n,o){super(),this.requestId=e,this.rejectCode=r,this.rejectMessage=n,this.rejectErrorCode=o,this.name="UncertifiedRejectUpdateErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`The replica returned a rejection error:
94
- Request ID: ${ue(this.requestId)}
95
- Reject code: ${this.rejectCode}
96
- Reject text: ${this.rejectMessage}
97
- Error code: ${this.rejectErrorCode}
98
- `}},pd=class t extends be{constructor(e){super(),this.requestId=e,this.name="RequestStatusDoneNoReplyErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Call was marked as done but we never saw the reply:
99
- Request ID: ${ue(this.requestId)}
100
- `}},dn=class t extends be{constructor(e){super(),this.shouldFetchRootKey=e,this.name="MissingRootKeyErrorCode",Object.setPrototypeOf(this,t.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.`}},hd=class t extends be{constructor(e){super(),this.value=e,this.name="HashValueErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}},wi=class t extends be{constructor(e){super(),this.error=e,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return this.error}},Co=class t extends be{constructor(){super(),this.name="IdentityInvalidErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"This identity has expired due this application's security policy. Please refresh your authentication."}},ys=class t extends be{constructor(e,r){super(),this.message=e,this.providedIngressExpiryInMinutes=r,this.name="IngressExpiryInvalidErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}},md=class t extends be{constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}},yd=class t extends be{constructor(e){super(),this.error=e,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}},_d=class t extends be{constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}},bd=class t extends be{constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}},gd=class t extends be{constructor(e){super(),this.nodeId=e,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}},kt=class t extends be{constructor(e){super(),this.error=e,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Unexpected error: ${za(this.error)}`}},Po=class t extends be{constructor(e){super(),this.error=e,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}},ja=class t extends be{constructor(e,r,n,o){super(),this.status=e,this.statusText=r,this.headers=n,this.bodyText=o,this.name="HttpErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){let e=`HTTP request failed:
101
- Status: ${this.status} (${this.statusText})
102
- Headers: ${JSON.stringify(this.headers)}
103
- `;return this.bodyText&&(e+=` Body: ${this.bodyText}
104
- `),e}},Ha=class t extends be{constructor(){super(),this.name="HttpV3ApiNotSupportedErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return"HTTP request failed: v3 API is not supported"}},$a=class t extends be{constructor(e){super(),this.error=e,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${za(this.error)}`}},Ka=class t extends be{constructor(e){super(),this.receivedCanisterId=e,this.name="MissingCanisterIdErrorCode",Object.setPrototypeOf(this,t.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.`}},xd=class t extends be{constructor(e){super(),this.request=e,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}},Ga=class t extends be{constructor(e){super(),this.error=e,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,t.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}};function za(t){if(t instanceof Error)return t.stack??t.message;try{return JSON.stringify(t)}catch{return String(t)}}var Do=new Error("unreachable");var xs={};z1(xs,{Bool:()=>Pg,BoolClass:()=>Nd,ConstructType:()=>pn,Empty:()=>Bg,EmptyClass:()=>Ya,FixedIntClass:()=>Gn,FixedNatClass:()=>fn,Float32:()=>Lg,Float64:()=>qg,FloatClass:()=>Ja,Func:()=>tx,FuncClass:()=>gs,Int:()=>Vg,Int16:()=>kg,Int32:()=>jg,Int64:()=>Hg,Int8:()=>Mg,IntClass:()=>Wa,Nat:()=>Ug,Nat16:()=>Kg,Nat32:()=>Gg,Nat64:()=>zg,Nat8:()=>$g,NatClass:()=>Xa,Null:()=>Dg,NullClass:()=>_s,Opt:()=>Xg,OptClass:()=>Uo,PrimitiveType:()=>nr,Principal:()=>Zg,PrincipalClass:()=>Id,Rec:()=>ex,RecClass:()=>gr,Record:()=>Jg,RecordClass:()=>bs,Reserved:()=>Cg,ReservedClass:()=>hn,Service:()=>rx,ServiceClass:()=>Ni,Text:()=>Fg,TextClass:()=>vd,Tuple:()=>Yg,TupleClass:()=>Rd,Type:()=>Ei,Unknown:()=>r8,UnknownClass:()=>Od,Variant:()=>Qg,VariantClass:()=>Oi,Vec:()=>Wg,VecClass:()=>Ti,Visitor:()=>Mh,decode:()=>t8,encode:()=>e8,resetSubtypeCache:()=>kh,subtype:()=>Hh});function Re(...t){let e=new Uint8Array(t.reduce((n,o)=>n+o.byteLength,0)),r=0;for(let n of t)e.set(n,r),r+=n.byteLength;return e}var Fr=class{save(){return this._view}restore(e){if(!(e instanceof Uint8Array))throw new Error("Checkpoint must be a Uint8Array");this._view=e}constructor(e,r=e?.byteLength||0){if(e&&!(e instanceof Uint8Array))try{e=ln(e)}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(e&&r>e.byteLength)throw new Error("Length cannot exceed buffer length");this._buffer=e||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(e){let r=this._view.subarray(0,e);return this._view=this._view.subarray(e),r.slice()}readUint8(){if(this._view.byteLength===0)return;let e=this._view[0];return this._view=this._view.subarray(1),e}write(e){if(!(e instanceof Uint8Array))throw new Error("Buffer must be a Uint8Array");let r=this._view.byteLength;this._view.byteOffset+this._view.byteLength+e.byteLength>=this._buffer.byteLength?this.alloc(e.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+e.byteLength),this._view.set(e,r)}get end(){return this._view.byteLength===0}alloc(e){if(e<=0||!Number.isInteger(e))throw new Error("Amount must be a positive integer");let r=new Uint8Array((this._buffer.byteLength+e)*1.2|0),n=new Uint8Array(r.buffer,0,this._view.byteLength+e);n.set(this._view),this._buffer=r,this._view=n}};function ln(t){if(!t)throw new Error("Input cannot be null or undefined");return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):Array.isArray(t)?new Uint8Array(t):"buffer"in t?ln(t.buffer):new Uint8Array(t)}function Dh(t,e){if(t.byteLength!==e.byteLength)return t.byteLength-e.byteLength;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return t[r]-e[r];return 0}function Ng(t,e){return Dh(t,e)===0}function vg(t){if(!(t instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(t.buffer,t.byteOffset,t.byteLength)}function QO(t){let r=new TextEncoder().encode(t),n=0;for(let o of r)n=(n*223+o)%2**32;return n}function jt(t){if(/^_\d+_$/.test(t)||/^_0x[0-9a-fA-F]+_$/.test(t)){let e=+t.slice(1,-1);if(Number.isSafeInteger(e)&&e>=0&&e<2**32)return e}return QO(t)}function Fh(t){let e=BigInt(t);if(t<=0)throw new RangeError("Input must be positive");return e.toString(2).length-1}function wd(t){let e=BigInt(t);if(t<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<e}function Rg(){throw new Error("unexpected end of buffer")}function Vo(t,e){return t.byteLength<e&&Rg(),t.read(e)}function Fo(t){let e=t.readUint8();return e===void 0&&Rg(),e}function ke(t){if(typeof t=="number"&&(t=BigInt(t)),t<BigInt(0))throw new Error("Cannot leb encode negative values.");let e=(t===BigInt(0)?0:Fh(t))+1,r=new Fr(new Uint8Array(e),0);for(;;){let n=Number(t&BigInt(127));if(t/=BigInt(128),t===BigInt(0)){r.write(new Uint8Array([n]));break}else r.write(new Uint8Array([n|128]))}return r.buffer}function tt(t){let e=BigInt(1),r=BigInt(0),n;do n=Fo(t),r+=BigInt(n&127).valueOf()*e,e*=BigInt(128);while(n>=128);return r}function rt(t){typeof t=="number"&&(t=BigInt(t));let e=t<BigInt(0);e&&(t=-t-BigInt(1));let r=(t===BigInt(0)?0:Fh(t))+1,n=new Fr(new Uint8Array(r),0);for(;;){let s=o(t);if(t/=BigInt(128),e&&t===BigInt(0)&&(s&64)!==0||!e&&t===BigInt(0)&&(s&64)===0){n.write(new Uint8Array([s]));break}else n.write(new Uint8Array([s|128]))}function o(s){let i=s%BigInt(128);return Number(e?BigInt(128)-i-BigInt(1):i)}return n.buffer}function $n(t){let e=new Uint8Array(t.buffer),r=0;for(;r<e.byteLength;r++)if(e[r]<128){if((e[r]&64)===0)return tt(t);break}let n=new Uint8Array(Vo(t,r+1)),o=BigInt(0);for(let s=n.byteLength-1;s>=0;s--)o=o*BigInt(128)+BigInt(128-(n[s]&127)-1);return-o-BigInt(1)}function Ig(t,e){if(BigInt(t)<BigInt(0))throw new Error("Cannot write negative values.");return Vh(t,e)}function Vh(t,e){t=BigInt(t);let r=new Fr(new Uint8Array(Math.min(1,e)),0),n=0,o=BigInt(256),s=BigInt(0),i=Number(t%o);for(r.write(new Uint8Array([i]));++n<e;)t<0&&s===BigInt(0)&&i!==0&&(s=BigInt(1)),i=Number((t/o-s)%BigInt(256)),r.write(new Uint8Array([i])),o*=BigInt(256);return r.buffer}function Uh(t,e){if(e<=0||!Number.isInteger(e))throw new Error("Byte length must be a positive integer");let r=BigInt(Fo(t)),n=BigInt(1),o=0;for(;++o<e;){n*=BigInt(256);let s=BigInt(Fo(t));r=r+n*s}return r}function Sg(t,e){if(e<=0||!Number.isInteger(e))throw new Error("Byte length must be a positive integer");let r=Uh(t,e),n=BigInt(2)**(BigInt(8)*BigInt(e-1)+BigInt(7));return r>=n&&(r-=n*BigInt(2)),r}var Be;(function(t){t[t.Null=-1]="Null",t[t.Bool=-2]="Bool",t[t.Nat=-3]="Nat",t[t.Int=-4]="Int",t[t.Float32=-13]="Float32",t[t.Float64=-14]="Float64",t[t.Text=-15]="Text",t[t.Reserved=-16]="Reserved",t[t.Empty=-17]="Empty",t[t.Opt=-18]="Opt",t[t.Vector=-19]="Vector",t[t.Record=-20]="Record",t[t.Variant=-21]="Variant",t[t.Func=-22]="Func",t[t.Service=-23]="Service",t[t.Principal=-24]="Principal"})(Be||(Be={}));var Ed="DIDL",Ag=400;function Za(t,e,r){return t.map((n,o)=>r(n,e[o]))}var qh=class{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(e){return this._idx.has(e.name)}add(e,r){let n=this._typs.length;this._idx.set(e.name,n),this._idxRefCount.set(n,1),this._typs.push(r)}merge(e,r){let n=this._idx.get(e.name),o=this._idx.get(r);if(n===void 0)throw new Error("Missing type index for "+e);if(o===void 0)throw new Error("Missing type index for "+r);this._typs[n]=this._typs[o];let s=this._getIdxRefCount(o);this._idxRefCount.set(o,s-1),this._idx.delete(r),this._compactFromEnd()}_getIdxRefCount(e){return this._idxRefCount.get(e)||0}_compactFromEnd(){for(;this._typs.length>0;){let e=this._typs.length-1;if(this._getIdxRefCount(e)>0)break;this._typs.pop(),this._idxRefCount.delete(e)}}encode(){let e=ke(this._typs.length),r=Re(...this._typs);return Re(e,r)}indexOf(e){if(!this._idx.has(e))throw new Error("Missing type index for "+e);return rt(this._idx.get(e)||0)}},Mh=class{visitType(e,r){throw new Error("Not implemented")}visitPrimitive(e,r){return this.visitType(e,r)}visitEmpty(e,r){return this.visitPrimitive(e,r)}visitBool(e,r){return this.visitPrimitive(e,r)}visitNull(e,r){return this.visitPrimitive(e,r)}visitReserved(e,r){return this.visitPrimitive(e,r)}visitText(e,r){return this.visitPrimitive(e,r)}visitNumber(e,r){return this.visitPrimitive(e,r)}visitInt(e,r){return this.visitNumber(e,r)}visitNat(e,r){return this.visitNumber(e,r)}visitFloat(e,r){return this.visitPrimitive(e,r)}visitFixedInt(e,r){return this.visitNumber(e,r)}visitFixedNat(e,r){return this.visitNumber(e,r)}visitPrincipal(e,r){return this.visitPrimitive(e,r)}visitConstruct(e,r){return this.visitType(e,r)}visitVec(e,r,n){return this.visitConstruct(e,n)}visitOpt(e,r,n){return this.visitConstruct(e,n)}visitRecord(e,r,n){return this.visitConstruct(e,n)}visitTuple(e,r,n){let o=r.map((s,i)=>[`_${i}_`,s]);return this.visitRecord(e,o,n)}visitVariant(e,r,n){return this.visitConstruct(e,n)}visitRec(e,r,n){return this.visitConstruct(r,n)}visitFunc(e,r){return this.visitConstruct(e,r)}visitService(e,r){return this.visitConstruct(e,r)}},fe;(function(t){t.EmptyClass="__IDL_EmptyClass__",t.UnknownClass="__IDL_UnknownClass__",t.BoolClass="__IDL_BoolClass__",t.NullClass="__IDL_NullClass__",t.ReservedClass="__IDL_ReservedClass__",t.TextClass="__IDL_TextClass__",t.IntClass="__IDL_IntClass__",t.NatClass="__IDL_NatClass__",t.FloatClass="__IDL_FloatClass__",t.FixedIntClass="__IDL_FixedIntClass__",t.FixedNatClass="__IDL_FixedNatClass__",t.VecClass="__IDL_VecClass__",t.OptClass="__IDL_OptClass__",t.RecordClass="__IDL_RecordClass__",t.TupleClass="__IDL_TupleClass__",t.VariantClass="__IDL_VariantClass__",t.RecClass="__IDL_RecClass__",t.PrincipalClass="__IDL_PrincipalClass__",t.FuncClass="__IDL_FuncClass__",t.ServiceClass="__IDL_ServiceClass__"})(fe||(fe={}));var Ei=class{display(){return this.name}valueToString(e){return Je(e)}buildTypeTable(e){e.has(this)||this._buildTypeTableImpl(e)}},nr=class extends Ei{checkType(e){if(this.name!==e.name)throw new Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`);return e}_buildTypeTableImpl(e){}},pn=class extends Ei{checkType(e){if(e instanceof gr){let r=e.getType();if(typeof r>"u")throw new Error("type mismatch with uninitialized type");return r}throw new Error(`type mismatch: type on the wire ${e.name}, expect type ${this.name}`)}encodeType(e){return e.indexOf(this.name)}},Ya=class extends nr{get typeName(){return fe.EmptyClass}static[Symbol.hasInstance](e){return e.typeName===fe.EmptyClass}accept(e,r){return e.visitEmpty(this,r)}covariant(e){throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return rt(Be.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}},Od=class extends Ei{get typeName(){return fe.UnknownClass}static[Symbol.hasInstance](e){return e.typeName===fe.UnknownClass}checkType(e){throw new Error("Method not implemented for unknown.")}accept(e,r){throw e.visitType(this,r)}covariant(e){throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}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(e,r){let n=r.decodeValue(e,r);Object(n)!==n&&(n=Object(n));let o;return r instanceof gr?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"}},Nd=class extends nr{get typeName(){return fe.BoolClass}static[Symbol.hasInstance](e){return e.typeName===fe.BoolClass}accept(e,r){return e.visitBool(this,r)}covariant(e){if(typeof e=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){return new Uint8Array([e?1:0])}encodeType(){return rt(Be.Bool)}decodeValue(e,r){switch(this.checkType(r),Fo(e)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}},_s=class extends nr{get typeName(){return fe.NullClass}static[Symbol.hasInstance](e){return e.typeName===fe.NullClass}accept(e,r){return e.visitNull(this,r)}covariant(e){if(e===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return rt(Be.Null)}decodeValue(e,r){return this.checkType(r),null}get name(){return"null"}},hn=class extends nr{get typeName(){return fe.ReservedClass}static[Symbol.hasInstance](e){return e.typeName===fe.ReservedClass}accept(e,r){return e.visitReserved(this,r)}covariant(e){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return rt(Be.Reserved)}decodeValue(e,r){return r.name!==this.name&&r.decodeValue(e,r),null}get name(){return"reserved"}},vd=class extends nr{get typeName(){return fe.TextClass}static[Symbol.hasInstance](e){return e.typeName===fe.TextClass}accept(e,r){return e.visitText(this,r)}covariant(e){if(typeof e=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){let r=new TextEncoder().encode(e),n=ke(r.byteLength);return Re(n,r)}encodeType(){return rt(Be.Text)}decodeValue(e,r){this.checkType(r);let n=tt(e),o=Vo(e,Number(n));return new TextDecoder("utf8",{fatal:!0}).decode(o)}get name(){return"text"}valueToString(e){return'"'+e+'"'}},Wa=class extends nr{get typeName(){return fe.IntClass}static[Symbol.hasInstance](e){return e.typeName===fe.IntClass}accept(e,r){return e.visitInt(this,r)}covariant(e){if(typeof e=="bigint"||Number.isInteger(e))return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){return rt(e)}encodeType(){return rt(Be.Int)}decodeValue(e,r){return this.checkType(r),$n(e)}get name(){return"int"}valueToString(e){return e.toString()}},Xa=class extends nr{get typeName(){return fe.NatClass}static[Symbol.hasInstance](e){return e.typeName===fe.NatClass}accept(e,r){return e.visitNat(this,r)}covariant(e){if(typeof e=="bigint"&&e>=BigInt(0)||Number.isInteger(e)&&e>=0)return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){return ke(e)}encodeType(){return rt(Be.Nat)}decodeValue(e,r){return this.checkType(r),tt(e)}get name(){return"nat"}valueToString(e){return e.toString()}},Ja=class extends nr{get typeName(){return fe.FloatClass}static[Symbol.hasInstance](e){return e.typeName===fe.FloatClass}constructor(e){if(super(),this._bits=e,e!==32&&e!==64)throw new Error("not a valid float type")}accept(e,r){return e.visitFloat(this,r)}covariant(e){if(typeof e=="number"||e instanceof Number)return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){let r=new ArrayBuffer(this._bits/8),n=new DataView(r);return this._bits===32?n.setFloat32(0,e,!0):n.setFloat64(0,e,!0),new Uint8Array(r)}encodeType(){let e=this._bits===32?Be.Float32:Be.Float64;return rt(e)}decodeValue(e,r){this.checkType(r);let n=Vo(e,this._bits/8),o=vg(n);return this._bits===32?o.getFloat32(0,!0):o.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(e){return e.toString()}},Gn=class extends nr{get typeName(){return fe.FixedIntClass}static[Symbol.hasInstance](e){return e.typeName===fe.FixedIntClass}constructor(e){super(),this._bits=e}accept(e,r){return e.visitFixedInt(this,r)}covariant(e){let r=wd(this._bits-1)*BigInt(-1),n=wd(this._bits-1)-BigInt(1),o=!1;if(typeof e=="bigint")o=e>=r&&e<=n;else if(Number.isInteger(e)){let s=BigInt(e);o=s>=r&&s<=n}else o=!1;if(o)return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){return Vh(e,this._bits/8)}encodeType(){let e=Math.log2(this._bits)-3;return rt(-9-e)}decodeValue(e,r){this.checkType(r);let n=Sg(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`int${this._bits}`}valueToString(e){return e.toString()}},fn=class extends nr{get typeName(){return fe.FixedNatClass}static[Symbol.hasInstance](e){return e.typeName===fe.FixedNatClass}constructor(e){super(),this._bits=e}accept(e,r){return e.visitFixedNat(this,r)}covariant(e){let r=wd(this._bits),n=!1;if(typeof e=="bigint"&&e>=BigInt(0)?n=e<r:Number.isInteger(e)&&e>=0?n=BigInt(e)<r:n=!1,n)return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){return Ig(e,this._bits/8)}encodeType(){let e=Math.log2(this._bits)-3;return rt(-5-e)}decodeValue(e,r){this.checkType(r);let n=Uh(e,this._bits/8);return this._bits<=32?Number(n):n}get name(){return`nat${this._bits}`}valueToString(e){return e.toString()}},Ti=class t extends pn{get typeName(){return fe.VecClass}static[Symbol.hasInstance](e){return e.typeName===fe.VecClass}constructor(e){super(),this._type=e,this._blobOptimization=!1,e instanceof fn&&e._bits===8&&(this._blobOptimization=!0)}accept(e,r){return e.visitVec(this,this._type,r)}covariant(e){let r=this._type instanceof fn?this._type._bits:this._type instanceof Gn?this._type._bits:0;if(ArrayBuffer.isView(e)&&r==e.BYTES_PER_ELEMENT*8||Array.isArray(e)&&e.every((n,o)=>{try{return this._type.covariant(n)}catch(s){throw new Error(`Invalid ${this.display()} argument:
105
-
106
- index ${o} -> ${s.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){let r=ke(e.length);if(this._blobOptimization)return Re(r,new Uint8Array(e));if(ArrayBuffer.isView(e))if(e instanceof Int16Array||e instanceof Uint16Array){let o=new DataView(new ArrayBuffer(e.length*2));for(let s=0;s<e.length;s++)e instanceof Int16Array?o.setInt16(s*2,e[s],!0):o.setUint16(s*2,e[s],!0);return Re(r,new Uint8Array(o.buffer))}else if(e instanceof Int32Array||e instanceof Uint32Array){let o=new DataView(new ArrayBuffer(e.length*4));for(let s=0;s<e.length;s++)e instanceof Int32Array?o.setInt32(s*4,e[s],!0):o.setUint32(s*4,e[s],!0);return Re(r,new Uint8Array(o.buffer))}else if(e instanceof BigInt64Array||e instanceof BigUint64Array){let o=new DataView(new ArrayBuffer(e.length*8));for(let s=0;s<e.length;s++)e instanceof BigInt64Array?o.setBigInt64(s*8,e[s],!0):o.setBigUint64(s*8,e[s],!0);return Re(r,new Uint8Array(o.buffer))}else return Re(r,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));let n=new Fr(new Uint8Array(r.byteLength+e.length),0);n.write(r);for(let o of e){let s=this._type.encodeValue(o);n.write(new Uint8Array(s))}return n.buffer}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let r=rt(Be.Vector),n=this._type.encodeType(e);e.add(this,Re(r,n))}decodeValue(e,r){let n=this.checkType(r);if(!(n instanceof t))throw new Error("Not a vector type");let o=Number(tt(e));if(this._type instanceof fn){if(this._type._bits==8)return new Uint8Array(e.read(o));if(this._type._bits==16){let i=e.read(o*2);return new Uint16Array(i.buffer,i.byteOffset,o)}if(this._type._bits==32){let i=e.read(o*4);return new Uint32Array(i.buffer,i.byteOffset,o)}if(this._type._bits==64)return new BigUint64Array(e.read(o*8).buffer)}if(this._type instanceof Gn){if(this._type._bits==8)return new Int8Array(e.read(o));if(this._type._bits==16){let i=e.read(o*2),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new Int16Array(o);for(let d=0;d<o;d++)c[d]=a.getInt16(d*2,!0);return c}if(this._type._bits==32){let i=e.read(o*4),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new Int32Array(o);for(let d=0;d<o;d++)c[d]=a.getInt32(d*4,!0);return c}if(this._type._bits==64){let i=e.read(o*8),a=new DataView(i.buffer,i.byteOffset,i.byteLength),c=new BigInt64Array(o);for(let d=0;d<o;d++)c[d]=a.getBigInt64(d*8,!0);return c}}let s=[];for(let i=0;i<o;i++)s.push(this._type.decodeValue(e,n._type));return s}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(e){return"vec {"+e.map(n=>this._type.valueToString(n)).join("; ")+"}"}},Uo=class t extends pn{get typeName(){return fe.OptClass}static[Symbol.hasInstance](e){return e.typeName===fe.OptClass}constructor(e){super(),this._type=e}accept(e,r){return e.visitOpt(this,this._type,r)}covariant(e){try{if(Array.isArray(e)&&(e.length===0||e.length===1&&this._type.covariant(e[0])))return!0}catch(r){throw new Error(`Invalid ${this.display()} argument: ${Je(e)}
107
-
108
- -> ${r.message}`)}throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){return e.length===0?new Uint8Array([0]):Re(new Uint8Array([1]),this._type.encodeValue(e[0]))}_buildTypeTableImpl(e){this._type.buildTypeTable(e);let r=rt(Be.Opt),n=this._type.encodeType(e);e.add(this,Re(r,n))}decodeValue(e,r){if(r instanceof _s)return[];if(r instanceof hn)return[];let n=r;if(r instanceof gr){let o=r.getType();if(typeof o>"u")throw new Error("type mismatch with uninitialized type");n=o}if(n instanceof t)switch(Fo(e)){case 0:return[];case 1:{let o=e.save();try{return[this._type.decodeValue(e,n._type)]}catch{return e.restore(o),n._type.decodeValue(e,n._type),[]}}default:throw new Error("Not an option value")}else{if(this._type instanceof _s||this._type instanceof t||this._type instanceof hn)return n.decodeValue(e,n),[];{let o=e.save();try{return[this._type.decodeValue(e,r)]}catch{return e.restore(o),n.decodeValue(e,r),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(e){return e.length===0?"null":`opt ${this._type.valueToString(e[0])}`}},bs=class t extends pn{get typeName(){return fe.RecordClass}static[Symbol.hasInstance](e){return e.typeName===fe.RecordClass||e.typeName===fe.TupleClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((r,n)=>jt(r[0])-jt(n[0]))}accept(e,r){return e.visitRecord(this,this._fields,r)}tryAsTuple(){let e=[];for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(n!==`_${r}_`)return null;e.push(o)}return e}covariant(e){if(typeof e=="object"&&this._fields.every(([r,n])=>{if(!e.hasOwnProperty(r))throw new Error(`Record is missing key "${r}".`);try{return n.covariant(e[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
109
-
110
- field ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){let r=this._fields.map(([o])=>e[o]),n=Za(this._fields,r,([,o],s)=>o.encodeValue(s));return Re(...n)}_buildTypeTableImpl(e){this._fields.forEach(([s,i])=>i.buildTypeTable(e));let r=rt(Be.Record),n=ke(this._fields.length),o=this._fields.map(([s,i])=>Re(ke(jt(s)),i.encodeType(e)));e.add(this,Re(r,n,Re(...o)))}decodeValue(e,r){let n=this.checkType(r);if(!(n instanceof t))throw new Error("Not a record type");let o={},s=0,i=0;for(;i<n._fields.length;){let[a,c]=n._fields[i];if(s>=this._fields.length){c.decodeValue(e,c),i++;continue}let[d,p]=this._fields[s],l=jt(this._fields[s][0]),u=jt(a);if(l===u)o[d]=p.decodeValue(e,c),s++,i++;else if(u>l)if(p instanceof Uo||p instanceof hn)o[d]=[],s++;else throw new Error("Cannot find required field "+d);else c.decodeValue(e,c),i++}for(let[a,c]of this._fields.slice(s))if(c instanceof Uo||c instanceof hn)o[a]=[];else throw new Error("Cannot find required field "+a);return o}get fieldsAsObject(){let e={};for(let[r,n]of this._fields)e[jt(r)]=n;return e}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(e){let r=this._fields.map(([o])=>e[o]);return`record {${Za(this._fields,r,([o,s],i)=>o+"="+s.valueToString(i)).join("; ")}}`}},Rd=class t extends bs{get typeName(){return fe.TupleClass}static[Symbol.hasInstance](e){return e.typeName===fe.TupleClass}constructor(e){let r={};e.forEach((n,o)=>r["_"+o+"_"]=n),super(r),this._components=e}accept(e,r){return e.visitTuple(this,this._components,r)}covariant(e){if(Array.isArray(e)&&e.length>=this._fields.length&&this._components.every((r,n)=>{try{return r.covariant(e[n])}catch(o){throw new Error(`Invalid ${this.display()} argument:
111
-
112
- index ${n} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){let r=Za(this._components,e,(n,o)=>n.encodeValue(o));return Re(...r)}decodeValue(e,r){let n=this.checkType(r);if(!(n instanceof t))throw new Error("not a tuple type");if(n._components.length<this._components.length)throw new Error("tuple mismatch");let o=[];for(let[s,i]of n._components.entries())s>=this._components.length?i.decodeValue(e,i):o.push(this._components[s].decodeValue(e,i));return o}display(){return`record {${this._components.map(r=>r.display()).join("; ")}}`}valueToString(e){return`record {${Za(this._components,e,(n,o)=>n.valueToString(o)).join("; ")}}`}},Oi=class t extends pn{get typeName(){return fe.VariantClass}static[Symbol.hasInstance](e){return e.typeName===fe.VariantClass}constructor(e={}){super(),this._fields=Object.entries(e).sort((r,n)=>jt(r[0])-jt(n[0]))}accept(e,r){return e.visitVariant(this,this._fields,r)}covariant(e){if(typeof e=="object"&&Object.entries(e).length===1&&this._fields.every(([r,n])=>{try{return!e.hasOwnProperty(r)||n.covariant(e[r])}catch(o){throw new Error(`Invalid ${this.display()} argument:
113
-
114
- variant ${r} -> ${o.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){for(let r=0;r<this._fields.length;r++){let[n,o]=this._fields[r];if(e.hasOwnProperty(n)){let s=ke(r),i=o.encodeValue(e[n]);return Re(s,i)}}throw Error("Variant has no data: "+e)}_buildTypeTableImpl(e){this._fields.forEach(([,s])=>{s.buildTypeTable(e)});let r=rt(Be.Variant),n=ke(this._fields.length),o=this._fields.map(([s,i])=>Re(ke(jt(s)),i.encodeType(e)));e.add(this,Re(r,n,...o))}decodeValue(e,r){let n=this.checkType(r);if(!(n instanceof t))throw new Error("Not a variant type");let o=Number(tt(e));if(o>=n._fields.length)throw Error("Invalid variant index: "+o);let[s,i]=n._fields[o];for(let[a,c]of this._fields)if(jt(s)===jt(a)){let d=c.decodeValue(e,i);return{[a]:d}}throw new Error("Cannot find field hash "+s)}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(e){for(let[r,n]of this._fields)if(e.hasOwnProperty(r)){let o=n.valueToString(e[r]);return o==="null"?`variant {${r}}`:`variant {${r}=${o}}`}throw new Error("Variant has no data: "+e)}get alternativesAsObject(){let e={};for(let[r,n]of this._fields)e[jt(r)]=n;return e}},gr=class t extends pn{constructor(){super(...arguments),this._id=t._counter++}get typeName(){return fe.RecClass}static{this._counter=0}static[Symbol.hasInstance](e){return e.typeName===fe.RecClass}accept(e,r){if(!this._type)throw Error("Recursive type uninitialized.");return e.visitRec(this,this._type,r)}fill(e){this._type=e}getType(){return this._type}covariant(e){if(this._type&&this._type.covariant(e))return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(e)}_buildTypeTableImpl(e){if(!this._type)throw Error("Recursive type uninitialized.");e.add(this,new Uint8Array([])),this._type.buildTypeTable(e),e.merge(this,this._type.name)}decodeValue(e,r){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(e,r)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`\u03BC${this.name}.${this._type.name}`}valueToString(e){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(e)}};function jh(t){if(Fo(t)!==1)throw new Error("Cannot decode principal");let r=Number(tt(t));return se.fromUint8Array(new Uint8Array(Vo(t,r)))}var Id=class extends nr{get typeName(){return fe.PrincipalClass}static[Symbol.hasInstance](e){return e.typeName===fe.PrincipalClass}accept(e,r){return e.visitPrincipal(this,r)}covariant(e){if(e&&e._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){let r=e.toUint8Array(),n=ke(r.byteLength);return Re(new Uint8Array([1]),n,r)}encodeType(){return rt(Be.Principal)}decodeValue(e,r){return this.checkType(r),jh(e)}get name(){return"principal"}valueToString(e){return`${this.name} "${e.toText()}"`}},gs=class extends pn{get typeName(){return fe.FuncClass}static[Symbol.hasInstance](e){return e.typeName===fe.FuncClass}static argsToString(e,r){if(e.length!==r.length)throw new Error("arity mismatch");return"("+e.map((n,o)=>n.valueToString(r[o])).join(", ")+")"}constructor(e,r,n=[]){super(),this.argTypes=e,this.retTypes=r,this.annotations=n}accept(e,r){return e.visitFunc(this,r)}covariant(e){if(Array.isArray(e)&&e.length===2&&e[0]&&e[0]._isPrincipal&&typeof e[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue([e,r]){let n=e.toUint8Array(),o=ke(n.byteLength),s=Re(new Uint8Array([1]),o,n),i=new TextEncoder().encode(r),a=ke(i.byteLength);return Re(new Uint8Array([1]),s,a,i)}_buildTypeTableImpl(e){this.argTypes.forEach(d=>d.buildTypeTable(e)),this.retTypes.forEach(d=>d.buildTypeTable(e));let r=rt(Be.Func),n=ke(this.argTypes.length),o=Re(...this.argTypes.map(d=>d.encodeType(e))),s=ke(this.retTypes.length),i=Re(...this.retTypes.map(d=>d.encodeType(e))),a=ke(this.annotations.length),c=Re(...this.annotations.map(d=>this.encodeAnnotation(d)));e.add(this,Re(r,n,o,s,i,a,c))}decodeValue(e,r){let n=r instanceof gr?r.getType()??r:r;if(!Hh(n,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${n.display()}`);if(Fo(e)!==1)throw new Error("Cannot decode function reference");let s=jh(e),i=Number(tt(e)),a=Vo(e,i),d=new TextDecoder("utf8",{fatal:!0}).decode(a);return[s,d]}get name(){let e=this.argTypes.map(o=>o.name).join(", "),r=this.retTypes.map(o=>o.name).join(", "),n=" "+this.annotations.join(" ");return`(${e}) -> (${r})${n}`}valueToString([e,r]){return`func "${e.toText()}".${r}`}display(){let e=this.argTypes.map(o=>o.display()).join(", "),r=this.retTypes.map(o=>o.display()).join(", "),n=" "+this.annotations.join(" ");return`(${e}) \u2192 (${r})${n}`}encodeAnnotation(e){if(e==="query")return new Uint8Array([1]);if(e==="oneway")return new Uint8Array([2]);if(e==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}},Ni=class extends pn{get typeName(){return fe.ServiceClass}static[Symbol.hasInstance](e){return e.typeName===fe.ServiceClass}constructor(e){super(),this._fields=Object.entries(e).sort((r,n)=>r[0]<n[0]?-1:r[0]>n[0]?1:0)}accept(e,r){return e.visitService(this,r)}covariant(e){if(e&&e._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${Je(e)}`)}encodeValue(e){let r=e.toUint8Array(),n=ke(r.length);return Re(new Uint8Array([1]),n,r)}_buildTypeTableImpl(e){this._fields.forEach(([s,i])=>i.buildTypeTable(e));let r=rt(Be.Service),n=ke(this._fields.length),o=this._fields.map(([s,i])=>{let a=new TextEncoder().encode(s),c=ke(a.length);return Re(c,a,i.encodeType(e))});e.add(this,Re(r,n,...o))}decodeValue(e,r){let n=r instanceof gr?r.getType()??r:r;if(!Hh(n,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${n.display()}`);return jh(e)}get name(){return`service {${this._fields.map(([r,n])=>r+":"+n.name).join("; ")}}`}valueToString(e){return`service "${e.toText()}"`}fieldsAsObject(){let e={};for(let[r,n]of this._fields)e[r]=n;return e}};function Je(t){let e=JSON.stringify(t,(r,n)=>typeof n=="bigint"?`BigInt(${n})`:n);return e&&e.length>Ag?e.substring(0,Ag-3)+"...":e}function e8(t,e){if(e.length<t.length)throw Error("Wrong number of message arguments");let r=new qh;t.forEach(c=>c.buildTypeTable(r));let n=new TextEncoder().encode(Ed),o=r.encode(),s=ke(e.length),i=Re(...t.map(c=>c.encodeType(r))),a=Re(...Za(t,e,(c,d)=>{try{c.covariant(d)}catch(p){throw new Error(p.message+`
115
-
116
- `)}return c.encodeValue(d)}));return Re(n,o,s,i,a)}function t8(t,e){let r=new Fr(e);if(e.byteLength<Ed.length)throw new Error("Message length smaller than magic number");let n=Vo(r,Ed.length),o=new TextDecoder().decode(n);if(o!==Ed)throw new Error("Wrong magic number: "+JSON.stringify(o));function s(u){let f=[],h=Number(tt(u));for(let y=0;y<h;y++){let x=Number($n(u));switch(x){case Be.Opt:case Be.Vector:{let _=Number($n(u));f.push([x,_]);break}case Be.Record:case Be.Variant:{let _=[],T=Number(tt(u)),N;for(;T--;){let v=Number(tt(u));if(v>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof N=="number"&&N>=v)throw new Error("field id collision or not sorted");N=v;let R=Number($n(u));_.push([v,R])}f.push([x,_]);break}case Be.Func:{let _=[],T=Number(tt(u));for(;T--;)_.push(Number($n(u)));let N=[],v=Number(tt(u));for(;v--;)N.push(Number($n(u)));let R=[],A=Number(tt(u));for(;A--;)switch(Number(tt(u))){case 1:{R.push("query");break}case 2:{R.push("oneway");break}case 3:{R.push("composite_query");break}default:throw new Error("unknown annotation")}f.push([x,[_,N,R]]);break}case Be.Service:{let _=Number(tt(u)),T=[];for(;_--;){let N=Number(tt(u)),v=new TextDecoder().decode(Vo(u,N)),R=$n(u);T.push([v,R])}f.push([x,T]);break}default:throw new Error("Illegal op_code: "+x)}}let m=[],b=Number(tt(u));for(let y=0;y<b;y++)m.push(Number($n(u)));return[f,m]}let[i,a]=s(r);if(a.length<t.length)throw new Error("Wrong number of return values");let c=i.map(u=>ex());function d(u){if(u<-24)throw new Error("future value not supported");if(u<0)switch(u){case-1:return Dg;case-2:return Pg;case-3:return Ug;case-4:return Vg;case-5:return $g;case-6:return Kg;case-7:return Gg;case-8:return zg;case-9:return Mg;case-10:return kg;case-11:return jg;case-12:return Hg;case-13:return Lg;case-14:return qg;case-15:return Fg;case-16:return Cg;case-17:return Bg;case-24:return Zg;default:throw new Error("Illegal op_code: "+u)}if(u>=i.length)throw new Error("type index out of range");return c[u]}function p(u){switch(u[0]){case Be.Vector:{let f=d(u[1]);return Wg(f)}case Be.Opt:{let f=d(u[1]);return Xg(f)}case Be.Record:{let f={};for(let[b,y]of u[1]){let x=`_${b}_`;f[x]=d(y)}let h=Jg(f),m=h.tryAsTuple();return Array.isArray(m)?Yg(...m):h}case Be.Variant:{let f={};for(let[h,m]of u[1]){let b=`_${h}_`;f[b]=d(m)}return Qg(f)}case Be.Func:{let[f,h,m]=u[1];return tx(f.map(b=>d(b)),h.map(b=>d(b)),m)}case Be.Service:{let f={},h=u[1];for(let[m,b]of h){let y=d(b);if(y instanceof gr&&(y=y.getType()),!(y instanceof gs))throw new Error("Illegal service definition: services can only contain functions");f[m]=y}return rx(f)}default:throw new Error("Illegal op_code: "+u[0])}}i.forEach((u,f)=>{if(u[0]===Be.Func){let h=p(u);c[f].fill(h)}}),i.forEach((u,f)=>{if(u[0]!==Be.Func){let h=p(u);c[f].fill(h)}}),kh();let l=a.map(u=>d(u));try{let u=t.map((f,h)=>f.decodeValue(r,l[h]));for(let f=t.length;f<l.length;f++)l[f].decodeValue(r,l[f]);if(r.byteLength>0)throw new Error("decode: Left-over bytes");return u}finally{kh()}}var Bg=new Ya,Cg=new hn,r8=new Od,Pg=new Nd,Dg=new _s,Fg=new vd,Vg=new Wa,Ug=new Xa,Lg=new Ja(32),qg=new Ja(64),Mg=new Gn(8),kg=new Gn(16),jg=new Gn(32),Hg=new Gn(64),$g=new fn(8),Kg=new fn(16),Gg=new fn(32),zg=new fn(64),Zg=new Id;function Yg(...t){return new Rd(t)}function Wg(t){return new Ti(t)}function Xg(t){return new Uo(t)}function Jg(t){return new bs(t)}function Qg(t){return new Oi(t)}function ex(){return new gr}function tx(t,e,r=[]){return new gs(t,e,r)}function rx(t){return new Ni(t)}var Sd=class t{constructor(e=new Map){this.rels=e}copy(){let e=new Map;for(let[r,n]of this.rels.entries()){let o=new Map(n);e.set(r,o)}return new t(e)}known(e,r){return this.rels.get(e.name)?.get(r.name)}addNegative(e,r){this.addNames(e.name,r.name,!1)}add(e,r){this.addNames(e.name,r.name,!0)}display(){let e="";for(let[r,n]of this.rels)for(let[o,s]of n)e+=`${r} ${s?":<":"!<:"} ${o}
117
- `;return e}addNames(e,r,n){let o=this.rels.get(e);if(o==null){let s=new Map;s.set(r,n),this.rels.set(e,s)}else o.set(r,n)}},Td=new Sd;function kh(){Td=new Sd}function n8(t,e){let r=new Set(t.annotations),n=new Set(e.annotations);if(r.size!==n.size)return!1;for(let o of r)if(!n.has(o))return!1;return!0}function Lh(t){return t instanceof Uo||t instanceof _s||t instanceof hn}function Hh(t,e){let r=Td.copy(),n=Kn(r,t,e);return n?Td.add(t,e):Td.addNegative(t,e),n}function Kn(t,e,r){if(e.name===r.name)return!0;let n=t.known(e,r);if(n!==void 0)return n;if(t.add(e,r),r instanceof hn||e instanceof Ya||e instanceof Xa&&r instanceof Wa)return!0;if(e instanceof Ti&&r instanceof Ti)return Kn(t,e._type,r._type);if(r instanceof Uo)return!0;if(e instanceof bs&&r instanceof bs){let o=e.fieldsAsObject;for(let[s,i]of r._fields){let a=o[jt(s)];if(a){if(!Kn(t,a,i))return!1}else if(!Lh(i))return!1}return!0}if(e instanceof gs&&r instanceof gs){if(!n8(e,r))return!1;for(let o=0;o<e.argTypes.length;o++){let s=e.argTypes[o];if(o<r.argTypes.length){if(!Kn(t,r.argTypes[o],s))return!1}else if(!Lh(s))return!1}for(let o=0;o<r.retTypes.length;o++){let s=r.retTypes[o];if(o<e.retTypes.length){if(!Kn(t,e.retTypes[o],s))return!1}else if(!Lh(s))return!1}return!0}if(e instanceof Oi&&r instanceof Oi){let o=r.alternativesAsObject;for(let[s,i]of e._fields){let a=o[jt(s)];if(!a||!Kn(t,i,a))return!1}return!0}if(e instanceof Ni&&r instanceof Ni){let o=e.fieldsAsObject();for(let[s,i]of r._fields){let a=o[s];if(!a||!Kn(t,a,i))return!1}return!0}return e instanceof gr?Kn(t,e.getType(),r):r instanceof gr?Kn(t,e,r.getType()):!1}function vi(t){if(!t)throw new Error("Input cannot be null or undefined");return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):Array.isArray(t)?new Uint8Array(t):"buffer"in t?vi(t.buffer):new Uint8Array(t)}function ws(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function $h(t){if(typeof t=="string")return nx(t);if(typeof t=="number")return Pt(ke(t));if(t instanceof Uint8Array||ArrayBuffer.isView(t))return Pt(vi(t));if(Array.isArray(t)){let e=t.map($h);return Pt(le(...e))}else{if(t&&typeof t=="object"&&t._isPrincipal)return Pt(t.toUint8Array());if(typeof t=="object"&&t!==null&&typeof t.toHash=="function")return $h(t.toHash());if(typeof t=="object")return Qa(t);if(typeof t=="bigint")return Pt(ke(t))}throw Ne.fromCode(new hd(t))}var nx=t=>{let e=new TextEncoder().encode(t);return Pt(e)};function zn(t){return Qa(t)}function Qa(t){let n=Object.entries(t).filter(([,i])=>i!==void 0).map(([i,a])=>{let c=nx(i),d=$h(a);return[c,d]}).sort(([i],[a])=>Dh(i,a)),o=le(...n.map(i=>le(...i)));return Pt(o)}var ec=new TextEncoder().encode(`
118
- ic-request`),Kh=new TextEncoder().encode("\vic-response"),Gh=new TextEncoder().encode("ic-request-auth-delegation");var mn=class{getPrincipal(){return this._principal||(this._principal=se.selfAuthenticating(new Uint8Array(this.getPublicKey().toDer()))),this._principal}async transformRequest(e){let{body:r,...n}=e,o=zn(r);return{...n,body:{content:r,sender_pubkey:this.getPublicKey().toDer(),sender_sig:await this.sign(le(ec,o))}}}},xr=class{getPrincipal(){return se.anonymous()}async transformRequest(e){return{...e,body:{content:e.body}}}};var Zn=class extends Error{constructor(e){super(e),this.name="DecodingError"}},sx=55799,ix=Symbol("CBOR_STOP_CODE"),Lr=(t=>(t[t.False=20]="False",t[t.True=21]="True",t[t.Null=22]="Null",t[t.Undefined=23]="Undefined",t[t.Break=31]="Break",t))(Lr||{}),at=(t=>(t[t.UnsignedInteger=0]="UnsignedInteger",t[t.NegativeInteger=1]="NegativeInteger",t[t.ByteString=2]="ByteString",t[t.TextString=3]="TextString",t[t.Array=4]="Array",t[t.Map=5]="Map",t[t.Tag=6]="Tag",t[t.Simple=7]="Simple",t))(at||{}),o8=23,s8=255,i8=65535,a8=4294967295,c8=BigInt("0xffffffffffffffff"),Ur=(t=>(t[t.Value=23]="Value",t[t.OneByte=24]="OneByte",t[t.TwoBytes=25]="TwoBytes",t[t.FourBytes=26]="FourBytes",t[t.EightBytes=27]="EightBytes",t[t.Indefinite=31]="Indefinite",t))(Ur||{}),Ri=!1;function u8(t){return t==null}function ax(t,e){let r=new Uint8Array(e);return r.set(t),r}var d8=new TextDecoder;function l8(t){return(t&224)>>5}function f8(t){return t&31}var nc=new Uint8Array,tc,qr=0;function cx(t,e){nc=t,qr=0;let r=Es(e);return e?.(r)??r}function Es(t){let[e,r]=Ad();switch(e){case at.UnsignedInteger:return Ii(r);case at.NegativeInteger:return y8(r);case at.ByteString:return ux(r);case at.TextString:return Zh(r);case at.Array:return p8(r,t);case at.Map:return m8(r,t);case at.Tag:return _8(r,t);case at.Simple:return h8(r)}throw new Zn(`Unsupported major type: ${e}`)}function Ad(){let t=nc.at(qr);if(u8(t))throw new Zn("Provided CBOR data is empty");let e=l8(t),r=f8(t);return qr++,[e,r]}function p8(t,e){let r=Ii(t);if(r===1/0){let o=[],s=Es(e);for(;s!==ix;)o.push(e?.(s)??s),s=Es(e);return o}let n=new Array(r);for(let o=0;o<r;o++){let s=Es(e);n[o]=e?.(s)??s}return n}function h8(t){switch(t){case Lr.False:return!1;case Lr.True:return!0;case Lr.Null:return null;case Lr.Undefined:return;case Lr.Break:return ix}throw new Zn(`Unrecognized simple type: ${t.toString(2)}`)}function m8(t,e){let r=Ii(t),n={};if(r===1/0){let[o,s]=Ad();for(;o!==at.Simple&&s!==Lr.Break;){let i=Zh(s),a=Es(e);n[i]=e?.(a,i)??a,[o,s]=Ad()}return n}for(let o=0;o<r;o++){let[s,i]=Ad();if(s!==at.TextString)throw new Zn("Map keys must be text strings");let a=Zh(i),c=Es(e);n[a]=e?.(c,a)??c}return n}function Ii(t){if(t<=Ur.Value)return t;switch(tc=new DataView(nc.buffer,nc.byteOffset+qr),t){case Ur.OneByte:return qr++,tc.getUint8(0);case Ur.TwoBytes:return qr+=2,tc.getUint16(0,Ri);case Ur.FourBytes:return qr+=4,tc.getUint32(0,Ri);case Ur.EightBytes:return qr+=8,tc.getBigUint64(0,Ri);case Ur.Indefinite:return 1/0;default:throw new Zn(`Unsupported integer info: ${t.toString(2)}`)}}function y8(t){let e=Ii(t);return typeof e=="number"?-1-e:-1n-e}function ux(t){let e=Ii(t);if(e>Number.MAX_SAFE_INTEGER)throw new Zn("Byte length is too large");let r=Number(e);return qr+=r,nc.slice(qr-r,qr)}function Zh(t){let e=ux(t);return d8.decode(e)}function _8(t,e){let r=Ii(t);if(r===sx)return Es(e);throw new Zn(`Unsupported tag: ${r}.`)}var oc=class extends Error{constructor(e){super(e),this.name="SerializationError"}},b8=2*1024,g8=100,x8=new TextEncoder;function rc(t){return t<<5}var dr=new Uint8Array(b8),Vr=new DataView(dr.buffer),it=0,zh=[];function dx(t,e){it=0;let r=e?.(t)??t;return I8(sx,r,e),dr.slice(0,it)}function Yh(t,e){if(it>dr.length-g8&&(dr=ax(dr,dr.length*2),Vr=new DataView(dr.buffer)),t===!1||t===!0||t===null||t===void 0){T8(t);return}if(typeof t=="number"||typeof t=="bigint"){R8(t);return}if(typeof t=="string"){px(t);return}if(t instanceof Uint8Array){ox(t);return}if(t instanceof ArrayBuffer){ox(new Uint8Array(t));return}if(Array.isArray(t)){w8(t,e);return}if(typeof t=="object"){E8(t,e);return}throw new oc(`Unsupported type: ${typeof t}`)}function w8(t,e){Si(at.Array,t.length),t.forEach((r,n)=>{Yh(e?.(r,n.toString())??r,e)})}function E8(t,e){zh=Object.entries(t),Si(at.Map,zh.length),zh.forEach(([r,n])=>{px(r),Yh(e?.(n,r)??n,e)})}function Si(t,e){if(e<=o8){Vr.setUint8(it++,rc(t)|Number(e));return}if(e<=s8){Vr.setUint8(it++,rc(t)|Ur.OneByte),Vr.setUint8(it,Number(e)),it+=1;return}if(e<=i8){Vr.setUint8(it++,rc(t)|Ur.TwoBytes),Vr.setUint16(it,Number(e),Ri),it+=2;return}if(e<=a8){Vr.setUint8(it++,rc(t)|Ur.FourBytes),Vr.setUint32(it,Number(e),Ri),it+=4;return}if(e<=c8){Vr.setUint8(it++,rc(t)|Ur.EightBytes),Vr.setBigUint64(it,BigInt(e),Ri),it+=8;return}throw new oc(`Value too large to encode: ${e}`)}function T8(t){Si(at.Simple,O8(t))}function O8(t){if(t===!1)return Lr.False;if(t===!0)return Lr.True;if(t===null)return Lr.Null;if(t===void 0)return Lr.Undefined;throw new oc(`Unrecognized simple value: ${t.toString()}`)}function lx(t,e){Si(t,e.length),it>dr.length-e.length&&(dr=ax(dr,dr.length+e.length),Vr=new DataView(dr.buffer)),dr.set(e,it),it+=e.length}function fx(t,e){Si(t,e)}function N8(t){fx(at.UnsignedInteger,t)}function v8(t){fx(at.NegativeInteger,typeof t=="bigint"?-1n-t:-1-t)}function R8(t){t>=0?N8(t):v8(t)}function px(t){lx(at.TextString,x8.encode(t))}function ox(t){lx(at.ByteString,t)}function I8(t,e,r){Si(at.Tag,t),Yh(e,r)}function A8(t){return typeof t=="object"&&t!==null&&"toCborValue"in t}function sc(t){try{return dx(t,e=>se.isPrincipal(e)?e.toUint8Array():Ai.isExpiry(e)?e.toBigInt():A8(e)?e.toCborValue():e)}catch(e){throw Ne.fromCode(new ud(e,t))}}function or(t){try{return cx(t)}catch(e){throw Ne.fromCode(new cd(e,t))}}var Bd={encode:sc,decode:or};var ic=()=>{if(typeof window<"u"&&window.crypto&&window.crypto.getRandomValues){let t=new Uint32Array(1);return window.crypto.getRandomValues(t),t[0]}if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]}return typeof crypto<"u"&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)};var Yn;(function(t){t.Query="read",t.ReadState="read_state",t.Call="call"})(Yn||(Yn={}));var Cd;(function(t){t.Call="call"})(Cd||(Cd={}));var Ts;(function(t){t.Query="query",t.ReadState="read_state"})(Ts||(Ts={}));function ac(){let t=new ArrayBuffer(16),e=new DataView(t),r=ic(),n=ic(),o=ic(),s=ic();return e.setUint32(0,r),e.setUint32(4,n),e.setUint32(8,o),e.setUint32(12,s),Object.assign(new Uint8Array(t),{__nonce__:void 0})}var Pd="__expiry__",Xh=BigInt(1e3),B8=BigInt(1e6),hx=BigInt(60),C8=BigInt(90)*Xh;function mx(t){return t/Xh}function P8(t){return mx(t)/hx}var Ai=class t{constructor(e){this.__expiry__=e,this._isExpiry=!0}static fromDeltaInMilliseconds(e,r=0){let n=BigInt(e),o=BigInt(Date.now())+n+BigInt(r),s;return n<C8?s=mx(o):s=P8(o)*hx,new t(s*Xh*B8)}toBigInt(){return this.__expiry__}toHash(){return ke(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[Pd]:this.toString()}}static fromJSON(e){let r=JSON.parse(e);if(r[Pd])try{let n=BigInt(r[Pd]);return new t(n)}catch(n){throw new Ne(new Ga(`Not a valid BigInt: ${n}`))}throw new Ne(new Ga(`The input does not contain the key ${Pd}`))}static isExpiry(e){return e instanceof t||typeof e=="object"&&e!==null&&"_isExpiry"in e&&e._isExpiry===!0&&"__expiry__"in e&&typeof e.__expiry__=="bigint"}};function Jh(t=ac){return async e=>{let r=e.request.headers;e.request.headers=r,e.endpoint===Yn.Call&&(e.body.nonce=t())}}function Dd(t){let e=[];return t.forEach((r,n)=>{e.push([n,r])}),e}var e0=BigInt(0),Fd=BigInt(1);function Os(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Lo(t,e,r=""){let n=cn(t),o=t?.length,s=e!==void 0;if(!n||s&&o!==e){let i=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${o}`:`type=${typeof t}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return t}function yx(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?e0:BigInt("0x"+t)}function sr(t){return yx(ue(t))}function Wn(t){return Xe(t),yx(ue(Uint8Array.from(t).reverse()))}function ct(t,e){return ht(t.toString(16).padStart(e*2,"0"))}function t0(t,e){return ct(t,e).reverse()}function Ze(t,e,r){let n;if(typeof e=="string")try{n=ht(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(cn(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let o=n.length;if(typeof r=="number"&&o!==r)throw new Error(t+" of length "+r+" expected, got "+o);return n}function _x(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function r0(t){return Uint8Array.from(t)}var Qh=t=>typeof t=="bigint"&&e0<=t;function n0(t,e,r){return Qh(t)&&Qh(e)&&Qh(r)&&e<=t&&t<r}function Vd(t,e,r,n){if(!n0(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Xn(t){let e;for(e=0;t>e0;t>>=Fd,e+=1);return e}function bx(t,e){return t>>BigInt(e)&Fd}var Mr=t=>(Fd<<BigInt(t))-Fd;function gx(t){return typeof t=="function"&&Number.isSafeInteger(t.outputLen)}function Jn(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(o,s,i){let a=t[o];if(i&&a===void 0)return;let c=typeof a;if(c!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([o,s])=>n(o,s,!1)),Object.entries(r).forEach(([o,s])=>n(o,s,!0))}var Bi=()=>{throw new Error("not implemented")};function qo(t){let e=new WeakMap;return(r,...n)=>{let o=e.get(r);if(o!==void 0)return o;let s=t(r,...n);return e.set(r,s),s}}var Ht=BigInt(0),yt=BigInt(1),Ns=BigInt(2),wx=BigInt(3),Ex=BigInt(4),Tx=BigInt(5),D8=BigInt(7),Ox=BigInt(8),F8=BigInt(9),Nx=BigInt(16);function Ke(t,e){let r=t%e;return r>=Ht?r:e+r}function kr(t,e,r){let n=t;for(;e-- >Ht;)n*=n,n%=r;return n}function xx(t,e){if(t===Ht)throw new Error("invert: expected non-zero number");if(e<=Ht)throw new Error("invert: expected positive modulus, got "+e);let r=Ke(t,e),n=e,o=Ht,s=yt,i=yt,a=Ht;for(;r!==Ht;){let d=n/r,p=n%r,l=o-i*d,u=s-a*d;n=r,r=p,o=i,s=a,i=l,a=u}if(n!==yt)throw new Error("invert: does not exist");return Ke(o,e)}function o0(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function vx(t,e){let r=(t.ORDER+yt)/Ex,n=t.pow(e,r);return o0(t,n,e),n}function V8(t,e){let r=(t.ORDER-Tx)/Ox,n=t.mul(e,Ns),o=t.pow(n,r),s=t.mul(e,o),i=t.mul(t.mul(s,Ns),o),a=t.mul(s,t.sub(i,t.ONE));return o0(t,a,e),a}function U8(t){let e=$t(t),r=Rx(t),n=r(e,e.neg(e.ONE)),o=r(e,n),s=r(e,e.neg(n)),i=(t+D8)/Nx;return(a,c)=>{let d=a.pow(c,i),p=a.mul(d,n),l=a.mul(d,o),u=a.mul(d,s),f=a.eql(a.sqr(p),c),h=a.eql(a.sqr(l),c);d=a.cmov(d,p,f),p=a.cmov(u,l,h);let m=a.eql(a.sqr(p),c),b=a.cmov(d,p,m);return o0(a,b,c),b}}function Rx(t){if(t<wx)throw new Error("sqrt is not defined for small field");let e=t-yt,r=0;for(;e%Ns===Ht;)e/=Ns,r++;let n=Ns,o=$t(t);for(;cc(o,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return vx;let s=o.pow(n,e),i=(e+yt)/Ns;return function(c,d){if(c.is0(d))return d;if(cc(c,d)!==1)throw new Error("Cannot find square root");let p=r,l=c.mul(c.ONE,s),u=c.pow(d,e),f=c.pow(d,i);for(;!c.eql(u,c.ONE);){if(c.is0(u))return c.ZERO;let h=1,m=c.sqr(u);for(;!c.eql(m,c.ONE);)if(h++,m=c.sqr(m),h===p)throw new Error("Cannot find square root");let b=yt<<BigInt(p-h-1),y=c.pow(l,b);p=h,l=c.sqr(y),u=c.mul(u,l),f=c.mul(f,y)}return f}}function L8(t){return t%Ex===wx?vx:t%Ox===Tx?V8:t%Nx===F8?U8(t):Rx(t)}var Qn=(t,e)=>(Ke(t,e)&yt)===yt,q8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ud(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=q8.reduce((n,o)=>(n[o]="function",n),e);return Jn(t,r),t}function uc(t,e,r){if(r<Ht)throw new Error("invalid exponent, negatives unsupported");if(r===Ht)return t.ONE;if(r===yt)return e;let n=t.ONE,o=e;for(;r>Ht;)r&yt&&(n=t.mul(n,o)),o=t.sqr(o),r>>=yt;return n}function wr(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),o=e.reduce((i,a,c)=>t.is0(a)?i:(n[c]=i,t.mul(i,a)),t.ONE),s=t.inv(o);return e.reduceRight((i,a,c)=>t.is0(a)?i:(n[c]=t.mul(i,n[c]),t.mul(i,a)),s),n}function cc(t,e){let r=(t.ORDER-yt)/Ns,n=t.pow(e,r),o=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),i=t.eql(n,t.neg(t.ONE));if(!o&&!s&&!i)throw new Error("invalid Legendre symbol result");return o?1:s?0:-1}function s0(t,e){e!==void 0&&Rh(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function $t(t,e,r=!1,n={}){if(t<=Ht)throw new Error("invalid field: expected ORDER > 0, got "+t);let o,s,i=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let u=e;u.BITS&&(o=u.BITS),u.sqrt&&(s=u.sqrt),typeof u.isLE=="boolean"&&(r=u.isLE),typeof u.modFromBytes=="boolean"&&(i=u.modFromBytes),a=u.allowedLengths}else typeof e=="number"&&(o=e),n.sqrt&&(s=n.sqrt);let{nBitLength:c,nByteLength:d}=s0(t,o);if(d>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let p,l=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:d,MASK:Mr(c),ZERO:Ht,ONE:yt,allowedLengths:a,create:u=>Ke(u,t),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return Ht<=u&&u<t},is0:u=>u===Ht,isValidNot0:u=>!l.is0(u)&&l.isValid(u),isOdd:u=>(u&yt)===yt,neg:u=>Ke(-u,t),eql:(u,f)=>u===f,sqr:u=>Ke(u*u,t),add:(u,f)=>Ke(u+f,t),sub:(u,f)=>Ke(u-f,t),mul:(u,f)=>Ke(u*f,t),pow:(u,f)=>uc(l,u,f),div:(u,f)=>Ke(u*xx(f,t),t),sqrN:u=>u*u,addN:(u,f)=>u+f,subN:(u,f)=>u-f,mulN:(u,f)=>u*f,inv:u=>xx(u,t),sqrt:s||(u=>(p||(p=L8(t)),p(l,u))),toBytes:u=>r?t0(u,d):ct(u,d),fromBytes:(u,f=!0)=>{if(a){if(!a.includes(u.length)||u.length>d)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);let m=new Uint8Array(d);m.set(u,r?0:m.length-u.length),u=m}if(u.length!==d)throw new Error("Field.fromBytes: expected "+d+" bytes, got "+u.length);let h=r?Wn(u):sr(u);if(i&&(h=Ke(h,t)),!f&&!l.isValid(h))throw new Error("invalid field element: outside of range 0..ORDER");return h},invertBatch:u=>wr(l,u),cmov:(u,f,h)=>h?f:u});return Object.freeze(l)}function Ix(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Ld(t){let e=Ix(t);return e+Math.ceil(e/2)}function i0(t,e,r=!1){let n=t.length,o=Ix(e),s=Ld(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);let i=r?Wn(t):sr(t),a=Ke(i,e-yt)+yt;return r?t0(a,o):ct(a,o)}var Ci=BigInt(0),vs=BigInt(1);function dc(t,e){let r=e.negate();return t?r:e}function Er(t,e){let r=wr(t.Fp,e.map(n=>n.Z));return e.map((n,o)=>t.fromAffine(n.toAffine(r[o])))}function Cx(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function a0(t,e){Cx(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),o=2**t,s=Mr(t),i=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:o,shiftBy:i}}function Sx(t,e,r){let{windowSize:n,mask:o,maxNumber:s,shiftBy:i}=r,a=Number(t&o),c=t>>i;a>n&&(a-=s,c+=vs);let d=e*n,p=d+Math.abs(a)-1,l=a===0,u=a<0,f=e%2!==0;return{nextN:c,offset:p,isZero:l,isNeg:u,isNegF:f,offsetF:d}}function k8(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function j8(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}var c0=new WeakMap,Px=new WeakMap;function u0(t){return Px.get(t)||1}function Ax(t){if(t!==Ci)throw new Error("invalid wNAF")}var Pi=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let o=e;for(;r>Ci;)r&vs&&(n=n.add(o)),o=o.double(),r>>=vs;return n}precomputeWindow(e,r){let{windows:n,windowSize:o}=a0(r,this.bits),s=[],i=e,a=i;for(let c=0;c<n;c++){a=i,s.push(a);for(let d=1;d<o;d++)a=a.add(i),s.push(a);i=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let o=this.ZERO,s=this.BASE,i=a0(e,this.bits);for(let a=0;a<i.windows;a++){let{nextN:c,offset:d,isZero:p,isNeg:l,isNegF:u,offsetF:f}=Sx(n,a,i);n=c,p?s=s.add(dc(u,r[f])):o=o.add(dc(l,r[d]))}return Ax(n),{p:o,f:s}}wNAFUnsafe(e,r,n,o=this.ZERO){let s=a0(e,this.bits);for(let i=0;i<s.windows&&n!==Ci;i++){let{nextN:a,offset:c,isZero:d,isNeg:p}=Sx(n,i,s);if(n=a,!d){let l=r[c];o=o.add(p?l.negate():l)}}return Ax(n),o}getPrecomputes(e,r,n){let o=c0.get(r);return o||(o=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(o=n(o)),c0.set(r,o))),o}cached(e,r,n){let o=u0(e);return this.wNAF(o,this.getPrecomputes(o,e,n),r)}unsafe(e,r,n,o){let s=u0(e);return s===1?this._unsafeLadder(e,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,o)}createCache(e,r){Cx(r,this.bits),Px.set(e,r),c0.delete(e)}hasCache(e){return u0(e)!==1}};function Dx(t,e,r,n){let o=e,s=t.ZERO,i=t.ZERO;for(;r>Ci||n>Ci;)r&vs&&(s=s.add(o)),n&vs&&(i=i.add(o)),o=o.double(),r>>=vs,n>>=vs;return{p1:s,p2:i}}function Di(t,e,r,n){k8(r,t),j8(n,e);let o=r.length,s=n.length;if(o!==s)throw new Error("arrays of points and scalars must have equal length");let i=t.ZERO,a=Xn(BigInt(o)),c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);let d=Mr(c),p=new Array(Number(d)+1).fill(i),l=Math.floor((e.BITS-1)/c)*c,u=i;for(let f=l;f>=0;f-=c){p.fill(i);for(let m=0;m<s;m++){let b=n[m],y=Number(b>>BigInt(f)&d);p[y]=p[y].add(r[m])}let h=i;for(let m=p.length-1,b=i;m>0;m--)b=b.add(p[m]),h=h.add(b);if(u=u.add(h),f!==0)for(let m=0;m<c;m++)u=u.double()}return u}function Bx(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ud(e),e}else return $t(t,{isLE:r})}function qd(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let c of["p","n","h"]){let d=e[c];if(!(typeof d=="bigint"&&d>Ci))throw new Error(`CURVE.${c} must be positive bigint`)}let o=Bx(e.p,r.Fp,n),s=Bx(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}var H8=sr;function Mo(t,e){if(lc(t),lc(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);let r=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)r[n]=t&255,t>>>=8;return new Uint8Array(r)}function $8(t,e){let r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]^e[n];return r}function lc(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function Fx(t){if(!cn(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or string");return typeof t=="string"?Ve(t):t}function K8(t,e,r,n){Xe(t),lc(r),e=Fx(e),e.length>255&&(e=n(le(Ve("H2C-OVERSIZE-DST-"),e)));let{outputLen:o,blockLen:s}=n,i=Math.ceil(r/o);if(r>65535||i>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=le(e,Mo(e.length,1)),c=Mo(0,s),d=Mo(r,2),p=new Array(i),l=n(le(c,t,d,Mo(0,1),a));p[0]=n(le(l,Mo(1,1),a));for(let f=1;f<=i;f++){let h=[$8(l,p[f-1]),Mo(f+1,1),a];p[f]=n(le(...h))}return le(...p).slice(0,r)}function G8(t,e,r,n,o){if(Xe(t),lc(r),e=Fx(e),e.length>255){let s=Math.ceil(2*n/8);e=o.create({dkLen:s}).update(Ve("H2C-OVERSIZE-DST-")).update(e).digest()}if(r>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return o.create({dkLen:r}).update(t).update(Mo(r,2)).update(e).update(Mo(e.length,1)).digest()}function d0(t,e,r){Jn(r,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:n,k:o,m:s,hash:i,expand:a,DST:c}=r;if(!gx(r.hash))throw new Error("expected valid hash");Xe(t),lc(e);let d=n.toString(2).length,p=Math.ceil((d+o)/8),l=e*s*p,u;if(a==="xmd")u=K8(t,c,l,i);else if(a==="xof")u=G8(t,c,l,o,i);else if(a==="_internal_pass")u=t;else throw new Error('expand must be "xmd" or "xof"');let f=new Array(e);for(let h=0;h<e;h++){let m=new Array(s);for(let b=0;b<s;b++){let y=p*(b+h*s),x=u.subarray(y,y+p);m[b]=Ke(H8(x),n)}f[h]=m}return f}function l0(t,e){let r=e.map(n=>Array.from(n).reverse());return(n,o)=>{let[s,i,a,c]=r.map(l=>l.reduce((u,f)=>t.add(t.mul(u,n),f))),[d,p]=wr(t,[i,c],!0);return n=t.mul(s,d),o=t.mul(o,t.mul(a,p)),{x:n,y:o}}}var z8=Ve("HashToScalar-");function f0(t,e,r){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function n(s){return t.fromAffine(e(s))}function o(s){let i=s.clearCofactor();return i.equals(t.ZERO)?t.ZERO:(i.assertValidity(),i)}return{defaults:r,hashToCurve(s,i){let a=Object.assign({},r,i),c=d0(s,2,a),d=n(c[0]),p=n(c[1]);return o(d.add(p))},encodeToCurve(s,i){let a=r.encodeDST?{DST:r.encodeDST}:{},c=Object.assign({},r,a,i),d=d0(s,1,c),p=n(d[0]);return o(p)},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(let i of s)if(typeof i!="bigint")throw new Error("expected array of bigints");return o(n(s))},hashToScalar(s,i){let a=t.Fn.ORDER,c=Object.assign({},r,{p:a,m:1,DST:z8},i);return d0(s,1,c)[0][0]}}}var Vx=(t,e)=>(t+(t>=0?e:-e)/eo)/e;function Z8(t,e,r){let[[n,o],[s,i]]=e,a=Vx(i*t,r),c=Vx(-o*t,r),d=t-a*n-c*s,p=-a*o-c*i,l=d<Rs,u=p<Rs;l&&(d=-d),u&&(p=-p);let f=Mr(Math.ceil(Xn(r)/2))+Kt;if(d<Rs||d>=f||p<Rs||p>=f)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:l,k1:d,k2neg:u,k2:p}}var Rs=BigInt(0),Kt=BigInt(1),eo=BigInt(2),Fi=BigInt(3),p0=BigInt(4);function fc(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let o=Ze("private key",e);try{n=t.fromBytes(o)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Y8(t,e={}){let r=qd("weierstrass",t,e),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i,n:a}=s;Jn(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let d=J8(n,o);function p(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(C,g,w){let{x:O,y:P}=g.toAffine(),L=n.toBytes(O);if(Os(w,"isCompressed"),w){p();let I=!n.isOdd(P);return le(W8(I),L)}else return le(Uint8Array.of(4),L,n.toBytes(P))}function u(C){Lo(C,void 0,"Point");let{publicKey:g,publicKeyUncompressed:w}=d,O=C.length,P=C[0],L=C.subarray(1);if(O===g&&(P===2||P===3)){let I=n.fromBytes(L);if(!n.isValid(I))throw new Error("bad point: is not on curve, wrong x");let B=m(I),F;try{F=n.sqrt(B)}catch(H){let Z=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+Z)}p();let U=n.isOdd(F);return(P&1)===1!==U&&(F=n.neg(F)),{x:I,y:F}}else if(O===w&&P===4){let I=n.BYTES,B=n.fromBytes(L.subarray(0,I)),F=n.fromBytes(L.subarray(I,I*2));if(!b(B,F))throw new Error("bad point: is not on curve");return{x:B,y:F}}else throw new Error(`bad point: got length ${O}, expected compressed=${g} or uncompressed=${w}`)}let f=e.toBytes||l,h=e.fromBytes||u;function m(C){let g=n.sqr(C),w=n.mul(g,C);return n.add(n.add(w,n.mul(C,s.a)),s.b)}function b(C,g){let w=n.sqr(g),O=m(C);return n.eql(w,O)}if(!b(s.Gx,s.Gy))throw new Error("bad curve params: generator point");let y=n.mul(n.pow(s.a,Fi),p0),x=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(y,x)))throw new Error("bad curve params: a or b");function _(C,g,w=!1){if(!n.isValid(g)||w&&n.is0(g))throw new Error(`bad point coordinate ${C}`);return g}function T(C){if(!(C instanceof E))throw new Error("ProjectivePoint expected")}function N(C){if(!c||!c.basises)throw new Error("no endo");return Z8(C,c.basises,o.ORDER)}let v=qo((C,g)=>{let{X:w,Y:O,Z:P}=C;if(n.eql(P,n.ONE))return{x:w,y:O};let L=C.is0();g==null&&(g=L?n.ONE:n.inv(P));let I=n.mul(w,g),B=n.mul(O,g),F=n.mul(P,g);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(F,n.ONE))throw new Error("invZ was invalid");return{x:I,y:B}}),R=qo(C=>{if(C.is0()){if(e.allowInfinityPoint&&!n.is0(C.Y))return;throw new Error("bad point: ZERO")}let{x:g,y:w}=C.toAffine();if(!n.isValid(g)||!n.isValid(w))throw new Error("bad point: x or y not field elements");if(!b(g,w))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function A(C,g,w,O,P){return w=new E(n.mul(w.X,C),w.Y,w.Z),g=dc(O,g),w=dc(P,w),g.add(w)}class E{constructor(g,w,O){this.X=_("x",g),this.Y=_("y",w,!0),this.Z=_("z",O),Object.freeze(this)}static CURVE(){return s}static fromAffine(g){let{x:w,y:O}=g||{};if(!g||!n.isValid(w)||!n.isValid(O))throw new Error("invalid affine point");if(g instanceof E)throw new Error("projective point not allowed");return n.is0(w)&&n.is0(O)?E.ZERO:new E(w,O,n.ONE)}static fromBytes(g){let w=E.fromAffine(h(Lo(g,void 0,"point")));return w.assertValidity(),w}static fromHex(g){return E.fromBytes(Ze("pointHex",g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,w=!0){return V.createCache(this,g),w||this.multiply(Fi),this}assertValidity(){R(this)}hasEvenY(){let{y:g}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(g)}equals(g){T(g);let{X:w,Y:O,Z:P}=this,{X:L,Y:I,Z:B}=g,F=n.eql(n.mul(w,B),n.mul(L,P)),U=n.eql(n.mul(O,B),n.mul(I,P));return F&&U}negate(){return new E(this.X,n.neg(this.Y),this.Z)}double(){let{a:g,b:w}=s,O=n.mul(w,Fi),{X:P,Y:L,Z:I}=this,B=n.ZERO,F=n.ZERO,U=n.ZERO,q=n.mul(P,P),H=n.mul(L,L),Z=n.mul(I,I),G=n.mul(P,L);return G=n.add(G,G),U=n.mul(P,I),U=n.add(U,U),B=n.mul(g,U),F=n.mul(O,Z),F=n.add(B,F),B=n.sub(H,F),F=n.add(H,F),F=n.mul(B,F),B=n.mul(G,B),U=n.mul(O,U),Z=n.mul(g,Z),G=n.sub(q,Z),G=n.mul(g,G),G=n.add(G,U),U=n.add(q,q),q=n.add(U,q),q=n.add(q,Z),q=n.mul(q,G),F=n.add(F,q),Z=n.mul(L,I),Z=n.add(Z,Z),q=n.mul(Z,G),B=n.sub(B,q),U=n.mul(Z,H),U=n.add(U,U),U=n.add(U,U),new E(B,F,U)}add(g){T(g);let{X:w,Y:O,Z:P}=this,{X:L,Y:I,Z:B}=g,F=n.ZERO,U=n.ZERO,q=n.ZERO,H=s.a,Z=n.mul(s.b,Fi),G=n.mul(w,L),ae=n.mul(O,I),te=n.mul(P,B),Ce=n.add(w,O),ne=n.add(L,I);Ce=n.mul(Ce,ne),ne=n.add(G,ae),Ce=n.sub(Ce,ne),ne=n.add(w,P);let me=n.add(L,B);return ne=n.mul(ne,me),me=n.add(G,te),ne=n.sub(ne,me),me=n.add(O,P),F=n.add(I,B),me=n.mul(me,F),F=n.add(ae,te),me=n.sub(me,F),q=n.mul(H,ne),F=n.mul(Z,te),q=n.add(F,q),F=n.sub(ae,q),q=n.add(ae,q),U=n.mul(F,q),ae=n.add(G,G),ae=n.add(ae,G),te=n.mul(H,te),ne=n.mul(Z,ne),ae=n.add(ae,te),te=n.sub(G,te),te=n.mul(H,te),ne=n.add(ne,te),G=n.mul(ae,ne),U=n.add(U,G),G=n.mul(me,ne),F=n.mul(Ce,F),F=n.sub(F,G),G=n.mul(Ce,ae),q=n.mul(me,q),q=n.add(q,G),new E(F,U,q)}subtract(g){return this.add(g.negate())}is0(){return this.equals(E.ZERO)}multiply(g){let{endo:w}=e;if(!o.isValidNot0(g))throw new Error("invalid scalar: out of range");let O,P,L=I=>V.cached(this,I,B=>Er(E,B));if(w){let{k1neg:I,k1:B,k2neg:F,k2:U}=N(g),{p:q,f:H}=L(B),{p:Z,f:G}=L(U);P=H.add(G),O=A(w.beta,q,Z,I,F)}else{let{p:I,f:B}=L(g);O=I,P=B}return Er(E,[O,P])[0]}multiplyUnsafe(g){let{endo:w}=e,O=this;if(!o.isValid(g))throw new Error("invalid scalar: out of range");if(g===Rs||O.is0())return E.ZERO;if(g===Kt)return O;if(V.hasCache(this))return this.multiply(g);if(w){let{k1neg:P,k1:L,k2neg:I,k2:B}=N(g),{p1:F,p2:U}=Dx(E,O,L,B);return A(w.beta,F,U,P,I)}else return V.unsafe(O,g)}multiplyAndAddUnsafe(g,w,O){let P=this.multiplyUnsafe(w).add(g.multiplyUnsafe(O));return P.is0()?void 0:P}toAffine(g){return v(this,g)}isTorsionFree(){let{isTorsionFree:g}=e;return i===Kt?!0:g?g(E,this):V.unsafe(this,a).is0()}clearCofactor(){let{clearCofactor:g}=e;return i===Kt?this:g?g(E,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return Os(g,"isCompressed"),this.assertValidity(),f(E,this,g)}toHex(g=!0){return ue(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(g=!0){return this.toBytes(g)}_setWindowSize(g){this.precompute(g)}static normalizeZ(g){return Er(E,g)}static msm(g,w){return Di(E,o,g,w)}static fromPrivateKey(g){return E.BASE.multiply(fc(o,g))}}E.BASE=new E(s.Gx,s.Gy,n.ONE),E.ZERO=new E(n.ZERO,n.ONE,n.ZERO),E.Fp=n,E.Fn=o;let S=o.BITS,V=new Pi(E,e.endo?Math.ceil(S/2):S);return E.BASE.precompute(8),E}function W8(t){return Uint8Array.of(t?2:3)}function X8(t,e){let r=t.ORDER,n=Rs;for(let h=r-Kt;h%eo===Rs;h/=eo)n+=Kt;let o=n,s=eo<<o-Kt-Kt,i=s*eo,a=(r-Kt)/i,c=(a-Kt)/eo,d=i-Kt,p=s,l=t.pow(e,a),u=t.pow(e,(a+Kt)/eo),f=(h,m)=>{let b=l,y=t.pow(m,d),x=t.sqr(y);x=t.mul(x,m);let _=t.mul(h,x);_=t.pow(_,c),_=t.mul(_,y),y=t.mul(_,m),x=t.mul(_,h);let T=t.mul(x,y);_=t.pow(T,p);let N=t.eql(_,t.ONE);y=t.mul(x,u),_=t.mul(T,b),x=t.cmov(y,x,N),T=t.cmov(_,T,N);for(let v=o;v>Kt;v--){let R=v-eo;R=eo<<R-Kt;let A=t.pow(T,R),E=t.eql(A,t.ONE);y=t.mul(x,b),b=t.mul(b,b),A=t.mul(T,b),x=t.cmov(y,x,E),T=t.cmov(A,T,E)}return{isValid:N,value:x}};if(t.ORDER%p0===Fi){let h=(t.ORDER-Fi)/p0,m=t.sqrt(t.neg(e));f=(b,y)=>{let x=t.sqr(y),_=t.mul(b,y);x=t.mul(x,_);let T=t.pow(x,h);T=t.mul(T,_);let N=t.mul(T,m),v=t.mul(t.sqr(T),y),R=t.eql(v,b),A=t.cmov(N,T,R);return{isValid:R,value:A}}}return f}function h0(t,e){Ud(t);let{A:r,B:n,Z:o}=e;if(!t.isValid(r)||!t.isValid(n)||!t.isValid(o))throw new Error("mapToCurveSimpleSWU: invalid opts");let s=X8(t,o);if(!t.isOdd)throw new Error("Field does not have .isOdd()");return i=>{let a,c,d,p,l,u,f,h;a=t.sqr(i),a=t.mul(a,o),c=t.sqr(a),c=t.add(c,a),d=t.add(c,t.ONE),d=t.mul(d,n),p=t.cmov(o,t.neg(c),!t.eql(c,t.ZERO)),p=t.mul(p,r),c=t.sqr(d),u=t.sqr(p),l=t.mul(u,r),c=t.add(c,l),c=t.mul(c,d),u=t.mul(u,p),l=t.mul(u,n),c=t.add(c,l),f=t.mul(a,d);let{isValid:m,value:b}=s(c,u);h=t.mul(a,i),h=t.mul(h,b),f=t.cmov(f,d,m),h=t.cmov(h,b,m);let y=t.isOdd(i)===t.isOdd(h);h=t.cmov(t.neg(h),h,y);let x=wr(t,[p],!0)[0];return f=t.mul(f,x),{x:f,y:h}}}function J8(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function m0(t){let{CURVE:e,curveOpts:r}=Q8(t),n=Y8(e,r);return t3(t,n)}function Q8(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(i=>Math.ceil(i/2)))):void 0,o=$t(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),s={Fp:r,Fn:o,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function e3(t,e,r){function n(o){let s=t.sqr(o),i=t.mul(s,o);return t.add(t.add(i,t.mul(o,e)),r)}return n}function t3(t,e){let{Fp:r,Fn:n}=e;function o(i){return n0(i,Kt,n.ORDER)}let s=e3(r,t.a,t.b);return Object.assign({},{CURVE:t,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:i=>fc(n,i),weierstrassEquation:s,isWithinCurveOrder:o})}var r3=BigInt(0),Md=BigInt(1),Ux=BigInt(2),Vi=BigInt(3);function n3(t){let e=[];for(;t>Md;t>>=Md)(t&Md)===r3?e.unshift(0):(t&Vi)===Vi?(e.unshift(-1),t+=Md):e.unshift(1);return e}function y0(t){if(!Array.isArray(t)||t.length===0)throw new Error("expected non-empty array")}function o3(t,e,r,n){let{Fp2:o,Fp12:s}=t,{twistType:i,ateLoopSize:a,xNegative:c,postPrecompute:d}=n,p;if(i==="multiplicative")p=(_,T,N,v,R,A)=>s.mul014(v,_,o.mul(T,R),o.mul(N,A));else if(i==="divisive")p=(_,T,N,v,R,A)=>s.mul034(v,o.mul(N,A),o.mul(T,R),_);else throw new Error("bls: unknown twist type");let l=o.div(o.ONE,o.mul(o.ONE,Ux));function u(_,T,N,v){let R=o.sqr(N),A=o.sqr(v),E=o.mulByB(o.mul(A,Vi)),S=o.mul(E,Vi),V=o.sub(o.sub(o.sqr(o.add(N,v)),A),R),C=o.sub(E,R),g=o.mul(o.sqr(T),Vi),w=o.neg(V);return _.push([C,g,w]),T=o.mul(o.mul(o.mul(o.sub(R,S),T),N),l),N=o.sub(o.sqr(o.mul(o.add(R,S),l)),o.mul(o.sqr(E),Vi)),v=o.mul(R,V),{Rx:T,Ry:N,Rz:v}}function f(_,T,N,v,R,A){let E=o.sub(N,o.mul(A,v)),S=o.sub(T,o.mul(R,v)),V=o.sub(o.mul(E,R),o.mul(S,A)),C=o.neg(E),g=S;_.push([V,C,g]);let w=o.sqr(S),O=o.mul(w,S),P=o.mul(w,T),L=o.add(o.sub(O,o.mul(P,Ux)),o.mul(o.sqr(E),v));return T=o.mul(S,L),N=o.sub(o.mul(o.sub(P,L),E),o.mul(O,N)),v=o.mul(v,O),{Rx:T,Ry:N,Rz:v}}let h=n3(a),m=qo(_=>{let T=_,{x:N,y:v}=T.toAffine(),R=N,A=v,E=o.neg(v),S=R,V=A,C=o.ONE,g=[];for(let w of h){let O=[];({Rx:S,Ry:V,Rz:C}=u(O,S,V,C)),w&&({Rx:S,Ry:V,Rz:C}=f(O,S,V,C,R,w===-1?E:A)),g.push(O)}if(d){let w=g[g.length-1];d(S,V,C,R,A,f.bind(null,w))}return g});function b(_,T=!1){let N=s.ONE;if(_.length){let v=_[0][0].length;for(let R=0;R<v;R++){N=s.sqr(N);for(let[A,E,S]of _)for(let[V,C,g]of A[R])N=p(V,C,g,N,E,S)}}return c&&(N=s.conjugate(N)),T?s.finalExponentiate(N):N}function y(_,T=!0){let N=[];Er(e,_.map(({g1:v})=>v)),Er(r,_.map(({g2:v})=>v));for(let{g1:v,g2:R}of _){if(v.is0()||R.is0())throw new Error("pairing is not available for ZERO point");v.assertValidity(),R.assertValidity();let A=v.toAffine();N.push([m(R),A.x,A.y])}return b(N,T)}function x(_,T,N=!0){return y([{g1:_,g2:T}],N)}return{Fp12:s,millerLoopBatch:b,pairing:x,pairingBatch:y,calcPairingPrecomputes:m}}function Lx(t,e,r,n,o){let{Fp12:s,pairingBatch:i}=t;function a(l){return l instanceof e.Point?l:e.Point.fromHex(l)}function c(l){return l instanceof r.Point?l:r.Point.fromHex(l)}function d(l){if(!(l instanceof r.Point))throw new Error(`expected valid message hashed to ${o?"G1":"G2"} curve`);return l}let p=o?(l,u)=>({g1:u,g2:l}):(l,u)=>({g1:l,g2:u});return{getPublicKey(l){let u=fc(e.Point.Fn,l);return e.Point.BASE.multiply(u)},sign(l,u,f){if(f!=null)throw new Error("sign() expects 2 arguments");let h=fc(e.Point.Fn,u);return d(l).assertValidity(),l.multiply(h)},verify(l,u,f,h){if(h!=null)throw new Error("verify() expects 3 arguments");l=c(l),f=a(f);let m=f.negate(),b=e.Point.BASE,y=d(u),x=l,_=i([p(m,y),p(b,x)]);return s.eql(_,s.ONE)},verifyBatch(l,u,f){if(y0(u),f.length!==u.length)throw new Error("amount of public keys and messages should be equal");let h=c(l),m=u,b=f.map(a),y=new Map;for(let T=0;T<b.length;T++){let N=b[T],v=m[T],R=y.get(v);R===void 0&&(R=[],y.set(v,R)),R.push(N)}let x=[],_=e.Point.BASE;try{for(let[T,N]of y){let v=N.reduce((R,A)=>R.add(A));x.push(p(v,T))}return x.push(p(_.negate(),h)),s.eql(i(x),s.ONE)}catch{return!1}},aggregatePublicKeys(l){y0(l),l=l.map(f=>a(f));let u=l.reduce((f,h)=>f.add(h),e.Point.ZERO);return u.assertValidity(),u},aggregateSignatures(l){y0(l),l=l.map(f=>c(f));let u=l.reduce((f,h)=>f.add(h),r.Point.ZERO);return u.assertValidity(),u},hash(l,u){Xe(l);let f=u?{DST:u}:void 0;return r.hashToCurve(l,f)},Signature:n}}function qx(t){let{Fp:e,Fr:r,Fp2:n,Fp6:o,Fp12:s}=t.fields,i=m0(t.G1),a=Object.assign(i,f0(i.Point,t.G1.mapToCurve,{...t.htfDefaults,...t.G1.htfDefaults})),c=m0(t.G2),d=Object.assign(c,f0(c.Point,t.G2.mapToCurve,{...t.htfDefaults,...t.G2.htfDefaults})),p=o3(t.fields,a.Point,d.Point,{...t.params,postPrecompute:t.postPrecompute}),{millerLoopBatch:l,pairing:u,pairingBatch:f,calcPairingPrecomputes:h}=p,m=Lx(p,a,d,t.G2.Signature,!1),b=Lx(p,d,a,t.G1.ShortSignature,!0),y=t.randomBytes||yi,x=()=>{let I=Ld(r.ORDER);return i0(y(I),r.ORDER)},_={randomSecretKey:x,randomPrivateKey:x,calcPairingPrecomputes:h},{ShortSignature:T}=t.G1,{Signature:N}=t.G2;function v(I,B){return I instanceof a.Point?I:b.hash(Ze("point",I),B?.DST)}function R(I,B){return I instanceof d.Point?I:m.hash(Ze("point",I),B?.DST)}function A(I){return m.getPublicKey(I).toBytes(!0)}function E(I){return b.getPublicKey(I).toBytes(!0)}function S(I,B,F){let U=R(I,F),q=m.sign(U,B);return I instanceof d.Point?q:N.toBytes(q)}function V(I,B,F){let U=v(I,F),q=b.sign(U,B);return I instanceof a.Point?q:T.toBytes(q)}function C(I,B,F,U){let q=R(B,U);return m.verify(I,q,F)}function g(I,B,F,U){let q=v(B,U);return b.verify(I,q,F)}function w(I){let B=m.aggregatePublicKeys(I);return I[0]instanceof a.Point?B:B.toBytes(!0)}function O(I){let B=m.aggregateSignatures(I);return I[0]instanceof d.Point?B:N.toBytes(B)}function P(I){let B=b.aggregateSignatures(I);return I[0]instanceof a.Point?B:T.toBytes(B)}function L(I,B,F,U){let q=B.map(H=>R(H,U));return m.verifyBatch(I,q,F)}return a.Point.BASE.precompute(4),{longSignatures:m,shortSignatures:b,millerLoopBatch:l,pairing:u,pairingBatch:f,verifyBatch:L,fields:{Fr:r,Fp:e,Fp2:n,Fp6:o,Fp12:s},params:{ateLoopSize:t.params.ateLoopSize,twistType:t.params.twistType,r:t.params.r,G1b:t.G1.b,G2b:t.G2.b},utils:_,getPublicKey:A,getPublicKeyForShortSignatures:E,sign:S,signShortSignature:V,verify:C,verifyShortSignature:g,aggregatePublicKeys:w,aggregateSignatures:O,aggregateShortSignatures:P,G1:a,G2:d,Signature:N,ShortSignature:T}}var Mx=BigInt(0),to=BigInt(1),Gt=BigInt(2),kx=BigInt(3);function x0(t,e,r,n,o=1,s){let i=BigInt(s===void 0?n:s),a=r**BigInt(n),c=[];for(let d=0;d<o;d++){let p=BigInt(d+1),l=[];for(let u=0,f=to;u<n;u++){let h=(p*f-p)/i%a;l.push(t.pow(e,h)),f*=r}c.push(l)}return c}function Hx(t,e,r){let n=e.pow(r,(t.ORDER-to)/kx),o=e.pow(r,(t.ORDER-to)/Gt);function s(u,f){let h=e.mul(e.frobeniusMap(u,1),n),m=e.mul(e.frobeniusMap(f,1),o);return[h,m]}let i=e.pow(r,(t.ORDER**Gt-to)/kx),a=e.pow(r,(t.ORDER**Gt-to)/Gt);if(!e.eql(a,e.neg(e.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(u,f){return[e.mul(u,i),e.neg(f)]}let d=u=>(f,h)=>{let m=h.toAffine(),b=u(m.x,m.y);return f.fromAffine({x:b[0],y:b[1]})},p=d(s),l=d(c);return{psi:s,psi2:c,G2psi:p,G2psi2:l,PSI_X:n,PSI_Y:o,PSI2_X:i,PSI2_Y:a}}var jx=(t,e)=>{if(e.length!==2)throw new Error("invalid tuple");let r=e.map(n=>t.create(n));return{c0:r[0],c1:r[1]}},_0=class{constructor(e,r={}){this.MASK=to;let n=e.ORDER,o=n*n;this.Fp=e,this.ORDER=o,this.BITS=Xn(o),this.BYTES=Math.ceil(Xn(o)/8),this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO},this.Fp_NONRESIDUE=e.create(r.NONRESIDUE||BigInt(-1)),this.Fp_div2=e.div(e.ONE,Gt),this.NONRESIDUE=jx(e,r.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=x0(e,this.Fp_NONRESIDUE,e.ORDER,2)[0],this.mulByB=r.Fp2mulByB,Object.seal(this)}fromBigTuple(e){return jx(this.Fp,e)}create(e){return e}isValid({c0:e,c1:r}){function n(o,s){return typeof o=="bigint"&&Mx<=o&&o<s}return n(e,this.ORDER)&&n(r,this.ORDER)}is0({c0:e,c1:r}){return this.Fp.is0(e)&&this.Fp.is0(r)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}eql({c0:e,c1:r},{c0:n,c1:o}){return this.Fp.eql(e,n)&&this.Fp.eql(r,o)}neg({c0:e,c1:r}){return{c0:this.Fp.neg(e),c1:this.Fp.neg(r)}}pow(e,r){return uc(this,e,r)}invertBatch(e){return wr(this,e)}add(e,r){let{c0:n,c1:o}=e,{c0:s,c1:i}=r;return{c0:this.Fp.add(n,s),c1:this.Fp.add(o,i)}}sub({c0:e,c1:r},{c0:n,c1:o}){return{c0:this.Fp.sub(e,n),c1:this.Fp.sub(r,o)}}mul({c0:e,c1:r},n){let{Fp:o}=this;if(typeof n=="bigint")return{c0:o.mul(e,n),c1:o.mul(r,n)};let{c0:s,c1:i}=n,a=o.mul(e,s),c=o.mul(r,i),d=o.sub(a,c),p=o.sub(o.mul(o.add(e,r),o.add(s,i)),o.add(a,c));return{c0:d,c1:p}}sqr({c0:e,c1:r}){let{Fp:n}=this,o=n.add(e,r),s=n.sub(e,r),i=n.add(e,e);return{c0:n.mul(o,s),c1:n.mul(i,r)}}addN(e,r){return this.add(e,r)}subN(e,r){return this.sub(e,r)}mulN(e,r){return this.mul(e,r)}sqrN(e){return this.sqr(e)}div(e,r){let{Fp:n}=this;return this.mul(e,typeof r=="bigint"?n.inv(n.create(r)):this.inv(r))}inv({c0:e,c1:r}){let{Fp:n}=this,o=n.inv(n.create(e*e+r*r));return{c0:n.mul(o,n.create(e)),c1:n.mul(o,n.create(-r))}}sqrt(e){let{Fp:r}=this,n=this,{c0:o,c1:s}=e;if(r.is0(s))return cc(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 i=r.sqrt(r.sub(r.sqr(o),r.mul(r.sqr(s),this.Fp_NONRESIDUE))),a=r.mul(r.add(i,o),this.Fp_div2);cc(r,a)===-1&&(a=r.sub(a,i));let d=r.sqrt(a),p=n.create({c0:d,c1:r.div(r.mul(s,this.Fp_div2),d)});if(!n.eql(n.sqr(p),e))throw new Error("Cannot find square root");let l=p,u=n.neg(l),{re:f,im:h}=n.reim(l),{re:m,im:b}=n.reim(u);return h>b||h===b&&f>m?l:u}isOdd(e){let{re:r,im:n}=this.reim(e),o=r%Gt,s=r===Mx,i=n%Gt;return BigInt(o||s&&i)==to}fromBytes(e){let{Fp:r}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);return{c0:r.fromBytes(e.subarray(0,r.BYTES)),c1:r.fromBytes(e.subarray(r.BYTES))}}toBytes({c0:e,c1:r}){return le(this.Fp.toBytes(e),this.Fp.toBytes(r))}cmov({c0:e,c1:r},{c0:n,c1:o},s){return{c0:this.Fp.cmov(e,n,s),c1:this.Fp.cmov(r,o,s)}}reim({c0:e,c1:r}){return{re:e,im:r}}Fp4Square(e,r){let n=this,o=n.sqr(e),s=n.sqr(r);return{first:n.add(n.mulByNonresidue(s),o),second:n.sub(n.sub(n.sqr(n.add(e,r)),o),s)}}mulByNonresidue({c0:e,c1:r}){return this.mul({c0:e,c1:r},this.NONRESIDUE)}frobeniusMap({c0:e,c1:r},n){return{c0:e,c1:this.Fp.mul(r,this.FROBENIUS_COEFFICIENTS[n%2])}}},b0=class{constructor(e){this.MASK=to,this.Fp2=e,this.ORDER=e.ORDER,this.BITS=3*e.BITS,this.BYTES=3*e.BYTES,this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO,c2:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO,c2:e.ZERO};let{Fp:r}=e,n=x0(e,e.NONRESIDUE,r.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=n[0],this.FROBENIUS_COEFFICIENTS_2=n[1],Object.seal(this)}add({c0:e,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return{c0:a.add(e,o),c1:a.add(r,s),c2:a.add(n,i)}}sub({c0:e,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return{c0:a.sub(e,o),c1:a.sub(r,s),c2:a.sub(n,i)}}mul({c0:e,c1:r,c2:n},o){let{Fp2:s}=this;if(typeof o=="bigint")return{c0:s.mul(e,o),c1:s.mul(r,o),c2:s.mul(n,o)};let{c0:i,c1:a,c2:c}=o,d=s.mul(e,i),p=s.mul(r,a),l=s.mul(n,c);return{c0:s.add(d,s.mulByNonresidue(s.sub(s.mul(s.add(r,n),s.add(a,c)),s.add(p,l)))),c1:s.add(s.sub(s.mul(s.add(e,r),s.add(i,a)),s.add(d,p)),s.mulByNonresidue(l)),c2:s.sub(s.add(p,s.mul(s.add(e,n),s.add(i,c))),s.add(d,l))}}sqr({c0:e,c1:r,c2:n}){let{Fp2:o}=this,s=o.sqr(e),i=o.mul(o.mul(e,r),Gt),a=o.mul(o.mul(r,n),Gt),c=o.sqr(n);return{c0:o.add(o.mulByNonresidue(a),s),c1:o.add(o.mulByNonresidue(c),i),c2:o.sub(o.sub(o.add(o.add(i,o.sqr(o.add(o.sub(e,r),n))),a),s),c)}}addN(e,r){return this.add(e,r)}subN(e,r){return this.sub(e,r)}mulN(e,r){return this.mul(e,r)}sqrN(e){return this.sqr(e)}create(e){return e}isValid({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return o.isValid(e)&&o.isValid(r)&&o.isValid(n)}is0({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return o.is0(e)&&o.is0(r)&&o.is0(n)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.neg(e),c1:o.neg(r),c2:o.neg(n)}}eql({c0:e,c1:r,c2:n},{c0:o,c1:s,c2:i}){let{Fp2:a}=this;return a.eql(e,o)&&a.eql(r,s)&&a.eql(n,i)}sqrt(e){return Bi()}div(e,r){let{Fp2:n}=this,{Fp:o}=n;return this.mul(e,typeof r=="bigint"?o.inv(o.create(r)):this.inv(r))}pow(e,r){return uc(this,e,r)}invertBatch(e){return wr(this,e)}inv({c0:e,c1:r,c2:n}){let{Fp2:o}=this,s=o.sub(o.sqr(e),o.mulByNonresidue(o.mul(n,r))),i=o.sub(o.mulByNonresidue(o.sqr(n)),o.mul(e,r)),a=o.sub(o.sqr(r),o.mul(e,n)),c=o.inv(o.add(o.mulByNonresidue(o.add(o.mul(n,i),o.mul(r,a))),o.mul(e,s)));return{c0:o.mul(c,s),c1:o.mul(c,i),c2:o.mul(c,a)}}fromBytes(e){let{Fp2:r}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);let n=r.BYTES;return{c0:r.fromBytes(e.subarray(0,n)),c1:r.fromBytes(e.subarray(n,n*2)),c2:r.fromBytes(e.subarray(2*n))}}toBytes({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return le(o.toBytes(e),o.toBytes(r),o.toBytes(n))}cmov({c0:e,c1:r,c2:n},{c0:o,c1:s,c2:i},a){let{Fp2:c}=this;return{c0:c.cmov(e,o,a),c1:c.cmov(r,s,a),c2:c.cmov(n,i,a)}}fromBigSix(e){let{Fp2:r}=this;if(!Array.isArray(e)||e.length!==6)throw new Error("invalid Fp6 usage");return{c0:r.fromBigTuple(e.slice(0,2)),c1:r.fromBigTuple(e.slice(2,4)),c2:r.fromBigTuple(e.slice(4,6))}}frobeniusMap({c0:e,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.frobeniusMap(e,o),c1:s.mul(s.frobeniusMap(r,o),this.FROBENIUS_COEFFICIENTS_1[o%6]),c2:s.mul(s.frobeniusMap(n,o),this.FROBENIUS_COEFFICIENTS_2[o%6])}}mulByFp2({c0:e,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.mul(e,o),c1:s.mul(r,o),c2:s.mul(n,o)}}mulByNonresidue({c0:e,c1:r,c2:n}){let{Fp2:o}=this;return{c0:o.mulByNonresidue(n),c1:e,c2:r}}mul1({c0:e,c1:r,c2:n},o){let{Fp2:s}=this;return{c0:s.mulByNonresidue(s.mul(n,o)),c1:s.mul(e,o),c2:s.mul(r,o)}}mul01({c0:e,c1:r,c2:n},o,s){let{Fp2:i}=this,a=i.mul(e,o),c=i.mul(r,s);return{c0:i.add(i.mulByNonresidue(i.sub(i.mul(i.add(r,n),s),c)),a),c1:i.sub(i.sub(i.mul(i.add(o,s),i.add(e,r)),a),c),c2:i.add(i.sub(i.mul(i.add(e,n),o),a),c)}}},g0=class{constructor(e,r){this.MASK=to;let{Fp2:n}=e,{Fp:o}=n;this.Fp6=e,this.ORDER=n.ORDER,this.BITS=2*e.BITS,this.BYTES=2*e.BYTES,this.isLE=e.isLE,this.ZERO={c0:e.ZERO,c1:e.ZERO},this.ONE={c0:e.ONE,c1:e.ZERO},this.FROBENIUS_COEFFICIENTS=x0(n,n.NONRESIDUE,o.ORDER,12,1,6)[0],this.X_LEN=r.X_LEN,this.finalExponentiate=r.Fp12finalExponentiate}create(e){return e}isValid({c0:e,c1:r}){let{Fp6:n}=this;return n.isValid(e)&&n.isValid(r)}is0({c0:e,c1:r}){let{Fp6:n}=this;return n.is0(e)&&n.is0(r)}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}neg({c0:e,c1:r}){let{Fp6:n}=this;return{c0:n.neg(e),c1:n.neg(r)}}eql({c0:e,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return s.eql(e,n)&&s.eql(r,o)}sqrt(e){Bi()}inv({c0:e,c1:r}){let{Fp6:n}=this,o=n.inv(n.sub(n.sqr(e),n.mulByNonresidue(n.sqr(r))));return{c0:n.mul(e,o),c1:n.neg(n.mul(r,o))}}div(e,r){let{Fp6:n}=this,{Fp2:o}=n,{Fp:s}=o;return this.mul(e,typeof r=="bigint"?s.inv(s.create(r)):this.inv(r))}pow(e,r){return uc(this,e,r)}invertBatch(e){return wr(this,e)}add({c0:e,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return{c0:s.add(e,n),c1:s.add(r,o)}}sub({c0:e,c1:r},{c0:n,c1:o}){let{Fp6:s}=this;return{c0:s.sub(e,n),c1:s.sub(r,o)}}mul({c0:e,c1:r},n){let{Fp6:o}=this;if(typeof n=="bigint")return{c0:o.mul(e,n),c1:o.mul(r,n)};let{c0:s,c1:i}=n,a=o.mul(e,s),c=o.mul(r,i);return{c0:o.add(a,o.mulByNonresidue(c)),c1:o.sub(o.mul(o.add(e,r),o.add(s,i)),o.add(a,c))}}sqr({c0:e,c1:r}){let{Fp6:n}=this,o=n.mul(e,r);return{c0:n.sub(n.sub(n.mul(n.add(n.mulByNonresidue(r),e),n.add(e,r)),o),n.mulByNonresidue(o)),c1:n.add(o,o)}}addN(e,r){return this.add(e,r)}subN(e,r){return this.sub(e,r)}mulN(e,r){return this.mul(e,r)}sqrN(e){return this.sqr(e)}fromBytes(e){let{Fp6:r}=this;if(e.length!==this.BYTES)throw new Error("fromBytes invalid length="+e.length);return{c0:r.fromBytes(e.subarray(0,r.BYTES)),c1:r.fromBytes(e.subarray(r.BYTES))}}toBytes({c0:e,c1:r}){let{Fp6:n}=this;return le(n.toBytes(e),n.toBytes(r))}cmov({c0:e,c1:r},{c0:n,c1:o},s){let{Fp6:i}=this;return{c0:i.cmov(e,n,s),c1:i.cmov(r,o,s)}}fromBigTwelve(e){let{Fp6:r}=this;return{c0:r.fromBigSix(e.slice(0,6)),c1:r.fromBigSix(e.slice(6,12))}}frobeniusMap(e,r){let{Fp6:n}=this,{Fp2:o}=n,{c0:s,c1:i,c2:a}=n.frobeniusMap(e.c1,r),c=this.FROBENIUS_COEFFICIENTS[r%12];return{c0:n.frobeniusMap(e.c0,r),c1:n.create({c0:o.mul(s,c),c1:o.mul(i,c),c2:o.mul(a,c)})}}mulByFp2({c0:e,c1:r},n){let{Fp6:o}=this;return{c0:o.mulByFp2(e,n),c1:o.mulByFp2(r,n)}}conjugate({c0:e,c1:r}){return{c0:e,c1:this.Fp6.neg(r)}}mul014({c0:e,c1:r},n,o,s){let{Fp6:i}=this,{Fp2:a}=i,c=i.mul01(e,n,o),d=i.mul1(r,s);return{c0:i.add(i.mulByNonresidue(d),c),c1:i.sub(i.sub(i.mul01(i.add(r,e),n,a.add(o,s)),c),d)}}mul034({c0:e,c1:r},n,o,s){let{Fp6:i}=this,{Fp2:a}=i,c=i.create({c0:a.mul(e.c0,n),c1:a.mul(e.c1,n),c2:a.mul(e.c2,n)}),d=i.mul01(r,o,s),p=i.mul01(i.add(e,r),a.add(n,o),s);return{c0:i.add(i.mulByNonresidue(d),c),c1:i.sub(p,i.add(c,d))}}_cyclotomicSquare({c0:e,c1:r}){let{Fp6:n}=this,{Fp2:o}=n,{c0:s,c1:i,c2:a}=e,{c0:c,c1:d,c2:p}=r,{first:l,second:u}=o.Fp4Square(s,d),{first:f,second:h}=o.Fp4Square(c,a),{first:m,second:b}=o.Fp4Square(i,p),y=o.mulByNonresidue(b);return{c0:n.create({c0:o.add(o.mul(o.sub(l,s),Gt),l),c1:o.add(o.mul(o.sub(f,i),Gt),f),c2:o.add(o.mul(o.sub(m,a),Gt),m)}),c1:n.create({c0:o.add(o.mul(o.add(y,c),Gt),y),c1:o.add(o.mul(o.add(u,d),Gt),u),c2:o.add(o.mul(o.add(h,p),Gt),h)})}}_cyclotomicExp(e,r){let n=this.ONE;for(let o=this.X_LEN-1;o>=0;o--)n=this._cyclotomicSquare(n),bx(r,o)&&(n=this.mul(n,e));return n}};function $x(t){let e=$t(t.ORDER),r=new _0(e,t),n=new b0(r),o=new g0(n,t);return{Fp:e,Fp2:r,Fp6:n,Fp12:o}}var Dt=BigInt(0),kd=BigInt(1),Tr=BigInt(2),jd=BigInt(3),pc=BigInt(4),ko=BigInt("0xd201000000010000"),s3=Xn(ko),Is={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Dt,b:pc,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},i3=$t(Is.n,{modFromBytes:!0,isLE:!0}),{Fp:J,Fp2:we,Fp6:a3,Fp12:Ie}=$x({ORDER:Is.p,X_LEN:s3,FP2_NONRESIDUE:[kd,kd],Fp2mulByB:({c0:t,c1:e})=>{let r=J.mul(t,pc),n=J.mul(e,pc);return{c0:J.sub(r,n),c1:J.add(r,n)}},Fp12finalExponentiate:t=>{let e=ko,r=Ie.div(Ie.frobeniusMap(t,6),t),n=Ie.mul(Ie.frobeniusMap(r,2),r),o=Ie.conjugate(Ie._cyclotomicExp(n,e)),s=Ie.mul(Ie.conjugate(Ie._cyclotomicSquare(n)),o),i=Ie.conjugate(Ie._cyclotomicExp(s,e)),a=Ie.conjugate(Ie._cyclotomicExp(i,e)),c=Ie.mul(Ie.conjugate(Ie._cyclotomicExp(a,e)),Ie._cyclotomicSquare(o)),d=Ie.conjugate(Ie._cyclotomicExp(c,e)),p=Ie.frobeniusMap(Ie.mul(o,a),2),l=Ie.frobeniusMap(Ie.mul(i,n),3),u=Ie.frobeniusMap(Ie.mul(c,Ie.conjugate(n)),1),f=Ie.mul(Ie.mul(d,Ie.conjugate(s)),n);return Ie.mul(Ie.mul(Ie.mul(p,l),u),f)}}),{G2psi:Kx,G2psi2:c3}=Hx(J,we,we.div(we.ONE,we.NONRESIDUE)),w0=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:J.ORDER,m:2,k:128,expand:"xmd",hash:Pt}),O0={p:we.ORDER,n:Is.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:we.ZERO,b:we.fromBigTuple([pc,pc]),Gx:we.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:we.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},Hd=hc(J.toBytes(Dt),{infinity:!0,compressed:!0});function $d(t){t=t.slice();let e=t[0]&224,r=!!(e>>7&1),n=!!(e>>6&1),o=!!(e>>5&1);return t[0]&=31,{compressed:r,infinity:n,sort:o,value:t}}function hc(t,e){if(t[0]&224)throw new Error("setMask: non-empty mask");return e.compressed&&(t[0]|=128),e.infinity&&(t[0]|=64),e.sort&&(t[0]|=32),t}function u3(t,e,r){let{BYTES:n,ORDER:o}=J,s=e.is0(),{x:i,y:a}=e.toAffine();if(r){if(s)return Hd.slice();let c=!!(a*Tr/o);return hc(ct(i,n),{compressed:!0,sort:c})}else return s?le(Uint8Array.of(64),new Uint8Array(2*n-1)):le(ct(i,n),ct(a,n))}function E0(t){t.assertValidity();let{BYTES:e,ORDER:r}=J,{x:n,y:o}=t.toAffine();if(t.is0())return Hd.slice();let s=!!(o*Tr/r);return hc(ct(n,e),{compressed:!0,sort:s})}function d3(t){let{compressed:e,infinity:r,sort:n,value:o}=$d(t),{BYTES:s,ORDER:i}=J;if(o.length===48&&e){let a=sr(o),c=J.create(a&Mr(J.BITS));if(r){if(c!==Dt)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:Dt,y:Dt}}let d=J.add(J.pow(c,jd),J.create(Is.b)),p=J.sqrt(d);if(!p)throw new Error("invalid G1 point: compressed point");return p*Tr/i!==BigInt(n)&&(p=J.neg(p)),{x:J.create(c),y:J.create(p)}}else if(o.length===96&&!e){let a=sr(o.subarray(0,s)),c=sr(o.subarray(s));if(r){if(a!==Dt||c!==Dt)throw new Error("G1: non-empty point at infinity");return mc.G1.Point.ZERO.toAffine()}return{x:J.create(a),y:J.create(c)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function Gx(t){let{infinity:e,sort:r,value:n}=$d(Ze("signatureHex",t,48)),o=J.ORDER,s=mc.G1.Point,i=sr(n);if(e)return s.ZERO;let a=J.create(i&Mr(J.BITS)),c=J.add(J.pow(a,jd),J.create(Is.b)),d=J.sqrt(c);if(!d)throw new Error("invalid G1 point: compressed");let p=BigInt(r);d*Tr/o!==p&&(d=J.neg(d));let l=s.fromAffine({x:a,y:d});return l.assertValidity(),l}function l3(t,e,r){let{BYTES:n,ORDER:o}=J,s=e.is0(),{x:i,y:a}=e.toAffine();if(r){if(s)return le(Hd,ct(Dt,n));let c=!!(a.c1===Dt?a.c0*Tr/o:a.c1*Tr/o);return le(hc(ct(i.c1,n),{compressed:!0,sort:c}),ct(i.c0,n))}else{if(s)return le(Uint8Array.of(64),new Uint8Array(4*n-1));let{re:c,im:d}=we.reim(i),{re:p,im:l}=we.reim(a);return le(ct(d,n),ct(c,n),ct(l,n),ct(p,n))}}function T0(t){t.assertValidity();let{BYTES:e}=J;if(t.is0())return le(Hd,ct(Dt,e));let{x:r,y:n}=t.toAffine(),{re:o,im:s}=we.reim(r),{re:i,im:a}=we.reim(n),d=!!((a>Dt?a*Tr:i*Tr)/J.ORDER&kd),p=o;return le(hc(ct(s,e),{sort:d,compressed:!0}),ct(p,e))}function f3(t){let{BYTES:e,ORDER:r}=J,{compressed:n,infinity:o,sort:s,value:i}=$d(t);if(!n&&!o&&s||!n&&o&&s||s&&o&&n)throw new Error("invalid encoding flag: "+(t[0]&224));let a=(c,d,p)=>sr(c.slice(d,p));if(i.length===96&&n){if(o){if(i.reduce((h,m)=>h!==0?m+1:m,0)>0)throw new Error("invalid G2 point: compressed");return{x:we.ZERO,y:we.ZERO}}let c=a(i,0,e),d=a(i,e,2*e),p=we.create({c0:J.create(d),c1:J.create(c)}),l=we.add(we.pow(p,jd),O0.b),u=we.sqrt(l),f=u.c1===Dt?u.c0*Tr/r:u.c1*Tr/r?kd:Dt;return u=s&&f>0?u:we.neg(u),{x:p,y:u}}else if(i.length===192&&!n){if(o){if(i.reduce((u,f)=>u!==0?f+1:f,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:we.ZERO,y:we.ZERO}}let c=a(i,0*e,1*e),d=a(i,1*e,2*e),p=a(i,2*e,3*e),l=a(i,3*e,4*e);return{x:we.fromBigTuple([d,c]),y:we.fromBigTuple([l,p])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function zx(t){let{ORDER:e}=J,{infinity:r,sort:n,value:o}=$d(Ze("signatureHex",t)),s=mc.G2.Point,i=o.length/2;if(i!==48&&i!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");let a=sr(o.slice(0,i)),c=sr(o.slice(i));if(r)return s.ZERO;let d=J.create(a&Mr(J.BITS)),p=J.create(c),l=we.create({c0:p,c1:d}),u=we.add(we.pow(l,jd),O0.b),f=we.sqrt(u);if(!f)throw new Error("Failed to find a square root");let{re:h,im:m}=we.reim(f),b=BigInt(n),y=m>Dt&&m*Tr/e!==b,x=m===Dt&&h*Tr/e!==b;(y||x)&&(f=we.neg(f));let _=s.fromAffine({x:l,y:f});return _.assertValidity(),_}var mc=qx({fields:{Fp:J,Fp2:we,Fp6:a3,Fp12:Ie,Fr:i3},G1:{...Is,Fp:J,htfDefaults:{...w0,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(t,e)=>{let r=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),n=new t(J.mul(e.X,r),e.Y,e.Z);return e.multiplyUnsafe(ko).negate().multiplyUnsafe(ko).equals(n)},clearCofactor:(t,e)=>e.multiplyUnsafe(ko).add(e),mapToCurve:_3,fromBytes:d3,toBytes:u3,ShortSignature:{fromBytes(t){return Xe(t),Gx(t)},fromHex(t){return Gx(t)},toBytes(t){return E0(t)},toRawBytes(t){return E0(t)},toHex(t){return ue(E0(t))}}},G2:{...O0,Fp:we,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...w0},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:b3,isTorsionFree:(t,e)=>e.multiplyUnsafe(ko).negate().equals(Kx(t,e)),clearCofactor:(t,e)=>{let r=ko,n=e.multiplyUnsafe(r).negate(),o=Kx(t,e),s=e.double();return s=c3(t,s),s=s.subtract(o),o=n.add(o),o=o.multiplyUnsafe(r).negate(),s=s.add(o),s=s.subtract(n),s.subtract(e)},fromBytes:f3,toBytes:l3,Signature:{fromBytes(t){return Xe(t),zx(t)},fromHex(t){return zx(t)},toBytes(t){return T0(t)},toRawBytes(t){return T0(t)},toHex(t){return ue(T0(t))}}},params:{ateLoopSize:ko,r:Is.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:w0,hash:Pt}),p3=l0(we,[[["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(t=>t.map(e=>we.fromBigTuple(e.map(BigInt))))),h3=l0(J,[["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(t=>t.map(e=>BigInt(e)))),m3=h0(J,{A:J.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:J.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:J.create(BigInt(11))}),y3=h0(we,{A:we.create({c0:J.create(Dt),c1:J.create(BigInt(240))}),B:we.create({c0:J.create(BigInt(1012)),c1:J.create(BigInt(1012))}),Z:we.create({c0:J.create(BigInt(-2)),c1:J.create(BigInt(-1))})});function _3(t){let{x:e,y:r}=m3(J.create(t[0]));return h3(e,r)}function b3(t){let{x:e,y:r}=y3(we.fromBigTuple(t));return p3(e,r)}function Zx(t,e,r){let n=typeof t=="string"?t:ue(t),o=typeof e=="string"?e:ue(e),s=typeof r=="string"?r:ue(r);return mc.verifyShortSignature(o,s,n)}var x3=BigInt(1e6),N0=t=>tt(new Fr(t)),Ui=t=>{let r=N0(t)/x3;return new Date(Number(r))};var Yx=60*1e3,w3=60,E3=24,T3=E3*w3,O3=5,N3=5,v3=30*T3,Et;(function(t){t[t.Empty=0]="Empty",t[t.Fork=1]="Fork",t[t.Labeled=2]="Labeled",t[t.Leaf=3]="Leaf",t[t.Pruned=4]="Pruned"})(Et||(Et={}));function R3(t,e){for(let r=0;r<t.length;r++)if(t[r]>e[r])return!0;return!1}var jo=class t{#e=!1;#t=void 0;static async create(e){let r=t.createUnverified(e);return await r.verify(),r}static createUnverified(e){return new t(e.certificate,e.rootKey,e.canisterId,e.blsVerify??Zx,e.maxAgeInMinutes,e.disableTimeVerification,e.agent)}constructor(e,r,n,o,s=O3,i=!1,a){this._rootKey=r,this._canisterId=n,this._blsVerify=o,this._maxAgeInMinutes=s,this.#e=i,this.cert=or(e),a&&"getTimeDiffMsecs"in a&&"hasSyncedTime"in a&&"syncTime"in a&&(this.#t=a)}lookup_path(e){return As(e,this.cert.tree)}lookup_subtree(e){return zd(e,this.cert.tree)}async verify(){let e=await Kd(this.cert.tree),r=await this._checkDelegationAndGetKey(this.cert.delegation),n=this.cert.signature,o=S3(r),s=le(_c("ic-state-root"),e),i=Ft(this.lookup_path(["time"]));if(!i)throw Me.fromCode(new Bo("Certificate does not contain a time"));if(!this.#e){let a=this.#t?.getTimeDiffMsecs()??0,c=this._maxAgeInMinutes*Yx,d=new Date,p=d.getTime()+a,l=p-c,u=p+N3*Yx,f=Ui(i),h=f.getTime()<l,m=f.getTime()>u;if((h||m)&&this.#t&&!this.#t.hasSyncedTime())return await this.#t.syncTime(this._canisterId),await this.verify();if(h)throw Mt.fromCode(new hs(this._maxAgeInMinutes,f,d,a,"past"));if(m)throw this.#t?.hasSyncedTime()?st.fromCode(new kt("System time has been synced with the IC network, but certificate is still too far in the future.")):Mt.fromCode(new hs(5,f,d,a,"future"))}try{if(!await this._blsVerify(o,n,s))throw Mt.fromCode(new Bo("Invalid signature"))}catch(a){throw Mt.fromCode(new Bo("Signature verification failed",a))}}async _checkDelegationAndGetKey(e){if(!e)return this._rootKey;let r=t.createUnverified({certificate:e.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,disableTimeVerification:this.#e,maxAgeInMinutes:v3,agent:this.#t});if(r.cert.delegation)throw Me.fromCode(new od);await r.verify();let n=e.subnet_id,o=se.fromUint8Array(n);if(!v0({canisterId:this._canisterId,subnetId:o,tree:r.cert.tree}))throw Mt.fromCode(new _i(this._canisterId,o));let i=Ft(r.lookup_path(["subnet",n,"public_key"]));if(!i)throw Mt.fromCode(new sd(`Could not find subnet key for subnet ID ${o.toText()}`));return i}},yc=ht("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),I3=96;function S3(t){let e=yc.byteLength+I3;if(t.byteLength!==e)throw Me.fromCode(new gi(e,t.byteLength));let r=t.slice(0,yc.byteLength);if(!ws(r,yc))throw Me.fromCode(new id(yc,r));return t.slice(yc.byteLength)}function Ft(t){if(t.status===ir.Found&&t.value instanceof Uint8Array)return t.value}async function Kd(t){switch(t[0]){case Et.Empty:return Pt(_c("ic-hashtree-empty"));case Et.Pruned:return t[1];case Et.Leaf:return Pt(le(_c("ic-hashtree-leaf"),t[1]));case Et.Labeled:return Pt(le(_c("ic-hashtree-labeled"),t[1],await Kd(t[2])));case Et.Fork:return Pt(le(_c("ic-hashtree-fork"),await Kd(t[1]),await Kd(t[2])));default:throw Do}}function _c(t){let e=new Uint8Array([t.length]),r=new TextEncoder().encode(t);return le(e,r)}function Wx(t){return typeof t[0]=="string"?Ve(t[0]):t[0]}var ir;(function(t){t.Unknown="Unknown",t.Absent="Absent",t.Found="Found",t.Error="Error"})(ir||(ir={}));var Ss;(function(t){t.Absent="Absent",t.Unknown="Unknown",t.Found="Found"})(Ss||(Ss={}));var Ge;(function(t){t.Absent="Absent",t.Unknown="Unknown",t.Found="Found",t.Less="Less",t.Greater="Greater"})(Ge||(Ge={}));function As(t,e){if(t.length===0)switch(e[0]){case Et.Empty:return{status:ir.Absent};case Et.Leaf:{if(!e[1])throw st.fromCode(new Po("Invalid tree structure for leaf"));if(e[1]instanceof Uint8Array)return{status:ir.Found,value:e[1].slice(e[1].byteOffset,e[1].byteLength+e[1].byteOffset)};throw Do}case Et.Pruned:return{status:ir.Unknown};case Et.Labeled:case Et.Fork:return{status:ir.Error};default:throw Do}let r=Wx(t),n=bc(r,e);switch(n.status){case Ge.Found:return As(t.slice(1),n.value);case Ge.Absent:case Ge.Greater:case Ge.Less:return{status:ir.Absent};case Ge.Unknown:return{status:ir.Unknown};default:throw Do}}function zd(t,e){if(t.length===0)return{status:Ss.Found,value:e};let r=Wx(t),n=bc(r,e);switch(n.status){case Ge.Found:return zd(t.slice(1),n.value);case Ge.Unknown:return{status:Ss.Unknown};case Ge.Absent:case Ge.Greater:case Ge.Less:return{status:Ss.Absent};default:throw Do}}function Gd(t){switch(t[0]){case Et.Empty:return[];case Et.Fork:return Gd(t[1]).concat(Gd(t[2]));default:return[t]}}function bc(t,e){switch(e[0]){case Et.Labeled:return R3(t,e[1])?{status:Ge.Greater}:ws(t,e[1])?{status:Ge.Found,value:e[2]}:{status:Ge.Less};case Et.Fork:{let r=bc(t,e[1]);switch(r.status){case Ge.Greater:{let n=bc(t,e[2]);return n.status===Ge.Less?{status:Ge.Absent}:n}case Ge.Unknown:{let n=bc(t,e[2]);return n.status===Ge.Less?{status:Ge.Unknown}:n}default:return r}}case Et.Pruned:return{status:Ge.Unknown};default:return{status:Ge.Absent}}}function v0(t){let{canisterId:e,subnetId:r,tree:n}=t,o=As(["subnet",r.toUint8Array(),"canister_ranges"],n);if(o.status!==ir.Found)throw Me.fromCode(new Hn(`Could not find canister ranges for subnet ${r.toText()}`,o.status));if(!(o.value instanceof Uint8Array))throw Me.fromCode(new bi(`Could not find canister ranges for subnet ${r.toText()}`));return or(o.value).map(c=>[se.fromUint8Array(c[0]),se.fromUint8Array(c[1])]).some(c=>c[0].ltEq(e)&&c[1].gtEq(e))}var R0=async t=>{let{agent:e,paths:r,disableCertificateTimeVerification:n=!1}=t,o=se.from(t.canisterId),s=[...new Set(r)],i=new Map,a=s.map((c,d)=>{let p=B3(c,o);return(async()=>{try{if(e.rootKey===null)throw mt.fromCode(new dn);let l=e.rootKey,u=await e.readState(o,{paths:[p]}),f=await jo.create({certificate:u.certificate,rootKey:l,canisterId:o,disableTimeVerification:n,agent:e}),h=(y,x)=>{if(x==="subnet"){let _=A3(u.certificate,o,l);return{path:x,data:_}}else return{path:x,data:Ft(y.lookup_path(p))}},{path:m,data:b}=h(f,s[d]);if(!b)console.warn(`Expected to find result for path ${m}, but instead found nothing.`),typeof m=="string"?i.set(m,null):i.set(m.key,null);else switch(m){case"time":{i.set(m,Ui(b));break}case"controllers":{i.set(m,C3(b));break}case"module_hash":{i.set(m,ue(b));break}case"subnet":{i.set(m,b);break}case"candid":{i.set(m,new TextDecoder().decode(b));break}default:if(typeof m!="string"&&"key"in m&&"path"in m)switch(m.decodeStrategy){case"raw":i.set(m.key,b);break;case"leb128":{i.set(m.key,N0(b));break}case"cbor":{i.set(m.key,or(b));break}case"hex":{i.set(m.key,ue(b));break}case"utf-8":i.set(m.key,new TextDecoder().decode(b))}}}catch(l){if(l instanceof Pr&&(l.hasCode(Bo)||l.hasCode(hs)))throw l;typeof c!="string"&&"key"in c&&"path"in c?i.set(c.key,null):i.set(c,null),console.group(),console.warn(`Expected to find result for path ${c}, but instead found nothing.`),console.warn(l),console.groupEnd()}})()});return await Promise.all(a),i},A3=(t,e,r)=>{if(!e._isPrincipal)throw Ne.fromCode(new kt("Invalid canisterId"));let n=or(t),o=n.tree,s=n.delegation,i;if(s&&s.subnet_id?i=se.fromUint8Array(new Uint8Array(s.subnet_id)):!s&&typeof r<"u"?(i=se.selfAuthenticating(new Uint8Array(r)),s={subnet_id:i.toUint8Array(),certificate:new Uint8Array(0)}):(i=se.selfAuthenticating(se.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),s={subnet_id:i.toUint8Array(),certificate:new Uint8Array(0)}),!v0({canisterId:e,subnetId:i,tree:o}))throw Mt.fromCode(new _i(e,i));let c=zd(["subnet",s.subnet_id,"node"],o);if(c.status!==Ss.Found)throw Me.fromCode(new Hn("Node not found",c.status));if(c.value instanceof Uint8Array)throw st.fromCode(new Po("Invalid node tree"));let d=Gd(c.value),p=new Map;return d.forEach(l=>{let u=se.from(l[1]).toText(),f=As(["public_key"],l[2]);if(f.status!==ir.Found)throw Me.fromCode(new Hn("Public key not found",f.status));let h=f.value;if(h.byteLength!==44)throw Me.fromCode(new gi(44,h.byteLength));p.set(u,h)}),{subnetId:se.fromUint8Array(new Uint8Array(s.subnet_id)).toText(),nodeKeys:p}},B3=(t,e)=>{let r=e.toUint8Array();switch(t){case"time":return[Ve("time")];case"controllers":return[Ve("canister"),r,Ve("controllers")];case"module_hash":return[Ve("canister"),r,Ve("module_hash")];case"subnet":return[Ve("subnet")];case"candid":return[Ve("canister"),r,Ve("metadata"),Ve("candid:service")];default:if("key"in t&&"path"in t)if(typeof t.path=="string"||t.path instanceof Uint8Array){let n=t.path,o=typeof n=="string"?Ve(n):n;return[Ve("canister"),r,Ve("metadata"),o]}else return t.path}throw st.fromCode(new kt(`Error while encoding your path for canister status. Please ensure that your path ${t} was formatted correctly.`))},C3=t=>or(t).map(r=>se.fromUint8Array(r));var Ho=BigInt(0),_t=BigInt(1),I0=BigInt(2),P3=BigInt(8);function D3(t,e,r,n){let o=t.sqr(r),s=t.sqr(n),i=t.add(t.mul(e.a,o),s),a=t.add(t.ONE,t.mul(e.d,t.mul(o,s)));return t.eql(i,a)}function F3(t,e={}){let r=qd("edwards",t,e,e.FpFnLE),{Fp:n,Fn:o}=r,s=r.CURVE,{h:i}=s;Jn(e,{},{uvRatio:"function"});let a=I0<<BigInt(o.BYTES*8)-_t,c=b=>n.create(b),d=e.uvRatio||((b,y)=>{try{return{isValid:!0,value:n.sqrt(n.div(b,y))}}catch{return{isValid:!1,value:Ho}}});if(!D3(n,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function p(b,y,x=!1){let _=x?_t:Ho;return Vd("coordinate "+b,y,_,a),y}function l(b){if(!(b instanceof h))throw new Error("ExtendedPoint expected")}let u=qo((b,y)=>{let{X:x,Y:_,Z:T}=b,N=b.is0();y==null&&(y=N?P3:n.inv(T));let v=c(x*y),R=c(_*y),A=n.mul(T,y);if(N)return{x:Ho,y:_t};if(A!==_t)throw new Error("invZ was invalid");return{x:v,y:R}}),f=qo(b=>{let{a:y,d:x}=s;if(b.is0())throw new Error("bad point: ZERO");let{X:_,Y:T,Z:N,T:v}=b,R=c(_*_),A=c(T*T),E=c(N*N),S=c(E*E),V=c(R*y),C=c(E*c(V+A)),g=c(S+c(x*c(R*A)));if(C!==g)throw new Error("bad point: equation left != right (1)");let w=c(_*T),O=c(N*v);if(w!==O)throw new Error("bad point: equation left != right (2)");return!0});class h{constructor(y,x,_,T){this.X=p("x",y),this.Y=p("y",x),this.Z=p("z",_,!0),this.T=p("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){if(y instanceof h)throw new Error("extended point not allowed");let{x,y:_}=y||{};return p("x",x),p("y",_),new h(x,_,_t,c(x*_))}static fromBytes(y,x=!1){let _=n.BYTES,{a:T,d:N}=s;y=r0(Lo(y,_,"point")),Os(x,"zip215");let v=r0(y),R=y[_-1];v[_-1]=R&-129;let A=Wn(v),E=x?a:n.ORDER;Vd("point.y",A,Ho,E);let S=c(A*A),V=c(S-_t),C=c(N*S-T),{isValid:g,value:w}=d(V,C);if(!g)throw new Error("bad point: invalid y coordinate");let O=(w&_t)===_t,P=(R&128)!==0;if(!x&&w===Ho&&P)throw new Error("bad point: x=0 and x_0=1");return P!==O&&(w=c(-w)),h.fromAffine({x:w,y:A})}static fromHex(y,x=!1){return h.fromBytes(Ze("point",y),x)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,x=!0){return m.createCache(this,y),x||this.multiply(I0),this}assertValidity(){f(this)}equals(y){l(y);let{X:x,Y:_,Z:T}=this,{X:N,Y:v,Z:R}=y,A=c(x*R),E=c(N*T),S=c(_*R),V=c(v*T);return A===E&&S===V}is0(){return this.equals(h.ZERO)}negate(){return new h(c(-this.X),this.Y,this.Z,c(-this.T))}double(){let{a:y}=s,{X:x,Y:_,Z:T}=this,N=c(x*x),v=c(_*_),R=c(I0*c(T*T)),A=c(y*N),E=x+_,S=c(c(E*E)-N-v),V=A+v,C=V-R,g=A-v,w=c(S*C),O=c(V*g),P=c(S*g),L=c(C*V);return new h(w,O,L,P)}add(y){l(y);let{a:x,d:_}=s,{X:T,Y:N,Z:v,T:R}=this,{X:A,Y:E,Z:S,T:V}=y,C=c(T*A),g=c(N*E),w=c(R*_*V),O=c(v*S),P=c((T+N)*(A+E)-C-g),L=O-w,I=O+w,B=c(g-x*C),F=c(P*L),U=c(I*B),q=c(P*B),H=c(L*I);return new h(F,U,H,q)}subtract(y){return this.add(y.negate())}multiply(y){if(!o.isValidNot0(y))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:x,f:_}=m.cached(this,y,T=>Er(h,T));return Er(h,[x,_])[0]}multiplyUnsafe(y,x=h.ZERO){if(!o.isValid(y))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return y===Ho?h.ZERO:this.is0()||y===_t?this:m.unsafe(this,y,_=>Er(h,_),x)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(y){return u(this,y)}clearCofactor(){return i===_t?this:this.multiplyUnsafe(i)}toBytes(){let{x:y,y:x}=this.toAffine(),_=n.toBytes(x);return _[_.length-1]|=y&_t?128:0,_}toHex(){return ue(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(y){return Er(h,y)}static msm(y,x){return Di(h,o,y,x)}_setWindowSize(y){this.precompute(y)}toRawBytes(){return this.toBytes()}}h.BASE=new h(s.Gx,s.Gy,_t,c(s.Gx*s.Gy)),h.ZERO=new h(Ho,_t,_t,Ho),h.Fp=n,h.Fn=o;let m=new Pi(h,o.BITS);return h.BASE.precompute(8),h}var Zd=class{constructor(e){this.ep=e}static fromBytes(e){Bi()}static fromHex(e){Bi()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(e){return this.ep.toAffine(e)}toHex(){return ue(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(e){return this.assertSame(e),this.init(this.ep.add(e.ep))}subtract(e){return this.assertSame(e),this.init(this.ep.subtract(e.ep))}multiply(e){return this.init(this.ep.multiply(e))}multiplyUnsafe(e){return this.init(this.ep.multiplyUnsafe(e))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(e,r){return this.init(this.ep.precompute(e,r))}toRawBytes(){return this.toBytes()}};function V3(t,e,r={}){if(typeof e!="function")throw new Error('"hash" function param is required');Jn(r,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=r,{BASE:o,Fp:s,Fn:i}=t,a=r.randomBytes||yi,c=r.adjustScalarBytes||(E=>E),d=r.domain||((E,S,V)=>{if(Os(V,"phflag"),S.length||V)throw new Error("Contexts/pre-hash are not supported");return E});function p(E){return i.create(Wn(E))}function l(E){let S=_.secretKey;E=Ze("private key",E,S);let V=Ze("hashed private key",e(E),2*S),C=c(V.slice(0,S)),g=V.slice(S,2*S),w=p(C);return{head:C,prefix:g,scalar:w}}function u(E){let{head:S,prefix:V,scalar:C}=l(E),g=o.multiply(C),w=g.toBytes();return{head:S,prefix:V,scalar:C,point:g,pointBytes:w}}function f(E){return u(E).pointBytes}function h(E=Uint8Array.of(),...S){let V=le(...S);return p(e(d(V,Ze("context",E),!!n)))}function m(E,S,V={}){E=Ze("message",E),n&&(E=n(E));let{prefix:C,scalar:g,pointBytes:w}=u(S),O=h(V.context,C,E),P=o.multiply(O).toBytes(),L=h(V.context,P,w,E),I=i.create(O+L*g);if(!i.isValid(I))throw new Error("sign failed: invalid s");let B=le(P,i.toBytes(I));return Lo(B,_.signature,"result")}let b={zip215:!0};function y(E,S,V,C=b){let{context:g,zip215:w}=C,O=_.signature;E=Ze("signature",E,O),S=Ze("message",S),V=Ze("publicKey",V,_.publicKey),w!==void 0&&Os(w,"zip215"),n&&(S=n(S));let P=O/2,L=E.subarray(0,P),I=Wn(E.subarray(P,O)),B,F,U;try{B=t.fromBytes(V,w),F=t.fromBytes(L,w),U=o.multiplyUnsafe(I)}catch{return!1}if(!w&&B.isSmallOrder())return!1;let q=h(g,F.toBytes(),B.toBytes(),S);return F.add(B.multiplyUnsafe(q)).subtract(U).clearCofactor().is0()}let x=s.BYTES,_={secretKey:x,publicKey:x,signature:2*x,seed:x};function T(E=a(_.seed)){return Lo(E,_.seed,"seed")}function N(E){let S=A.randomSecretKey(E);return{secretKey:S,publicKey:f(S)}}function v(E){return cn(E)&&E.length===i.BYTES}function R(E,S){try{return!!t.fromBytes(E,S)}catch{return!1}}let A={getExtendedPublicKey:u,randomSecretKey:T,isValidSecretKey:v,isValidPublicKey:R,toMontgomery(E){let{y:S}=t.fromBytes(E),V=_.publicKey,C=V===32;if(!C&&V!==57)throw new Error("only defined for 25519 and 448");let g=C?s.div(_t+S,_t-S):s.div(S-_t,S+_t);return s.toBytes(g)},toMontgomerySecret(E){let S=_.secretKey;Lo(E,S);let V=e(E.subarray(0,S));return c(V).subarray(0,S)},randomPrivateKey:T,precompute(E=8,S=t.BASE){return S.precompute(E,!1)}};return Object.freeze({keygen:N,getPublicKey:f,sign:m,verify:y,utils:A,Point:t,lengths:_})}function U3(t){let e={a:t.a,d:t.d,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=$t(e.n,t.nBitLength,!0),o={Fp:r,Fn:n,uvRatio:t.uvRatio},s={randomBytes:t.randomBytes,adjustScalarBytes:t.adjustScalarBytes,domain:t.domain,prehash:t.prehash,mapToCurve:t.mapToCurve};return{CURVE:e,curveOpts:o,hash:t.hash,eddsaOpts:s}}function L3(t,e){let r=e.Point;return Object.assign({},e,{ExtendedPoint:r,CURVE:t,nBitLength:r.Fn.BITS,nByteLength:r.Fn.BYTES})}function Xx(t){let{CURVE:e,curveOpts:r,hash:n,eddsaOpts:o}=U3(t),s=F3(e,r),i=V3(s,n,o);return L3(t,i)}var q3=BigInt(0),ro=BigInt(1),Jx=BigInt(2),oS=BigInt(3),M3=BigInt(5),k3=BigInt(8),Li=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),gc={p:Li,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:k3,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function j3(t){let e=BigInt(10),r=BigInt(20),n=BigInt(40),o=BigInt(80),s=Li,a=t*t%s*t%s,c=kr(a,Jx,s)*a%s,d=kr(c,ro,s)*t%s,p=kr(d,M3,s)*d%s,l=kr(p,e,s)*p%s,u=kr(l,r,s)*l%s,f=kr(u,n,s)*u%s,h=kr(f,o,s)*f%s,m=kr(h,o,s)*f%s,b=kr(m,e,s)*p%s;return{pow_p_5_8:kr(b,Jx,s)*t%s,b2:a}}function H3(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}var S0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function C0(t,e){let r=Li,n=Ke(e*e*e,r),o=Ke(n*n*e,r),s=j3(t*o).pow_p_5_8,i=Ke(t*n*s,r),a=Ke(e*i*i,r),c=i,d=Ke(i*S0,r),p=a===t,l=a===Ke(-t,r),u=a===Ke(-t*S0,r);return p&&(i=c),(l||u)&&(i=d),Qn(i,r)&&(i=Ke(-i,r)),{isValid:p||l,value:i}}var $o=$t(gc.p,{isLE:!0}),$3=$t(gc.n,{isLE:!0}),K3={...gc,Fp:$o,hash:Tg,adjustScalarBytes:H3,uvRatio:C0},zt=Xx(K3);var A0=S0,G3=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),z3=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),Z3=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Y3=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),Qx=t=>C0(ro,t),W3=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),B0=t=>zt.Point.Fp.create(Wn(t)&W3);function ew(t){let{d:e}=gc,r=Li,n=y=>$o.create(y),o=n(A0*t*t),s=n((o+ro)*Z3),i=BigInt(-1),a=n((i-e*o)*n(o+e)),{isValid:c,value:d}=C0(s,a),p=n(d*t);Qn(p,r)||(p=n(-p)),c||(d=p),c||(i=o);let l=n(i*(o-ro)*Y3-a),u=d*d,f=n((d+d)*a),h=n(l*G3),m=n(ro-u),b=n(ro+u);return new zt.Point(n(f*b),n(m*h),n(h*b),n(f*m))}function X3(t){Xe(t,64);let e=B0(t.subarray(0,32)),r=ew(e),n=B0(t.subarray(32,64)),o=ew(n);return new no(r.add(o))}var no=class t extends Zd{constructor(e){super(e)}static fromAffine(e){return new t(zt.Point.fromAffine(e))}assertSame(e){if(!(e instanceof t))throw new Error("RistrettoPoint expected")}init(e){return new t(e)}static hashToCurve(e){return X3(Ze("ristrettoHash",e,64))}static fromBytes(e){Xe(e,32);let{a:r,d:n}=gc,o=Li,s=T=>$o.create(T),i=B0(e);if(!_x($o.toBytes(i),e)||Qn(i,o))throw new Error("invalid ristretto255 encoding 1");let a=s(i*i),c=s(ro+r*a),d=s(ro-r*a),p=s(c*c),l=s(d*d),u=s(r*n*p-l),{isValid:f,value:h}=Qx(s(u*l)),m=s(h*d),b=s(h*m*u),y=s((i+i)*m);Qn(y,o)&&(y=s(-y));let x=s(c*b),_=s(y*x);if(!f||Qn(_,o)||x===q3)throw new Error("invalid ristretto255 encoding 2");return new t(new zt.Point(y,x,ro,_))}static fromHex(e){return t.fromBytes(Ze("ristrettoHex",e,32))}static msm(e,r){return Di(t,zt.Point.Fn,e,r)}toBytes(){let{X:e,Y:r,Z:n,T:o}=this.ep,s=Li,i=b=>$o.create(b),a=i(i(n+r)*i(n-r)),c=i(e*r),d=i(c*c),{value:p}=Qx(i(a*d)),l=i(p*a),u=i(p*c),f=i(l*u*o),h;if(Qn(o*f,s)){let b=i(r*A0),y=i(e*A0);e=b,r=y,h=i(l*z3)}else h=u;Qn(e*f,s)&&(r=i(-r));let m=i((n-r)*h);return Qn(m,s)&&(m=i(-m)),$o.toBytes(m)}equals(e){this.assertSame(e);let{X:r,Y:n}=this.ep,{X:o,Y:s}=e.ep,i=d=>$o.create(d),a=i(r*s)===i(n*o),c=i(n*s)===i(r*o);return a||c}is0(){return this.equals(t.ZERO)}};no.BASE=new no(zt.Point.BASE);no.ZERO=new no(zt.Point.ZERO);no.Fp=$o;no.Fn=$3;var tw,rw,Yd=class{static{tw=Symbol.iterator,rw=Symbol.toStringTag}#e;#t;constructor(e={}){this[tw]=this.entries.bind(this),this[rw]="ExpirableMap";let{source:r=[],expirationTime:n=600*1e3}=e,o=Date.now();this.#e=new Map([...r].map(([s,i])=>[s,{value:i,timestamp:o}])),this.#t=n}prune(){let e=Date.now();for(let[r,n]of this.#e.entries())e-n.timestamp>this.#t&&this.#e.delete(r);return this}set(e,r){this.prune();let n={value:r,timestamp:Date.now()};return this.#e.set(e,n),this}get(e){let r=this.#e.get(e);if(r!==void 0){if(Date.now()-r.timestamp>this.#t){this.#e.delete(e);return}return r.value}}clear(){this.#e.clear()}entries(){let e=this.#e.entries();return function*(){for(let[n,o]of e)yield[n,o.value]}()}values(){let e=this.#e.values();return function*(){for(let n of e)yield n.value}()}keys(){return this.#e.keys()}forEach(e,r){for(let[n,o]of this.#e.entries())e.call(r,o.value,n,this)}has(e){return this.#e.has(e)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}};var nw=t=>{if(t<=127)return 1;if(t<=255)return 2;if(t<=65535)return 3;if(t<=16777215)return 4;throw Ne.fromCode(new ka("Length too long (> 4 bytes)"))},ow=(t,e,r)=>{if(r<=127)return t[e]=r,1;if(r<=255)return t[e]=129,t[e+1]=r,2;if(r<=65535)return t[e]=130,t[e+1]=r>>8,t[e+2]=r,3;if(r<=16777215)return t[e]=131,t[e+1]=r>>16,t[e+2]=r>>8,t[e+3]=r,4;throw Ne.fromCode(new ka("Length too long (> 4 bytes)"))},P0=(t,e)=>{if(t[e]<128)return 1;if(t[e]===128)throw Ne.fromCode(new Dr("Invalid length 0"));if(t[e]===129)return 2;if(t[e]===130)return 3;if(t[e]===131)return 4;throw Ne.fromCode(new Dr("Length too long (> 4 bytes)"))},J3=(t,e)=>{let r=P0(t,e);if(r===1)return t[e];if(r===2)return t[e+1];if(r===3)return(t[e+1]<<8)+t[e+2];if(r===4)return(t[e+1]<<16)+(t[e+2]<<8)+t[e+3];throw Ne.fromCode(new Dr("Length too long (> 4 bytes)"))},xc=Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]),Bs=Uint8Array.from([48,5,6,3,43,101,112]),uS=Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]),dS=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 Cs(t,e){let r=2+nw(t.byteLength+1),n=e.byteLength+r+t.byteLength,o=0,s=new Uint8Array(1+nw(n)+n);return s[o++]=48,o+=ow(s,o,n),s.set(e,o),o+=e.byteLength,s[o++]=3,o+=ow(s,o,t.byteLength+1),s[o++]=0,s.set(new Uint8Array(t),o),s}var Ps=(t,e)=>{let r=0,n=(a,c)=>{if(o[r++]!==a)throw Ne.fromCode(new Dr(`Expected ${c} at offset ${r}`))},o=new Uint8Array(t);if(n(48,"sequence"),r+=P0(o,r),!ws(o.slice(r,r+e.byteLength),e))throw Ne.fromCode(new Dr("Not the expected OID."));r+=e.byteLength,n(3,"bit string");let s=J3(o,r)-1;r+=P0(o,r),n(0,"0 padding");let i=o.slice(r);if(s!==i.length)throw Ne.fromCode(new ad(s,i.length));return i};var Wd=class t{static from(e){return this.fromDer(e.toDer())}static fromRaw(e){return new t(e)}static fromDer(e){return new t(this.derDecode(e))}static{this.RAW_KEY_LENGTH=32}static derEncode(e){return Cs(e,Bs)}static derDecode(e){let r=Ps(e,Bs);if(r.length!==this.RAW_KEY_LENGTH)throw Ne.fromCode(new Dr("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(e){if(e.byteLength!==t.RAW_KEY_LENGTH)throw Ne.fromCode(new Dr("An Ed25519 public key must be exactly 32 bytes long"));this.#e=e,this.#t=t.derEncode(e)}toDer(){return this.derKey}toRaw(){return this.rawKey}};var D0=class{constructor(){this.observers=[]}subscribe(e){this.observers.push(e)}unsubscribe(e){this.observers=this.observers.filter(r=>r!==e)}notify(e,...r){this.observers.forEach(n=>n(e,...r))}},Xd=class extends D0{constructor(){super()}print(e,...r){this.notify({message:e,level:"info"},...r)}warn(e,...r){this.notify({message:e,level:"warn"},...r)}error(e,r,...n){this.notify({message:e,level:"error",error:r},...n)}};var Jd=class t{#e;#t;#r;#c;#i;#d;#n;#o;#a=0;static{this.default={initialInterval:500,randomizationFactor:.5,multiplier:1.5,maxInterval:6e4,maxElapsedTime:9e5,maxIterations:10,date:Date}}constructor(e=t.default){let{initialInterval:r=500,randomizationFactor:n=.5,multiplier:o=1.5,maxInterval:s=6e4,maxElapsedTime:i=9e5,maxIterations:a=10,date:c=Date}=e;this.#e=r,this.#t=n,this.#r=o,this.#c=s,this.#o=c,this.#i=c.now(),this.#d=i,this.#n=a}get ellapsedTimeInMsec(){return this.#o.now()-this.#i}get currentInterval(){return this.#e}get count(){return this.#a}get randomValueFromInterval(){let e=this.#t*this.#e,r=this.#e-e,n=this.#e+e;return Math.random()*(n-r)+r}incrementCurrentInterval(){return this.#e=Math.min(this.#e*this.#r,this.#c),this.#a++,this.#e}next(){return this.ellapsedTimeInMsec>=this.#d||this.#a>=this.#n?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};var yn;(function(t){t.Received="received",t.Processing="processing",t.Replied="replied",t.Rejected="rejected",t.Unknown="unknown",t.Done="done"})(yn||(yn={}));var U0=60*1e3,Q3=1e6,eN=0,tN="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae";var rN="ic0.app",nN=".ic0.app",oN="icp0.io",sN=".icp0.io",iN="icp-api.io",aN=".icp-api.io",F0=200,cN=202,uN=404;function dN(){let t;if(typeof window<"u")if(window.fetch)t=window.fetch.bind(window);else throw mt.fromCode(new wi("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)t=global.fetch.bind(global);else throw mt.fromCode(new wi("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&&(t=self.fetch.bind(self));if(t)return t;throw mt.fromCode(new wi("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function lN(t){let e;if(t!==void 0)!t.match(/^[a-z]+:/)&&typeof window<"u"?e=new URL(window.location.protocol+"//"+t):e=new URL(t);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,s=o?.hostname,i;s&&typeof s=="string"&&(n.some(a=>s.endsWith(a))?i=s:i=r.find(a=>s.endsWith(a))),o&&i?e=new URL(`${o.protocol}//${i}${o.port?":"+o.port:""}`):e=new URL("https://icp-api.io")}return e.toString()}var Ds=class t{#e;#t;#r;#c;#i;#d;#n;#o;#a;#g;#s;#l;#f;#u;get#T(){return this.#u*U0}#p;#h;#m;#y;constructor(e={}){this.#e=null,this.#t=!1,this.#r=eN,this.#c=!1,this.#i=null,this.#d=!1,this._isAgent=!0,this.config={},this.log=new Xd,this.#p=[],this.#h=[],this.#m=new Yd({expirationTime:5*U0}),this.#y=!0,this.#w=(o,s)=>{if(this.#y===!1)return o;let{status:i,signatures:a=[],requestId:c}=o;for(let d of a){let{timestamp:p,identity:l}=d,u=se.fromUint8Array(l).toText(),f;if(i===vo.Replied){let{reply:x}=o;f=Qa({status:i,reply:x,timestamp:BigInt(p),request_id:c})}else if(i===vo.Rejected){let{reject_code:x,reject_message:_,error_code:T}=o;f=Qa({status:i,reject_code:x,reject_message:_,error_code:T,timestamp:BigInt(p),request_id:c})}else throw st.fromCode(new kt(`Unknown status: ${i}`));let h=le(Kh,f),m=s.nodeKeys.get(u);if(!m)throw Me.fromCode(new bd);let b=Wd.fromDer(m).rawKey;if(zt.verify(d.signature,h,b))return o;throw Mt.fromCode(new gd(u))}return o},this.config=e,this.#o=e.fetch||dN()||fetch.bind(global),this.#a=e.fetchOptions,this.#g=e.callOptions,this.#t=e.shouldFetchRootKey??!1,this.#d=e.shouldSyncTime??!1,e.rootKey?this.rootKey=e.rootKey:this.#t?this.rootKey=null:this.rootKey=ht(tN);let r=lN(e.host);this.host=new URL(r),e.verifyQuerySignatures!==void 0&&(this.#y=e.verifyQuerySignatures),this.#l=e.retryTimes??3;let n=()=>new Jd({maxIterations:this.#l});if(this.#f=e.backoffStrategy||n,this.host.hostname.endsWith(nN)?this.host.hostname=rN:this.host.hostname.endsWith(sN)?this.host.hostname=oN:this.host.hostname.endsWith(aN)&&(this.host.hostname=iN),e.credentials){let{name:o,password:s}=e.credentials;this.#s=`${o}${s?":"+s:""}`}if(this.#n=Promise.resolve(e.identity||new xr),e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes>5)throw Ne.fromCode(new ys("The maximum ingress expiry time is 5 minutes.",e.ingressExpiryInMinutes));if(e.ingressExpiryInMinutes&&e.ingressExpiryInMinutes<=0)throw Ne.fromCode(new ys("Ingress expiry time must be greater than 0.",e.ingressExpiryInMinutes));this.#u=e.ingressExpiryInMinutes||5,this.addTransform("update",Jh(ac)),e.useQueryNonces&&this.addTransform("query",Jh(ac)),e.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(e={}){return new this({...e})}static async create(e={}){let r=t.createSync(e);return await r.#b(),r}static async from(e){try{return"config"in e?await t.create(e.config):await t.create({fetch:e._fetch,fetchOptions:e._fetchOptions,callOptions:e._callOptions,host:e._host.toString(),identity:e._identity??void 0})}catch{throw Ne.fromCode(new md)}}isLocal(){let e=this.host.hostname;return e==="127.0.0.1"||e.endsWith("127.0.0.1")}addTransform(e,r,n=r.priority||0){if(e==="update"){let o=this.#h.findIndex(s=>(s.priority||0)<n);this.#h.splice(o>=0?o:this.#h.length,0,Object.assign(r,{priority:n}))}else if(e==="query"){let o=this.#p.findIndex(s=>(s.priority||0)<n);this.#p.splice(o>=0?o:this.#p.length,0,Object.assign(r,{priority:n}))}}async getPrincipal(){if(!this.#n)throw mt.fromCode(new Co);return(await this.#n).getPrincipal()}async call(e,r,n){let o=r.callSync??!0,s=await(n??this.#n);if(!s)throw mt.fromCode(new Co);let i=se.from(e),a=r.effectiveCanisterId?se.from(r.effectiveCanisterId):i;await this.#b(a);let c=s.getPrincipal(),d=V0(this.#u,this.#r),p={request_type:Cd.Call,canister_id:i,method_name:r.methodName,arg:r.arg,sender:c,ingress_expiry:d},l=await this._transform({request:{body:null,method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:Yn.Call,body:p}),u;r?.nonce?u=f(r.nonce):l.body.nonce?u=f(l.body.nonce):u=void 0,p.nonce=u;function f(y){return Object.assign(y,{__nonce__:void 0})}l=await s.transformRequest(l);let h=sc(l.body),m=this.#f(),b=zn(p);try{let _=o?()=>(this.log.print(`fetching "/api/v3/canister/${a.toText()}/call" with request:`,l),this.#o(""+new URL(`/api/v3/canister/${a.toText()}/call`,this.host),{...this.#g,...l.request,body:h})):()=>(this.log.print(`fetching "/api/v2/canister/${a.toText()}/call" with request:`,l),this.#o(""+new URL(`/api/v2/canister/${a.toText()}/call`,this.host),{...this.#g,...l.request,body:h})),{responseBodyBytes:T,...N}=await this.#_({requestFn:_,backoff:m,tries:0}),v=T.byteLength>0?or(T):null;return{requestId:b,response:{...N,body:v},requestDetails:p}}catch(y){let x;if(y instanceof Pr){if(y.hasCode(Ha))return this.log.warn("v3 api not supported. Fall back to v2"),this.call(e,{...r,callSync:!1},n);if(y.hasCode(ys)&&!this.#c)return await this.syncTime(i),this.call(i,r,n);y.code.requestContext={requestId:b,senderPubKey:l.body.sender_pubkey,senderSignature:l.body.sender_sig,ingressExpiry:l.body.content.ingress_expiry},x=y}else x=st.fromCode(new kt(y));throw this.log.error(`Error while making call: ${x.message}`,x),x}}async#x(e){let{ecid:r,transformedRequest:n,body:o,requestId:s,backoff:i,tries:a}=e,c=a===0?0:i.next();if(this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with tries:`,{tries:a,backoff:i,delay:c}),c===null)throw st.fromCode(new ms(`Backoff strategy exhausted after ${a} attempts.`,s));c>0&&await new Promise(f=>setTimeout(f,c));let d;try{this.log.print(`fetching "/api/v2/canister/${r.toString()}/query" with request:`,n);let f=await this.#o(""+new URL(`/api/v2/canister/${r.toString()}/query`,this.host),{...this.#a,...n.request,body:o});if(f.status===F0)d={...or(vi(await f.arrayBuffer())),httpDetails:{ok:f.ok,status:f.status,statusText:f.statusText,headers:Dd(f.headers)},requestId:s};else throw Me.fromCode(new ja(f.status,f.statusText,Dd(f.headers),await f.text()))}catch(f){if(a<this.#l)return this.log.warn(`Caught exception while attempting to make query:
119
- ${f}
120
- Retrying query.`),await this.#x({...e,tries:a+1});throw f instanceof Pr?f:Ma.fromCode(new $a(f))}if(!this.#y)return d;let p=d.signatures?.[0]?.timestamp;if(!p)throw Me.fromCode(new yd("Timestamp not found in query response. This suggests a malformed or malicious response."));let l=Number(BigInt(p)/BigInt(Q3));if(Date.now()+this.#r-l>this.#T){if(a<this.#l)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:s,signatureTimestampMs:l}),await this.#x({...e,tries:a+1});throw Mt.fromCode(new dd(this.#u,s,a))}return d}async#_(e){let{requestFn:r,backoff:n,tries:o}=e,s=o===0?0:n.next();if(s===null)throw Me.fromCode(new ms(`Retry strategy exhausted after ${o} attempts.`));s>0&&await new Promise(p=>setTimeout(p,s));let i,a=new Uint8Array;try{i=await r(),i.status===F0&&(a=vi(await i.clone().arrayBuffer()))}catch(p){if(o<this.#l)return this.log.warn(`Caught exception while attempting to make request:
121
- ${p}
122
- Retrying request.`),await this.#_({requestFn:r,backoff:n,tries:o+1});throw Ma.fromCode(new $a(p))}let c=Dd(i.headers);if(i.status===F0||i.status===cN)return{ok:i.ok,status:i.status,statusText:i.statusText,responseBodyBytes:a,headers:c};let d=await i.text();if(i.status===uN&&i.url.includes("api/v3"))throw Me.fromCode(new Ha);if(d.startsWith("Invalid request expiry: "))throw Ne.fromCode(new ys(d,this.#u));if(o<this.#l)return await this.#_({requestFn:r,backoff:n,tries:o+1});throw Me.fromCode(new ja(i.status,i.statusText,c,d))}async query(e,r,n){let o=this.#f(),s=r.effectiveCanisterId?se.from(r.effectiveCanisterId):se.from(e);await this.#b(s),this.log.print(`ecid ${s.toString()}`),this.log.print(`canisterId ${e.toString()}`);let i,a=await(n??this.#n);if(!a)throw mt.fromCode(new Co);let c=se.from(e),d=a.getPrincipal(),p=V0(this.#u,this.#r),l={request_type:Ts.Query,canister_id:c,method_name:r.methodName,arg:r.arg,sender:d,ingress_expiry:p},u=zn(l);i=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:Yn.Query,body:l}),i=await a.transformRequest(i);let f=sc(i.body),h={canister:c.toText(),ecid:s,transformedRequest:i,body:f,requestId:u,backoff:o,tries:0},m=async()=>{let y=await this.#x(h);return{requestDetails:l,...y}},b=async()=>{let y=this.#m.get(s.toString());if(y)return y;await this.fetchSubnetKeys(s.toString());let x=this.#m.get(s.toString());if(!x)throw Mt.fromCode(new _d);return x};try{if(!this.#y)return await m();let[y,x]=await Promise.all([m(),b()]);try{return this.#w(y,x)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#m.delete(s.toString());let _=await b();return this.#w(y,_)}}catch(y){let x;throw y instanceof Pr?(y.code.requestContext={requestId:u,senderPubKey:i.body.sender_pubkey,senderSignature:i.body.sender_sig,ingressExpiry:i.body.content.ingress_expiry},x=y):x=st.fromCode(new kt(y)),this.log.error(`Error while making query: ${x.message}`,x),x}}#w;async createReadStateRequest(e,r){await this.#b();let n=await(r??this.#n);if(!n)throw mt.fromCode(new Co);let o=n.getPrincipal(),s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#s?{Authorization:"Basic "+btoa(this.#s)}:{}}},endpoint:Yn.ReadState,body:{request_type:Ts.ReadState,paths:e.paths,sender:o,ingress_expiry:V0(this.#u,this.#r)}});return n.transformRequest(s)}async readState(e,r,n,o){await this.#E();let s=se.from(e);function i(p){for(let l of p.paths){let[u,f]=l,h=new TextEncoder().encode("request_status");if(ws(u,h))return f}}let a,c;if(o)a=o,c=zn(a);else{c=i(r);let p=await this.#n;if(!p)throw mt.fromCode(new Co);a=await this.createReadStateRequest(r,p)}this.log.print(`fetching "/api/v2/canister/${s}/read_state" with request:`,a);let d=this.#f();try{let{responseBodyBytes:p}=await this.#_({requestFn:()=>this.#o(""+new URL(`/api/v2/canister/${s.toString()}/read_state`,this.host),{...this.#a,...a.request,body:sc(a.body)}),backoff:d,tries:0}),l=or(p);return this.log.print("Read state response:",l),l}catch(p){let l;throw p instanceof Pr?(p.code.requestContext={requestId:c,senderPubKey:a.body.sender_pubkey,senderSignature:a.body.sender_sig,ingressExpiry:a.body.content.ingress_expiry},l=p):l=st.fromCode(new kt(p)),this.log.error(`Error while making read state: ${l.message}`,l),l}}parseTimeFromResponse(e){let r;if(e.certificate){let n=or(e.certificate);if(n&&"tree"in n)r=n.tree;else throw Me.fromCode(new Po("Could not decode time from response"));let o=As(["time"],r);if(o.status!==ir.Found)throw Me.fromCode(new Hn("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 Me.fromCode(new bi("Time was not in its expected format."));let s=Ui(o.value);return this.log.print("Time from response:",s),this.log.print("Time from response in milliseconds:",s.getTime()),s.getTime()}else this.log.warn("No certificate found in response");return 0}async syncTime(e){this.#i=this.#i??(async()=>{await this.#E();let r=Date.now();try{e||this.log.print("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");let n=e??se.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),o=t.createSync({identity:new xr,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 c=(await R0({canisterId:n,agent:o,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(c instanceof Date)return c.getTime()},[]))).reduce((a,c)=>typeof c=="number"&&c>a?c:a,0);i>0&&(this.#r=i-r,this.#c=!0,this.log.notify({message:`Syncing time: offset of ${this.#r}`,level:"info"}))}catch(n){let o=n instanceof Pr?n:st.fromCode(new kt(n));throw this.log.error("Caught exception while attempting to sync time",o),o}})(),await this.#i.finally(()=>{this.#i=null})}async status(){let e=this.#s?{Authorization:"Basic "+btoa(this.#s)}:{};this.log.print('fetching "/api/v2/status"');let r=this.#f(),{responseBodyBytes:n}=await this.#_({backoff:r,requestFn:()=>this.#o(""+new URL("/api/v2/status",this.host),{headers:e,...this.#a}),tries:0});return or(n)}async fetchRootKey(){return this.#e=this.#e??(async()=>{let e=await this.status();return this.rootKey=e.root_key,this.rootKey})(),await this.#e.finally(()=>{this.#e=null})}async#b(e){await Promise.all([this.#E(),this.#O(e)])}async#E(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#t)await this.fetchRootKey();else throw mt.fromCode(new dn(this.#t))}async#O(e){this.#d&&!this.hasSyncedTime()&&await this.syncTime(e)}invalidateIdentity(){this.#n=null}replaceIdentity(e){this.#n=Promise.resolve(e)}async fetchSubnetKeys(e){let r=se.from(e);await this.#b(r);let o=(await R0({canisterId:r,paths:["subnet"],agent:this})).get("subnet");if(o&&typeof o=="object"&&"nodeKeys"in o)return this.#m.set(r.toText(),o),o}_transform(e){let r=Promise.resolve(e);if(e.endpoint===Yn.Call)for(let n of this.#h)r=r.then(o=>n(o).then(s=>s||o));else for(let n of this.#p)r=r.then(o=>n(o).then(s=>s||o));return r}getTimeDiffMsecs(){return this.#r}hasSyncedTime(){return this.#c}};function V0(t,e){let r=t*U0;return Ai.fromDeltaInMilliseconds(r,e)}var fN=300*1e3;function sw(){return _N(hN(pN(),1e3),yN(1e3,1.2),mN(fN))}function pN(){let t=!0;return async()=>t?(t=!1,!0):!1}function hN(t,e){return async(r,n,o)=>{if(await t(r,n,o))return new Promise(s=>setTimeout(s,e))}}function mN(t){let e=Date.now()+t;return async(r,n,o)=>{if(Date.now()>e)throw Me.fromCode(new ms(`Request timed out after ${t} msec`,n,o))}}function yN(t,e){let r=t;return()=>new Promise(n=>setTimeout(()=>{r*=e,n()},r))}function _N(...t){return async(e,r,n)=>{for(let o of t)await o(e,r,n)}}var aw={preSignReadStateRequest:!1};function cw(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function L0(t,e){return t!==null&&typeof t=="object"&&cw(t,e)}function gN(t,e){return cw(t,e)&&typeof t[e]=="function"}function iw(t){return L0(t,"body")&&L0(t.body,"content")&&t.body.content.request_type===Ts.ReadState&&L0(t.body.content,"ingress_expiry")&&typeof t.body.content.ingress_expiry=="object"&&t.body.content.ingress_expiry!==null&&gN(t.body.content.ingress_expiry,"toHash")}async function q0(t,e,r,n={}){let o=[Ve("request_status"),r],s,i;if(n.preSignReadStateRequest??!1?(i=await xN({paths:[o],agent:t,pollingOptions:n}),s=await t.readState(e,{paths:[o]},void 0,i)):s=await t.readState(e,{paths:[o]}),t.rootKey==null)throw mt.fromCode(new dn);let c=await jo.create({certificate:s.certificate,rootKey:t.rootKey,canisterId:e,blsVerify:n.blsVerify,agent:t}),d=Ft(c.lookup_path([...o,Ve("status")])),p;switch(typeof d>"u"?p=yn.Unknown:p=new TextDecoder().decode(d),p){case yn.Replied:return{reply:Ft(c.lookup_path([...o,"reply"])),certificate:c};case yn.Received:case yn.Unknown:case yn.Processing:{let l=n.strategy??sw();return await l(e,r,p),q0(t,e,r,{...n,strategy:l,request:i})}case yn.Rejected:{let l=new Uint8Array(Ft(c.lookup_path([...o,"reject_code"])))[0],u=new TextDecoder().decode(Ft(c.lookup_path([...o,"reject_message"]))),f=Ft(c.lookup_path([...o,"error_code"])),h=f?new TextDecoder().decode(f):void 0;throw Ao.fromCode(new xi(r,l,u,h))}case yn.Done:throw st.fromCode(new pd(r))}throw Do}async function xN(t){let{paths:e,agent:r,pollingOptions:n}=t;if(n.request&&iw(n.request))return n.request;let o=await r.createReadStateRequest?.({paths:e},void 0);if(!iw(o))throw Ne.fromCode(new xd(o));return o}var Or=Symbol.for("ic-agent-metadata"),Qd=class t{static agentOf(e){return e[Or].config.agent}static interfaceOf(e){return e[Or].service}static canisterIdOf(e){return se.from(e[Or].config.canisterId)}static createActorClass(e,r){let n=e({IDL:xs});class o extends t{constructor(i){if(!i.canisterId)throw Ne.fromCode(new Ka(i.canisterId));let a=typeof i.canisterId=="string"?se.fromText(i.canisterId):i.canisterId;super({config:{...uw,...i,canisterId:a},service:n});for(let[c,d]of n._fields)r?.httpDetails&&d.annotations.push(M0),r?.certificate&&d.annotations.push(dw),this[c]=EN(this,c,d,i.blsVerify)}}return o}static createActor(e,r){if(!r.canisterId)throw Ne.fromCode(new Ka(r.canisterId));return new(this.createActorClass(e))(r)}static createActorWithHttpDetails(e,r){return new(this.createActorClass(e,{httpDetails:!0}))(r)}static createActorWithExtendedDetails(e,r,n={httpDetails:!0,certificate:!0}){return new(this.createActorClass(e,n))(r)}constructor(e){this[Or]=Object.freeze(e)}};function qi(t,e){let r=xs.decode(t,e);switch(r.length){case 0:return;case 1:return r[0];default:return r}}var uw={pollingOptions:aw},M0="http-details",dw="certificate";function EN(t,e,r,n){let o;r.annotations.includes("query")||r.annotations.includes("composite_query")?o=async(i,...a)=>{i={...i,...t[Or].config.queryTransform?.(e,a,{...t[Or].config,...i})};let c=i.agent||t[Or].config.agent||new Ds,d=se.from(i.canisterId||t[Or].config.canisterId),p=xs.encode(r.argTypes,a),l=await c.query(d,{methodName:e,arg:p,effectiveCanisterId:i.effectiveCanisterId}),u={...l.httpDetails,requestDetails:l.requestDetails};switch(l.status){case vo.Rejected:{let f=new ld(l.requestId,l.reject_code,l.reject_message,l.error_code,l.signatures);throw f.callContext={canisterId:d,methodName:e,httpDetails:u},Ao.fromCode(f)}case vo.Replied:return r.annotations.includes(M0)?{httpDetails:u,result:qi(r.retTypes,l.reply.arg)}:qi(r.retTypes,l.reply.arg)}}:o=async(i,...a)=>{i={...i,...t[Or].config.callTransform?.(e,a,{...t[Or].config,...i})};let c=i.agent||t[Or].config.agent||Ds.createSync(),{canisterId:d,effectiveCanisterId:p,pollingOptions:l}={...uw,...t[Or].config,...i},u=se.from(d),f=p!==void 0?se.from(p):u,h=xs.encode(r.argTypes,a),{requestId:m,response:b,requestDetails:y}=await c.call(u,{methodName:e,arg:h,effectiveCanisterId:f,nonce:i.nonce}),x,_;if(og(b.body)){if(c.rootKey==null)throw mt.fromCode(new dn);let R=b.body.certificate;_=await jo.create({certificate:R,rootKey:c.rootKey,canisterId:f,blsVerify:n,agent:c});let A=[Ve("request_status"),m];switch(new TextDecoder().decode(Ft(_.lookup_path([...A,"status"])))){case"replied":x=Ft(_.lookup_path([...A,"reply"]));break;case"rejected":{let S=new Uint8Array(Ft(_.lookup_path([...A,"reject_code"])))[0],V=new TextDecoder().decode(Ft(_.lookup_path([...A,"reject_message"]))),C=Ft(_.lookup_path([...A,"error_code"])),g=C?new TextDecoder().decode(C):void 0,w=new xi(m,S,V,g);throw w.callContext={canisterId:u,methodName:e,httpDetails:b},Ao.fromCode(w)}}}else if(ng(b.body)){let{reject_code:R,reject_message:A,error_code:E}=b.body,S=new fd(m,R,A,E);throw S.callContext={canisterId:u,methodName:e,httpDetails:b},Ao.fromCode(S)}if(b.status===202){let R={...l,blsVerify:n},A=await q0(c,f,m,R);_=A.certificate,x=A.reply}let T=r.annotations.includes(M0),N=r.annotations.includes(dw),v={...b,requestDetails:y};if(x!==void 0)return T&&N?{httpDetails:v,certificate:_,result:qi(r.retTypes,x)}:N?{certificate:_,result:qi(r.retTypes,x)}:T?{httpDetails:v,result:qi(r.retTypes,x)}:qi(r.retTypes,x);{let R=new kt(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${r.retTypes.map(A=>A.display()).join(",")}].`);throw R.callContext={canisterId:u,methodName:e,httpDetails:v},st.fromCode(R)}};let s=(...i)=>o({},...i);return s.withOptions=i=>(...a)=>o(i,...a),s}var yw=Fe(De(),1);var Zt=Fe(De(),1),ww=Fe(De(),1),TN=({authData:t})=>{if(t.byteLength<37)return{invalidAuthData:null};if(t.byteLength<53)return{invalidAuthData:null};let e=t.slice(37,53),r=ON({bytes:e});return"aaguid"in r?{aaguidBytes:e,aaguidText:r.aaguid}:{unknownProvider:null}},ON=({bytes:t})=>{if(t.length!==16)return{invalidBytes:null};let e=(t instanceof Uint8Array?(0,mw.uint8ArrayToArrayOfNumber)(t):t).map(r=>r.toString(16).padStart(2,"0")).join("").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/,"$1-$2-$3-$4-$5");return e==="00000000-0000-0000-0000-000000000000"?{unknownProvider:null}:{aaguid:e}};function NN(t){let e=new DataView(new ArrayBuffer(2)),r=t.slice(53,55);[...new Uint8Array(r)].forEach((o,s)=>e.setUint8(s,o));let n=e.getUint16(0);return t.slice(55+n)}function vN(t){return Cs(t,xc)}var RN=class{constructor(t){this._cose=t,this.#e=vN(t)}#e;toDer(){return this.#e}toRaw(){return new Uint8Array(this.#e)}},_w=class{#e;#t;constructor({rawId:t,cose:e}){this.#e=t,this.#t=new RN(e)}getPublicKey(){return this.#t}getCredentialId(){return this.#e}getCredentialIdText(){return(0,yw.uint8ArrayToBase64)(this.#e)}},IN=class extends _w{#e;#t;constructor({authData:t,...e}){super(e);let r=TN({authData:t});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}},SN=class extends _w{},AN=class extends Error{},BN=class extends Error{},CN=class extends Error{},PN=class extends Error{},DN=class extends Error{},FN=class extends Error{},VN=class extends Error{},lw=class extends Error{};var UN={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},LN=6e4,bw=()=>window.crypto.getRandomValues(new Uint8Array(16)),qN=()=>bw(),MN=()=>bw(),kN=()=>{let{location:{href:t}}=window;try{let{hostname:e}=new URL(t);return e}catch{throw new AN}},gw=({appId:t})=>t?.id??kN(),jN=({appId:t,user:e}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:t?.name??r,id:gw({appId:t})}}),o=()=>({user:{id:MN(),name:e?.name??e?.displayName??r,displayName:e?.displayName??r}});return{attestation:"direct",challenge:qN(),...n(),...o(),pubKeyCredParams:Object.values(UN).map(s=>({type:"public-key",alg:s})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},HN=(t={})=>({rpId:gw(t),allowCredentials:[],userVerification:"required"}),k0=async({fn:t,step:e,onProgress:r})=>{r?.({step:e,state:"in_progress"});try{let n=await t();return r?.({step:e,state:"success"}),n}catch(n){throw r?.({step:e,state:"error"}),n}},Ko=(t=>(t[t.RequestingUserCredential=0]="RequestingUserCredential",t[t.FinalizingCredential=1]="FinalizingCredential",t[t.Signing=2]="Signing",t))(Ko||{}),xw=({timeout:t})=>AbortSignal.timeout(t??LN),$N=async({challenge:t,credentialIds:e,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...HN(r),challenge:t.buffer,allowCredentials:(e??[]).map(o=>({id:o.buffer,type:"public-key"}))},signal:xw({timeout:n})}),fw=t=>{if(t.status!=="initialized")throw new BN},pw=t=>{if((0,Zt.isNullish)(t))throw new CN},hw=({type:t})=>{if(t!=="public-key")throw new PN},j0=class wc extends mn{#e;#t;constructor({onProgress:e,...r}){if(super(),this.#e=e,"retrievePublicKey"in r){let{retrievePublicKey:n}=r;this.#t={status:"pending",retrievePublicKey:n};return}this.#t=wc.#r({credential:new IN(r)})}static#r({credential:e}){return{status:"initialized",credential:e}}static async createWithNewCredential({passkeyOptions:e,timeout:r,...n}={}){let o=await navigator.credentials.create({publicKey:jN(e),signal:xw({timeout:r})});pw(o),hw(o);let{response:{attestationObject:s},rawId:i}=o;if((0,Zt.isNullish)(s))throw new DN;let{authData:a}=Bd.decode((0,Zt.arrayBufferToUint8Array)(s)),c=NN(a);return new wc({...n,rawId:(0,Zt.arrayBufferToUint8Array)(i),cose:c,authData:a})}static async createWithExistingCredential(e){return new wc(e)}getPublicKey(){fw(this.#t);let{credential:e}=this.#t;return e.getPublicKey()}getCredential(){fw(this.#t);let{credential:e}=this.#t;return e}async sign(e){let r=await k0({fn:async()=>{let n=await $N({challenge:e,...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return pw(n),hw(n),n},step:0,onProgress:this.#e});return await k0({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!(0,Zt.uint8ArraysEqual)({a:this.#t.credential.getCredentialId(),b:(0,Zt.arrayBufferToUint8Array)(n)}))throw new FN;return}let{retrievePublicKey:o}=this.#t,s=await o({credentialId:(0,Zt.arrayBufferToUint8Array)(n)});this.#t=wc.#r({credential:new SN({rawId:(0,Zt.arrayBufferToUint8Array)(n),cose:s})})},step:1,onProgress:this.#e}),await k0({fn:async()=>{let{response:n}=r,{clientDataJSON:o}=n,{authenticatorData:s,signature:i}="authenticatorData"in n&&"signature"in n?n:{};if((0,Zt.isNullish)(s))throw new lw;if((0,Zt.isNullish)(i))throw new lw;let a=Bd.encode({authenticator_data:s,client_data_json:new TextDecoder().decode(o),signature:(0,Zt.arrayBufferToUint8Array)(i)});if((0,Zt.isNullish)(a))throw new VN;return Object.assign(a,{__signature__:void 0}),a},step:2,onProgress:this.#e})}},KN=async()=>(0,ww.nonNullish)(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var O1=Fe(De(),1);var Mi=class{callbacks=[];populate(e){this.callbacks.forEach(({callback:r})=>r(e))}subscribe(e){let r=Symbol();return this.callbacks.push({id:r,callback:e}),()=>this.callbacks=this.callbacks.filter(({id:n})=>n!==r)}};var Nr=class t extends Mi{static instance;authUser=null;constructor(){super()}static getInstance(){return t.instance||(t.instance=new t),t.instance}set(e){this.authUser=e,this.populate(e)}get(){return this.authUser}subscribe(e){let r=super.subscribe(e);return e(this.authUser),r}reset(){this.authUser=null,this.populate(this.authUser)}};var H0=({message:t,detail:e})=>{let r=new CustomEvent(t,{detail:e,bubbles:!0});document.dispatchEvent(r)};var T1=Fe(De(),1);var tl=Fe(De(),1);var el=Fe(De(),1);var $0=Fe(De(),1);var ki="http://127.0.0.1:5987",Ew="rdmx6-jaaaa-aaaaa-aaadq-cai";var Tw=async({identity:t,container:e})=>{let n=(0,$0.nonNullish)(e)&&e!==!1?e===!0?ki:e:"https://icp-api.io",o=(0,$0.nonNullish)(e);return await Ds.create({identity:t,shouldFetchRootKey:o,host:n})};var ji=class t{static instance;#e=void 0;constructor(){}static getInstance(){return(0,el.isNullish)(t.instance)&&(t.instance=new t),t.instance}async getAgent({identity:e,...r}){let n=e.getPrincipal().toText();if((0,el.isNullish)(this.#e)||(0,el.isNullish)(this.#e[n])){let o=await Tw({identity:e,...r});return this.#e={...this.#e??{},[n]:o},o}return this.#e[n]}reset(){this.#e=null}};var Hi=class t{static instance;#e=void 0;constructor(){}static getInstance(){return(0,tl.isNullish)(t.instance)&&(t.instance=new t),t.instance}async getActor({satelliteId:e,identity:r,actorKey:n,...o}){let s=`${n}#${r.getPrincipal().toText()}#${e};`;if((0,tl.isNullish)(this.#e)||(0,tl.isNullish)(this.#e[s])){let i=await this.createActor({satelliteId:e,identity:r,...o});return this.#e={...this.#e??{},[s]:i},i}return this.#e[s]}reset(){this.#e=null}async createActor({idlFactory:e,satelliteId:r,...n}){let o=await ji.getInstance().getAgent(n);return Qd.createActor(e,{agent:o,canisterId:r})}};var Ow=t=>(t.preventDefault(),t.returnValue="Are you sure you want to exit?"),GN=()=>{window.addEventListener("beforeunload",Ow,{capture:!0})},zN=()=>{window.removeEventListener("beforeunload",Ow,{capture:!0})},K0=async({fn:t})=>{try{return GN(),await t()}finally{zN()}};var qs=Fe(De(),1);var lr=class t extends Mi{static instance;env;constructor(){super()}static getInstance(){return t.instance||(t.instance=new t),t.instance}set(e){this.env=e,this.populate(e)}get(){return this.env}reset(){this.env=null}subscribe(e){let r=super.subscribe(e);return e(this.env),r}};var Nw=BigInt(144e11),vw=!1,Rw={width:576,height:576},Iw={width:424,height:576},Sw={width:505,height:705},Ec="internetcomputer.org",Aw="ic0.app",Bw="id.ai";var G0=Fe(De(),1);var rl=Fe(De(),1),Cw=async t=>{let e=new Blob([JSON.stringify(t,rl.jsonReplacer)],{type:"application/json; charset=utf-8"});return new Uint8Array(await e.arrayBuffer())},nl=async t=>{let e=new Blob([t instanceof Uint8Array?t:new Uint8Array(t)],{type:"application/json; charset=utf-8"});return JSON.parse(await e.text(),rl.jsonReviver)},ol=()=>typeof window<"u";var sl=({width:t,height:e})=>{if(!ol()||(0,G0.isNullish)(window)||(0,G0.isNullish)(window.top))return;let{top:{innerWidth:r,innerHeight:n}}=window,o=n/2+screenY-e/2,s=r/2+screenX-t/2;return`toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=${t}, height=${e}, top=${o}, left=${s}`};function Pw(t){return t!==null&&typeof t=="object"}var Tc=class t{static from(e){if(typeof e=="string"){let r=ht(e);return this.fromRaw(r)}else if(Pw(e)){let r=e;if(Pw(r)&&Object.hasOwnProperty.call(r,"__derEncodedPublicKey__"))return this.fromDer(r);if(ArrayBuffer.isView(r)){let n=r;return this.fromRaw(ln(n.buffer))}else{if(r instanceof ArrayBuffer)return this.fromRaw(ln(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(e){return new t(e)}static fromDer(e){return new t(this.derDecode(e))}static{this.RAW_KEY_LENGTH=32}static derEncode(e){let r=Cs(e,Bs);return r.__derEncodedPublicKey__=void 0,r}static derDecode(e){let r=Ps(e,Bs);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(e){if(e.byteLength!==t.RAW_KEY_LENGTH)throw new Error("An Ed25519 public key must be exactly 32bytes long");this.#e=e,this.#t=t.derEncode(e)}toDer(){return this.derKey}toRaw(){return this.rawKey}},$i=class t extends mn{static generate(e){if(e&&e.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");e||(e=zt.utils.randomPrivateKey()),Ng(e,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]=e[o];let n=zt.getPublicKey(r);return t.fromKeyPair(n,r)}static fromParsedJson(e){let[r,n]=e;return new t(Tc.fromDer(ht(r)),ht(n))}static fromJSON(e){let r=JSON.parse(e);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(e)}`)}static fromKeyPair(e,r){return new t(Tc.fromRaw(e),r)}static fromSecretKey(e){let r=zt.getPublicKey(e);return t.fromKeyPair(r,e)}#e;#t;constructor(e,r){super(),this.#e=Tc.from(e),this.#t=r}toJSON(){return[ue(this.#e.toDer()),ue(this.#t)]}getKeyPair(){return{secretKey:this.#t,publicKey:this.#e}}getPublicKey(){return this.#e}async sign(e){let r=zt.sign(e,this.#t.slice(0,32));return Object.defineProperty(r,"__signature__",{enumerable:!1,value:void 0}),r}static verify(e,r,n){let[o,s,i]=[e,r,n].map(a=>(typeof a=="string"&&(a=ht(a)),ln(a)));return zt.verify(o,s,i)}};var z0=class t extends Error{constructor(e){super(e),this.message=e,Object.setPrototypeOf(this,t.prototype)}};function Dw(t){if(typeof global<"u"&&global.crypto&&global.crypto.subtle)return global.crypto.subtle;if(t)return t;if(typeof crypto<"u"&&crypto.subtle)return crypto.subtle;throw new z0("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 Fs=class t extends mn{static async generate(e){let{extractable:r=!1,keyUsages:n=["sign","verify"],subtleCrypto:o}=e??{},s=Dw(o),i=await s.generateKey({name:"ECDSA",namedCurve:"P-256"},r,n),a=ln(await s.exportKey("spki",i.publicKey));return Object.assign(a,{__derEncodedPublicKey__:void 0}),new this(i,a,s)}static async fromKeyPair(e,r){let n=Dw(r),o=ln(await n.exportKey("spki",e.publicKey));return Object.assign(o,{__derEncodedPublicKey__:void 0}),new t(e,o,n)}constructor(e,r,n){super(),this._keyPair=e,this._derKey=r,this._subtleCrypto=n}getKeyPair(){return this._keyPair}getPublicKey(){let e=this._derKey,r=Object.create(this._keyPair.publicKey);return r.toDer=function(){return e},r}async sign(e){let r={name:"ECDSA",hash:{name:"SHA-256"}},n=ln(await this._subtleCrypto.sign(r,this._keyPair.privateKey,e));return Object.assign(n,{__signature__:void 0}),n}};var il=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 se.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(e){this.#e=e}};function Z0(t){if(typeof t!="string"||t.length<64)throw new Error("Invalid public key.");return ht(t)}var Ki=class{constructor(e,r,n){this.pubkey=e,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:ue(this.pubkey),...this.targets&&{targets:this.targets.map(e=>e.toHex())}}}};async function ZN(t,e,r,n){let o=new Ki(e.toDer(),BigInt(+r)*BigInt(1e6),n),s=new Uint8Array([...Gh,...new Uint8Array(zn({...o}))]),i=await t.sign(s);return{delegation:o,signature:i}}var Vs=class t{static async create(e,r,n=new Date(Date.now()+900*1e3),o={}){let s=await ZN(e,r,n,o.targets);return new t([...o.previous?.delegations||[],s],o.previous?.publicKey||e.getPublicKey().toDer())}static fromJSON(e){let{publicKey:r,delegations:n}=typeof e=="string"?JSON.parse(e):e;if(!Array.isArray(n))throw new Error("Invalid delegations.");let o=n.map(s=>{let{delegation:i,signature:a}=s,{pubkey:c,expiration:d,targets:p}=i;if(p!==void 0&&!Array.isArray(p))throw new Error("Invalid targets.");return{delegation:new Ki(Z0(c),BigInt("0x"+d),p&&p.map(l=>{if(typeof l!="string")throw new Error("Invalid target.");return se.fromHex(l)})),signature:Z0(a)}});return new this(o,Z0(r))}static fromDelegations(e,r){return new this(e,r)}constructor(e,r){this.delegations=e,this.publicKey=r}toJSON(){return{delegations:this.delegations.map(e=>{let{delegation:r,signature:n}=e,{targets:o}=r;return{delegation:{expiration:r.expiration.toString(16),pubkey:ue(r.pubkey),...o&&{targets:o.map(s=>s.toHex())}},signature:ue(n)}}),publicKey:ue(this.publicKey)}}},Us=class extends mn{static fromDelegation(e,r){return new this(e,r)}constructor(e,r){super(),this._inner=e,this._delegation=r}getDelegation(){return this._delegation}getPublicKey(){return{derKey:this._delegation.publicKey,toDer:()=>this._delegation.publicKey}}sign(e){return this._inner.sign(e)}async transformRequest(e){let{body:r,...n}=e,o=await zn(r);return{...n,body:{content:r,sender_sig:await this.sign(new Uint8Array([...ec,...new Uint8Array(o)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}}}},Oc=class t extends il{#e;get delegation(){return this.#e}constructor(e,r){super(e),this.#e=r}static fromDelegation(e,r){return new t(e,r)}};function Y0(t,e){for(let{delegation:o}of t.delegations)if(+new Date(Number(o.expiration/BigInt(1e6)))<=+Date.now())return!1;let r=[],n=e?.scope;n&&(Array.isArray(n)?r.push(...n.map(o=>typeof o=="string"?se.fromText(o):o)):r.push(typeof n=="string"?se.fromText(n):n));for(let o of r){let s=o.toText();for(let{delegation:i}of t.delegations){if(i.targets===void 0)continue;let a=!0;for(let c of i.targets)if(c.toText()===s){a=!1;break}if(a)return!1}}return!0}var Fw=["mousedown","mousemove","keydown","touchstart","wheel"],Nc=class{callbacks=[];idleTimeout=600*1e3;timeoutID=void 0;static create(e={}){return new this(e)}constructor(e={}){let{onIdle:r,idleTimeout:n=600*1e3}=e||{};this.callbacks=r?[r]:[],this.idleTimeout=n;let o=this._resetTimer.bind(this);window.addEventListener("load",o,!0),Fw.forEach(function(i){document.addEventListener(i,o,!0)});let s=(i,a)=>{let c;return(...d)=>{let p=this,l=function(){c=void 0,i.apply(p,d)};clearTimeout(c),c=window.setTimeout(l,a)}};if(e?.captureScroll){let i=s(o,e?.scrollDebounce??100);window.addEventListener("scroll",i,!0)}o()}registerCallback(e){this.callbacks.push(e)}exit(){clearTimeout(this.timeoutID),window.removeEventListener("load",this._resetTimer,!0);let e=this._resetTimer.bind(this);Fw.forEach(function(r){document.removeEventListener(r,e,!0)}),this.callbacks.forEach(r=>r())}_resetTimer(){let e=this.exit.bind(this);window.clearTimeout(this.timeoutID),this.timeoutID=window.setTimeout(e,this.idleTimeout)}};var YN=(t,e)=>e.some(r=>t instanceof r),Vw,Uw;function WN(){return Vw||(Vw=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function XN(){return Uw||(Uw=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var Lw=new WeakMap,X0=new WeakMap,qw=new WeakMap,W0=new WeakMap,Q0=new WeakMap;function JN(t){let e=new Promise((r,n)=>{let o=()=>{t.removeEventListener("success",s),t.removeEventListener("error",i)},s=()=>{r(_n(t.result)),o()},i=()=>{n(t.error),o()};t.addEventListener("success",s),t.addEventListener("error",i)});return e.then(r=>{r instanceof IDBCursor&&Lw.set(r,t)}).catch(()=>{}),Q0.set(e,t),e}function QN(t){if(X0.has(t))return;let e=new Promise((r,n)=>{let o=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",i),t.removeEventListener("abort",i)},s=()=>{r(),o()},i=()=>{n(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",s),t.addEventListener("error",i),t.addEventListener("abort",i)});X0.set(t,e)}var J0={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return X0.get(t);if(e==="objectStoreNames")return t.objectStoreNames||qw.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return _n(t[e])},set(t,e,r){return t[e]=r,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};function Mw(t){J0=t(J0)}function ev(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(al(this),e,...r);return qw.set(n,e.sort?e.sort():[e]),_n(n)}:XN().includes(t)?function(...e){return t.apply(al(this),e),_n(Lw.get(this))}:function(...e){return _n(t.apply(al(this),e))}}function tv(t){return typeof t=="function"?ev(t):(t instanceof IDBTransaction&&QN(t),YN(t,WN())?new Proxy(t,J0):t)}function _n(t){if(t instanceof IDBRequest)return JN(t);if(W0.has(t))return W0.get(t);let e=tv(t);return e!==t&&(W0.set(t,e),Q0.set(e,t)),e}var al=t=>Q0.get(t);function jw(t,e,{blocked:r,upgrade:n,blocking:o,terminated:s}={}){let i=indexedDB.open(t,e),a=_n(i);return n&&i.addEventListener("upgradeneeded",c=>{n(_n(i.result),c.oldVersion,c.newVersion,_n(i.transaction),c)}),r&&i.addEventListener("blocked",c=>r(c.oldVersion,c.newVersion,c)),a.then(c=>{s&&c.addEventListener("close",()=>s()),o&&c.addEventListener("versionchange",d=>o(d.oldVersion,d.newVersion,d))}).catch(()=>{}),a}var rv=["get","getKey","getAll","getAllKeys","count"],nv=["put","add","delete","clear"],em=new Map;function kw(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(em.get(e))return em.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,o=nv.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||rv.includes(r)))return;let s=async function(i,...a){let c=this.transaction(i,o?"readwrite":"readonly"),d=c.store;return n&&(d=d.index(a.shift())),(await Promise.all([d[r](...a),o&&c.done]))[0]};return em.set(e,s),s}Mw(t=>({...t,get:(e,r,n)=>kw(e,r)||t.get(e,r,n),has:(e,r)=>!!kw(e,r)||t.has(e,r)}));var Hw="auth-client-db",$w="ic-keyval",ov=async(t=Hw,e=$w,r)=>(cl&&localStorage?.getItem(fr)&&(localStorage.removeItem(fr),localStorage.removeItem(Yt)),await jw(t,r,{upgrade:n=>{n.objectStoreNames.contains(e)&&n.clear(e),n.createObjectStore(e)}}));async function sv(t,e,r){return await t.get(e,r)}async function iv(t,e,r,n){return await t.put(e,n,r)}async function av(t,e,r){return await t.delete(e,r)}var vc=class t{_db;_storeName;static async create(e){let{dbName:r=Hw,storeName:n=$w,version:o=Kw}=e??{},s=await ov(r,n,o);return new t(s,n)}constructor(e,r){this._db=e,this._storeName=r}async set(e,r){return await iv(this._db,this._storeName,e,r)}async get(e){return await sv(this._db,this._storeName,e)??null}async remove(e){return await av(this._db,this._storeName,e)}};var Yt="identity",fr="delegation",Gw="iv",Kw=1,cl=typeof window<"u",Rc=class{prefix;_localStorage;constructor(e="ic-",r){this.prefix=e,this._localStorage=r}get(e){return Promise.resolve(this._getLocalStorage().getItem(this.prefix+e))}set(e,r){return this._getLocalStorage().setItem(this.prefix+e,r),Promise.resolve()}remove(e){return this._getLocalStorage().removeItem(this.prefix+e),Promise.resolve()}_getLocalStorage(){if(this._localStorage)return this._localStorage;let e=typeof window>"u"?typeof global>"u"?typeof self>"u"?void 0:self.localStorage:global.localStorage:window.localStorage;if(!e)throw new Error("Could not find local storage.");return e}},oo=class{#e;constructor(e){this.#e=e??{}}initializedDb;get _db(){return new Promise(e=>{if(this.initializedDb){e(this.initializedDb);return}vc.create(this.#e).then(r=>{this.initializedDb=r,e(r)})})}async get(e){return await(await this._db).get(e)}async set(e,r){await(await this._db).set(e,r)}async remove(e){await(await this._db).remove(e)}};var cv=BigInt(1e9),uv=BigInt(3600),dv=cv*uv,lv="https://identity.internetcomputer.org",fv="#authorize",pv=BigInt(8)*dv,tm="ECDSA",rm="Ed25519",hv=500,om="UserInterrupt",ul=class{_identity;_key;_chain;_storage;idleManager;_createOptions;_idpWindow;_eventHandler;static async create(e={}){let r=e.storage??new oo,n=e.keyType??tm,o=null;if(e.identity)o=e.identity;else{let c=await r.get(Yt);if(!c&&cl)try{let d=new Rc,p=await d.get(fr),l=await d.get(Yt);p&&l&&n===tm&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await r.set(fr,p),await r.set(Yt,l),c=p,await d.remove(fr),await d.remove(Yt))}catch(d){console.error("error while attempting to recover localstorage: "+d)}if(c)try{typeof c=="object"?n===rm&&typeof c=="string"?o=$i.fromJSON(c):o=await Fs.fromKeyPair(c):typeof c=="string"&&(o=$i.fromJSON(c))}catch{}}let s=new xr,i=null;if(o)try{let c=await r.get(fr);if(typeof c=="object"&&c!==null)throw new Error("Delegation chain is incorrectly stored. A delegation chain should be stored as a string.");e.identity?s=e.identity:c&&(i=Vs.fromJSON(c),Y0(i)?"toDer"in o?s=Oc.fromDelegation(o,i):s=Us.fromDelegation(o,i):(await nm(r),o=null))}catch(c){console.error(c),await nm(r),o=null}let a;return e.idleOptions?.disableIdle?a=void 0:(i||e.identity)&&(a=Nc.create(e.idleOptions)),o||(n===rm?(o=$i.generate(),await r.set(Yt,JSON.stringify(o.toJSON()))):(e.storage&&n===tm&&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 '${rm}' as the key type, as it can serialize to a string`),o=await Fs.generate(),await r.set(Yt,o.getKeyPair()))),new this(s,o,i,r,a,e)}constructor(e,r,n,o,s,i,a,c){this._identity=e,this._key=r,this._chain=n,this._storage=o,this.idleManager=s,this._createOptions=i,this._idpWindow=a,this._eventHandler=c,this._registerDefaultIdleCallback()}_registerDefaultIdleCallback(){let e=this._createOptions?.idleOptions;!e?.onIdle&&!e?.disableDefaultIdleCallback&&this.idleManager?.registerCallback(()=>{this.logout(),location.reload()})}async _handleSuccess(e,r){let n=e.delegations.map(a=>({delegation:new Ki(a.delegation.pubkey,a.delegation.expiration,a.delegation.targets),signature:a.signature})),o=Vs.fromDelegations(n,e.userPublicKey),s=this._key;if(!s)return;this._chain=o,"toDer"in s?this._identity=Oc.fromDelegation(s,this._chain):this._identity=Us.fromDelegation(s,this._chain),this._idpWindow?.close();let i=this._createOptions?.idleOptions;!this.idleManager&&!i?.disableIdle&&(this.idleManager=Nc.create(i),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(fr,JSON.stringify(this._chain.toJSON())),r?.(e)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null&&Y0(this._chain)}async login(e){let r=mv(this._createOptions?.loginOptions,e),n=r?.maxTimeToLive??pv,o=new URL(r?.identityProvider?.toString()||lv);o.hash=fv,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 s=()=>{this._idpWindow&&(this._idpWindow.closed?this._handleFailure(om,r?.onError):setTimeout(s,hv))};s()}_getEventHandler(e,r){return async n=>{if(n.origin!==e.origin)return;let o=n.data;switch(o.kind){case"authorize-ready":{let s={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(s,e.origin);break}case"authorize-client-success":try{await this._handleSuccess(o,r?.onSuccess)}catch(s){this._handleFailure(s.message,r?.onError)}break;case"authorize-client-failure":this._handleFailure(o.text,r?.onError);break;default:break}}}_handleFailure(e,r){this._idpWindow?.close(),r?.(e),this._removeEventListener(),delete this._idpWindow}_removeEventListener(){this._eventHandler&&window.removeEventListener("message",this._eventHandler),this._eventHandler=void 0}async logout(e={}){if(await nm(this._storage),this._identity=new xr,this._chain=null,e.returnTo)try{window.history.pushState({},"",e.returnTo)}catch{window.location.href=e.returnTo}}};async function nm(t){await t.remove(Yt),await t.remove(fr),await t.remove(Gw)}function mv(t,e){if(!t&&!e)return;let r=t?.customValues||e?.customValues?{...t?.customValues,...e?.customValues}:void 0;return{...t,...e,customValues:r}}var Zw=Fe(De(),1);var bn=async({fn:t,step:e,onProgress:r})=>{r?.({step:e,state:"in_progress"});try{let n=await t();return r?.({step:e,state:"success"}),n}catch(n){throw r?.({step:e,state:"error"}),n}};var zw=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))(zw||{});var dl=class extends Error{},Ls=class extends Error{},ll=class extends Error{},fl=class extends Error{},pl=class extends Error{},hl=class extends Error{},ml=class extends Error{},yl=class extends Error{};var Gi=class{async signIn({options:e,authClient:r,initAuth:n}){await bn({fn:async()=>await this.#e({options:e,authClient:r}),step:0,onProgress:e?.onProgress}),await bn({fn:async()=>await n({provider:this.id}),step:1,onProgress:e?.onProgress})}#e({options:e,authClient:r}){return new Promise(async(n,o)=>{if((0,Zw.isNullish)(r)){o(new Ls("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:s=>{if(s===om){o(new ll(s));return}o(new dl(s))},maxTimeToLive:e?.maxTimeToLiveInNanoseconds??Nw,allowPinAuthentication:e?.allowPin??vw,...e?.derivationOrigin!==void 0&&{derivationOrigin:e.derivationOrigin},...this.signInOptions({windowed:e?.windowed})})})}};var _l=class extends Gi{#e;constructor({domain:e}){super(),this.#e=e}get id(){return"internet_identity"}signInOptions({windowed:e}){let n=(()=>{let s=lr.getInstance().get()?.container;if((0,qs.isNullish)(s)||s===!1){let p=[Ec,Aw].includes(this.#e??Ec);return(0,qs.isEmptyString)(this.#e)?`https://identity.${Ec}`:p?`https://identity.${this.#e??Ec}`:`https://${this.#e}`}let i=lr.getInstance().get(),a=(0,qs.nonNullish)(i)&&(0,qs.nonNullish)(i?.internetIdentityId)?i.internetIdentityId:Ew,{host:c,protocol:d}=new URL(s===!0?ki:s);return/apple/i.test(navigator?.vendor)?`${d}//${c}?canisterId=${a}`:`${d}//${a}.${c.replace("127.0.0.1","localhost")}`})();return{...e!==!1&&{windowOpenerFeatures:sl((()=>{try{let{hostname:s}=new URL(n);return s.includes(Bw)}catch{return!1}})()?Iw:Rw)},identityProvider:n}}};var bl=class extends Gi{#e;#t;constructor({appName:e,logoUrl:r}){super(),this.#e=e,this.#t=r}get id(){return"nfid"}signInOptions({windowed:e}){return{...e!==!1&&{windowOpenerFeatures:sl(Sw)},identityProvider:`https://nfid.one/authenticate/?applicationName=${encodeURI(this.#e)}&applicationLogo=${encodeURI(this.#t)}`}}};var zi=Fe(De(),1);var gn={certified:!1};var Yw=Fe(De(),1);var Ye=t=>(0,Yw.nonNullish)(t)?t:gl()??new xr;var jr=Fe(De(),1);var Qw=Fe(De(),1);var yv=Fe(De(),1),_v=Fe(De(),1);var Ww=({IDL:t})=>{let e=t.Variant({Heap:t.Null,Stable:t.Null}),r=t.Record({system_memory:t.Opt(e)}),n=t.Record({controllers:t.Vec(t.Principal),storage:t.Opt(r)}),o=t.Record({batch_id:t.Nat,headers:t.Vec(t.Tuple(t.Text,t.Text)),chunk_ids:t.Vec(t.Nat)}),s=t.Record({sha256:t.Vec(t.Nat8),proposal_id:t.Nat}),i=t.Variant({UpdatedAt:t.Null,Keys:t.Null,CreatedAt:t.Null}),a=t.Record({field:i,desc:t.Bool}),c=t.Variant({Equal:t.Nat64,Between:t.Tuple(t.Nat64,t.Nat64),GreaterThan:t.Nat64,LessThan:t.Nat64}),d=t.Record({key:t.Opt(t.Text),updated_at:t.Opt(c),description:t.Opt(t.Text),created_at:t.Opt(c)}),p=t.Record({start_after:t.Opt(t.Text),limit:t.Opt(t.Nat64)}),l=t.Record({order:t.Opt(a),owner:t.Opt(t.Principal),matcher:t.Opt(d),paginate:t.Opt(p)}),u=t.Record({controllers:t.Vec(t.Principal)}),f=t.Variant({Write:t.Null,Admin:t.Null,Submit:t.Null}),h=t.Record({updated_at:t.Nat64,metadata:t.Vec(t.Tuple(t.Text,t.Text)),created_at:t.Nat64,scope:f,expires_at:t.Opt(t.Nat64)}),m=t.Record({version:t.Opt(t.Nat64)}),b=t.Variant({Db:t.Null,Storage:t.Null}),y=t.Record({version:t.Opt(t.Nat64)}),x=t.Record({proposal_ids:t.Vec(t.Nat)}),_=t.Record({cycles:t.Nat,destination_id:t.Principal}),T=t.Record({token:t.Opt(t.Text),collection:t.Text,owner:t.Principal,name:t.Text,description:t.Opt(t.Text),full_path:t.Text}),N=t.Record({modified:t.Nat64,sha256:t.Vec(t.Nat8),total_length:t.Nat}),v=t.Record({key:T,updated_at:t.Nat64,encodings:t.Vec(t.Tuple(t.Text,N)),headers:t.Vec(t.Tuple(t.Text,t.Text)),created_at:t.Nat64,version:t.Opt(t.Nat64)}),R=t.Record({derivation_origin:t.Opt(t.Text),external_alternative_origins:t.Opt(t.Vec(t.Text))}),A=t.Record({allowed_callers:t.Vec(t.Principal)}),E=t.Record({updated_at:t.Opt(t.Nat64),created_at:t.Opt(t.Nat64),version:t.Opt(t.Nat64),internet_identity:t.Opt(R),rules:t.Opt(A)}),S=t.Record({stable:t.Opt(t.Nat64),heap:t.Opt(t.Nat64)}),V=t.Record({updated_at:t.Opt(t.Nat64),created_at:t.Opt(t.Nat64),version:t.Opt(t.Nat64),max_memory_size:t.Opt(S)}),C=t.Variant({Deny:t.Null,AllowAny:t.Null,SameOrigin:t.Null}),g=t.Variant({Deny:t.Null,Allow:t.Null}),w=t.Record({status_code:t.Nat16,location:t.Text}),O=t.Record({iframe:t.Opt(C),updated_at:t.Opt(t.Nat64),rewrites:t.Vec(t.Tuple(t.Text,t.Text)),headers:t.Vec(t.Tuple(t.Text,t.Vec(t.Tuple(t.Text,t.Text)))),created_at:t.Opt(t.Nat64),version:t.Opt(t.Nat64),max_memory_size:t.Opt(S),raw_access:t.Opt(g),redirects:t.Opt(t.Vec(t.Tuple(t.Text,w)))}),P=t.Record({db:t.Opt(V),authentication:t.Opt(E),storage:O}),L=t.Record({updated_at:t.Nat64,owner:t.Principal,data:t.Vec(t.Nat8),description:t.Opt(t.Text),created_at:t.Nat64,version:t.Opt(t.Nat64)}),I=t.Variant({Initialized:t.Null,Failed:t.Null,Open:t.Null,Rejected:t.Null,Executed:t.Null,Accepted:t.Null}),B=t.Record({clear_existing_assets:t.Opt(t.Bool)}),F=t.Record({orbiter:t.Opt(t.Text),mission_control_version:t.Opt(t.Text),satellite_version:t.Opt(t.Text)}),U=t.Variant({AssetsUpgrade:B,SegmentsDeployment:F}),q=t.Record({status:I,updated_at:t.Nat64,sha256:t.Opt(t.Vec(t.Nat8)),executed_at:t.Opt(t.Nat64),owner:t.Principal,created_at:t.Nat64,version:t.Opt(t.Nat64),proposal_type:U}),H=t.Variant({Controllers:t.Null,Private:t.Null,Public:t.Null,Managed:t.Null}),Z=t.Record({max_tokens:t.Nat64,time_per_token_ns:t.Nat64}),G=t.Record({max_capacity:t.Opt(t.Nat32),memory:t.Opt(e),updated_at:t.Nat64,max_size:t.Opt(t.Nat),read:H,created_at:t.Nat64,version:t.Opt(t.Nat64),mutable_permissions:t.Opt(t.Bool),rate_config:t.Opt(Z),write:H,max_changes_per_user:t.Opt(t.Nat32)}),ae=t.Record({url:t.Text,method:t.Text,body:t.Vec(t.Nat8),headers:t.Vec(t.Tuple(t.Text,t.Text)),certificate_version:t.Opt(t.Nat16)}),te=t.Record({memory:e,token:t.Opt(t.Text),sha256:t.Opt(t.Vec(t.Nat8)),headers:t.Vec(t.Tuple(t.Text,t.Text)),index:t.Nat64,encoding_type:t.Text,full_path:t.Text}),Ce=t.Variant({Callback:t.Record({token:te,callback:t.Func([],[],["query"])})}),ne=t.Record({body:t.Vec(t.Nat8),headers:t.Vec(t.Tuple(t.Text,t.Text)),streaming_strategy:t.Opt(Ce),status_code:t.Nat16}),me=t.Record({token:t.Opt(te),body:t.Vec(t.Nat8)}),Tt=t.Record({token:t.Opt(t.Text),collection:t.Text,name:t.Text,description:t.Opt(t.Text),encoding_type:t.Opt(t.Text),full_path:t.Text}),Vt=t.Record({batch_id:t.Nat}),pr=t.Record({matches_pages:t.Opt(t.Nat64),matches_length:t.Nat64,items_page:t.Opt(t.Nat64),items:t.Vec(t.Tuple(t.Text,v)),items_length:t.Nat64}),xn=t.Record({updated_at:t.Nat64,created_at:t.Nat64,version:t.Opt(t.Nat64),bn_id:t.Opt(t.Text)}),so=t.Record({matches_pages:t.Opt(t.Nat64),matches_length:t.Nat64,items_page:t.Opt(t.Nat64),items:t.Vec(t.Tuple(t.Text,L)),items_length:t.Nat64}),Yi=t.Record({desc:t.Bool}),Wi=t.Record({start_after:t.Opt(t.Nat),limit:t.Opt(t.Nat)}),ks=t.Record({order:t.Opt(Yi),paginate:t.Opt(Wi)}),js=t.Record({proposal_id:t.Nat}),Xi=t.Record({matches_length:t.Nat64,items:t.Vec(t.Tuple(js,q)),items_length:t.Nat64}),D=t.Record({include_system:t.Bool}),j=t.Record({matcher:t.Opt(D)}),ie=t.Record({matches_length:t.Nat64,items:t.Vec(t.Tuple(t.Text,G)),items_length:t.Nat64}),Ot=t.Record({stable:t.Nat64,heap:t.Nat64}),Nt=t.Record({version:t.Opt(t.Nat64),internet_identity:t.Opt(R),rules:t.Opt(A)}),bt=t.Record({metadata:t.Vec(t.Tuple(t.Text,t.Text)),scope:f,expires_at:t.Opt(t.Nat64)}),io=t.Record({controller:bt,controllers:t.Vec(t.Principal)}),wn=t.Record({version:t.Opt(t.Nat64),max_memory_size:t.Opt(S)}),ao=t.Record({data:t.Vec(t.Nat8),description:t.Opt(t.Text),version:t.Opt(t.Nat64)}),Tl=t.Record({max_capacity:t.Opt(t.Nat32),memory:t.Opt(e),max_size:t.Opt(t.Nat),read:H,version:t.Opt(t.Nat64),mutable_permissions:t.Opt(t.Bool),rate_config:t.Opt(Z),write:H,max_changes_per_user:t.Opt(t.Nat32)}),Ol=t.Record({iframe:t.Opt(C),rewrites:t.Vec(t.Tuple(t.Text,t.Text)),headers:t.Vec(t.Tuple(t.Text,t.Vec(t.Tuple(t.Text,t.Text)))),version:t.Opt(t.Nat64),max_memory_size:t.Opt(S),raw_access:t.Opt(g),redirects:t.Opt(t.Vec(t.Tuple(t.Text,w)))}),Ji=t.Record({content:t.Vec(t.Nat8),batch_id:t.Nat,order_id:t.Opt(t.Nat)}),Qi=t.Record({chunk_id:t.Nat});return t.Service({commit_asset_upload:t.Func([o],[],[]),commit_proposal:t.Func([s],[t.Null],[]),commit_proposal_asset_upload:t.Func([o],[],[]),commit_proposal_many_assets_upload:t.Func([t.Vec(o)],[],[]),count_assets:t.Func([t.Text,l],[t.Nat64],["query"]),count_collection_assets:t.Func([t.Text],[t.Nat64],["query"]),count_collection_docs:t.Func([t.Text],[t.Nat64],["query"]),count_docs:t.Func([t.Text,l],[t.Nat64],["query"]),count_proposals:t.Func([],[t.Nat64],["query"]),del_asset:t.Func([t.Text,t.Text],[],[]),del_assets:t.Func([t.Text],[],[]),del_controllers:t.Func([u],[t.Vec(t.Tuple(t.Principal,h))],[]),del_custom_domain:t.Func([t.Text],[],[]),del_doc:t.Func([t.Text,t.Text,m],[],[]),del_docs:t.Func([t.Text],[],[]),del_filtered_assets:t.Func([t.Text,l],[],[]),del_filtered_docs:t.Func([t.Text,l],[],[]),del_many_assets:t.Func([t.Vec(t.Tuple(t.Text,t.Text))],[],[]),del_many_docs:t.Func([t.Vec(t.Tuple(t.Text,t.Text,m))],[],[]),del_rule:t.Func([b,t.Text,y],[],[]),delete_proposal_assets:t.Func([x],[],[]),deposit_cycles:t.Func([_],[],[]),get_asset:t.Func([t.Text,t.Text],[t.Opt(v)],["query"]),get_auth_config:t.Func([],[t.Opt(E)],["query"]),get_config:t.Func([],[P],[]),get_db_config:t.Func([],[t.Opt(V)],["query"]),get_doc:t.Func([t.Text,t.Text],[t.Opt(L)],["query"]),get_many_assets:t.Func([t.Vec(t.Tuple(t.Text,t.Text))],[t.Vec(t.Tuple(t.Text,t.Opt(v)))],["query"]),get_many_docs:t.Func([t.Vec(t.Tuple(t.Text,t.Text))],[t.Vec(t.Tuple(t.Text,t.Opt(L)))],["query"]),get_proposal:t.Func([t.Nat],[t.Opt(q)],["query"]),get_rule:t.Func([b,t.Text],[t.Opt(G)],["query"]),get_storage_config:t.Func([],[O],["query"]),http_request:t.Func([ae],[ne],["query"]),http_request_streaming_callback:t.Func([te],[me],["query"]),init_asset_upload:t.Func([Tt],[Vt],[]),init_proposal:t.Func([U],[t.Nat,q],[]),init_proposal_asset_upload:t.Func([Tt,t.Nat],[Vt],[]),init_proposal_many_assets_upload:t.Func([t.Vec(Tt),t.Nat],[t.Vec(t.Tuple(t.Text,Vt))],[]),list_assets:t.Func([t.Text,l],[pr],["query"]),list_controllers:t.Func([],[t.Vec(t.Tuple(t.Principal,h))],["query"]),list_custom_domains:t.Func([],[t.Vec(t.Tuple(t.Text,xn))],["query"]),list_docs:t.Func([t.Text,l],[so],["query"]),list_proposals:t.Func([ks],[Xi],["query"]),list_rules:t.Func([b,j],[ie],["query"]),memory_size:t.Func([],[Ot],["query"]),reject_proposal:t.Func([s],[t.Null],[]),set_auth_config:t.Func([Nt],[E],[]),set_controllers:t.Func([io],[t.Vec(t.Tuple(t.Principal,h))],[]),set_custom_domain:t.Func([t.Text,t.Opt(t.Text)],[],[]),set_db_config:t.Func([wn],[V],[]),set_doc:t.Func([t.Text,t.Text,ao],[L],[]),set_many_docs:t.Func([t.Vec(t.Tuple(t.Text,t.Text,ao))],[t.Vec(t.Tuple(t.Text,L))],[]),set_rule:t.Func([b,t.Text,Tl],[G],[]),set_storage_config:t.Func([Ol],[O],[]),submit_proposal:t.Func([t.Nat],[t.Nat,q],[]),switch_storage_system_memory:t.Func([],[],[]),upload_asset_chunk:t.Func([Ji],[Qi],[]),upload_proposal_asset_chunk:t.Func([Ji],[Qi],[])})},Xw=({IDL:t})=>{let e=t.Variant({Heap:t.Null,Stable:t.Null}),r=t.Record({system_memory:t.Opt(e)}),n=t.Record({controllers:t.Vec(t.Principal),storage:t.Opt(r)}),o=t.Record({batch_id:t.Nat,headers:t.Vec(t.Tuple(t.Text,t.Text)),chunk_ids:t.Vec(t.Nat)}),s=t.Record({sha256:t.Vec(t.Nat8),proposal_id:t.Nat}),i=t.Variant({UpdatedAt:t.Null,Keys:t.Null,CreatedAt:t.Null}),a=t.Record({field:i,desc:t.Bool}),c=t.Variant({Equal:t.Nat64,Between:t.Tuple(t.Nat64,t.Nat64),GreaterThan:t.Nat64,LessThan:t.Nat64}),d=t.Record({key:t.Opt(t.Text),updated_at:t.Opt(c),description:t.Opt(t.Text),created_at:t.Opt(c)}),p=t.Record({start_after:t.Opt(t.Text),limit:t.Opt(t.Nat64)}),l=t.Record({order:t.Opt(a),owner:t.Opt(t.Principal),matcher:t.Opt(d),paginate:t.Opt(p)}),u=t.Record({controllers:t.Vec(t.Principal)}),f=t.Variant({Write:t.Null,Admin:t.Null,Submit:t.Null}),h=t.Record({updated_at:t.Nat64,metadata:t.Vec(t.Tuple(t.Text,t.Text)),created_at:t.Nat64,scope:f,expires_at:t.Opt(t.Nat64)}),m=t.Record({version:t.Opt(t.Nat64)}),b=t.Variant({Db:t.Null,Storage:t.Null}),y=t.Record({version:t.Opt(t.Nat64)}),x=t.Record({proposal_ids:t.Vec(t.Nat)}),_=t.Record({cycles:t.Nat,destination_id:t.Principal}),T=t.Record({token:t.Opt(t.Text),collection:t.Text,owner:t.Principal,name:t.Text,description:t.Opt(t.Text),full_path:t.Text}),N=t.Record({modified:t.Nat64,sha256:t.Vec(t.Nat8),total_length:t.Nat}),v=t.Record({key:T,updated_at:t.Nat64,encodings:t.Vec(t.Tuple(t.Text,N)),headers:t.Vec(t.Tuple(t.Text,t.Text)),created_at:t.Nat64,version:t.Opt(t.Nat64)}),R=t.Record({derivation_origin:t.Opt(t.Text),external_alternative_origins:t.Opt(t.Vec(t.Text))}),A=t.Record({allowed_callers:t.Vec(t.Principal)}),E=t.Record({updated_at:t.Opt(t.Nat64),created_at:t.Opt(t.Nat64),version:t.Opt(t.Nat64),internet_identity:t.Opt(R),rules:t.Opt(A)}),S=t.Record({stable:t.Opt(t.Nat64),heap:t.Opt(t.Nat64)}),V=t.Record({updated_at:t.Opt(t.Nat64),created_at:t.Opt(t.Nat64),version:t.Opt(t.Nat64),max_memory_size:t.Opt(S)}),C=t.Variant({Deny:t.Null,AllowAny:t.Null,SameOrigin:t.Null}),g=t.Variant({Deny:t.Null,Allow:t.Null}),w=t.Record({status_code:t.Nat16,location:t.Text}),O=t.Record({iframe:t.Opt(C),updated_at:t.Opt(t.Nat64),rewrites:t.Vec(t.Tuple(t.Text,t.Text)),headers:t.Vec(t.Tuple(t.Text,t.Vec(t.Tuple(t.Text,t.Text)))),created_at:t.Opt(t.Nat64),version:t.Opt(t.Nat64),max_memory_size:t.Opt(S),raw_access:t.Opt(g),redirects:t.Opt(t.Vec(t.Tuple(t.Text,w)))}),P=t.Record({db:t.Opt(V),authentication:t.Opt(E),storage:O}),L=t.Record({updated_at:t.Nat64,owner:t.Principal,data:t.Vec(t.Nat8),description:t.Opt(t.Text),created_at:t.Nat64,version:t.Opt(t.Nat64)}),I=t.Variant({Initialized:t.Null,Failed:t.Null,Open:t.Null,Rejected:t.Null,Executed:t.Null,Accepted:t.Null}),B=t.Record({clear_existing_assets:t.Opt(t.Bool)}),F=t.Record({orbiter:t.Opt(t.Text),mission_control_version:t.Opt(t.Text),satellite_version:t.Opt(t.Text)}),U=t.Variant({AssetsUpgrade:B,SegmentsDeployment:F}),q=t.Record({status:I,updated_at:t.Nat64,sha256:t.Opt(t.Vec(t.Nat8)),executed_at:t.Opt(t.Nat64),owner:t.Principal,created_at:t.Nat64,version:t.Opt(t.Nat64),proposal_type:U}),H=t.Variant({Controllers:t.Null,Private:t.Null,Public:t.Null,Managed:t.Null}),Z=t.Record({max_tokens:t.Nat64,time_per_token_ns:t.Nat64}),G=t.Record({max_capacity:t.Opt(t.Nat32),memory:t.Opt(e),updated_at:t.Nat64,max_size:t.Opt(t.Nat),read:H,created_at:t.Nat64,version:t.Opt(t.Nat64),mutable_permissions:t.Opt(t.Bool),rate_config:t.Opt(Z),write:H,max_changes_per_user:t.Opt(t.Nat32)}),ae=t.Record({url:t.Text,method:t.Text,body:t.Vec(t.Nat8),headers:t.Vec(t.Tuple(t.Text,t.Text)),certificate_version:t.Opt(t.Nat16)}),te=t.Record({memory:e,token:t.Opt(t.Text),sha256:t.Opt(t.Vec(t.Nat8)),headers:t.Vec(t.Tuple(t.Text,t.Text)),index:t.Nat64,encoding_type:t.Text,full_path:t.Text}),Ce=t.Variant({Callback:t.Record({token:te,callback:t.Func([],[],[])})}),ne=t.Record({body:t.Vec(t.Nat8),headers:t.Vec(t.Tuple(t.Text,t.Text)),streaming_strategy:t.Opt(Ce),status_code:t.Nat16}),me=t.Record({token:t.Opt(te),body:t.Vec(t.Nat8)}),Tt=t.Record({token:t.Opt(t.Text),collection:t.Text,name:t.Text,description:t.Opt(t.Text),encoding_type:t.Opt(t.Text),full_path:t.Text}),Vt=t.Record({batch_id:t.Nat}),pr=t.Record({matches_pages:t.Opt(t.Nat64),matches_length:t.Nat64,items_page:t.Opt(t.Nat64),items:t.Vec(t.Tuple(t.Text,v)),items_length:t.Nat64}),xn=t.Record({updated_at:t.Nat64,created_at:t.Nat64,version:t.Opt(t.Nat64),bn_id:t.Opt(t.Text)}),so=t.Record({matches_pages:t.Opt(t.Nat64),matches_length:t.Nat64,items_page:t.Opt(t.Nat64),items:t.Vec(t.Tuple(t.Text,L)),items_length:t.Nat64}),Yi=t.Record({desc:t.Bool}),Wi=t.Record({start_after:t.Opt(t.Nat),limit:t.Opt(t.Nat)}),ks=t.Record({order:t.Opt(Yi),paginate:t.Opt(Wi)}),js=t.Record({proposal_id:t.Nat}),Xi=t.Record({matches_length:t.Nat64,items:t.Vec(t.Tuple(js,q)),items_length:t.Nat64}),D=t.Record({include_system:t.Bool}),j=t.Record({matcher:t.Opt(D)}),ie=t.Record({matches_length:t.Nat64,items:t.Vec(t.Tuple(t.Text,G)),items_length:t.Nat64}),Ot=t.Record({stable:t.Nat64,heap:t.Nat64}),Nt=t.Record({version:t.Opt(t.Nat64),internet_identity:t.Opt(R),rules:t.Opt(A)}),bt=t.Record({metadata:t.Vec(t.Tuple(t.Text,t.Text)),scope:f,expires_at:t.Opt(t.Nat64)}),io=t.Record({controller:bt,controllers:t.Vec(t.Principal)}),wn=t.Record({version:t.Opt(t.Nat64),max_memory_size:t.Opt(S)}),ao=t.Record({data:t.Vec(t.Nat8),description:t.Opt(t.Text),version:t.Opt(t.Nat64)}),Tl=t.Record({max_capacity:t.Opt(t.Nat32),memory:t.Opt(e),max_size:t.Opt(t.Nat),read:H,version:t.Opt(t.Nat64),mutable_permissions:t.Opt(t.Bool),rate_config:t.Opt(Z),write:H,max_changes_per_user:t.Opt(t.Nat32)}),Ol=t.Record({iframe:t.Opt(C),rewrites:t.Vec(t.Tuple(t.Text,t.Text)),headers:t.Vec(t.Tuple(t.Text,t.Vec(t.Tuple(t.Text,t.Text)))),version:t.Opt(t.Nat64),max_memory_size:t.Opt(S),raw_access:t.Opt(g),redirects:t.Opt(t.Vec(t.Tuple(t.Text,w)))}),Ji=t.Record({content:t.Vec(t.Nat8),batch_id:t.Nat,order_id:t.Opt(t.Nat)}),Qi=t.Record({chunk_id:t.Nat});return t.Service({commit_asset_upload:t.Func([o],[],[]),commit_proposal:t.Func([s],[t.Null],[]),commit_proposal_asset_upload:t.Func([o],[],[]),commit_proposal_many_assets_upload:t.Func([t.Vec(o)],[],[]),count_assets:t.Func([t.Text,l],[t.Nat64],[]),count_collection_assets:t.Func([t.Text],[t.Nat64],[]),count_collection_docs:t.Func([t.Text],[t.Nat64],[]),count_docs:t.Func([t.Text,l],[t.Nat64],[]),count_proposals:t.Func([],[t.Nat64],[]),del_asset:t.Func([t.Text,t.Text],[],[]),del_assets:t.Func([t.Text],[],[]),del_controllers:t.Func([u],[t.Vec(t.Tuple(t.Principal,h))],[]),del_custom_domain:t.Func([t.Text],[],[]),del_doc:t.Func([t.Text,t.Text,m],[],[]),del_docs:t.Func([t.Text],[],[]),del_filtered_assets:t.Func([t.Text,l],[],[]),del_filtered_docs:t.Func([t.Text,l],[],[]),del_many_assets:t.Func([t.Vec(t.Tuple(t.Text,t.Text))],[],[]),del_many_docs:t.Func([t.Vec(t.Tuple(t.Text,t.Text,m))],[],[]),del_rule:t.Func([b,t.Text,y],[],[]),delete_proposal_assets:t.Func([x],[],[]),deposit_cycles:t.Func([_],[],[]),get_asset:t.Func([t.Text,t.Text],[t.Opt(v)],[]),get_auth_config:t.Func([],[t.Opt(E)],[]),get_config:t.Func([],[P],[]),get_db_config:t.Func([],[t.Opt(V)],[]),get_doc:t.Func([t.Text,t.Text],[t.Opt(L)],[]),get_many_assets:t.Func([t.Vec(t.Tuple(t.Text,t.Text))],[t.Vec(t.Tuple(t.Text,t.Opt(v)))],[]),get_many_docs:t.Func([t.Vec(t.Tuple(t.Text,t.Text))],[t.Vec(t.Tuple(t.Text,t.Opt(L)))],[]),get_proposal:t.Func([t.Nat],[t.Opt(q)],[]),get_rule:t.Func([b,t.Text],[t.Opt(G)],[]),get_storage_config:t.Func([],[O],[]),http_request:t.Func([ae],[ne],[]),http_request_streaming_callback:t.Func([te],[me],[]),init_asset_upload:t.Func([Tt],[Vt],[]),init_proposal:t.Func([U],[t.Nat,q],[]),init_proposal_asset_upload:t.Func([Tt,t.Nat],[Vt],[]),init_proposal_many_assets_upload:t.Func([t.Vec(Tt),t.Nat],[t.Vec(t.Tuple(t.Text,Vt))],[]),list_assets:t.Func([t.Text,l],[pr],[]),list_controllers:t.Func([],[t.Vec(t.Tuple(t.Principal,h))],[]),list_custom_domains:t.Func([],[t.Vec(t.Tuple(t.Text,xn))],[]),list_docs:t.Func([t.Text,l],[so],[]),list_proposals:t.Func([ks],[Xi],[]),list_rules:t.Func([b,j],[ie],[]),memory_size:t.Func([],[Ot],[]),reject_proposal:t.Func([s],[t.Null],[]),set_auth_config:t.Func([Nt],[E],[]),set_controllers:t.Func([io],[t.Vec(t.Tuple(t.Principal,h))],[]),set_custom_domain:t.Func([t.Text,t.Opt(t.Text)],[],[]),set_db_config:t.Func([wn],[V],[]),set_doc:t.Func([t.Text,t.Text,ao],[L],[]),set_many_docs:t.Func([t.Vec(t.Tuple(t.Text,t.Text,ao))],[t.Vec(t.Tuple(t.Text,L))],[]),set_rule:t.Func([b,t.Text,Tl],[G],[]),set_storage_config:t.Func([Ol],[O],[]),submit_proposal:t.Func([t.Nat],[t.Nat,q],[]),switch_storage_system_memory:t.Func([],[],[]),upload_asset_chunk:t.Func([Ji],[Qi],[]),upload_proposal_asset_chunk:t.Func([Ji],[Qi],[])})};var xl=Fe(De(),1);var Jw=({satelliteId:t,container:e})=>{let{satelliteId:r}=sm({satelliteId:t}),{container:n}=im({container:e});if((0,xl.nonNullish)(n)&&n!==!1){let{host:o,protocol:s}=new URL(n===!0?ki:n);return`${s}//${r??"unknown"}.${o.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},sm=({satelliteId:t})=>(0,xl.nonNullish)(t)?{satelliteId:t}:lr.getInstance().get()??{satelliteId:void 0},im=({container:t})=>(0,xl.nonNullish)(t)?{container:t}:lr.getInstance().get()??{container:void 0};var ut=({satellite:t,options:{certified:e}})=>t1({idlFactory:e?Xw:Ww,actorKey:`stock#${e?"update":"query"}`,...t}),e1=({idlFactory:t,...e})=>t1({idlFactory:t,actorKey:"extended#query",...e}),t1=async({satelliteId:t,container:e,...r})=>{let{satelliteId:n}=sm({satelliteId:t});(0,Qw.assertNonNullish)(n,"No satellite ID defined. Did you initialize Juno?");let{container:o}=im({container:e});return await Hi.getInstance().getActor({satelliteId:n,container:o,...r})};var nt=Fe(De(),1);var r1=t=>{if((0,nt.isNullish)(t))return(0,nt.toNullable)();switch(t.matcher){case"equal":return(0,nt.toNullable)({Equal:t.timestamp});case"greaterThan":return(0,nt.toNullable)({GreaterThan:t.timestamp});case"lessThan":return(0,nt.toNullable)({LessThan:t.timestamp});case"between":return(0,nt.toNullable)({Between:[t.timestamps.start,t.timestamps.end]});default:throw new yl("Invalid list matcher for timestamp",t)}},Go=({matcher:t,paginate:e,order:r,owner:n})=>({matcher:(0,nt.isNullish)(t)?[]:[{key:(0,nt.toNullable)(t.key),description:(0,nt.toNullable)(t.description),created_at:r1(t.createdAt),updated_at:r1(t.updatedAt)}],paginate:(0,nt.toNullable)((0,nt.isNullish)(e)?void 0:{start_after:(0,nt.toNullable)(e.startAfter),limit:(0,nt.toNullable)((0,nt.isNullish)(e.limit)?void 0:BigInt(e.limit))}),order:(0,nt.toNullable)((0,nt.isNullish)(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:(0,nt.toNullable)((0,nt.isNullish)(n)?void 0:typeof n=="string"?se.fromText(n):n)});var n1=async({data:t})=>{try{return await nl(t)}catch(e){console.error("The data parsing has failed, mapping to undefined as a fallback.",e);return}};var Ms=Fe(De(),1);var am=async t=>{let{data:e,version:r,description:n}=t;return{description:(0,Ms.toNullable)(n),data:await Cw(e),version:(0,Ms.toNullable)(r)}},cm=t=>{let{version:e}=t;return{version:(0,Ms.toNullable)(e)}},Ic=async({doc:t,key:e})=>{let{owner:r,version:n,description:o,data:s,...i}=t;return{key:e,description:(0,Ms.fromNullable)(o),owner:r.toText(),data:await nl(s),version:(0,Ms.fromNullable)(n),...i}};var o1=async({collection:t,key:e,...r})=>{let{get_doc:n}=await ut(r),o=(0,jr.fromNullable)(await n(t,e));if(!(0,jr.isNullish)(o))return Ic({doc:o,key:e})},s1=async({docs:t,...e})=>{let{get_many_docs:r}=await ut(e),n=t.map(({collection:i,key:a})=>[i,a]),o=await r(n),s=[];for(let[i,a]of o){let c=(0,jr.fromNullable)(a);s.push((0,jr.nonNullish)(c)?await Ic({key:i,doc:c}):void 0)}return s},i1=async({collection:t,doc:e,...r})=>{let{set_doc:n}=await ut(r),{key:o}=e,s=await am(e),i=await n(t,o,s);return await Ic({key:o,doc:i})},a1=async({docs:t,...e})=>{let{set_many_docs:r}=await ut(e),n=[];for(let{collection:i,doc:a}of t){let{key:c}=a;n.push([i,c,await am(a)])}let o=await r(n),s=[];for(let[i,a]of o)s.push(await Ic({key:i,doc:a}));return s},c1=async({collection:t,doc:e,...r})=>{let{del_doc:n}=await ut(r),{key:o}=e;return n(t,o,cm(e))},u1=async({docs:t,...e})=>{let{del_many_docs:r}=await ut(e),n=t.map(({collection:o,doc:s})=>[o,s.key,cm(s)]);await r(n)},d1=async({collection:t,filter:e,...r})=>{let{del_filtered_docs:n}=await ut(r);return n(t,Go(e))},l1=async({collection:t,filter:e,...r})=>{let{list_docs:n}=await ut(r),{items:o,items_page:s,items_length:i,matches_length:a,matches_pages:c}=await n(t,Go(e)),d=[];for(let[p,l]of o){let{data:u,owner:f,description:h,version:m,...b}=l;d.push({key:p,description:(0,jr.fromNullable)(h),owner:f.toText(),data:await n1({data:u}),version:(0,jr.fromNullable)(m),...b})}return{items:d,items_length:i,items_page:(0,jr.fromNullable)(s),matches_length:a,matches_pages:(0,jr.fromNullable)(c)}},f1=async({collection:t,filter:e,...r})=>{let{count_docs:n}=await ut(r);return n(t,Go(e))};var wl=async({satellite:t,options:e,...r})=>{let n=Ye(t?.identity);return await o1({...r,satellite:{...t,identity:n},options:e??gn})},P7=async({satellite:t,options:e,...r})=>{let n=Ye(t?.identity);return await s1({...r,satellite:{...t,identity:n},options:e??gn})},p1=async({satellite:t,...e})=>{let r=Ye(t?.identity);return await i1({...e,satellite:{...t,identity:r},options:{certified:!0}})},h1=async({satellite:t,...e})=>{let r=Ye(t?.identity);return await a1({...e,satellite:{...t,identity:r},options:{certified:!0}})},D7=async({satellite:t,...e})=>{let r=Ye(t?.identity);return await c1({...e,satellite:{...t,identity:r},options:{certified:!0}})},F7=async({satellite:t,...e})=>{let r=Ye(t?.identity);return await u1({...e,satellite:{...t,identity:r},options:{certified:!0}})},V7=async({satellite:t,filter:e,...r})=>{let n=Ye(t?.identity);return await d1({...r,filter:e??{},satellite:{...t,identity:n},options:{certified:!0}})},U7=async({satellite:t,options:e,filter:r,...n})=>{let o=Ye(t?.identity);return await l1({...n,filter:r??{},satellite:{...t,identity:o},options:e??gn})},L7=async({satellite:t,options:e,filter:r,...n})=>{let o=Ye(t?.identity);return await f1({...n,filter:r??{},satellite:{...t,identity:o},options:e??gn})};var El=Fe(De(),1);var m1=async({delegationIdentity:t,passkeyIdentity:e,satelliteId:r})=>{let n=e.getCredential().getAAGUID(),[o,s]=await h1({docs:[{collection:"#user",doc:{key:t.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...(0,El.nonNullish)(n)&&{aaguid:(0,El.uint8ArrayToArrayOfNumber)(n)}}}}}},{collection:"#user-webauthn",doc:{key:e.getCredential().getCredentialIdText(),data:{publicKey:e.getPublicKey().toRaw()}}}],satellite:{identity:t,satelliteId:r}});return o};var y1=(s=>(s[s.RequestingUserCredential=0]="RequestingUserCredential",s[s.FinalizingCredential=1]="FinalizingCredential",s[s.Signing=2]="Signing",s[s.FinalizingSession=3]="FinalizingSession",s[s.RetrievingUser=4]="RetrievingUser",s))(y1||{}),_1=(i=>(i[i.CreatingUserCredential=0]="CreatingUserCredential",i[i.ValidatingUserCredential=1]="ValidatingUserCredential",i[i.FinalizingCredential=2]="FinalizingCredential",i[i.Signing=3]="Signing",i[i.FinalizingSession=4]="FinalizingSession",i[i.RegisteringUser=5]="RegisteringUser",i))(_1||{});var Sc=class{get id(){return"webauthn"}async signUp({options:{onProgress:e,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:o}){let{satelliteId:s}=lr.getInstance().get()??{satelliteId:void 0};if((0,zi.isNullish)(s))throw new Ls("Satellite ID not set. Have you initialized the Satellite?");let i=({step:m,state:b})=>{switch(m){case Ko.RequestingUserCredential:e?.({step:1,state:b});break;case Ko.FinalizingCredential:e?.({step:2,state:b});break;case Ko.Signing:e?.({step:3,state:b});break}},c=await bn({fn:async()=>await j0.createWithNewCredential({onProgress:i,passkeyOptions:n}),step:0,onProgress:e}),{delegationIdentity:d,sessionKey:p}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),u=await bn({fn:async()=>await m1({delegationIdentity:d,passkeyIdentity:c,satelliteId:s}),step:5,onProgress:e});await bn({fn:async()=>await this.#t({delegationIdentity:d,sessionKey:p}),step:4,onProgress:e}),await bn({fn:async()=>await o({user:u}),step:5,onProgress:e})}async signIn({options:{onProgress:e,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:o}=lr.getInstance().get()??{satelliteId:void 0};if((0,zi.isNullish)(o))throw new Ls("Satellite ID not set. Have you initialized the Satellite?");let s=async({credentialId:l})=>{let u=await wl({collection:"#user-webauthn",key:(0,zi.uint8ArrayToBase64)(l),options:{certified:!0},satellite:{identity:new xr,satelliteId:o}});if((0,zi.isNullish)(u))throw new pl("No public key found for the selected passkey.");let{data:f}=u,{publicKey:h}=f;return Ps(h,xc)},i=({step:l,state:u})=>{switch(l){case Ko.RequestingUserCredential:e?.({step:0,state:u});break;case Ko.FinalizingCredential:e?.({step:1,state:u});break;case Ko.Signing:e?.({step:2,state:u});break}},a=await j0.createWithExistingCredential({retrievePublicKey:s,onProgress:i}),{delegationIdentity:c,sessionKey:d}=await this.#e({identity:a,maxTimeToLiveInMilliseconds:r});await bn({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:d}),step:3,onProgress:e}),await bn({fn:n,step:4,onProgress:e})}async#e({identity:e,maxTimeToLiveInMilliseconds:r}){let n=await Fs.generate({extractable:!1}),o=r??144e5,s=await Vs.create(e,n.getPublicKey(),new Date(Date.now()+o));return{delegationIdentity:Us.fromDelegation(n,s),sessionKey:n}}async#t({sessionKey:e,delegationIdentity:r}){let n=new oo;await Promise.all([n.set(Yt,e.getKeyPair()),n.set(fr,JSON.stringify(r.getDelegation().toJSON()))])}};var Ac=()=>ul.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),b1=async()=>(await new oo().remove(Yt),await Ac());var Bc=Fe(De(),1);var um=({error:t,type:e})=>typeof t=="string"?t.includes(e):t instanceof Error?t.message.includes(e):!1;var g1="juno.datastore.error.user.cannot_update";var x1=async({provider:t})=>{let{user:e,userId:r}=await dm();if((0,Bc.nonNullish)(e))return e;try{return await gv({userId:r,provider:t})}catch(n){if(um({error:n,type:g1})){let o=await w1({userId:r});if((0,Bc.nonNullish)(o))return o}throw n}},dm=async()=>{let t=gl();if((0,Bc.isNullish)(t))throw new ml("No identity to initialize the user. Have you initialized Juno?");let e=t.getPrincipal().toText(),r=await w1({userId:e});return{userId:e,user:r}},w1=({userId:t})=>wl({collection:"#user",key:t}),gv=({userId:t,...e})=>p1({collection:"#user",doc:{key:t,data:e}});var vr,lm=async()=>{await fm({fn:async()=>{let{user:e}=await dm();Nr.getInstance().set(e??null)}})},xv=async({user:t})=>{await fm({fn:async()=>{Nr.getInstance().set(t)}})},E1=async({provider:t})=>{await fm({fn:async()=>{let r=await x1({provider:t});Nr.getInstance().set(r)}})},fm=async({fn:t})=>{if(vr=await Ac(),!await vr.isAuthenticated()){vr=await b1();return}await t()},wv=async t=>{let e=async()=>await Tv(t);if(Object.values(t)[0].context?.windowGuard===!1){await e();return}await K0({fn:e})},Ev=async t=>{let e=async()=>await Ov(t);if(Object.values(t)?.[0].context?.windowGuard===!1){await e();return}await K0({fn:e})},Tv=async t=>{if("webauthn"in t){let{webauthn:{options:e}}=t;await new Sc().signIn({options:e,loadAuth:lm});return}if("nfid"in t){let{nfid:{options:e}}=t,{appName:r,logoUrl:n,...o}=e??{};await new bl({appName:r,logoUrl:n}).signIn({options:o,authClient:vr,initAuth:E1});return}if("internet_identity"in t){let{internet_identity:{options:e}}=t,{domain:r,...n}=e??{};await new _l({domain:r}).signIn({options:n,authClient:vr,initAuth:E1});return}throw new fl("An unknown or unsupported provider was provided for sign-in.")},Ov=async t=>{if("webauthn"in t){let{webauthn:{options:e}}=t;await new Sc().signUp({options:e,loadAuthWithUser:xv});return}throw new hl("An unknown or unsupported provider was provided for sign-up.")},pm=async t=>{await Nv(),vr=await Ac(),t?.windowReload!==!1&&window.location.reload()},Nv=async()=>{await vr?.logout(),vr=null,Nr.getInstance().reset(),Hi.getInstance().reset(),ji.getInstance().reset()},gl=()=>vr?.getIdentity(),vv=async()=>(vr??await Ac()).getIdentity(),Rv=async()=>{let t=Nr.getInstance().get();return(0,T1.isNullish)(t)||!(await vr?.isAuthenticated()??!1)?null:vr?.getIdentity()??null};var N1=t=>{let e=t===!0?"./workers/auth.worker.js":t,r=new Worker(e),n=async()=>{H0({message:"junoSignOutAuthTimer"}),await pm()};return r.onmessage=async({data:o})=>{let{msg:s,data:i}=o;switch(s){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":H0({message:"junoDelegationRemainingTime",detail:i?.authRemainingTime});return}},Nr.getInstance().subscribe(o=>{if((0,O1.isNullish)(o)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var v1=()=>{let t=()=>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??t():t()},R1=()=>{let t=()=>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??t():t()};var S9=async({idlFactory:t,satellite:e})=>{let r=Ye(e?.identity);return await e1({idlFactory:t,...e,identity:r})};var Pc=Fe(De(),1);var Cc=Fe(De(),1);var Zi=Fe(De(),1);var I1=async({asset:{data:t,headers:e,...r},actor:n,progress:o})=>{let{init_asset_upload:s,upload_asset_chunk:i,commit_asset_upload:a}=n,{batch_id:c}=await s(Iv(r));o?.onInitiatedBatch();let{chunkIds:d}=await Bv({data:t,uploadFn:i,batchId:c});o?.onUploadedFileChunks(r.fullPath),await Av({commitFn:a,batchId:c,data:t,headers:e,chunkIds:d}),o?.onCommittedBatch()};var Iv=({filename:t,collection:e,token:r,fullPath:n,encoding:o,description:s})=>({collection:e,full_path:n,name:t,token:(0,Zi.toNullable)(r),encoding_type:(0,Zi.toNullable)(o),description:(0,Zi.toNullable)(s)}),Sv=({batchId:t,chunkIds:e,headers:r,data:n})=>{let o=r.find(([s,i])=>s.toLowerCase()==="content-type")===void 0&&n.type!==void 0&&n.type!==""?[["Content-Type",n.type]]:void 0;return{batch_id:t,chunk_ids:e.map(({chunk_id:s})=>s),headers:[...r,...o??[]]}},Av=async({commitFn:t,...e})=>{let r=Sv(e);await t(r)},Bv=async({data:t,uploadFn:e,batchId:r})=>{let n=[],o=ol()?new Blob([await t.arrayBuffer()]):t,s=0n;for(let a=0;a<o.size;a+=19e5){let c=o.slice(a,a+19e5);n.push({batchId:r,chunk:c,uploadFn:e,orderId:s}),s++}let i=[];for await(let a of Cv({uploadChunks:n}))i=[...i,...a];return{chunkIds:i}};async function*Cv({uploadChunks:t,limit:e=12}){for(let r=0;r<t.length;r=r+e){let n=t.slice(r,r+e);yield await Promise.all(n.map(o=>Pv(o)))}}var Pv=async({batchId:t,chunk:e,uploadFn:r,orderId:n})=>r({batch_id:t,content:new Uint8Array(await e.arrayBuffer()),order_id:(0,Zi.toNullable)(n)});var S1=async({asset:t,...e})=>{let r=await ut(e);await I1({actor:r,asset:t})},A1=async({collection:t,filter:e,...r})=>{let{list_assets:n}=await ut(r),{items:o,items_length:s,items_page:i,matches_length:a,matches_pages:c}=await n(t,Go(e));return{items:o.map(([d,p])=>p),items_length:s,items_page:(0,Cc.fromNullable)(i),matches_length:a,matches_pages:(0,Cc.fromNullable)(c)}},B1=async({collection:t,filter:e,...r})=>{let{count_assets:n}=await ut(r);return n(t,Go(e))},C1=async({collection:t,fullPath:e,...r})=>(await ut(r)).del_asset(t,e),P1=async({assets:t,satellite:e})=>{let{del_many_assets:r}=await ut({satellite:e,options:{certified:!0}}),n=t.map(({collection:o,fullPath:s})=>[o,s]);await r(n)},D1=async({collection:t,filter:e,...r})=>{let{del_filtered_assets:n}=await ut(r);return n(t,Go(e))},F1=async({collection:t,fullPath:e,...r})=>{let{get_asset:n}=await ut(r);return(0,Cc.fromNullable)(await n(t,e))},V1=async({assets:t,...e})=>{let{get_many_assets:r}=await ut(e),n=t.map(({collection:s,fullPath:i})=>[s,i]);return(await r(n)).map(([s,i])=>(0,Cc.fromNullable)(i))};var U1=t=>btoa([...t].map(e=>String.fromCharCode(e)).join(""));var H9=t=>L1(t),$9=t=>L1({filename:t.data.name,...t}),L1=async({filename:t,data:e,collection:r,headers:n=[],fullPath:o,token:s,satellite:i,encoding:a,description:c})=>{let d=Ye(i?.identity),p=decodeURI(t),l=o??`/${r}/${p}`,u={...i,identity:d};return await S1({asset:{data:e,filename:p,collection:r,token:s,headers:n,fullPath:l,encoding:a,description:c},satellite:u,options:{certified:!0}}),{downloadUrl:q1({satellite:u,assetKey:{fullPath:l,token:s}}),fullPath:l,name:p}},K9=async({collection:t,filter:e,satellite:r,options:n})=>{let o={...r,identity:Ye(r?.identity)},{items:s,...i}=await A1({collection:t,filter:e??{},satellite:o,options:n??gn}),a=s.map(({key:{full_path:c,token:d,name:p,owner:l,description:u},headers:f,encodings:h,created_at:m,updated_at:b})=>{let y=(0,Pc.fromNullable)(d);return{fullPath:c,description:(0,Pc.fromNullable)(u),name:p,downloadUrl:q1({satellite:o,assetKey:{fullPath:c,token:y}}),token:y,headers:f,encodings:h.reduce((x,[_,{modified:T,sha256:N,total_length:v}])=>({...x,[_]:{modified:T,sha256:U1(N),total_length:v}}),{}),owner:l.toText(),created_at:m,updated_at:b}});return{items:a,assets:a,...i}},G9=async({collection:t,filter:e,satellite:r,options:n})=>{let o={...r,identity:Ye(r?.identity)};return await B1({collection:t,satellite:o,filter:e??{},options:n??gn})},z9=({collection:t,fullPath:e,satellite:r})=>C1({collection:t,fullPath:e,satellite:{...r,identity:Ye(r?.identity)},options:{certified:!0}}),Z9=({assets:t,satellite:e})=>P1({assets:t,satellite:{...e,identity:Ye(e?.identity)},options:{certified:!0}}),Y9=async({collection:t,satellite:e,filter:r})=>{let n={...e,identity:Ye(e?.identity)};return await D1({collection:t,satellite:n,filter:r??{},options:{certified:!0}})},W9=async({satellite:t,options:e,...r})=>{let n=Ye(t?.identity);return await F1({...r,satellite:{...t,identity:n},options:e??gn})},X9=async({satellite:t,options:e,...r})=>{let n=Ye(t?.identity);return await V1({...r,satellite:{...t,identity:n},options:e??gn})},q1=({assetKey:{fullPath:t,token:e},satellite:r})=>{let n={...r,identity:Ye(r?.identity)};return`${Jw(n)}${t}${(0,Pc.nonNullish)(e)?`?token=${e}`:""}`};var Dv=t=>{let e=t?.satelliteId??v1();(0,M1.assertNonNullish)(e,"Satellite ID is not configured. Juno cannot be initialized.");let r=t?.container??R1();return{satelliteId:e,internetIdentityId:t?.internetIdentityId,workers:t?.workers,container:r}},sC=t=>Fv(t),Fv=async t=>{let e=Dv(t);lr.getInstance().set(e),await lm();let r=e.workers?.auth!==void 0?N1(e.workers.auth):void 0;return[...r?[r]:[]]},Vv=t=>Nr.getInstance().subscribe(t),iC=Vv;export{zw as AuthClientSignInProgressStep,ml as InitError,_l as InternetIdentityProvider,yl as ListError,bl as NFIDProvider,dl as SignInError,Ls as SignInInitError,fl as SignInProviderNotSupportedError,ll as SignInUserInterruptError,hl as SignUpProviderNotSupportedError,y1 as WebAuthnSignInProgressStep,pl as WebAuthnSignInRetrievePublicKeyError,_1 as WebAuthnSignUpProgressStep,iC as authSubscribe,G9 as countAssets,L7 as countDocs,z9 as deleteAsset,D7 as deleteDoc,Y9 as deleteFilteredAssets,V7 as deleteFilteredDocs,Z9 as deleteManyAssets,F7 as deleteManyDocs,q1 as downloadUrl,W9 as getAsset,wl as getDoc,Rv as getIdentityOnce,X9 as getManyAssets,P7 as getManyDocs,S9 as getSatelliteExtendedActor,sC as initJuno,Fv as initSatellite,KN as isWebAuthnAvailable,K9 as listAssets,U7 as listDocs,Vv as onAuthStateChange,p1 as setDoc,h1 as setManyDocs,wv as signIn,pm as signOut,Ev as signUp,vv as unsafeIdentity,H9 as uploadBlob,$9 as uploadFile};
56
+ Retrying request.`),await this.#y({requestFn:r,backoff:n,tries:o+1});throw go.fromCode(new To(p))}let c=Gi(s.headers);if(s.status===$a||s.status===Qh)return{ok:s.ok,status:s.status,statusText:s.statusText,responseBodyBytes:a,headers:c};let u=await s.text();if(s.status===em&&s.url.includes("api/v3"))throw ne.fromCode(new wo);if(u.startsWith("Invalid request expiry: "))throw z.fromCode(new mn(u,this.#l));if(o<this.#d)return await this.#y({requestFn:r,backoff:n,tries:o+1});throw ne.fromCode(new bo(s.status,s.statusText,c,u))}async query(t,r,n){let o=this.#p(),i=r.effectiveCanisterId?M.from(r.effectiveCanisterId):M.from(t);await this.#g(i),this.log.print(`ecid ${i.toString()}`),this.log.print(`canisterId ${t.toString()}`);let s,a=await(n??this.#n);if(!a)throw Oe.fromCode(new br);let c=M.from(t),u=a.getPrincipal(),p=Ga(this.#l,this.#r),d={request_type:Tn.Query,canister_id:c,method_name:r.methodName,arg:r.arg,sender:u,ingress_expiry:p},l=Xt(d);s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#i?{Authorization:"Basic "+btoa(this.#i)}:{}}},endpoint:er.Query,body:d}),s=await a.transformRequest(s);let f=Uo(s.body),h={canister:c.toText(),ecid:i,transformedRequest:s,body:f,requestId:l,backoff:o,tries:0},m=async()=>{let _=await this.#b(h);return{requestDetails:d,..._}},g=async()=>{let _=this.#m.get(i.toString());if(_)return _;await this.fetchSubnetKeys(i.toString());let x=this.#m.get(i.toString());if(!x)throw Pe.fromCode(new Ai);return x};try{if(!this.#_)return await m();let[_,x]=await Promise.all([m(),g()]);try{return this.#w(_,x)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#m.delete(i.toString());let y=await g();return this.#w(_,y)}}catch(_){let x;throw _ instanceof ht?(_.code.requestContext={requestId:l,senderPubKey:s.body.sender_pubkey,senderSignature:s.body.sender_sig,ingressExpiry:s.body.content.ingress_expiry},x=_):x=ge.fromCode(new Be(_)),this.log.error(`Error while making query: ${x.message}`,x),x}}#w;async createReadStateRequest(t,r){await this.#g();let n=await(r??this.#n);if(!n)throw Oe.fromCode(new br);let o=n.getPrincipal(),i=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#i?{Authorization:"Basic "+btoa(this.#i)}:{}}},endpoint:er.ReadState,body:{request_type:Tn.ReadState,paths:t.paths,sender:o,ingress_expiry:Ga(this.#l,this.#r)}});return n.transformRequest(i)}async readState(t,r,n,o){await this.#T();let i=M.from(t);function s(p){for(let d of p.paths){let[l,f]=d,h=new TextEncoder().encode("request_status");if(bn(l,h))return f}}let a,c;if(o)a=o,c=Xt(a);else{c=s(r);let p=await this.#n;if(!p)throw Oe.fromCode(new br);a=await this.createReadStateRequest(r,p)}this.log.print(`fetching "/api/v2/canister/${i}/read_state" with request:`,a);let u=this.#p();try{let{responseBodyBytes:p}=await this.#y({requestFn:()=>this.#o(""+new URL(`/api/v2/canister/${i.toString()}/read_state`,this.host),{...this.#a,...a.request,body:Uo(a.body)}),backoff:u,tries:0}),d=Je(p);return this.log.print("Read state response:",d),d}catch(p){let d;throw p instanceof ht?(p.code.requestContext={requestId:c,senderPubKey:a.body.sender_pubkey,senderSignature:a.body.sender_sig,ingressExpiry:a.body.content.ingress_expiry},d=p):d=ge.fromCode(new Be(p)),this.log.error(`Error while making read state: ${d.message}`,d),d}}parseTimeFromResponse(t){let r;if(t.certificate){let n=Je(t.certificate);if(n&&"tree"in n)r=n.tree;else throw ne.fromCode(new wr("Could not decode time from response"));let o=An(["time"],r);if(o.status!==We.Found)throw ne.fromCode(new zt("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 ne.fromCode(new Un("Time was not in its expected format."));let i=ro(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.#s=this.#s??(async()=>{await this.#T();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??M.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),o=e.createSync({identity:new rt,host:this.host.toString(),fetch:this.#o,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),s=(await Promise.all(Array(3).fill(null).map(async()=>{let c=(await Ua({canisterId:n,agent:o,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(c instanceof Date)return c.getTime()},[]))).reduce((a,c)=>typeof c=="number"&&c>a?c:a,0);s>0&&(this.#r=s-r,this.#c=!0,this.log.notify({message:`Syncing time: offset of ${this.#r}`,level:"info"}))}catch(n){let o=n instanceof ht?n:ge.fromCode(new Be(n));throw this.log.error("Caught exception while attempting to sync time",o),o}})(),await this.#s.finally(()=>{this.#s=null})}async status(){let t=this.#i?{Authorization:"Basic "+btoa(this.#i)}:{};this.log.print('fetching "/api/v2/status"');let r=this.#p(),{responseBodyBytes:n}=await this.#y({backoff:r,requestFn:()=>this.#o(""+new URL("/api/v2/status",this.host),{headers:t,...this.#a}),tries:0});return Je(n)}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#g(t){await Promise.all([this.#T(),this.#O(t)])}async#T(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#t)await this.fetchRootKey();else throw Oe.fromCode(new Rt(this.#t))}async#O(t){this.#u&&!this.hasSyncedTime()&&await this.syncTime(t)}invalidateIdentity(){this.#n=null}replaceIdentity(t){this.#n=Promise.resolve(t)}async fetchSubnetKeys(t){let r=M.from(t);await this.#g(r);let o=(await Ua({canisterId:r,paths:["subnet"],agent:this})).get("subnet");if(o&&typeof o=="object"&&"nodeKeys"in o)return this.#m.set(r.toText(),o),o}_transform(t){let r=Promise.resolve(t);if(t.endpoint===er.Call)for(let n of this.#h)r=r.then(o=>n(o).then(i=>i||o));else for(let n of this.#f)r=r.then(o=>n(o).then(i=>i||o));return r}getTimeDiffMsecs(){return this.#r}hasSyncedTime(){return this.#c}};function Ga(e,t){let r=e*Ja;return Wn.fromDeltaInMilliseconds(r,t)}var nm=300*1e3;function Ku(){return cm(im(om(),1e3),am(1e3,1.2),sm(nm))}function om(){let e=!0;return async()=>e?(e=!1,!0):!1}function im(e,t){return async(r,n,o)=>{if(await e(r,n,o))return new Promise(i=>setTimeout(i,t))}}function sm(e){let t=Date.now()+e;return async(r,n,o)=>{if(Date.now()>t)throw ne.fromCode(new hn(`Request timed out after ${e} msec`,n,o))}}function am(e,t){let r=e;return()=>new Promise(n=>setTimeout(()=>{r*=t,n()},r))}function cm(...e){return async(t,r,n)=>{for(let o of e)await o(t,r,n)}}var $u={preSignReadStateRequest:!1};function Gu(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function za(e,t){return e!==null&&typeof e=="object"&&Gu(e,t)}function um(e,t){return Gu(e,t)&&typeof e[t]=="function"}function Hu(e){return za(e,"body")&&za(e.body,"content")&&e.body.content.request_type===Tn.ReadState&&za(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&um(e.body.content.ingress_expiry,"toHash")}async function Wa(e,t,r,n={}){let o=[ee("request_status"),r],i,s;if(n.preSignReadStateRequest??!1?(s=await dm({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 Oe.fromCode(new Rt);let c=await Sr.create({certificate:i.certificate,rootKey:e.rootKey,canisterId:t,blsVerify:n.blsVerify,agent:e}),u=Ve(c.lookup_path([...o,ee("status")])),p;switch(typeof u>"u"?p=Vt.Unknown:p=new TextDecoder().decode(u),p){case Vt.Replied:return{reply:Ve(c.lookup_path([...o,"reply"])),certificate:c};case Vt.Received:case Vt.Unknown:case Vt.Processing:{let d=n.strategy??Ku();return await d(t,r,p),Wa(e,t,r,{...n,strategy:d,request:s})}case Vt.Rejected:{let d=new Uint8Array(Ve(c.lookup_path([...o,"reject_code"])))[0],l=new TextDecoder().decode(Ve(c.lookup_path([...o,"reject_message"]))),f=Ve(c.lookup_path([...o,"error_code"])),h=f?new TextDecoder().decode(f):void 0;throw gr.fromCode(new Ln(r,d,l,h))}case Vt.Done:throw ge.fromCode(new Ei(r))}throw Tr}async function dm(e){let{paths:t,agent:r,pollingOptions:n}=e;if(n.request&&Hu(n.request))return n.request;let o=await r.createReadStateRequest?.({paths:t},void 0);if(!Hu(o))throw z.fromCode(new Vi(o));return o}var st=Symbol.for("ic-agent-metadata"),io=class e{static agentOf(t){return t[st].config.agent}static interfaceOf(t){return t[st].service}static canisterIdOf(t){return M.from(t[st].config.canisterId)}static createActorClass(t,r){let n=t({IDL:xn});class o extends e{constructor(s){if(!s.canisterId)throw z.fromCode(new No(s.canisterId));let a=typeof s.canisterId=="string"?M.fromText(s.canisterId):s.canisterId;super({config:{...Ju,...s,canisterId:a},service:n});for(let[c,u]of n._fields)r?.httpDetails&&u.annotations.push(Ya),r?.certificate&&u.annotations.push(zu),this[c]=fm(this,c,u,s.blsVerify)}}return o}static createActor(t,r){if(!r.canisterId)throw z.fromCode(new No(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[st]=Object.freeze(t)}};function oo(e,t){let r=xn.decode(e,t);switch(r.length){case 0:return;case 1:return r[0];default:return r}}var Ju={pollingOptions:$u},Ya="http-details",zu="certificate";function fm(e,t,r,n){let o;r.annotations.includes("query")||r.annotations.includes("composite_query")?o=async(s,...a)=>{s={...s,...e[st].config.queryTransform?.(t,a,{...e[st].config,...s})};let c=s.agent||e[st].config.agent||new lr,u=M.from(s.canisterId||e[st].config.canisterId),p=xn.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 hr.Rejected:{let f=new Ni(d.requestId,d.reject_code,d.reject_message,d.error_code,d.signatures);throw f.callContext={canisterId:u,methodName:t,httpDetails:l},gr.fromCode(f)}case hr.Replied:return r.annotations.includes(Ya)?{httpDetails:l,result:oo(r.retTypes,d.reply.arg)}:oo(r.retTypes,d.reply.arg)}}:o=async(s,...a)=>{s={...s,...e[st].config.callTransform?.(t,a,{...e[st].config,...s})};let c=s.agent||e[st].config.agent||lr.createSync(),{canisterId:u,effectiveCanisterId:p,pollingOptions:d}={...Ju,...e[st].config,...s},l=M.from(u),f=p!==void 0?M.from(p):l,h=xn.encode(r.argTypes,a),{requestId:m,response:g,requestDetails:_}=await c.call(l,{methodName:t,arg:h,effectiveCanisterId:f,nonce:s.nonce}),x,y;if(jc(g.body)){if(c.rootKey==null)throw Oe.fromCode(new Rt);let R=g.body.certificate;y=await Sr.create({certificate:R,rootKey:c.rootKey,canisterId:f,blsVerify:n,agent:c});let I=[ee("request_status"),m];switch(new TextDecoder().decode(Ve(y.lookup_path([...I,"status"])))){case"replied":x=Ve(y.lookup_path([...I,"reply"]));break;case"rejected":{let v=new Uint8Array(Ve(y.lookup_path([...I,"reject_code"])))[0],V=new TextDecoder().decode(Ve(y.lookup_path([...I,"reject_message"]))),S=Ve(y.lookup_path([...I,"error_code"])),b=S?new TextDecoder().decode(S):void 0,N=new Ln(m,v,V,b);throw N.callContext={canisterId:l,methodName:t,httpDetails:g},gr.fromCode(N)}}}else if(Mc(g.body)){let{reject_code:R,reject_message:I,error_code:w}=g.body,v=new Oi(m,R,I,w);throw v.callContext={canisterId:l,methodName:t,httpDetails:g},gr.fromCode(v)}if(g.status===202){let R={...d,blsVerify:n},I=await Wa(c,f,m,R);y=I.certificate,x=I.reply}let T=r.annotations.includes(Ya),E=r.annotations.includes(zu),O={...g,requestDetails:_};if(x!==void 0)return T&&E?{httpDetails:O,certificate:y,result:oo(r.retTypes,x)}:E?{certificate:y,result:oo(r.retTypes,x)}:T?{httpDetails:O,result:oo(r.retTypes,x)}:oo(r.retTypes,x);{let R=new Be(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${r.retTypes.map(I=>I.display()).join(",")}].`);throw R.callContext={canisterId:l,methodName:t,httpDetails:O},ge.fromCode(R)}};let i=(...s)=>o({},...s);return i.withOptions=s=>(...a)=>o(s,...a),i}var hm=(e=>(e[e.FractionalMoreThan8Decimals=0]="FractionalMoreThan8Decimals",e[e.InvalidFormat=1]="InvalidFormat",e[e.FractionalTooManyDecimals=2]="FractionalTooManyDecimals",e))(hm||{}),Nx=BigInt(1e8);var q=e=>e==null,X=e=>!q(e),ec=e=>X(e)&&e!=="",so=e=>!ec(e);var mm=class extends Error{},ei=(e,t)=>{if(e==null)throw new mm(t)};var ur=e=>new Uint8Array(e),ds=e=>Array.from(e);var Yu=({a:e,b:t})=>e.length===t.length&&e.every((r,n)=>r===t[n]);var Wu="abcdefghijklmnopqrstuvwxyz234567",Qo=Object.create(null);for(let e=0;e<Wu.length;e++)Qo[Wu[e]]=e;Qo[0]=Qo.o;Qo[1]=Qo.i;var Cr=e=>btoa(String.fromCharCode(...new Uint8Array(e))),Zu=e=>Uint8Array.from(atob(e),t=>t.charCodeAt(0)),Ox=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 Za="__bigint__",Xa="__principal__",Qa="__uint8array__",Xu=(e,t)=>typeof t=="bigint"?{[Za]:`${t}`}:X(t)&&M.isPrincipal(t)?{[Xa]:M.from(t).toText()}:X(t)&&t instanceof Uint8Array?{[Qa]:Array.from(t)}:t,Qu=(e,t)=>{let r=n=>t[n];return X(t)&&typeof t=="object"&&Za in t?BigInt(r(Za)):X(t)&&typeof t=="object"&&Xa in t?M.fromText(r(Xa)):X(t)&&typeof t=="object"&&Qa in t?Uint8Array.from(r(Qa)):t};var ue=e=>X(e)?[e]:[],ye=e=>e?.[0];var _m=({authData:e})=>{if(e.byteLength<37)return{invalidAuthData:null};if(e.byteLength<53)return{invalidAuthData:null};let t=e.slice(37,53),r=ym({bytes:t});return"aaguid"in r?{aaguidBytes:t,aaguidText:r.aaguid}:{unknownProvider:null}},ym=({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 gm(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 xm(e){return Fn(e,Xo)}var bm=class{constructor(e){this._cose=e,this.#e=xm(e)}#e;toDer(){return this.#e}toRaw(){return new Uint8Array(this.#e)}},od=class{#e;#t;constructor({rawId:e,cose:t}){this.#e=e,this.#t=new bm(t)}getPublicKey(){return this.#t}getCredentialId(){return this.#e}getCredentialIdText(){return Cr(this.#e)}},wm=class extends od{#e;#t;constructor({authData:e,...t}){super(t);let r=_m({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}},Tm=class extends od{},Nm=class extends Error{},Om=class extends Error{},Em=class extends Error{},Rm=class extends Error{},vm=class extends Error{},Im=class extends Error{},Am=class extends Error{},ed=class extends Error{};var Sm={ECDSA_WITH_SHA256:-7,RSA_WITH_SHA256:-257},Fm=6e4,id=()=>window.crypto.getRandomValues(new Uint8Array(16)),Vm=()=>id(),Cm=()=>id(),Pm=()=>{let{location:{href:e}}=window;try{let{hostname:t}=new URL(e);return t}catch{throw new Nm}},sd=({appId:e})=>e?.id??Pm(),Bm=({appId:e,user:t}={})=>{let{document:{title:r}}=window,n=()=>({rp:{name:e?.name??r,id:sd({appId:e})}}),o=()=>({user:{id:Cm(),name:t?.name??t?.displayName??r,displayName:t?.displayName??r}});return{attestation:"direct",challenge:Vm(),...n(),...o(),pubKeyCredParams:Object.values(Sm).map(i=>({type:"public-key",alg:i})),excludeCredentials:[],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"preferred",residentKey:"required",requireResidentKey:!0}}},Dm=(e={})=>({rpId:sd(e),allowCredentials:[],userVerification:"required"}),tc=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}},Pr=(e=>(e[e.RequestingUserCredential=0]="RequestingUserCredential",e[e.FinalizingCredential=1]="FinalizingCredential",e[e.Signing=2]="Signing",e))(Pr||{}),ad=({timeout:e})=>AbortSignal.timeout(e??Fm),Um=async({challenge:e,credentialIds:t,passkeyOptions:r,timeout:n})=>await navigator.credentials.get({publicKey:{...Dm(r),challenge:e.buffer,allowCredentials:(t??[]).map(o=>({id:o.buffer,type:"public-key"}))},signal:ad({timeout:n})}),td=e=>{if(e.status!=="initialized")throw new Om},rd=e=>{if(q(e))throw new Em},nd=({type:e})=>{if(e!=="public-key")throw new Rm},rc=class ti extends Ft{#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=ti.#r({credential:new wm(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:Bm(t),signal:ad({timeout:r})});rd(o),nd(o);let{response:{attestationObject:i},rawId:s}=o;if(q(i))throw new vm;let{authData:a}=Ki.decode(ur(i)),c=gm(a);return new ti({...n,rawId:ur(s),cose:c,authData:a})}static async createWithExistingCredential(t){return new ti(t)}getPublicKey(){td(this.#t);let{credential:t}=this.#t;return t.getPublicKey()}getCredential(){td(this.#t);let{credential:t}=this.#t;return t}async sign(t){let r=await tc({fn:async()=>{let n=await Um({challenge:t,...this.#t.status==="initialized"&&{credentialIds:[this.#t.credential.getCredentialId()]}});return rd(n),nd(n),n},step:0,onProgress:this.#e});return await tc({fn:async()=>{let{rawId:n}=r;if(this.#t.status==="initialized"){if(!Yu({a:this.#t.credential.getCredentialId(),b:ur(n)}))throw new Im;return}let{retrievePublicKey:o}=this.#t,i=await o({credentialId:ur(n)});this.#t=ti.#r({credential:new Tm({rawId:ur(n),cose:i})})},step:1,onProgress:this.#e}),await tc({fn:async()=>{let{response:n}=r,{clientDataJSON:o}=n,{authenticatorData:i,signature:s}="authenticatorData"in n&&"signature"in n?n:{};if(q(i))throw new ed;if(q(s))throw new ed;let a=Ki.encode({authenticator_data:i,client_data_json:new TextDecoder().decode(o),signature:ur(s)});if(q(a))throw new Am;return Object.assign(a,{__signature__:void 0}),a},step:2,onProgress:this.#e})}},km=async()=>X(window.PublicKeyCredential)&&"isUserVerifyingPlatformAuthenticatorAvailable"in PublicKeyCredential?await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable():!1;var ao=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 je=class e extends ao{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 nc=({message:e,detail:t})=>{let r=new CustomEvent(e,{detail:t,bubbles:!0});document.dispatchEvent(r)};var co="http://127.0.0.1:5987",cd="rdmx6-jaaaa-aaaaa-aaadq-cai";var ld=async({identity:e,container:t})=>{let n=X(t)&&t!==!1?t===!0?co:t:"https://icp-api.io",o=X(t);return await lr.create({identity:e,shouldFetchRootKey:o,host:n})};var lo=class e{static instance;#e=void 0;constructor(){}static getInstance(){return q(e.instance)&&(e.instance=new e),e.instance}async getAgent({identity:t,...r}){let n=t.getPrincipal().toText();if(q(this.#e)||q(this.#e[n])){let o=await ld({identity:t,...r});return this.#e={...this.#e??{},[n]:o},o}return this.#e[n]}reset(){this.#e=null}};var uo=class e{static instance;#e=void 0;constructor(){}static getInstance(){return q(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(q(this.#e)||q(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 lo.getInstance().getAgent(n);return io.createActor(t,{agent:o,canisterId:r})}};function ud(e){return e!==null&&typeof e=="object"}var ri=class e{static from(t){if(typeof t=="string"){let r=Ne(t);return this.fromRaw(r)}else if(ud(t)){let r=t;if(ud(r)&&Object.hasOwnProperty.call(r,"__derEncodedPublicKey__"))return this.fromDer(r);if(ArrayBuffer.isView(r)){let n=r;return this.fromRaw(vt(n.buffer))}else{if(r instanceof ArrayBuffer)return this.fromRaw(vt(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=Fn(t,Sn);return r.__derEncodedPublicKey__=void 0,r}static derDecode(t){let r=Vn(t,Sn);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}},Nt=class e extends Ft{static generate(t){if(t&&t.length!==32)throw new Error("Ed25519 Seed needs to be 32 bytes long.");t||(t=Me.utils.randomPrivateKey()),ll(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=Me.getPublicKey(r);return e.fromKeyPair(n,r)}static fromParsedJson(t){let[r,n]=t;return new e(ri.fromDer(Ne(r)),Ne(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(ri.fromRaw(t),r)}static fromSecretKey(t){let r=Me.getPublicKey(t);return e.fromKeyPair(r,t)}#e;#t;constructor(t,r){super(),this.#e=ri.from(t),this.#t=r}toJSON(){return[H(this.#e.toDer()),H(this.#t)]}getKeyPair(){return{secretKey:this.#t,publicKey:this.#e}}getPublicKey(){return this.#e}async sign(t){let r=Me.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=Ne(a)),vt(a)));return Me.verify(o,i,s)}};var oc=class e extends Error{constructor(t){super(t),this.message=t,Object.setPrototypeOf(this,e.prototype)}};function dd(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 oc("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 Ct=class e extends Ft{static async generate(t){let{extractable:r=!1,keyUsages:n=["sign","verify"],subtleCrypto:o}=t??{},i=dd(o),s=await i.generateKey({name:"ECDSA",namedCurve:"P-256"},r,n),a=vt(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=dd(r),o=vt(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=vt(await this._subtleCrypto.sign(r,this._keyPair.privateKey,t));return Object.assign(n,{__signature__:void 0}),n}};var ps=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 M.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 fs(e){return e instanceof Uint8Array?H(e):H(new Uint8Array(e))}function ic(e){if(typeof e!="string"||e.length<64)throw new Error("Invalid public key.");return Ne(e)}var Br=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:fs(this.pubkey),...this.targets&&{targets:this.targets.map(t=>t.toHex())}}}};async function Lm(e,t,r,n){let o=new Br(t.toDer(),BigInt(+r)*BigInt(1e6),n),i=new Uint8Array([...ra,...new Uint8Array(Xt({...o}))]),s=await e.sign(i);return{delegation:o,signature:s}}var dr=class e{static async create(t,r,n=new Date(Date.now()+900*1e3),o={}){let i=await Lm(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 Br(ic(c),BigInt("0x"+u),p&&p.map(d=>{if(typeof d!="string")throw new Error("Invalid target.");return M.fromHex(d)})),signature:ic(a)}});return new this(o,ic(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:fs(r.pubkey),...o&&{targets:o.map(i=>i.toHex())}},signature:fs(n)}}),publicKey:fs(this.publicKey)}}},pr=class extends Ft{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 Xt(r);return{...n,body:{content:r,sender_sig:await this.sign(new Uint8Array([...Vo,...new Uint8Array(o)])),sender_delegation:this._delegation.delegations,sender_pubkey:this._delegation.publicKey}}}},ni=class e extends ps{#e;get delegation(){return this.#e}constructor(t,r){super(t),this.#e=r}static fromDelegation(t,r){return new e(t,r)}};function sc(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"?M.fromText(o):o)):r.push(typeof n=="string"?M.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 pd=["mousedown","mousemove","keydown","touchstart","wheel"],oi=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),pd.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);pd.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 qm=(e,t)=>t.some(r=>e instanceof r),fd,hd;function Mm(){return fd||(fd=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function jm(){return hd||(hd=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}var md=new WeakMap,cc=new WeakMap,_d=new WeakMap,ac=new WeakMap,uc=new WeakMap;function Km(e){let t=new Promise((r,n)=>{let o=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{r(Pt(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(()=>{}),uc.set(t,e),t}function Hm(e){if(cc.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)});cc.set(e,t)}var lc={get(e,t,r){if(e instanceof IDBTransaction){if(t==="done")return cc.get(e);if(t==="objectStoreNames")return e.objectStoreNames||_d.get(e);if(t==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Pt(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 yd(e){lc=e(lc)}function $m(e){return e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(t,...r){let n=e.call(hs(this),t,...r);return _d.set(n,t.sort?t.sort():[t]),Pt(n)}:jm().includes(e)?function(...t){return e.apply(hs(this),t),Pt(md.get(this))}:function(...t){return Pt(e.apply(hs(this),t))}}function Gm(e){return typeof e=="function"?$m(e):(e instanceof IDBTransaction&&Hm(e),qm(e,Mm())?new Proxy(e,lc):e)}function Pt(e){if(e instanceof IDBRequest)return Km(e);if(ac.has(e))return ac.get(e);let t=Gm(e);return t!==e&&(ac.set(e,t),uc.set(t,e)),t}var hs=e=>uc.get(e);function xd(e,t,{blocked:r,upgrade:n,blocking:o,terminated:i}={}){let s=indexedDB.open(e,t),a=Pt(s);return n&&s.addEventListener("upgradeneeded",c=>{n(Pt(s.result),c.oldVersion,c.newVersion,Pt(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 Jm=["get","getKey","getAll","getAllKeys","count"],zm=["put","add","delete","clear"],dc=new Map;function gd(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t=="string"))return;if(dc.get(t))return dc.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,o=zm.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(o||Jm.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 dc.set(t,i),i}yd(e=>({...e,get:(t,r,n)=>gd(t,r)||e.get(t,r,n),has:(t,r)=>!!gd(t,r)||e.has(t,r)}));var bd="auth-client-db",wd="ic-keyval",Wm=async(e=bd,t=wd,r)=>(globalThis.localStorage?.getItem(Ke)&&(globalThis.localStorage.removeItem(Ke),globalThis.localStorage.removeItem(He)),await xd(e,r,{upgrade:n=>{n.objectStoreNames.contains(t)&&n.clear(t),n.createObjectStore(t)}}));async function Ym(e,t,r){return await e.get(t,r)}async function Zm(e,t,r,n){return await e.put(t,n,r)}async function Xm(e,t,r){return await e.delete(t,r)}var ms=class e{constructor(t,r){this._db=t,this._storeName=r}static async create(t){let{dbName:r=bd,storeName:n=wd,version:o=Td}=t??{},i=await Wm(r,n,o);return new e(i,n)}async set(t,r){return await Zm(this._db,this._storeName,t,r)}async get(t){return await Ym(this._db,this._storeName,t)??null}async remove(t){return await Xm(this._db,this._storeName,t)}};var He="identity",Ke="delegation",Nd="iv",Td=1,ii=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}},Bt=class{#e;constructor(t){this.#e=t??{}}initializedDb;get _db(){return new Promise((t,r)=>{if(this.initializedDb){t(this.initializedDb);return}ms.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 Qm=BigInt(1e9),e_=BigInt(3600),t_=Qm*e_,r_="https://identity.internetcomputer.org",n_="#authorize",o_=BigInt(8)*t_,pc="ECDSA",fc="Ed25519",i_=500,_s="UserInterrupt",si=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 Bt,n=t.keyType??pc,o=null;if(t.identity)o=t.identity;else{let c=await r.get(He);if(!c)try{let u=new ii,p=await u.get(Ke),d=await u.get(He);p&&d&&n===pc&&(console.log("Discovered an identity stored in localstorage. Migrating to IndexedDB"),await r.set(Ke,p),await r.set(He,d),c=p,await u.remove(Ke),await u.remove(He))}catch(u){console.error(`error while attempting to recover localstorage: ${u}`)}if(c)try{typeof c=="object"?n===fc&&typeof c=="string"?o=Nt.fromJSON(c):o=await Ct.fromKeyPair(c):typeof c=="string"&&(o=Nt.fromJSON(c))}catch{}}let i=new rt,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=dr.fromJSON(c),sc(s)?"toDer"in o?i=ni.fromDelegation(o,s):i=pr.fromDelegation(o,s):(await hc(r),o=null))}catch(c){console.error(c),await hc(r),o=null}let a;return t.idleOptions?.disableIdle?a=void 0:(s||t.identity)&&(a=oi.create(t.idleOptions)),o||(n===fc?o=Nt.generate():(t.storage&&n===pc&&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 '${fc}' as the key type, as it can serialize to a string`),o=await Ct.generate()),await Od(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 Br(a.delegation.pubkey,a.delegation.expiration,a.delegation.targets),signature:a.signature})),o=dr.fromDelegations(n,t.userPublicKey),i=this._key;if(!i)return;this._chain=o,"toDer"in i?this._identity=ni.fromDelegation(i,this._chain):this._identity=pr.fromDelegation(i,this._chain),this._idpWindow?.close();let s=this._createOptions?.idleOptions;!this.idleManager&&!s?.disableIdle&&(this.idleManager=oi.create(s),this._registerDefaultIdleCallback()),this._removeEventListener(),delete this._idpWindow,this._chain&&await this._storage.set(Ke,JSON.stringify(this._chain.toJSON())),await Od(this._storage,this._key),r?.(t)}getIdentity(){return this._identity}async isAuthenticated(){return!this.getIdentity().getPrincipal().isAnonymous()&&this._chain!==null&&sc(this._chain)}async login(t){let r=s_(this._createOptions?.loginOptions,t),n=r?.maxTimeToLive??o_,o=new URL(r?.identityProvider?.toString()||r_);o.hash=n_,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(_s,r?.onError):setTimeout(i,i_))};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 hc(this._storage),this._identity=new rt,this._chain=null,t.returnTo)try{window.history.pushState({},"",t.returnTo)}catch{window.location.href=t.returnTo}}};async function hc(e){await e.remove(He),await e.remove(Ke),await e.remove(Nd)}function s_(e,t){if(!e&&!t)return;let r=e?.customValues||t?.customValues?{...e?.customValues,...t?.customValues}:void 0;return{...e,...t,customValues:r}}function a_(e){if(e instanceof Ct)return e.getKeyPair();if(e instanceof Nt)return JSON.stringify(e.toJSON());throw new Error("Unsupported key type")}async function Od(e,t){let r=a_(t);await e.set(He,r)}var $e=class e{static#e;#t;constructor(){}static getInstance(){return q(this.#e)&&(this.#e=new e),this.#e}createAuthClient=async()=>(this.#t=await si.create({idleOptions:{disableIdle:!0,disableDefaultIdleCallback:!0}}),this.#t);safeCreateAuthClient=async()=>(await new Bt().remove(He),await this.createAuthClient());getAuthClient=()=>this.#t;logout=async()=>{await this.#t?.logout(),this.#t=null};setAuthClientStorage=async({delegationChain:t,sessionKey:r})=>{let n=new Bt;await Promise.all([n.set(He,r.getKeyPair()),n.set(Ke,JSON.stringify(t.toJSON()))])}};var mc=async e=>{await c_(),await $e.getInstance().createAuthClient(),e?.windowReload!==!1&&window.location.reload()},c_=async()=>{await $e.getInstance().logout(),je.getInstance().reset(),uo.getInstance().reset(),lo.getInstance().reset()};var Ed=e=>{let t=e===!0?"./workers/auth.worker.js":e,r=new Worker(t),n=async()=>{nc({message:"junoSignOutAuthTimer"}),await mc()};return r.onmessage=async({data:o})=>{let{msg:i,data:s}=o;switch(i){case"junoSignOutAuthTimer":await n();return;case"junoDelegationRemainingTime":nc({message:"junoDelegationRemainingTime",detail:s?.authRemainingTime});return}},je.getInstance().subscribe(o=>{if(q(o)){r.postMessage({msg:"junoStopAuthTimer"});return}r.postMessage({msg:"junoStartAuthTimer"})})};var ai=async({fn:e})=>{let{createAuthClient:t,safeCreateAuthClient:r}=$e.getInstance();if(!await(await t()).isAuthenticated()){await r();return}await e()};var _c=({error:e,type:t})=>typeof e=="string"?e.includes(t):e instanceof Error?e.message.includes(t):!1;var Rd="juno.datastore.error.user.cannot_update";var Dt={certified:!1};var ys=()=>$e.getInstance().getAuthClient()?.getIdentity(),l_=async()=>{let{getAuthClient:e,createAuthClient:t}=$e.getInstance();return(e()??await t()).getIdentity()},u_=async()=>{let e=je.getInstance().get();if(q(e))return null;let t=$e.getInstance().getAuthClient();return await t?.isAuthenticated()??!1?t?.getIdentity()??null:null};var de=e=>X(e)?e:ys()??new rt;var yc=({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}),f=e.Variant({PrepareDelegation:l,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),m=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),g=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),_=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),x=e.Record({field:_,desc:e.Bool}),y=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),T=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(y),description:e.Opt(e.Text),created_at:e.Opt(y)}),E=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),O=e.Record({order:e.Opt(x),owner:e.Opt(e.Principal),matcher:e.Opt(T),paginate:e.Opt(E)}),R=e.Record({controllers:e.Vec(e.Principal)}),I=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),w=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:I,expires_at:e.Opt(e.Nat64)}),v=e.Record({version:e.Opt(e.Nat64)}),V=e.Variant({Db:e.Null,Storage:e.Null}),S=e.Record({version:e.Opt(e.Nat64)}),b=e.Record({proposal_ids:e.Vec(e.Nat)}),N=e.Record({cycles:e.Nat,destination_id:e.Principal}),F=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}),B=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),k=e.Record({key:F,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,B)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),A=e.Variant({Google:e.Null}),C=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),P=e.Record({delegation:e.Opt(C),client_id:e.Text}),D=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(A,P))}),U=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),te=e.Record({allowed_callers:e.Vec(e.Principal)}),Q=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(D),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(U),rules:e.Opt(te)}),$=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),ie=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt($)}),pe=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),Ae=e.Variant({Deny:e.Null,Allow:e.Null}),re=e.Record({status_code:e.Nat16,location:e.Text}),ce=e.Record({iframe:e.Opt(pe),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($),raw_access:e.Opt(Ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,re)))}),Ur=e.Record({db:e.Opt(ie),authentication:e.Opt(Q),storage:ce}),kt=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),Ye=e.Variant({OpenId:kt}),kr=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),Lr=e.Record({signature:e.Vec(e.Nat8),delegation:kr}),at=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),qr=e.Variant({Ok:Lr,Err:at}),Mr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),jr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Lt=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),ct=e.Variant({AssetsUpgrade:jr,SegmentsDeployment:Lt}),Ze=e.Record({status:Mr,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:ct}),Xe=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),lt=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ut=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:Xe,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(lt),write:Xe,max_changes_per_user:e.Opt(e.Nat32)}),Kr=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)}),dt=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}),Hr=e.Variant({Callback:e.Record({token:dt,callback:e.Func([],[],["query"])})}),$r=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Hr),status_code:e.Nat16}),Gr=e.Record({token:e.Opt(dt),body:e.Vec(e.Nat8)}),pt=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}),Qe=e.Record({batch_id:e.Nat}),Jr=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,k)),items_length:e.Nat64}),zr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),Wr=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}),Yr=e.Record({desc:e.Bool}),Zr=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Xr=e.Record({order:e.Opt(Yr),paginate:e.Opt(Zr)}),Qr=e.Record({proposal_id:e.Nat}),en=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Qr,Ze)),items_length:e.Nat64}),tn=e.Record({include_system:e.Bool}),rn=e.Record({matcher:e.Opt(tn)}),nn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ut)),items_length:e.Nat64}),on=e.Record({stable:e.Nat64,heap:e.Nat64}),qt=e.Record({openid:e.Opt(D),version:e.Opt(e.Nat64),internet_identity:e.Opt(U),rules:e.Opt(te)}),sn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:I,expires_at:e.Opt(e.Nat64)}),an=e.Record({controller:sn,controllers:e.Vec(e.Principal)}),cn=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt($)}),Mt=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Bs=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:Xe,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(lt),write:Xe,max_changes_per_user:e.Opt(e.Nat32)}),Ds=e.Record({iframe:e.Opt(pe),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($),raw_access:e.Opt(Ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,re)))}),fo=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),ho=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),commit_asset_upload:e.Func([m],[],[]),commit_proposal:e.Func([g],[e.Null],[]),commit_proposal_asset_upload:e.Func([m],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(m)],[],[]),count_assets:e.Func([e.Text,O],[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,O],[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_controllers:e.Func([R],[e.Vec(e.Tuple(e.Principal,w))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,v],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,O],[],[]),del_filtered_docs:e.Func([e.Text,O],[],[]),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,v))],[],[]),del_rule:e.Func([V,e.Text,S],[],[]),delete_proposal_assets:e.Func([b],[],[]),deposit_cycles:e.Func([N],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(k)],["query"]),get_auth_config:e.Func([],[e.Opt(Q)],["query"]),get_config:e.Func([],[Ur],[]),get_db_config:e.Func([],[e.Opt(ie)],["query"]),get_delegation:e.Func([Ye],[qr],["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(k)))],["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(Ze)],["query"]),get_rule:e.Func([V,e.Text],[e.Opt(ut)],["query"]),get_storage_config:e.Func([],[ce],["query"]),http_request:e.Func([Kr],[$r],["query"]),http_request_streaming_callback:e.Func([dt],[Gr],["query"]),init_asset_upload:e.Func([pt],[Qe],[]),init_proposal:e.Func([ct],[e.Nat,Ze],[]),init_proposal_asset_upload:e.Func([pt,e.Nat],[Qe],[]),init_proposal_many_assets_upload:e.Func([e.Vec(pt),e.Nat],[e.Vec(e.Tuple(e.Text,Qe))],[]),list_assets:e.Func([e.Text,O],[Jr],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,w))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,zr))],["query"]),list_docs:e.Func([e.Text,O],[Wr],["query"]),list_proposals:e.Func([Xr],[en],["query"]),list_rules:e.Func([V,rn],[nn],["query"]),memory_size:e.Func([],[on],["query"]),reject_proposal:e.Func([g],[e.Null],[]),set_auth_config:e.Func([qt],[Q],[]),set_controllers:e.Func([an],[e.Vec(e.Tuple(e.Principal,w))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([cn],[ie],[]),set_doc:e.Func([e.Text,e.Text,Mt],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Mt))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([V,e.Text,Bs],[ut],[]),set_storage_config:e.Func([Ds],[ce],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ze],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([fo],[ho],[]),upload_proposal_asset_chunk:e.Func([fo],[ho],[])})},gc=({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}),f=e.Variant({PrepareDelegation:l,RegisterUser:e.Text}),h=e.Variant({Ok:c,Err:f}),m=e.Record({batch_id:e.Nat,headers:e.Vec(e.Tuple(e.Text,e.Text)),chunk_ids:e.Vec(e.Nat)}),g=e.Record({sha256:e.Vec(e.Nat8),proposal_id:e.Nat}),_=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),x=e.Record({field:_,desc:e.Bool}),y=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),T=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(y),description:e.Opt(e.Text),created_at:e.Opt(y)}),E=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),O=e.Record({order:e.Opt(x),owner:e.Opt(e.Principal),matcher:e.Opt(T),paginate:e.Opt(E)}),R=e.Record({controllers:e.Vec(e.Principal)}),I=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),w=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:I,expires_at:e.Opt(e.Nat64)}),v=e.Record({version:e.Opt(e.Nat64)}),V=e.Variant({Db:e.Null,Storage:e.Null}),S=e.Record({version:e.Opt(e.Nat64)}),b=e.Record({proposal_ids:e.Vec(e.Nat)}),N=e.Record({cycles:e.Nat,destination_id:e.Principal}),F=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}),B=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),k=e.Record({key:F,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,B)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),A=e.Variant({Google:e.Null}),C=e.Record({targets:e.Opt(e.Vec(e.Principal)),max_time_to_live:e.Opt(e.Nat64)}),P=e.Record({delegation:e.Opt(C),client_id:e.Text}),D=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(A,P))}),U=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),te=e.Record({allowed_callers:e.Vec(e.Principal)}),Q=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(D),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(U),rules:e.Opt(te)}),$=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),ie=e.Record({updated_at:e.Opt(e.Nat64),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),max_memory_size:e.Opt($)}),pe=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),Ae=e.Variant({Deny:e.Null,Allow:e.Null}),re=e.Record({status_code:e.Nat16,location:e.Text}),ce=e.Record({iframe:e.Opt(pe),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($),raw_access:e.Opt(Ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,re)))}),Ur=e.Record({db:e.Opt(ie),authentication:e.Opt(Q),storage:ce}),kt=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),Ye=e.Variant({OpenId:kt}),kr=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),Lr=e.Record({signature:e.Vec(e.Nat8),delegation:kr}),at=e.Variant({JwtFindProvider:u,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:p,GetOrFetchJwks:d,DeriveSeedFailed:e.Text}),qr=e.Variant({Ok:Lr,Err:at}),Mr=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),jr=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Lt=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),ct=e.Variant({AssetsUpgrade:jr,SegmentsDeployment:Lt}),Ze=e.Record({status:Mr,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:ct}),Xe=e.Variant({Controllers:e.Null,Private:e.Null,Public:e.Null,Managed:e.Null}),lt=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),ut=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),updated_at:e.Nat64,max_size:e.Opt(e.Nat),read:Xe,created_at:e.Nat64,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(lt),write:Xe,max_changes_per_user:e.Opt(e.Nat32)}),Kr=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)}),dt=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}),Hr=e.Variant({Callback:e.Record({token:dt,callback:e.Func([],[],[])})}),$r=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(Hr),status_code:e.Nat16}),Gr=e.Record({token:e.Opt(dt),body:e.Vec(e.Nat8)}),pt=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}),Qe=e.Record({batch_id:e.Nat}),Jr=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,k)),items_length:e.Nat64}),zr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),Wr=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}),Yr=e.Record({desc:e.Bool}),Zr=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Xr=e.Record({order:e.Opt(Yr),paginate:e.Opt(Zr)}),Qr=e.Record({proposal_id:e.Nat}),en=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(Qr,Ze)),items_length:e.Nat64}),tn=e.Record({include_system:e.Bool}),rn=e.Record({matcher:e.Opt(tn)}),nn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(e.Text,ut)),items_length:e.Nat64}),on=e.Record({stable:e.Nat64,heap:e.Nat64}),qt=e.Record({openid:e.Opt(D),version:e.Opt(e.Nat64),internet_identity:e.Opt(U),rules:e.Opt(te)}),sn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:I,expires_at:e.Opt(e.Nat64)}),an=e.Record({controller:sn,controllers:e.Vec(e.Principal)}),cn=e.Record({version:e.Opt(e.Nat64),max_memory_size:e.Opt($)}),Mt=e.Record({data:e.Vec(e.Nat8),description:e.Opt(e.Text),version:e.Opt(e.Nat64)}),Bs=e.Record({max_capacity:e.Opt(e.Nat32),memory:e.Opt(t),max_size:e.Opt(e.Nat),read:Xe,version:e.Opt(e.Nat64),mutable_permissions:e.Opt(e.Bool),rate_config:e.Opt(lt),write:Xe,max_changes_per_user:e.Opt(e.Nat32)}),Ds=e.Record({iframe:e.Opt(pe),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($),raw_access:e.Opt(Ae),redirects:e.Opt(e.Vec(e.Tuple(e.Text,re)))}),fo=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),ho=e.Record({chunk_id:e.Nat});return e.Service({authenticate:e.Func([i],[h],[]),commit_asset_upload:e.Func([m],[],[]),commit_proposal:e.Func([g],[e.Null],[]),commit_proposal_asset_upload:e.Func([m],[],[]),commit_proposal_many_assets_upload:e.Func([e.Vec(m)],[],[]),count_assets:e.Func([e.Text,O],[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,O],[e.Nat64],[]),count_proposals:e.Func([],[e.Nat64],[]),del_asset:e.Func([e.Text,e.Text],[],[]),del_assets:e.Func([e.Text],[],[]),del_controllers:e.Func([R],[e.Vec(e.Tuple(e.Principal,w))],[]),del_custom_domain:e.Func([e.Text],[],[]),del_doc:e.Func([e.Text,e.Text,v],[],[]),del_docs:e.Func([e.Text],[],[]),del_filtered_assets:e.Func([e.Text,O],[],[]),del_filtered_docs:e.Func([e.Text,O],[],[]),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,v))],[],[]),del_rule:e.Func([V,e.Text,S],[],[]),delete_proposal_assets:e.Func([b],[],[]),deposit_cycles:e.Func([N],[],[]),get_asset:e.Func([e.Text,e.Text],[e.Opt(k)],[]),get_auth_config:e.Func([],[e.Opt(Q)],[]),get_config:e.Func([],[Ur],[]),get_db_config:e.Func([],[e.Opt(ie)],[]),get_delegation:e.Func([Ye],[qr],[]),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(k)))],[]),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(Ze)],[]),get_rule:e.Func([V,e.Text],[e.Opt(ut)],[]),get_storage_config:e.Func([],[ce],[]),http_request:e.Func([Kr],[$r],[]),http_request_streaming_callback:e.Func([dt],[Gr],[]),init_asset_upload:e.Func([pt],[Qe],[]),init_proposal:e.Func([ct],[e.Nat,Ze],[]),init_proposal_asset_upload:e.Func([pt,e.Nat],[Qe],[]),init_proposal_many_assets_upload:e.Func([e.Vec(pt),e.Nat],[e.Vec(e.Tuple(e.Text,Qe))],[]),list_assets:e.Func([e.Text,O],[Jr],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,w))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,zr))],[]),list_docs:e.Func([e.Text,O],[Wr],[]),list_proposals:e.Func([Xr],[en],[]),list_rules:e.Func([V,rn],[nn],[]),memory_size:e.Func([],[on],[]),reject_proposal:e.Func([g],[e.Null],[]),set_auth_config:e.Func([qt],[Q],[]),set_controllers:e.Func([an],[e.Vec(e.Tuple(e.Principal,w))],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_db_config:e.Func([cn],[ie],[]),set_doc:e.Func([e.Text,e.Text,Mt],[s],[]),set_many_docs:e.Func([e.Vec(e.Tuple(e.Text,e.Text,Mt))],[e.Vec(e.Tuple(e.Text,s))],[]),set_rule:e.Func([V,e.Text,Bs],[ut],[]),set_storage_config:e.Func([Ds],[ce],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ze],[]),switch_storage_system_memory:e.Func([],[],[]),upload_asset_chunk:e.Func([fo],[ho],[]),upload_proposal_asset_chunk:e.Func([fo],[ho],[])})},d_=({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({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)}),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,mission_control: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}),m=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),g=e.Variant({PrepareDelegation:m,RegisterUser:e.Text}),_=e.Variant({Ok:d,Err:g}),x=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({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),user:e.Principal}),E=e.Variant({Heap:e.Null,Stable:e.Null}),O=e.Record({system_memory:e.Opt(E)}),R=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(O),user:e.Principal}),I=e.Record({controllers:e.Vec(e.Principal)}),w=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)}),V=e.Record({delegation:e.Opt(v),client_id:e.Text}),S=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,V))}),b=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),N=e.Record({allowed_callers:e.Vec(e.Principal)}),F=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(S),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(b),rules:e.Opt(N)}),B=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),k=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),A=e.Variant({Deny:e.Null,Allow:e.Null}),C=e.Record({status_code:e.Nat16,location:e.Text}),P=e.Record({iframe:e.Opt(B),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(k),raw_access:e.Opt(A),redirects:e.Opt(e.Vec(e.Tuple(e.Text,C)))}),D=e.Record({authentication:e.Opt(F),storage:P}),U=e.Record({user:e.Principal}),te=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),Q=e.Variant({OpenId:te}),$=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),ie=e.Record({signature:e.Vec(e.Nat8),delegation:$}),pe=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),Ae=e.Variant({Ok:ie,Err:pe}),re=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),ce=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Ur=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),kt=e.Variant({AssetsUpgrade:ce,SegmentsDeployment:Ur}),Ye=e.Record({status:re,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:kt}),kr=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)}),Lr=e.Variant({Heap:e.Null,Stable:e.Null}),at=e.Record({memory:Lr,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}),qr=e.Variant({Callback:e.Record({token:at,callback:e.Func([],[],["query"])})}),Mr=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(qr),status_code:e.Nat16}),jr=e.Record({token:e.Opt(at),body:e.Vec(e.Nat8)}),Lt=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}),ct=e.Record({batch_id:e.Nat}),Ze=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),Xe=e.Record({field:Ze,desc:e.Bool}),lt=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),ut=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(lt),description:e.Opt(e.Text),created_at:e.Opt(lt)}),Kr=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),dt=e.Record({order:e.Opt(Xe),owner:e.Opt(e.Principal),matcher:e.Opt(ut),paginate:e.Opt(Kr)}),Hr=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}),$r=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),Gr=e.Record({key:Hr,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,$r)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),pt=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,Gr)),items_length:e.Nat64}),Qe=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),Jr=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:Qe,expires_at:e.Opt(e.Nat64)}),zr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),Wr=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),Yr=e.Record({status:Wr,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)}),Zr=e.Record({desc:e.Bool}),Xr=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Qr=e.Record({order:e.Opt(Zr),paginate:e.Opt(Xr)}),en=e.Record({proposal_id:e.Nat}),tn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(en,Ye)),items_length:e.Nat64}),rn=e.Record({openid:e.Opt(S),version:e.Opt(e.Nat64),internet_identity:e.Opt(b),rules:e.Opt(N)}),nn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:Qe,expires_at:e.Opt(e.Nat64)}),on=e.Record({controller:nn,controllers:e.Vec(e.Principal)}),qt=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),sn=e.Record({iframe:e.Opt(B),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(k),raw_access:e.Opt(A),redirects:e.Opt(e.Vec(e.Tuple(e.Text,C)))}),an=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),cn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Mt=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],[_],[]),commit_proposal:e.Func([x],[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_orbiter:e.Func([T],[e.Principal],[]),create_satellite:e.Func([R],[e.Principal],[]),del_controllers:e.Func([I],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([w],[],[]),get_auth_config:e.Func([],[e.Opt(F)],["query"]),get_config:e.Func([],[D],["query"]),get_create_orbiter_fee:e.Func([U],[e.Opt(t)],["query"]),get_create_satellite_fee:e.Func([U],[e.Opt(t)],["query"]),get_credits:e.Func([],[t],["query"]),get_delegation:e.Func([Q],[Ae],["query"]),get_proposal:e.Func([e.Nat],[e.Opt(Ye)],["query"]),get_storage_config:e.Func([],[P],["query"]),get_user_mission_control_center:e.Func([],[e.Opt(p)],["query"]),http_request:e.Func([kr],[Mr],["query"]),http_request_streaming_callback:e.Func([at],[jr],["query"]),init_proposal:e.Func([kt],[e.Nat,Ye],[]),init_proposal_asset_upload:e.Func([Lt,e.Nat],[ct],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Lt),e.Nat],[e.Vec(e.Tuple(e.Text,ct))],[]),init_user_mission_control_center:e.Func([],[p],[]),list_assets:e.Func([e.Text,dt],[pt],["query"]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,Jr))],["query"]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,zr))],["query"]),list_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,Yr))],["query"]),list_proposals:e.Func([Qr],[tn],["query"]),list_user_mission_control_centers:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],["query"]),reject_proposal:e.Func([x],[e.Null],[]),set_auth_config:e.Func([rn],[F],[]),set_controllers:e.Func([on],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([qt,t],[],[]),set_storage_config:e.Func([sn],[P],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ye],[]),update_rate_config:e.Func([qt,an],[],[]),upload_proposal_asset_chunk:e.Func([cn],[Mt],[])})},p_=({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({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)}),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,mission_control: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}),m=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),g=e.Variant({PrepareDelegation:m,RegisterUser:e.Text}),_=e.Variant({Ok:d,Err:g}),x=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({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),user:e.Principal}),E=e.Variant({Heap:e.Null,Stable:e.Null}),O=e.Record({system_memory:e.Opt(E)}),R=e.Record({block_index:e.Opt(e.Nat64),subnet_id:e.Opt(e.Principal),storage:e.Opt(O),user:e.Principal}),I=e.Record({controllers:e.Vec(e.Principal)}),w=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)}),V=e.Record({delegation:e.Opt(v),client_id:e.Text}),S=e.Record({observatory_id:e.Opt(e.Principal),providers:e.Vec(e.Tuple(s,V))}),b=e.Record({derivation_origin:e.Opt(e.Text),external_alternative_origins:e.Opt(e.Vec(e.Text))}),N=e.Record({allowed_callers:e.Vec(e.Principal)}),F=e.Record({updated_at:e.Opt(e.Nat64),openid:e.Opt(S),created_at:e.Opt(e.Nat64),version:e.Opt(e.Nat64),internet_identity:e.Opt(b),rules:e.Opt(N)}),B=e.Variant({Deny:e.Null,AllowAny:e.Null,SameOrigin:e.Null}),k=e.Record({stable:e.Opt(e.Nat64),heap:e.Opt(e.Nat64)}),A=e.Variant({Deny:e.Null,Allow:e.Null}),C=e.Record({status_code:e.Nat16,location:e.Text}),P=e.Record({iframe:e.Opt(B),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(k),raw_access:e.Opt(A),redirects:e.Opt(e.Vec(e.Tuple(e.Text,C)))}),D=e.Record({authentication:e.Opt(F),storage:P}),U=e.Record({user:e.Principal}),te=e.Record({jwt:e.Text,session_key:e.Vec(e.Nat8),salt:e.Vec(e.Nat8),expiration:e.Nat64}),Q=e.Variant({OpenId:te}),$=e.Record({pubkey:e.Vec(e.Nat8),targets:e.Opt(e.Vec(e.Principal)),expiration:e.Nat64}),ie=e.Record({signature:e.Vec(e.Nat8),delegation:$}),pe=e.Variant({JwtFindProvider:l,GetCachedJwks:e.Null,NoSuchDelegation:e.Null,JwtVerify:f,GetOrFetchJwks:h,DeriveSeedFailed:e.Text}),Ae=e.Variant({Ok:ie,Err:pe}),re=e.Variant({Initialized:e.Null,Failed:e.Null,Open:e.Null,Rejected:e.Null,Executed:e.Null,Accepted:e.Null}),ce=e.Record({clear_existing_assets:e.Opt(e.Bool)}),Ur=e.Record({orbiter:e.Opt(e.Text),mission_control_version:e.Opt(e.Text),satellite_version:e.Opt(e.Text)}),kt=e.Variant({AssetsUpgrade:ce,SegmentsDeployment:Ur}),Ye=e.Record({status:re,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:kt}),kr=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)}),Lr=e.Variant({Heap:e.Null,Stable:e.Null}),at=e.Record({memory:Lr,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}),qr=e.Variant({Callback:e.Record({token:at,callback:e.Func([],[],[])})}),Mr=e.Record({body:e.Vec(e.Nat8),headers:e.Vec(e.Tuple(e.Text,e.Text)),streaming_strategy:e.Opt(qr),status_code:e.Nat16}),jr=e.Record({token:e.Opt(at),body:e.Vec(e.Nat8)}),Lt=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}),ct=e.Record({batch_id:e.Nat}),Ze=e.Variant({UpdatedAt:e.Null,Keys:e.Null,CreatedAt:e.Null}),Xe=e.Record({field:Ze,desc:e.Bool}),lt=e.Variant({Equal:e.Nat64,Between:e.Tuple(e.Nat64,e.Nat64),GreaterThan:e.Nat64,LessThan:e.Nat64}),ut=e.Record({key:e.Opt(e.Text),updated_at:e.Opt(lt),description:e.Opt(e.Text),created_at:e.Opt(lt)}),Kr=e.Record({start_after:e.Opt(e.Text),limit:e.Opt(e.Nat64)}),dt=e.Record({order:e.Opt(Xe),owner:e.Opt(e.Principal),matcher:e.Opt(ut),paginate:e.Opt(Kr)}),Hr=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}),$r=e.Record({modified:e.Nat64,sha256:e.Vec(e.Nat8),total_length:e.Nat}),Gr=e.Record({key:Hr,updated_at:e.Nat64,encodings:e.Vec(e.Tuple(e.Text,$r)),headers:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,version:e.Opt(e.Nat64)}),pt=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,Gr)),items_length:e.Nat64}),Qe=e.Variant({Write:e.Null,Admin:e.Null,Submit:e.Null}),Jr=e.Record({updated_at:e.Nat64,metadata:e.Vec(e.Tuple(e.Text,e.Text)),created_at:e.Nat64,scope:Qe,expires_at:e.Opt(e.Nat64)}),zr=e.Record({updated_at:e.Nat64,created_at:e.Nat64,version:e.Opt(e.Nat64),bn_id:e.Opt(e.Text)}),Wr=e.Variant({Refunded:e.Null,Acknowledged:e.Null,Completed:e.Null}),Yr=e.Record({status:Wr,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)}),Zr=e.Record({desc:e.Bool}),Xr=e.Record({start_after:e.Opt(e.Nat),limit:e.Opt(e.Nat)}),Qr=e.Record({order:e.Opt(Zr),paginate:e.Opt(Xr)}),en=e.Record({proposal_id:e.Nat}),tn=e.Record({matches_length:e.Nat64,items:e.Vec(e.Tuple(en,Ye)),items_length:e.Nat64}),rn=e.Record({openid:e.Opt(S),version:e.Opt(e.Nat64),internet_identity:e.Opt(b),rules:e.Opt(N)}),nn=e.Record({metadata:e.Vec(e.Tuple(e.Text,e.Text)),scope:Qe,expires_at:e.Opt(e.Nat64)}),on=e.Record({controller:nn,controllers:e.Vec(e.Principal)}),qt=e.Variant({Orbiter:e.Null,MissionControl:e.Null,Satellite:e.Null}),sn=e.Record({iframe:e.Opt(B),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(k),raw_access:e.Opt(A),redirects:e.Opt(e.Vec(e.Tuple(e.Text,C)))}),an=e.Record({max_tokens:e.Nat64,time_per_token_ns:e.Nat64}),cn=e.Record({content:e.Vec(e.Nat8),batch_id:e.Nat,order_id:e.Opt(e.Nat)}),Mt=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],[_],[]),commit_proposal:e.Func([x],[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_orbiter:e.Func([T],[e.Principal],[]),create_satellite:e.Func([R],[e.Principal],[]),del_controllers:e.Func([I],[],[]),del_custom_domain:e.Func([e.Text],[],[]),delete_proposal_assets:e.Func([w],[],[]),get_auth_config:e.Func([],[e.Opt(F)],[]),get_config:e.Func([],[D],[]),get_create_orbiter_fee:e.Func([U],[e.Opt(t)],[]),get_create_satellite_fee:e.Func([U],[e.Opt(t)],[]),get_credits:e.Func([],[t],[]),get_delegation:e.Func([Q],[Ae],[]),get_proposal:e.Func([e.Nat],[e.Opt(Ye)],[]),get_storage_config:e.Func([],[P],[]),get_user_mission_control_center:e.Func([],[e.Opt(p)],[]),http_request:e.Func([kr],[Mr],[]),http_request_streaming_callback:e.Func([at],[jr],[]),init_proposal:e.Func([kt],[e.Nat,Ye],[]),init_proposal_asset_upload:e.Func([Lt,e.Nat],[ct],[]),init_proposal_many_assets_upload:e.Func([e.Vec(Lt),e.Nat],[e.Vec(e.Tuple(e.Text,ct))],[]),init_user_mission_control_center:e.Func([],[p],[]),list_assets:e.Func([e.Text,dt],[pt],[]),list_controllers:e.Func([],[e.Vec(e.Tuple(e.Principal,Jr))],[]),list_custom_domains:e.Func([],[e.Vec(e.Tuple(e.Text,zr))],[]),list_payments:e.Func([],[e.Vec(e.Tuple(e.Nat64,Yr))],[]),list_proposals:e.Func([Qr],[tn],[]),list_user_mission_control_centers:e.Func([],[e.Vec(e.Tuple(e.Principal,p))],[]),reject_proposal:e.Func([x],[e.Null],[]),set_auth_config:e.Func([rn],[F],[]),set_controllers:e.Func([on],[],[]),set_custom_domain:e.Func([e.Text,e.Opt(e.Text)],[],[]),set_fee:e.Func([qt,t],[],[]),set_storage_config:e.Func([sn],[P],[]),submit_proposal:e.Func([e.Nat],[e.Nat,Ye],[]),update_rate_config:e.Func([qt,an],[],[]),upload_proposal_asset_chunk:e.Func([cn],[Mt],[])})};var f_=async({identity:e,host:t,localActor:r})=>await lr.create({identity:e,host:t,retryTimes:10,shouldFetchRootKey:r}),h_=async({agent:e,...t})=>e??await m_(t),m_=async({identity:e,container:t})=>{let r=X(t)&&t!==!1;return await f_({identity:e,host:r?t===!0?"http://127.0.0.1:5987":t:"https://icp-api.io",localActor:r})};var vd=({satelliteId:e,certified:t=!1,...r})=>Ad({canisterId:e,...r,idlFactory:t?gc:yc});var Id=({consoleId:e,certified:t=!1,...r})=>Ad({canisterId:e,...r,idlFactory:t?p_:d_}),Ad=({canisterId:e,idlFactory:t,...r})=>{if(q(e))throw new Error("No canister ID provided.");return __({canisterId:e,idlFactory:t,...r})},__=async({canisterId:e,idlFactory:t,config:r,...n})=>{let o=await h_(n);return io.createActor(t,{agent:o,canisterId:e,...r??{}})};var Ce=class e extends ao{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 Sd=({satelliteId:e,container:t})=>{let{satelliteId:r}=xc({satelliteId:e}),{container:n}=bc({container:t});if(X(n)&&n!==!1){let{host:o,protocol:i}=new URL(n===!0?co:n);return`${i}//${r??"unknown"}.${o.replace("127.0.0.1","localhost")}`}return`https://${r??"unknown"}.icp0.io`},xc=({satelliteId:e})=>X(e)?{satelliteId:e}:Ce.getInstance().get()??{satelliteId:void 0},bc=({container:e})=>X(e)?{container:e}:Ce.getInstance().get()??{container:void 0};var Te=({satellite:e,options:{certified:t}})=>Vd({idlFactory:t?gc:yc,actorKey:`stock#${t?"update":"query"}`,...e}),Fd=({idlFactory:e,...t})=>Vd({idlFactory:e,actorKey:"extended#query",...t}),Vd=async({satelliteId:e,container:t,...r})=>{let{satelliteId:n}=xc({satelliteId:e});ei(n,"No satellite ID defined. Did you initialize Juno?");let{container:o}=bc({container:t});return await uo.getInstance().getActor({satelliteId:n,container:o,...r})};var gs=class extends Error{},fr=class extends Error{},xs=class extends Error{},bs=class extends Error{},ws=class extends Error{},Ts=class extends Error{},Ns=class extends Error{},Os=class extends Error{},Es=class extends Error{};var Cd=e=>{if(q(e))return ue();switch(e.matcher){case"equal":return ue({Equal:e.timestamp});case"greaterThan":return ue({GreaterThan:e.timestamp});case"lessThan":return ue({LessThan:e.timestamp});case"between":return ue({Between:[e.timestamps.start,e.timestamps.end]});default:throw new Es("Invalid list matcher for timestamp",e)}},Dr=({matcher:e,paginate:t,order:r,owner:n})=>({matcher:q(e)?[]:[{key:ue(e.key),description:ue(e.description),created_at:Cd(e.createdAt),updated_at:Cd(e.updatedAt)}],paginate:ue(q(t)?void 0:{start_after:ue(t.startAfter),limit:ue(q(t.limit)?void 0:BigInt(t.limit))}),order:ue(q(r)?void 0:{desc:r.desc,field:r.field==="created_at"?{CreatedAt:null}:r.field==="updated_at"?{UpdatedAt:null}:{Keys:null}}),owner:ue(q(n)?void 0:typeof n=="string"?M.fromText(n):n)});var Pd=async e=>{let t=new Blob([JSON.stringify(e,Xu)],{type:"application/json; charset=utf-8"});return new Uint8Array(await t.arrayBuffer())},Rs=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(),Qu)},vs=()=>typeof window<"u";var Bd=async({data:e})=>{try{return await Rs(e)}catch(t){console.error("The data parsing has failed, mapping to undefined as a fallback.",t);return}};var wc=async e=>{let{data:t,version:r,description:n}=e;return{description:ue(n),data:await Pd(t),version:ue(r)}},Tc=e=>{let{version:t}=e;return{version:ue(t)}},Cn=async({doc:e,key:t})=>{let{owner:r,version:n,description:o,data:i,...s}=e;return{key:t,description:ye(o),owner:r.toText(),data:await Rs(i),version:ye(n),...s}};var Dd=async({collection:e,key:t,...r})=>{let{get_doc:n}=await Te(r),o=ye(await n(e,t));if(!q(o))return Cn({doc:o,key:t})},Ud=async({docs:e,...t})=>{let{get_many_docs:r}=await Te(t),n=e.map(({collection:s,key:a})=>[s,a]),o=await r(n),i=[];for(let[s,a]of o){let c=ye(a);i.push(X(c)?await Cn({key:s,doc:c}):void 0)}return i},kd=async({collection:e,doc:t,...r})=>{let{set_doc:n}=await Te(r),{key:o}=t,i=await wc(t),s=await n(e,o,i);return await Cn({key:o,doc:s})},Ld=async({docs:e,...t})=>{let{set_many_docs:r}=await Te(t),n=[];for(let{collection:s,doc:a}of e){let{key:c}=a;n.push([s,c,await wc(a)])}let o=await r(n),i=[];for(let[s,a]of o)i.push(await Cn({key:s,doc:a}));return i},qd=async({collection:e,doc:t,...r})=>{let{del_doc:n}=await Te(r),{key:o}=t;return n(e,o,Tc(t))},Md=async({docs:e,...t})=>{let{del_many_docs:r}=await Te(t),n=e.map(({collection:o,doc:i})=>[o,i.key,Tc(i)]);await r(n)},jd=async({collection:e,filter:t,...r})=>{let{del_filtered_docs:n}=await Te(r);return n(e,Dr(t))},Kd=async({collection:e,filter:t,...r})=>{let{list_docs:n}=await Te(r),{items:o,items_page:i,items_length:s,matches_length:a,matches_pages:c}=await n(e,Dr(t)),u=[];for(let[p,d]of o){let{data:l,owner:f,description:h,version:m,...g}=d;u.push({key:p,description:ye(h),owner:f.toText(),data:await Bd({data:l}),version:ye(m),...g})}return{items:u,items_length:s,items_page:ye(i),matches_length:a,matches_pages:ye(c)}},Hd=async({collection:e,filter:t,...r})=>{let{count_docs:n}=await Te(r);return n(e,Dr(t))};var Is=async({satellite:e,options:t,...r})=>{let n=de(e?.identity);return await Dd({...r,satellite:{...e,identity:n},options:t??Dt})},oT=async({satellite:e,options:t,...r})=>{let n=de(e?.identity);return await Ud({...r,satellite:{...e,identity:n},options:t??Dt})},$d=async({satellite:e,...t})=>{let r=de(e?.identity);return await kd({...t,satellite:{...e,identity:r},options:{certified:!0}})},Gd=async({satellite:e,...t})=>{let r=de(e?.identity);return await Ld({...t,satellite:{...e,identity:r},options:{certified:!0}})},iT=async({satellite:e,...t})=>{let r=de(e?.identity);return await qd({...t,satellite:{...e,identity:r},options:{certified:!0}})},sT=async({satellite:e,...t})=>{let r=de(e?.identity);return await Md({...t,satellite:{...e,identity:r},options:{certified:!0}})},aT=async({satellite:e,filter:t,...r})=>{let n=de(e?.identity);return await jd({...r,filter:t??{},satellite:{...e,identity:n},options:{certified:!0}})},cT=async({satellite:e,options:t,filter:r,...n})=>{let o=de(e?.identity);return await Kd({...n,filter:r??{},satellite:{...e,identity:o},options:t??Dt})},lT=async({satellite:e,options:t,filter:r,...n})=>{let o=de(e?.identity);return await Hd({...n,filter:r??{},satellite:{...e,identity:o},options:t??Dt})};var Jd=async({provider:e})=>{let{user:t,userId:r}=await Nc();if(X(t))return t;try{return await y_({userId:r,provider:e})}catch(n){if(_c({error:n,type:Rd})){let o=await zd({userId:r});if(X(o))return o}throw n}},Nc=async()=>{let e=ys();if(q(e))throw new Os("No identity to initialize the user. Have you initialized Juno?");let t=e.getPrincipal().toText(),r=await zd({userId:t});return{userId:t,user:r}},zd=({userId:e})=>Is({collection:"#user",key:e}),y_=({userId:e,...t})=>$d({collection:"#user",doc:{key:e,data:t}});var As=async()=>{await ai({fn:async()=>{let{user:t}=await Nc();je.getInstance().set(t??null)}})},Ss=async({user:e})=>{await ai({fn:async()=>{je.getInstance().set(e)}})};var Wd=()=>{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()},Yd=()=>{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()},Zd=()=>{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()};var Xd=BigInt(144e11),Qd=!1,ep={width:576,height:576},tp={width:424,height:576};var ci="internetcomputer.org",rp="ic0.app",np="id.ai";var op=({width:e,height:t})=>{if(!vs()||q(window)||q(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 Ut=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 ip=(r=>(r[r.AuthorizingWithProvider=0]="AuthorizingWithProvider",r[r.CreatingOrRetrievingUser=1]="CreatingOrRetrievingUser",r))(ip||{});var Fs=class{async signIn({options:t,authClient:r,initAuth:n}){await Ut({fn:async()=>await this.#e({options:t,authClient:r}),step:0,onProgress:t?.onProgress}),await Ut({fn:async()=>await n({provider:this.id}),step:1,onProgress:t?.onProgress})}#e({options:t,authClient:r}){return new Promise(async(n,o)=>{if(q(r)){o(new fr("No client is ready to perform a sign-in. Have you initialized the Satellite?"));return}await r.login({onSuccess:n,onError:i=>{if(i===_s){o(new xs(i));return}o(new gs(i))},maxTimeToLive:t?.maxTimeToLiveInNanoseconds??Xd,allowPinAuthentication:t?.allowPin??Qd,...t?.derivationOrigin!==void 0&&{derivationOrigin:t.derivationOrigin},...this.signInOptions({windowed:t?.windowed})})})}};var Vs=class extends Fs{#e;constructor({domain:t}){super(),this.#e=t}get id(){return"internet_identity"}signInOptions({windowed:t}){let n=(()=>{let i=Ce.getInstance().get()?.container;if(q(i)||i===!1){let p=[ci,rp].includes(this.#e??ci);return so(this.#e)?`https://identity.${ci}`:p?`https://identity.${this.#e??ci}`:`https://${this.#e}`}let s=Ce.getInstance().get(),a=X(s)&&X(s?.internetIdentityId)?s.internetIdentityId:cd,{host:c,protocol:u}=new URL(i===!0?co:i);return/apple/i.test(navigator?.vendor)?`${u}//${c}?canisterId=${a}`:`${u}//${a}.${c.replace("127.0.0.1","localhost")}`})();return{...t!==!1&&{windowOpenerFeatures:op((()=>{try{let{hostname:i}=new URL(n);return i.includes(np)}catch{return!1}})()?tp:ep)},identityProvider:n}}};var Oc=class extends Error{},Ec=class extends Error{},Rc=class extends Error{},vc=class extends Error{},Ic=class extends Error{},Ac=class extends Error{},Sc=class extends Error{},Fc=class extends Error{},Vc=class extends Error{},Cc=class extends Error{};var sp=({auth:e,identity:t})=>"satellite"in e?vd({...e.satellite,identity:t}):Id({...e.console,identity:t}),g_=async({actorParams:e,args:t})=>{let{authenticate:r}=await sp(e);return await r(t)},x_=async({actorParams:e,args:t})=>{let{get_delegation:r}=await sp(e);return await r(t)},b_=({delegations:e,sessionKey:t})=>{let[r,n]=e,o=dr.fromDelegations(n,Uint8Array.from(r));return{identity:pr.fromDelegation(t,o),delegationChain:o,sessionKey:t}},Pc=async({jwt:e,context:t,auth:r})=>{let n=await Ct.generate({extractable:!1}),o=new Uint8Array(n.getPublicKey().toDer()),{delegations:i,data:s}=await w_({jwt:e,publicKey:o,context:t,auth:r});return{identity:b_({sessionKey:n,delegations:i}),data:s}},w_=async({jwt:e,publicKey:t,context:{caller:r,salt:n},auth:o})=>{let i=await g_({args:{OpenId:{jwt:e,session_key:t,salt:n}},actorParams:{auth:o,identity:r}});if("Err"in i)throw new Ic("Authentication failed",{cause:i});let{delegation:{user_key:s,expiration:a},...c}=i.Ok,u=await T_({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 Br(Uint8Array.from(l),f,ye(h)),signature:Uint8Array.from(d)}]],data:c}},T_=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 x_({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 Vc("Getting delegation failed",{cause:c})}return c.Ok}throw new Cc};var Bc="juno:auth:openid",Dc={authUrl:"https://accounts.google.com/o/oauth2/v2/auth",authScopes:["openid","profile","email"],configUrl:"https://accounts.google.com/gsi/fedcm.json"};var ap=e=>Cr(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),N_=()=>window.crypto.getRandomValues(new Uint8Array(32)),O_=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 window.crypto.subtle.digest("SHA-256",n);return ap(ur(o))},E_=async({caller:e})=>{let t=N_();return{nonce:await O_({salt:t,caller:e}),salt:t}},cp="__caller__",lp="__salt__",up="__state__",R_=({caller:e,state:t,salt:r})=>{let n={[cp]:e.toJSON(),[lp]:Cr(r),[up]:t};return JSON.stringify(n)},v_=e=>{let{[cp]:t,[lp]:r,[up]:n}=JSON.parse(e);return{caller:Nt.fromParsedJson(t),salt:Zu(r),state:n}},I_=()=>ap(window.crypto.getRandomValues(new Uint8Array(12))),dp=async()=>{let e=Nt.generate(),{nonce:t,salt:r}=await E_({caller:e}),n=I_(),o=R_({caller:e,salt:r,state:n});return sessionStorage.setItem(Bc,o),{nonce:t,state:n}},pp=()=>{let e=sessionStorage.getItem(Bc);if(q(e))throw new Ec;return v_(e)};var Uc=async e=>{let t=pp();if("credentials"in e){let{credentials:{jwt:r},auth:n}=e;return await Pc({jwt:r,context:t,auth:n})}return await A_({...e,context:t})},A_=async({auth:e,context:t})=>{let{location:{hash:r}}=window;if(so(r)||!r.startsWith("#"))throw new Ac("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(so(s)||o!==s)throw new Sc("The provided state is invalid",{cause:o});if(so(i))throw new Fc;return await Pc({jwt:i,auth:e,context:t})};var fp=({authUrl:e,clientId:t,nonce:r,loginHint:n,authScopes:o,state:i,redirectUrl:s})=>{let a=(()=>{try{return new URL(e)}catch{throw new Oc("Cannot parse authURL",{cause: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),ec(n)?a.searchParams.set("login_hint",n):a.searchParams.set("prompt","select_account"),window.location.href=a.toString()},hp=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(q(i))throw new Rc;let{type:s}=i;if(s!=="identity"||!("token"in i)||typeof i.token!="string")throw new vc("Invalid credential received from FedCM API",{cause:i});let{token:a}=i;return{jwt:a}};async function kc({google:e}){let t=await dp();if("credentials"in e){let{credentials:i}=e,{configUrl:s}=Dc;return await hp({...i,...t,configUrl:s})}let{redirect:r}=e,{authUrl:n,authScopes:o}=Dc;fp({...r,...t,authUrl:n,authScopes:o})}var S_=async()=>{let{satelliteId:e}=Ce.getInstance().get()??{satelliteId:void 0};if(q(e))throw new fr("Satellite ID not set. Have you initialized the Satellite?");let t=Ce.getInstance().get()?.container,{identity:{delegationChain:r,sessionKey:n,identity:o},data:{doc:i}}=await Uc({redirect:null,auth:{satellite:{satelliteId:e,container:t}}});await $e.getInstance().setAuthClientStorage({delegationChain:r,sessionKey:n});let s=await Cn({doc:i,key:o.getPrincipal().toText()});await Ss({user:s})};var mp=e=>(e.preventDefault(),e.returnValue="Are you sure you want to exit?"),F_=()=>{window.addEventListener("beforeunload",mp,{capture:!0})},V_=()=>{window.removeEventListener("beforeunload",mp,{capture:!0})},Cs=async({fn:e})=>{try{return F_(),await e()}finally{V_()}};var Ps=class{get id(){return"google"}async signIn({options:t={}}){let r=t?.redirect?.clientId??Zd();if(q(r))throw new ws;let{redirect:n}=t;await kc({google:{redirect:{...n??{},clientId:r}}})}};var _p=async({delegationIdentity:e,passkeyIdentity:t,satelliteId:r})=>{let n=t.getCredential().getAAGUID(),[o,i]=await Gd({docs:[{collection:"#user",doc:{key:e.getPrincipal().toText(),data:{provider:"webauthn",providerData:{webauthn:{...X(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 yp=(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))(yp||{}),gp=(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))(gp||{});var po=class{get id(){return"webauthn"}async signUp({options:{onProgress:t,maxTimeToLiveInMilliseconds:r,passkey:n}={},loadAuthWithUser:o}){let{satelliteId:i}=Ce.getInstance().get()??{satelliteId:void 0};if(q(i))throw new fr("Satellite ID not set. Have you initialized the Satellite?");let s=({step:m,state:g})=>{switch(m){case Pr.RequestingUserCredential:t?.({step:1,state:g});break;case Pr.FinalizingCredential:t?.({step:2,state:g});break;case Pr.Signing:t?.({step:3,state:g});break}},c=await Ut({fn:async()=>await rc.createWithNewCredential({onProgress:s,passkeyOptions:n}),step:0,onProgress:t}),{delegationIdentity:u,sessionKey:p}=await this.#e({identity:c,maxTimeToLiveInMilliseconds:r}),l=await Ut({fn:async()=>await _p({delegationIdentity:u,passkeyIdentity:c,satelliteId:i}),step:5,onProgress:t});await Ut({fn:async()=>await this.#t({delegationIdentity:u,sessionKey:p}),step:4,onProgress:t}),await Ut({fn:async()=>await o({user:l}),step:5,onProgress:t})}async signIn({options:{onProgress:t,maxTimeToLiveInMilliseconds:r}={},loadAuth:n}){let{satelliteId:o}=Ce.getInstance().get()??{satelliteId:void 0};if(q(o))throw new fr("Satellite ID not set. Have you initialized the Satellite?");let i=async({credentialId:d})=>{let l=await Is({collection:"#user-webauthn",key:Cr(d),options:{certified:!0},satellite:{identity:new rt,satelliteId:o}});if(q(l))throw new Ts("No public key found for the selected passkey.");let{data:f}=l,{publicKey:h}=f;return Vn(h,Xo)},s=({step:d,state:l})=>{switch(d){case Pr.RequestingUserCredential:t?.({step:0,state:l});break;case Pr.FinalizingCredential:t?.({step:1,state:l});break;case Pr.Signing:t?.({step:2,state:l});break}},a=await rc.createWithExistingCredential({retrievePublicKey:i,onProgress:s}),{delegationIdentity:c,sessionKey:u}=await this.#e({identity:a,maxTimeToLiveInMilliseconds:r});await Ut({fn:async()=>await this.#t({delegationIdentity:c,sessionKey:u}),step:3,onProgress:t}),await Ut({fn:n,step:4,onProgress:t})}async#e({identity:t,maxTimeToLiveInMilliseconds:r}){let n=await Ct.generate({extractable:!1}),o=r??144e5,i=await dr.create(t,n.getPublicKey(),new Date(Date.now()+o));return{delegationIdentity:pr.fromDelegation(n,i),sessionKey:n}}async#t({sessionKey:t,delegationIdentity:r}){let n=new Bt;await Promise.all([n.set(He,t.getKeyPair()),n.set(Ke,JSON.stringify(r.getDelegation().toJSON()))])}};var P_=async({provider:e})=>{await ai({fn:async()=>{let r=await Jd({provider:e});je.getInstance().set(r)}})},B_=async e=>{if("google"in e){let{google:{options:t}}=e;await Lc({fn:()=>new Ps().signIn({options:t}),context:{windowGuard:!1}});return}if("webauthn"in e){let{webauthn:{options:t,context:r}}=e;await Lc({fn:()=>new po().signIn({options:t,loadAuth:As}),context:r});return}if("internet_identity"in e){let{internet_identity:{options:t,context:r}}=e,{domain:n,...o}=t??{};await Lc({fn:()=>new Vs({domain:n}).signIn({options:o,authClient:$e.getInstance().getAuthClient(),initAuth:P_}),context:r});return}throw new bs("An unknown or unsupported provider was provided for sign-in.")},Lc=async({fn:e,context:t})=>{if(t?.windowGuard===!1){await e();return}await Cs({fn:e})};var D_=async e=>{let t=async()=>await U_(e);if(Object.values(e)?.[0].context?.windowGuard===!1){await t();return}await Cs({fn:t})},U_=async e=>{if("webauthn"in e){let{webauthn:{options:t}}=e;await new po().signUp({options:t,loadAuthWithUser:Ss});return}throw new Ns("An unknown or unsupported provider was provided for sign-up.")};var SO=async({idlFactory:e,satellite:t})=>{let r=de(t?.identity);return await Fd({idlFactory:e,...t,identity:r})};var xp=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(k_(r));o?.onInitiatedBatch();let{chunkIds:u}=await M_({data:e,uploadFn:s,batchId:c});o?.onUploadedFileChunks(r.fullPath),await q_({commitFn:a,batchId:c,data:e,headers:t,chunkIds:u}),o?.onCommittedBatch()};var k_=({filename:e,collection:t,token:r,fullPath:n,encoding:o,description:i})=>({collection:t,full_path:n,name:e,token:ue(r),encoding_type:ue(o),description:ue(i)}),L_=({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??[]]}},q_=async({commitFn:e,...t})=>{let r=L_(t);await e(r)},M_=async({data:e,uploadFn:t,batchId:r})=>{let n=[],o=vs()?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 j_({uploadChunks:n}))s=[...s,...a];return{chunkIds:s}};async function*j_({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=>K_(o)))}}var K_=async({batchId:e,chunk:t,uploadFn:r,orderId:n})=>r({batch_id:e,content:new Uint8Array(await t.arrayBuffer()),order_id:ue(n)});var bp=async({asset:e,...t})=>{let r=await Te(t);await xp({actor:r,asset:e})},wp=async({collection:e,filter:t,...r})=>{let{list_assets:n}=await Te(r),{items:o,items_length:i,items_page:s,matches_length:a,matches_pages:c}=await n(e,Dr(t));return{items:o.map(([u,p])=>p),items_length:i,items_page:ye(s),matches_length:a,matches_pages:ye(c)}},Tp=async({collection:e,filter:t,...r})=>{let{count_assets:n}=await Te(r);return n(e,Dr(t))},Np=async({collection:e,fullPath:t,...r})=>(await Te(r)).del_asset(e,t),Op=async({assets:e,satellite:t})=>{let{del_many_assets:r}=await Te({satellite:t,options:{certified:!0}}),n=e.map(({collection:o,fullPath:i})=>[o,i]);await r(n)},Ep=async({collection:e,filter:t,...r})=>{let{del_filtered_assets:n}=await Te(r);return n(e,Dr(t))},Rp=async({collection:e,fullPath:t,...r})=>{let{get_asset:n}=await Te(r);return ye(await n(e,t))},vp=async({assets:e,...t})=>{let{get_many_assets:r}=await Te(t),n=e.map(({collection:i,fullPath:s})=>[i,s]);return(await r(n)).map(([i,s])=>ye(s))};var Ip=e=>btoa([...e].map(t=>String.fromCharCode(t)).join(""));var JO=e=>Ap(e),zO=e=>Ap({filename:e.data.name,...e}),Ap=async({filename:e,data:t,collection:r,headers:n=[],fullPath:o,token:i,satellite:s,encoding:a,description:c})=>{let u=de(s?.identity),p=decodeURI(e),d=o??`/${r}/${p}`,l={...s,identity:u};return await bp({asset:{data:t,filename:p,collection:r,token:i,headers:n,fullPath:d,encoding:a,description:c},satellite:l,options:{certified:!0}}),{downloadUrl:Sp({satellite:l,assetKey:{fullPath:d,token:i}}),fullPath:d,name:p}},WO=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:de(r?.identity)},{items:i,...s}=await wp({collection:e,filter:t??{},satellite:o,options:n??Dt}),a=i.map(({key:{full_path:c,token:u,name:p,owner:d,description:l},headers:f,encodings:h,created_at:m,updated_at:g})=>{let _=ye(u);return{fullPath:c,description:ye(l),name:p,downloadUrl:Sp({satellite:o,assetKey:{fullPath:c,token:_}}),token:_,headers:f,encodings:h.reduce((x,[y,{modified:T,sha256:E,total_length:O}])=>({...x,[y]:{modified:T,sha256:Ip(E),total_length:O}}),{}),owner:d.toText(),created_at:m,updated_at:g}});return{items:a,assets:a,...s}},YO=async({collection:e,filter:t,satellite:r,options:n})=>{let o={...r,identity:de(r?.identity)};return await Tp({collection:e,satellite:o,filter:t??{},options:n??Dt})},ZO=({collection:e,fullPath:t,satellite:r})=>Np({collection:e,fullPath:t,satellite:{...r,identity:de(r?.identity)},options:{certified:!0}}),XO=({assets:e,satellite:t})=>Op({assets:e,satellite:{...t,identity:de(t?.identity)},options:{certified:!0}}),QO=async({collection:e,satellite:t,filter:r})=>{let n={...t,identity:de(t?.identity)};return await Ep({collection:e,satellite:n,filter:r??{},options:{certified:!0}})},e6=async({satellite:e,options:t,...r})=>{let n=de(e?.identity);return await Rp({...r,satellite:{...e,identity:n},options:t??Dt})},t6=async({satellite:e,options:t,...r})=>{let n=de(e?.identity);return await vp({...r,satellite:{...e,identity:n},options:t??Dt})},Sp=({assetKey:{fullPath:e,token:t},satellite:r})=>{let n={...r,identity:de(r?.identity)};return`${Sd(n)}${e}${X(t)?`?token=${t}`:""}`};var H_=e=>{let t=e?.satelliteId??Wd();ei(t,"Satellite ID is not configured. Juno cannot be initialized.");let r=e?.container??Yd();return{satelliteId:t,internetIdentityId:e?.internetIdentityId,workers:e?.workers,container:r}},u6=e=>$_(e),$_=async e=>{let t=H_(e);Ce.getInstance().set(t),await As();let r=t.workers?.auth!==void 0?Ed(t.workers.auth):void 0;return[...r?[r]:[]]},G_=e=>je.getInstance().subscribe(e),d6=G_;export{ip as AuthClientSignInProgressStep,Os as InitError,Vs as InternetIdentityProvider,Es as ListError,gs as SignInError,fr as SignInInitError,ws as SignInMissingClientIdError,bs as SignInProviderNotSupportedError,xs as SignInUserInterruptError,Ns as SignUpProviderNotSupportedError,yp as WebAuthnSignInProgressStep,Ts as WebAuthnSignInRetrievePublicKeyError,gp as WebAuthnSignUpProgressStep,d6 as authSubscribe,YO as countAssets,lT as countDocs,ZO as deleteAsset,iT as deleteDoc,QO as deleteFilteredAssets,aT as deleteFilteredDocs,XO as deleteManyAssets,sT as deleteManyDocs,Sp as downloadUrl,e6 as getAsset,Is as getDoc,u_ as getIdentityOnce,t6 as getManyAssets,oT as getManyDocs,SO as getSatelliteExtendedActor,S_ as handleRedirectCallback,u6 as initJuno,$_ as initSatellite,km as isWebAuthnAvailable,WO as listAssets,cT as listDocs,G_ as onAuthStateChange,$d as setDoc,Gd as setManyDocs,B_ as signIn,mc as signOut,D_ as signUp,l_ as unsafeIdentity,JO as uploadBlob,zO as uploadFile};
123
57
  /*! Bundled license information:
124
58
 
125
- @noble/hashes/utils.js:
126
59
  @noble/hashes/esm/utils.js:
127
60
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
128
61
 
129
- @noble/curves/utils.js:
130
- @noble/curves/abstract/modular.js:
131
- @noble/curves/abstract/curve.js:
132
- @noble/curves/abstract/weierstrass.js:
133
- @noble/curves/abstract/bls.js:
134
- @noble/curves/abstract/tower.js:
135
- @noble/curves/bls12-381.js:
136
- @noble/curves/abstract/edwards.js:
137
- @noble/curves/abstract/montgomery.js:
138
- @noble/curves/ed25519.js:
139
62
  @noble/curves/esm/utils.js:
140
63
  @noble/curves/esm/abstract/modular.js:
141
64
  @noble/curves/esm/abstract/curve.js: