@0xpolygonid/js-sdk 1.32.4 → 1.33.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 (35) hide show
  1. package/dist/browser/esm/index.js +8 -4
  2. package/dist/browser/esm/index.js.map +1 -1
  3. package/dist/browser/umd/index.global.js +2 -2
  4. package/dist/browser/umd/index.global.js.map +1 -1
  5. package/dist/node/cjs/index.cjs +8 -4
  6. package/dist/node/cjs/index.cjs.map +1 -1
  7. package/dist/node/esm/index.js +8 -4
  8. package/dist/node/esm/index.js.map +1 -1
  9. package/dist/types/iden3comm/handlers/auth.d.ts +2 -1
  10. package/dist/types/iden3comm/handlers/auth.d.ts.map +1 -1
  11. package/dist/types/iden3comm/handlers/credential-proposal.d.ts +6 -3
  12. package/dist/types/iden3comm/handlers/credential-proposal.d.ts.map +1 -1
  13. package/dist/types/iden3comm/types/index.d.ts +2 -0
  14. package/dist/types/iden3comm/types/index.d.ts.map +1 -1
  15. package/dist/types/iden3comm/types/packer.d.ts +4 -1
  16. package/dist/types/iden3comm/types/packer.d.ts.map +1 -1
  17. package/dist/types/iden3comm/types/protocol/attachment.d.ts +11 -0
  18. package/dist/types/iden3comm/types/protocol/attachment.d.ts.map +1 -0
  19. package/dist/types/iden3comm/types/protocol/common.d.ts +11 -0
  20. package/dist/types/iden3comm/types/protocol/common.d.ts.map +1 -0
  21. package/dist/types/iden3comm/types/protocol/payment.d.ts +2 -4
  22. package/dist/types/iden3comm/types/protocol/payment.d.ts.map +1 -1
  23. package/dist/types/iden3comm/types/protocol/proposal-request.d.ts +4 -10
  24. package/dist/types/iden3comm/types/protocol/proposal-request.d.ts.map +1 -1
  25. package/package.json +1 -1
  26. package/src/iden3comm/handlers/auth.ts +5 -2
  27. package/src/iden3comm/handlers/credential-proposal.ts +14 -5
  28. package/src/iden3comm/types/index.ts +2 -0
  29. package/src/iden3comm/types/packer.ts +7 -1
  30. package/src/iden3comm/types/protocol/attachment.ts +12 -0
  31. package/src/iden3comm/types/protocol/common.ts +10 -0
  32. package/src/iden3comm/types/protocol/payment.ts +2 -4
  33. package/src/iden3comm/types/protocol/proposal-request.ts +5 -8
  34. package/src/storage/blockchain/errors.ts +1 -1
  35. package/src/verifiable/constants.ts +1 -1
@@ -33,7 +33,7 @@ if (cid) {
33
33
  // Make sure to use cid instead of value
34
34
  doSomethingWithCID(cid)
35
35
  }
36
- `;var N8={...A8,...v8,...C8,...S8,...D8,...L8,...B8,...T8,...P8,...R8},HDe={...O8,...G8};function CO(n,e,t,r){return{name:n,prefix:e,encoder:{name:n,prefix:e,encode:t},decoder:{decode:r}}}var vO=CO("utf8","u",n=>"u"+new TextDecoder("utf8").decode(n),n=>new TextEncoder().encode(n.substring(1))),U8=CO("ascii","a",n=>{let e="a";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return e},n=>{n=n.substring(1);let e=ay(n.length);for(let t=0;t<n.length;t++)e[t]=n.charCodeAt(t);return e}),Ete={utf8:vO,"utf-8":vO,hex:N8.base16,latin1:U8,ascii:U8,binary:U8,...N8},NI=Ete;function dy(n,e="utf8"){let t=NI[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?_f(globalThis.Buffer.from(n,"utf-8")):t.decoder.decode(`${t.prefix}${n}`)}function UI(n,e="utf8"){let t=NI[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(n.buffer,n.byteOffset,n.byteLength).toString("utf8"):t.encoder.encode(n).substring(1)}var j8=$n(UO(),1);var HO={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},KO={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},JO={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Yte=Hr(HO.p),zte=Hr(KO.p),jte=Hr(JO.p);var qO=g0({...HO,Fp:Yte,lowS:!1},c0);var yLe=g0({...KO,Fp:zte,lowS:!1},Lk);var wLe=g0({...JO,Fp:jte,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},LI);var JI=qO;var QO=c0;var Wte=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),YO=Uint8Array.from(new Array(16).fill(0).map((n,e)=>e)),Zte=YO.map(n=>(9*n+5)%16),zO=(()=>{let t=[[YO],[Zte]];for(let r=0;r<4;r++)for(let i of t)i.push(i[r].map(o=>Wte[o]));return t})(),jO=zO[0],WO=zO[1],ZO=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(n=>Uint8Array.from(n)),Xte=jO.map((n,e)=>n.map(t=>ZO[e][t])),_te=WO.map((n,e)=>n.map(t=>ZO[e][t])),$te=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),ene=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function VO(n,e,t,r){return n===0?e^t^r:n===1?e&t|~e&r:n===2?(e|~t)^r:n===3?e&r|t&~r:e^(t|~r)}var qI=new Uint32Array(16),QI=class extends Yf{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:e,h1:t,h2:r,h3:i,h4:o}=this;return[e,t,r,i,o]}set(e,t,r,i,o){this.h0=e|0,this.h1=t|0,this.h2=r|0,this.h3=i|0,this.h4=o|0}process(e,t){for(let f=0;f<16;f++,t+=4)qI[f]=e.getUint32(t,!0);let r=this.h0|0,i=r,o=this.h1|0,s=o,a=this.h2|0,l=a,c=this.h3|0,u=c,d=this.h4|0,h=d;for(let f=0;f<5;f++){let p=4-f,w=$te[f],y=ene[f],v=jO[f],B=WO[f],U=Xte[f],k=_te[f];for(let F=0;F<16;F++){let P=$g(r+VO(f,o,a,c)+qI[v[F]]+w,U[F])+d|0;r=d,d=c,c=$g(a,10)|0,a=o,o=P}for(let F=0;F<16;F++){let P=$g(i+VO(p,s,l,u)+qI[B[F]]+y,k[F])+h|0;i=h,h=u,u=$g(l,10)|0,l=s,s=P}}this.set(this.h1+a+u|0,this.h2+c+h|0,this.h3+d+i|0,this.h4+r+s|0,this.h0+o+l|0)}roundClean(){Li(qI)}destroy(){this.destroyed=!0,Li(this.buffer),this.set(0,0,0,0,0)}},XO=Zu(()=>new QI);var K8=XO;var tne=BigInt(0),hy=BigInt(1),nne=BigInt(2),rne=BigInt(7),ine=BigInt(256),one=BigInt(113),eG=[],tG=[],nG=[];for(let n=0,e=hy,t=1,r=0;n<24;n++){[t,r]=[r,(2*t+3*r)%5],eG.push(2*(5*r+t)),tG.push((n+1)*(n+2)/2%64);let i=tne;for(let o=0;o<7;o++)e=(e<<hy^(e>>rne)*one)%ine,e&nne&&(i^=hy<<(hy<<BigInt(o))-hy);nG.push(i)}var rG=CI(nG,!0),sne=rG[0],ane=rG[1],_O=(n,e,t)=>t>32?bk(n,e,t):yk(n,e,t),$O=(n,e,t)=>t>32?Ik(n,e,t):wk(n,e,t);function cne(n,e=24){let t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let s=0;s<10;s++)t[s]=n[s]^n[s+10]^n[s+20]^n[s+30]^n[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,l=(s+2)%10,c=t[l],u=t[l+1],d=_O(c,u,1)^t[a],h=$O(c,u,1)^t[a+1];for(let f=0;f<50;f+=10)n[s+f]^=d,n[s+f+1]^=h}let i=n[2],o=n[3];for(let s=0;s<24;s++){let a=tG[s],l=_O(i,o,a),c=$O(i,o,a),u=eG[s];i=n[u],o=n[u+1],n[u]=l,n[u+1]=c}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)t[a]=n[s+a];for(let a=0;a<10;a++)n[s+a]^=~t[(a+2)%10]&t[(a+4)%10]}n[0]^=sne[r],n[1]^=ane[r]}Li(t)}var J8=class n extends Wu{constructor(e,t,r,i=!1,o=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=i,this.rounds=o,ju(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=pk(this.state)}clone(){return this._cloneInto()}keccak(){VC(this.state32),cne(this.state32,this.rounds),VC(this.state32),this.posOut=0,this.pos=0}update(e){nl(this),e=Vf(e),An(e);let{blockLen:t,state:r}=this,i=e.length;for(let o=0;o<i;){let s=Math.min(t-this.pos,i-o);for(let a=0;a<s;a++)r[this.pos++]^=e[o++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:i}=this;e[r]^=t,(t&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){nl(this,!1),An(e),this.finish();let t=this.state,{blockLen:r}=this;for(let i=0,o=e.length;i<o;){this.posOut>=r&&this.keccak();let s=Math.min(r-this.posOut,o-i);e.set(t.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ju(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(xI(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Li(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:i,rounds:o,enableXOF:s}=this;return e||(e=new n(t,r,i,s,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=i,e.enableXOF=s,e.destroyed=this.destroyed,e}},lne=(n,e,t)=>Zu(()=>new J8(e,n,t));var iG=lne(1,136,256/8);var Cne=$n(sG(),1);var une="(?:%[0-9a-fA-F]{2})",aG=`(?:[a-zA-Z0-9._-]|${une})`,dne="([a-z0-9]+)",fne=`((?:${aG}*:)*(${aG}+))`,cG="[a-zA-Z0-9_.:%-]",hne=`;${cG}+=${cG}*`,pne=`((${hne})*)`,mne="(/[^#?]*)?",gne="([?][^#]*)?",yne="(#.*)?",wne=new RegExp(`^did:${dne}:${fne}${pne}${mne}${gne}${yne}$`);function lG(n){if(n===""||!n)return null;let e=n.match(wne);if(e){let t={did:`did:${e[1]}:${e[2]}`,method:e[1],id:e[2],didUrl:n};if(e[4]){let r=e[4].slice(1).split(";");t.params={};for(let i of r){let o=i.split("=");t.params[o[0]]=o[1]}}return e[6]&&(t.path=e[6]),e[7]&&(t.query=e[7].slice(1)),e[8]&&(t.fragment=e[8].slice(1)),t}return null}function hG(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function pG(n,e){return Array.isArray(e)?e.length===0?!0:n?e.every(t=>typeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function bne(n){if(typeof n!="function")throw new Error("function expected");return!0}function my(n,e){if(typeof e!="string")throw new Error(`${n}: string expected`);return!0}function mG(n){if(!Number.isSafeInteger(n))throw new Error(`invalid integer: ${n}`)}function q8(n){if(!Array.isArray(n))throw new Error("array expected")}function gG(n,e){if(!pG(!0,e))throw new Error(`${n}: array of strings expected`)}function yG(n,e){if(!pG(!1,e))throw new Error(`${n}: array of numbers expected`)}function Ine(...n){let e=o=>o,t=(o,s)=>a=>o(s(a)),r=n.map(o=>o.encode).reduceRight(t,e),i=n.map(o=>o.decode).reduce(t,e);return{encode:r,decode:i}}function Ene(n){let e=typeof n=="string"?n.split(""):n,t=e.length;gG("alphabet",e);let r=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(q8(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=t)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${n}`);return e[o]})),decode:i=>(q8(i),i.map(o=>{my("alphabet.decode",o);let s=r.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${n}`);return s}))}}function xne(n=""){return my("join",n),{encode:e=>(gG("join.decode",e),e.join(n)),decode:e=>(my("join.decode",e),e.split(n))}}var wG=(n,e)=>e===0?n:wG(e,n%e),YI=(n,e)=>n+(e-wG(n,e)),VI=(()=>{let n=[];for(let e=0;e<40;e++)n.push(2**e);return n})();function Q8(n,e,t,r){if(q8(n),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(YI(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${YI(e,t)}`);let i=0,o=0,s=VI[e],a=VI[t]-1,l=[];for(let c of n){if(mG(c),c>=s)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(i=i<<e|c,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=t;o-=t)l.push((i>>o-t&a)>>>0);let u=VI[o];if(u===void 0)throw new Error("invalid carry");i&=u-1}if(i=i<<t-o&a,!r&&o>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&o>0&&l.push(i>>>0),l}function Ane(n,e=!1){if(mG(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(YI(8,n)>32||YI(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!hG(t))throw new Error("radix2.encode input should be Uint8Array");return Q8(Array.from(t),8,n,!e)},decode:t=>(yG("radix2.decode",t),Uint8Array.from(Q8(t,n,8,e)))}}function uG(n){return bne(n),function(...e){try{return n.apply(null,e)}catch{}}}var V8=Ine(Ene("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),xne("")),dG=[996825010,642813549,513874426,1027748829,705979059];function py(n){let e=n>>25,t=(n&33554431)<<5;for(let r=0;r<dG.length;r++)(e>>r&1)===1&&(t^=dG[r]);return t}function fG(n,e,t=1){let r=n.length,i=1;for(let o=0;o<r;o++){let s=n.charCodeAt(o);if(s<33||s>126)throw new Error(`Invalid prefix (${n})`);i=py(i)^s>>5}i=py(i);for(let o=0;o<r;o++)i=py(i)^n.charCodeAt(o)&31;for(let o of e)i=py(i)^o;for(let o=0;o<6;o++)i=py(i);return i^=t,V8.encode(Q8([i%VI[30]],30,5,!1))}function vne(n){let e=n==="bech32"?1:734539939,t=Ane(5),r=t.decode,i=t.encode,o=uG(r);function s(d,h,f=90){my("bech32.encode prefix",d),hG(h)&&(h=Array.from(h)),yG("bech32.encode",h);let p=d.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);let w=p+7+h.length;if(f!==!1&&w>f)throw new TypeError(`Length ${w} exceeds limit ${f}`);let y=d.toLowerCase(),v=fG(y,h,e);return`${y}1${V8.encode(h)}${v}`}function a(d,h=90){my("bech32.decode input",d);let f=d.length;if(f<8||h!==!1&&f>h)throw new TypeError(`invalid string length: ${f} (${d}). Expected (8..${h})`);let p=d.toLowerCase();if(d!==p&&d!==d.toUpperCase())throw new Error("String must be lowercase or uppercase");let w=p.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');let y=p.slice(0,w),v=p.slice(w+1);if(v.length<6)throw new Error("Data must be at least 6 characters long");let B=V8.decode(v).slice(0,-6),U=fG(y,B,e);if(!v.endsWith(U))throw new Error(`Invalid checksum in ${d}: expected "${U}"`);return{prefix:y,words:B}}let l=uG(a);function c(d){let{prefix:h,words:f}=a(d,!1);return{prefix:h,words:f,bytes:r(f)}}function u(d,h){return s(d,i(h))}return{encode:s,decode:a,encodeFromBytes:u,decodeToBytes:c,decodeUnsafe:l,fromWords:r,fromWordsUnsafe:o,toWords:i}}var Y8=vne("bech32");var fa={toString:UI,fromString:dy,concat:w8};function Sne(n){return fa.toString(n,"base64url")}function ws(n){let e=n.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return fa.fromString(e,"base64url")}function AG(n){return fa.fromString(n,"base58btc")}function Dne(n){return fa.toString(n,"base58btc")}var zI={Secp256k1SignatureVerificationKey2018:"Secp256k1",Secp256k1VerificationKey2018:"Secp256k1",EcdsaSecp256k1VerificationKey2019:"Secp256k1",EcdsaPublicKeySecp256k1:"Secp256k1",EcdsaSecp256k1RecoveryMethod2020:"Secp256k1",EcdsaSecp256r1VerificationKey2019:"P-256",Ed25519VerificationKey2018:"Ed25519",Ed25519VerificationKey2020:"Ed25519",ED25519SignatureVerification:"Ed25519",X25519KeyAgreementKey2019:"X25519",X25519KeyAgreementKey2020:"X25519",ConditionalProof2022:void 0,JsonWebKey2020:void 0,Multikey:void 0},Lne={"ed25519-pub":237,"x25519-pub":236,"secp256k1-pub":231,"bls12_381-g1-pub":234,"bls12_381-g2-pub":235,"p256-pub":4608},Bne={"bls12_381-g1-pub":"Bls12381G1","bls12_381-g2-pub":"Bls12381G2","ed25519-pub":"Ed25519","p256-pub":"P-256","secp256k1-pub":"Secp256k1","x25519-pub":"X25519"};function WI(n){if(n.publicKeyBase58)return{keyBytes:AG(n.publicKeyBase58),keyType:zI[n.type]};if(n.publicKeyBase64)return{keyBytes:ws(n.publicKeyBase64),keyType:zI[n.type]};if(n.publicKeyHex)return{keyBytes:x0(n.publicKeyHex),keyType:zI[n.type]};if(n.publicKeyJwk&&n.publicKeyJwk.crv==="secp256k1"&&n.publicKeyJwk.x&&n.publicKeyJwk.y)return{keyBytes:No.ProjectivePoint.fromAffine({x:jI(ws(n.publicKeyJwk.x)),y:jI(ws(n.publicKeyJwk.y))}).toRawBytes(!1),keyType:"Secp256k1"};if(n.publicKeyJwk&&n.publicKeyJwk.crv==="P-256"&&n.publicKeyJwk.x&&n.publicKeyJwk.y)return{keyBytes:JI.ProjectivePoint.fromAffine({x:jI(ws(n.publicKeyJwk.x)),y:jI(ws(n.publicKeyJwk.y))}).toRawBytes(!1),keyType:"P-256"};if(n.publicKeyJwk&&n.publicKeyJwk.kty==="OKP"&&["Ed25519","X25519"].includes(n.publicKeyJwk.crv??"")&&n.publicKeyJwk.x)return{keyBytes:ws(n.publicKeyJwk.x),keyType:n.publicKeyJwk.crv};if(n.publicKeyMultibase){let{keyBytes:e,keyType:t}=Tne(n.publicKeyMultibase);return{keyBytes:e,keyType:t??zI[n.type]}}return{keyBytes:new Uint8Array}}function Tne(n){let e=(0,j8.decode)(n);if([32,33,48,64,65,96].includes(e.length))return{keyBytes:e};try{let[t,r]=th.decode(e),i=Object.entries(Lne).filter(([,o])=>o===t)?.[0][0]??"";return{keyBytes:e.slice(r),keyType:Bne[i]}}catch{return{keyBytes:e}}}function x0(n,e){let t=n.startsWith("0x")?n.substring(2):n;if(t.length%2!==0&&(t=`0${t}`),e){let r=Math.max(t.length,e*2);t=t.padStart(r,"00")}return fa.fromString(t.toLowerCase(),"base16")}function Pne(n){return fa.toString(ws(n))}function id(n){return fa.toString(n,"base16")}function jI(n){return BigInt("0x"+fa.toString(n,"base16"))}function Rne(n){return fa.fromString(n,"utf-8")}function W8({r:n,s:e,recoveryParam:t},r){let i=new Uint8Array(r?65:64);if(i.set(fa.fromString(n,"base16"),0),i.set(fa.fromString(e,"base16"),32),r){if(typeof t>"u")throw new Error("Signer did not return a recoveryParam");i[64]=t}return Sne(i)}function Mne(n){let e=ws(n);if(e.length<64||e.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${e.length}`);let t=id(e.slice(0,32)),r=id(e.slice(32,64)),i=e.length===65?e[64]:void 0;return{r:t,s:r,recoveryParam:i}}function bG(n,e=64){return n.length===e?n:"0".repeat(e-n.length)+n}function od(n){let e=typeof n=="string"?dy(n):n;return QO(e)}var Fne=iG;function vG(n){let e=dy(n.slice(2),"base16");return`0x${UI(Fne(e).slice(-20),"base16")}`}function CG(n,e=!1){let t=n;if(t.length!==32)throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${t.length}`);return function(r){try{let i=No.sign(od(r),t);return Promise.resolve(W8({r:bG(i.r.toString(16)),s:bG(i.s.toString(16)),recoveryParam:i.recovery},e))}catch(i){return Promise.reject(i)}}}function Z8(n){return typeof n=="object"&&"r"in n&&"s"in n}function kne(){return function(e,t){try{return Promise.resolve(t(e)).then(function(r){return Z8(r)?W8(r):r})}catch(r){return Promise.reject(r)}}}function IG(n){return function(t,r){try{return Promise.resolve(r(t)).then(function(i){if(Z8(i))return W8(i,n);if(n&&typeof Mne(i).recoveryParam>"u")throw new Error("not_supported: ES256K-R not supported when signer doesn't provide a recovery param");return i})}catch(i){return Promise.reject(i)}}}function EG(){return function(e,t){try{return Promise.resolve(t(e)).then(function(r){if(Z8(r))throw new Error("invalid_config: expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}var WLe={ES256:kne(),ES256K:IG(),"ES256K-R":IG(!0),Ed25519:EG(),EdDSA:EG()};function One(n,e){let t=id(AG(e).slice(0,1)),r=x0(n),i=K8(od(r)),o=t+id(i),s=od(x0(o)),a=od(s),l=id(a).substring(0,8),c=o+l;return Dne(x0(c))}function Gne(n,e){let t=No.ProjectivePoint.fromHex(n).toRawBytes(),r=K8(od(t)),i=Y8.toWords(r);return Y8.encode(e,i).replace(e,"")}function Nne(n,e){if(e){let t=e.split(":");switch(t[0]){case"bip122":t[t.length-1]=One(n,t[t.length-1]);break;case"cosmos":t[t.length-1]=Gne(n,t[1]);break;case"eip155":t[t.length-1]=vG(n);break;default:return!1}return t.join(":").toLowerCase()===e.toLowerCase()}return!1}function Une(n,e=!1){let t=ws(n);if(t.length!==(e?65:64))throw new Error("wrong signature length");let r=id(t.slice(0,32)),i=id(t.slice(32,64)),o={r,s:i};return e&&(o.recoveryParam=t[64]),o}function z8(n,e=!1){let t=ws(n);if(t.length!==(e?65:64))throw new Error("wrong signature length");return{compact:t.slice(0,64),recovery:t[64]}}function Hne(n,e,t){let r=od(n),i=JI.Signature.fromCompact(z8(e).compact),s=t.filter(a=>!a.ethereumAddress&&!a.blockchainAccountId).find(a=>{try{let{keyBytes:l}=WI(a);return JI.verify(i,r,l)}catch{return!1}});if(!s)throw new Error("invalid_signature: Signature invalid for JWT");return s}function Kne(n,e,t){let r=od(n),i=No.Signature.fromCompact(ws(e)).normalizeS(),o=t.filter(l=>!l.ethereumAddress&&!l.blockchainAccountId),s=t.filter(l=>l.ethereumAddress||l.blockchainAccountId),a=o.find(l=>{try{let{keyBytes:c}=WI(l);return No.verify(i,r,c)}catch{return!1}});if(!a&&s.length>0&&(a=SG(n,e,s)),!a)throw new Error("invalid_signature: Signature invalid for JWT");return a}function SG(n,e,t){let r=[];if(e.length>86)r.push(z8(e,!0));else{let s=z8(e,!1);r.push({...s,recovery:0}),r.push({...s,recovery:1})}let i=od(n),o=s=>{let l=No.Signature.fromCompact(s.compact).addRecoveryBit(s.recovery||0).recoverPublicKey(i),c=vG(l.toHex(!1)).toLowerCase(),u=l.toHex(!1),d=l.toHex(!0);return t.find(h=>{let{keyBytes:f}=WI(h),p=id(f);return p===u||p===d||h.ethereumAddress?.toLowerCase()===c||h.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===c||Nne(u,h.blockchainAccountId)})};for(let s of r){let a=o(s);if(a)return a}throw new Error("invalid_signature: Signature invalid for JWT")}function xG(n,e,t){let r=Rne(n),i=ws(e),o=t.find(s=>{let{keyBytes:a,keyType:l}=WI(s);return l==="Ed25519"?Ar.verify(i,r,a):!1});if(!o)throw new Error("invalid_signature: Signature invalid for JWT");return o}var Jne={ES256:Hne,ES256K:Kne,"ES256K-R":SG,Ed25519:xG,EdDSA:xG};function DG(n){let e=Jne[n];if(!e)throw new Error(`not_supported: Unsupported algorithm ${n}`);return e}DG.toSignatureObject=Une;var ZLe=typeof Symbol<"u"?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function qne(n){let e=n.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(Pne(e[1])),payload:e[2],signature:e[3],data:`${e[1]}.${e[2]}`};throw new Error("invalid_argument: Incorrect format JWS")}function Qne({header:n,data:e,signature:t},r){return Array.isArray(r)||(r=[r]),DG(n.alg)(e,t,r)}function LG(n,e){let t=qne(n);return Qne(t,e)}var XLe=typeof Symbol<"u"?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";var X8=class{keyType;_keyStore;constructor(e,t){if(e!=="Secp256k1")throw new Error("Key type must be Secp256k1");this.keyType=e,this._keyStore=t}async list(){return(await this._keyStore.list()).filter(t=>t.alias.startsWith(this.keyType))}async newPrivateKeyFromSeed(e){if(e.length!==32)throw new Error("Seed should be 32 bytes");let t=No.getPublicKey(e),r={type:this.keyType,id:qs(this.keyType,xi(t))};return await this._keyStore.importKey({alias:r.id,key:xi(e).padStart(64,"0")}),r}async publicKey(e){let t=await this.privateKey(e),r=No.getPublicKey(t,!1);return xi(r)}async sign(e,t,r={alg:"ES256K"}){let i=await this.privateKey(e),o=await CG(x0(i),r.alg==="ES256K-R")(t);if(typeof o!="string")throw new Error("signatureBase64 must be a string");return jd(o)}async verify(e,t,r){let i=await this.publicKey(r);return No.verify(t,Pc(e),i)}async privateKey(e){return this._keyStore.get({alias:e.id})}};var Fe=Object.freeze({ERRORS:{FiELD_IS_EMPTY:"fieldPath is empty",CONTEXT_TYPE_IS_EMPTY:"ctxType is empty",IDENTITY_DOES_NOT_EXIST:"Identity does not exist",IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR:"IdentityDoesNotExist",NO_AUTH_CRED_FOUND:"no auth credentials found",STATE_DOES_NOT_EXIST:"State does not exist",STATE_DOES_NOT_EXIST_CUSTOM_ERROR:"StateDoesNotExist",ROOT_DOES_NOT_EXIST:"Root does not exist",ROOT_DOES_NOT_EXIST_CUSTOM_ERROR:"RootDoesNotExist",ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY:"no credential satisfied query",ID_WALLET_SIGNER_IS_REQUIRED:"Ethereum signer is required to create Ethereum identities in order to transit state",ID_WALLET_PROVER_IS_REQUIRED:"prover is required to generate proofs for non ethereum identities",ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF:"credential must have coreClaim representation in the signature proof",ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF:"credential must have coreClaim representation in proofs",ID_WALLET_CORE_CLAIM_MISMATCH:"core claim representations is set in both proofs but they are not equal",ID_WALLET_CORE_CLAIM_IS_NOT_SET:"core claim is not set in credential proofs",ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND:"profile or identity not found",ID_WALLET_PROFILE_ALREADY_EXISTS:"profile with given nonce or verifier already exists",ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS:"profile with given verifier and tags already exists",ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF:"issuer auth credential must have proof",ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF:"mtp is required for auth bjj key to issue new credentials",PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE:"no credentials belong to did or its profiles",PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY:"credential not found for query",PROOF_SERVICE_PROFILE_GENESIS_DID_MISMATCH:"subject and auth profiles are not derived from the same did",PROOF_SERVICE_NO_QUERIES_IN_ZKP_REQUEST:"no queries in zkp request",CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED:"all claims are revoked"},CREDENTIAL_TYPE:{W3C_VERIFIABLE_CREDENTIAL:"VerifiableCredential",W3C_VERIFIABLE_PRESENTATION:"VerifiablePresentation"},CREDENTIAL_SUBJECT_PATH:"https://www.w3.org/2018/credentials#credentialSubject",JSONLD_SCHEMA:{IDEN3_CREDENTIAL:"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld",IDEN3_DISPLAY_METHOD:"https://schema.iden3.io/core/jsonld/displayMethod.jsonld",W3C_CREDENTIAL_2018:"https://www.w3.org/2018/credentials/v1",W3C_VC_DOCUMENT_2018:'{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","VerifiableCredential":{"@id":"https://www.w3.org/2018/credentials#VerifiableCredential","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","credentialSchema":{"@id":"cred:credentialSchema","@type":"@id","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","JsonSchemaValidator2018":"cred:JsonSchemaValidator2018"}},"credentialStatus":{"@id":"cred:credentialStatus","@type":"@id"},"credentialSubject":{"@id":"cred:credentialSubject","@type":"@id"},"evidence":{"@id":"cred:evidence","@type":"@id"},"expirationDate":{"@id":"cred:expirationDate","@type":"xsd:dateTime"},"holder":{"@id":"cred:holder","@type":"@id"},"issued":{"@id":"cred:issued","@type":"xsd:dateTime"},"issuer":{"@id":"cred:issuer","@type":"@id"},"issuanceDate":{"@id":"cred:issuanceDate","@type":"xsd:dateTime"},"proof":{"@id":"sec:proof","@type":"@id","@container":"@graph"},"refreshService":{"@id":"cred:refreshService","@type":"@id","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","ManualRefreshService2018":"cred:ManualRefreshService2018"}},"termsOfUse":{"@id":"cred:termsOfUse","@type":"@id"},"validFrom":{"@id":"cred:validFrom","@type":"xsd:dateTime"},"validUntil":{"@id":"cred:validUntil","@type":"xsd:dateTime"}}},"VerifiablePresentation":{"@id":"https://www.w3.org/2018/credentials#VerifiablePresentation","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","sec":"https://w3id.org/security#","holder":{"@id":"cred:holder","@type":"@id"},"proof":{"@id":"sec:proof","@type":"@id","@container":"@graph"},"verifiableCredential":{"@id":"cred:verifiableCredential","@type":"@id","@container":"@graph"}}},"EcdsaSecp256k1Signature2019":{"@id":"https://w3id.org/security#EcdsaSecp256k1Signature2019","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"EcdsaSecp256r1Signature2019":{"@id":"https://w3id.org/security#EcdsaSecp256r1Signature2019","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"Ed25519Signature2018":{"@id":"https://w3id.org/security#Ed25519Signature2018","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"RsaSignature2018":{"@id":"https://w3id.org/security#RsaSignature2018","@context":{"@version":1.1,"@protected":true,"challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"proof":{"@id":"https://w3id.org/security#proof","@type":"@id","@container":"@graph"}}}',IDEN3_PROOFS_DEFINITION_DOCUMENT:'{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","Iden3SparseMerkleTreeProof":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3SparseMerkleTreeProof","@context":{"@version":1.1,"@protected":true,"@propagate":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","@vocab":"https://schema.iden3.io/core/vocab/Iden3SparseMerkleTreeProof.md#","xsd":"http://www.w3.org/2001/XMLSchema#","mtp":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#SparseMerkleTreeProof","@type":"SparseMerkleTreeProof"},"coreClaim":{"@id":"coreClaim","@type":"xsd:string"},"issuerData":{"@id":"issuerData","@context":{"@version":1.1,"state":{"@id":"state","@context":{"txId":{"@id":"txId","@type":"xsd:string"},"blockTimestamp":{"@id":"blockTimestamp","@type":"xsd:integer"},"blockNumber":{"@id":"blockNumber","@type":"xsd:integer"},"rootOfRoots":{"@id":"rootOfRoots","@type":"xsd:string"},"claimsTreeRoot":{"@id":"claimsTreeRoot","@type":"xsd:string"},"revocationTreeRoot":{"@id":"revocationTreeRoot","@type":"xsd:string"},"authCoreClaim":{"@id":"authCoreClaim","@type":"xsd:string"},"value":{"@id":"value","@type":"xsd:string"}}}}}}},"SparseMerkleTreeProof":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#SparseMerkleTreeProof","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","smt-proof-vocab":"https://schema.iden3.io/core/vocab/SparseMerkleTreeProof.md#","xsd":"http://www.w3.org/2001/XMLSchema#","existence":{"@id":"smt-proof-vocab:existence","@type":"xsd:boolean"},"revocationNonce":{"@id":"smt-proof-vocab:revocationNonce","@type":"xsd:number"},"siblings":{"@id":"smt-proof-vocab:siblings","@container":"@list"},"nodeAux":"@nest","hIndex":{"@id":"smt-proof-vocab:hIndex","@nest":"nodeAux","@type":"xsd:string"},"hValue":{"@id":"smt-proof-vocab:hValue","@nest":"nodeAux","@type":"xsd:string"}}},"BJJSignature2021":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#BJJSignature2021","@context":{"@version":1.1,"@protected":true,"id":"@id","@vocab":"https://schema.iden3.io/core/vocab/BJJSignature2021.md#","@propagate":true,"type":"@type","xsd":"http://www.w3.org/2001/XMLSchema#","coreClaim":{"@id":"coreClaim","@type":"xsd:string"},"issuerData":{"@id":"issuerData","@context":{"@version":1.1,"authCoreClaim":{"@id":"authCoreClaim","@type":"xsd:string"},"mtp":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#SparseMerkleTreeProof","@type":"SparseMerkleTreeProof"},"revocationStatus":{"@id":"revocationStatus","@type":"@id"},"state":{"@id":"state","@context":{"@version":1.1,"rootOfRoots":{"@id":"rootOfRoots","@type":"xsd:string"},"claimsTreeRoot":{"@id":"claimsTreeRoot","@type":"xsd:string"},"revocationTreeRoot":{"@id":"revocationTreeRoot","@type":"xsd:string"},"value":{"@id":"value","@type":"xsd:string"}}}}},"signature":{"@id":"signature","@type":"https://w3id.org/security#multibase"},"domain":"https://w3id.org/security#domain","creator":{"@id":"creator","@type":"http://www.w3.org/2001/XMLSchema#string"},"challenge":"https://w3id.org/security#challenge","created":{"@id":"created","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},"expires":{"@id":"https://w3id.org/security#expiration","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},"nonce":"https://w3id.org/security#nonce","proofPurpose":{"@id":"https://w3id.org/security#proofPurpose","@type":"@vocab","@context":{"@protected":true,"id":"@id","type":"@type","assertionMethod":{"@id":"https://w3id.org/security#assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"https://w3id.org/security#authenticationMethod","@type":"@id","@container":"@set"},"capabilityInvocation":{"@id":"https://w3id.org/security#capabilityInvocationMethod","@type":"@id","@container":"@set"},"capabilityDelegation":{"@id":"https://w3id.org/security#capabilityDelegationMethod","@type":"@id","@container":"@set"},"keyAgreement":{"@id":"https://w3id.org/security#keyAgreementMethod","@type":"@id","@container":"@set"}}},"proofValue":{"@id":"https://w3id.org/security#proofValue","@type":"https://w3id.org/security#multibase"},"verificationMethod":{"@id":"https://w3id.org/security#verificationMethod","@type":"@id"}}},"Iden3ReverseSparseMerkleTreeProof":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3ReverseSparseMerkleTreeProof","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3-reverse-sparse-merkle-tree-proof-vocab":"https://schema.iden3.io/core/vocab/Iden3ReverseSparseMerkleTreeProof.md#","revocationNonce":"iden3-reverse-sparse-merkle-tree-proof-vocab:revocationNonce","statusIssuer":{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type"},"@id":"iden3-reverse-sparse-merkle-tree-proof-vocab:statusIssuer"}}},"Iden3commRevocationStatusV1.0":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3commRevocationStatusV1.0","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3-comm-revocation-statusV1.0-vocab":"https://schema.iden3.io/core/vocab/Iden3commRevocationStatusV1.0.md#","revocationNonce":"iden3-comm-revocation-statusV1.0-vocab:revocationNonce","statusIssuer":{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type"},"@id":"iden3-comm-revocation-statusV1.0-vocab:statusIssuer"}}},"Iden3OnchainSparseMerkleTreeProof2023":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3OnchainSparseMerkleTreeProof2023","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3-onchain-sparse-merkle-tree-proof-2023-vocab":"https://schema.iden3.io/core/vocab/Iden3OnchainSparseMerkleTreeProof2023.md#","revocationNonce":"iden3-onchain-sparse-merkle-tree-proof-2023-vocab:revocationNonce","statusIssuer":{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type"},"@id":"iden3-onchain-sparse-merkle-tree-proof-2023-vocab:statusIssuer"}}},"JsonSchema2023":"https://www.w3.org/ns/credentials#JsonSchema2023","Iden3RefreshService2023":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3RefreshService2023"}}',IDEN3_DISPLAY_METHOD_DEFINITION_DOCUMENT:'{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","displayMethod":{"@id":"https://schema.iden3.io/core/vocab/displayMethod.md#displayMethod","@type":"@id","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","Iden3BasicDisplayMethodV1":"https://schema.iden3.io/core/vocab/displayMethod.md#Iden3BasicDisplayMethodV1"}}}}'},JSON_SCHEMA_VALIDATOR:"JsonSchema2023",SERVICE_TYPE:{IDEN3_COMM:"iden3-communication",PUSH_NOTIFICATION:"push-notification"},AUTH:{AUTH_BJJ_CREDENTIAL_HASH:"013fd3f623559d850fb5b02ff012d0e2",AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL:"https://schema.iden3.io/core/json/auth.json",AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL:"https://schema.iden3.io/core/jsonld/auth.jsonld",AUTH_BJJ_CREDENTIAL_TYPE:"AuthBJJCredential",AUTH_BJJ_CREDENTIAL_SCHEMA_JSON:'{"$schema":"http://json-schema.org/draft-07/schema#","$metadata":{"uris":{"jsonLdContext":"https://schema.iden3.io/core/jsonld/auth.jsonld","jsonSchema":"https://schema.iden3.io/core/json/auth.json"},"serialization":{"indexDataSlotA":"x","indexDataSlotB":"y"}},"type":"object","required":["@context","id","type","issuanceDate","credentialSubject","credentialSchema","credentialStatus","issuer"],"properties":{"@context":{"type":["string","array","object"]},"id":{"type":"string"},"type":{"type":["string","array"],"items":{"type":"string"}},"issuer":{"type":["string","object"],"format":"uri","required":["id"],"properties":{"id":{"type":"string","format":"uri"}}},"issuanceDate":{"type":"string","format":"date-time"},"expirationDate":{"type":"string","format":"date-time"},"credentialSchema":{"type":"object","required":["id","type"],"properties":{"id":{"type":"string","format":"uri"},"type":{"type":"string"}}},"credentialSubject":{"type":"object","required":["x","y"],"properties":{"id":{"title":"Credential Subject ID","type":"string","format":"uri"},"x":{"type":"string"},"y":{"type":"string"}}}}}',AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD:'{"@context":[{"@version":1.1,"@protected":true,"id":"@id","type":"@type","AuthBJJCredential":{"@id":"https://schema.iden3.io/core/jsonld/auth.jsonld#AuthBJJCredential","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3_serialization":"iden3:v1:slotIndexA=x&slotIndexB=y","xsd":"http://www.w3.org/2001/XMLSchema#","auth-vocab":"https://schema.iden3.io/core/vocab/auth.md#","x":{"@id":"auth-vocab:x","@type":"xsd:positiveInteger"},"y":{"@id":"auth-vocab:y","@type":"xsd:positiveInteger"}}},"Iden3StateInfo2023":{"@id":"https://schema.iden3.io/core/jsonld/auth.jsonld#Iden3StateInfo2023","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","xsd":"http://www.w3.org/2001/XMLSchema#","@vocab":"https://schema.iden3.io/core/vocab/state-info.md#","@propagate":true,"stateContractAddress":{"@id":"stateContractAddress","@type":"xsd:string"},"published":{"@id":"published","@type":"xsd:boolean"},"info":{"@id":"info","@type":"@id","@context":{"@protected":true,"id":{"@id":"id","@type":"xsd:string"},"state":{"@id":"state","@type":"xsd:string"},"replacedByState":{"@id":"replacedByState","@type":"xsd:string"},"createdAtTimestamp":{"@id":"createdAtTimestamp","@type":"xsd:string"},"replacedAtTimestamp":{"@id":"replacedAtTimestamp","@type":"xsd:string"},"createdAtBlock":{"@id":"createdAtBlock","@type":"xsd:string"},"replacedAtBlock":{"@id":"replacedAtBlock","@type":"xsd:string"}}},"global":{"@id":"global","@type":"@id","@context":{"@protected":true,"sec":"https://w3id.org/security#","root":{"@id":"root","@type":"xsd:string"},"replacedByRoot":{"@id":"replacedByRoot","@type":"xsd:string"},"createdAtTimestamp":{"@id":"createdAtTimestamp","@type":"xsd:string"},"replacedAtTimestamp":{"@id":"replacedAtTimestamp","@type":"xsd:string"},"createdAtBlock":{"@id":"createdAtBlock","@type":"xsd:string"},"replacedAtBlock":{"@id":"replacedAtBlock","@type":"xsd:string"},"proof":{"@id":"sec:proof","@type":"@id","@container":"@graph"}}}}}}]}'}}),gy=(t=>(t.BJJSignature="BJJSignature2021",t.Iden3SparseMerkleTreeProof="Iden3SparseMerkleTreeProof",t))(gy||{}),A0=(i=>(i.SparseMerkleTreeProof="SparseMerkleTreeProof",i.Iden3ReverseSparseMerkleTreeProof="Iden3ReverseSparseMerkleTreeProof",i.Iden3commRevocationStatusV1="Iden3commRevocationStatusV1.0",i.Iden3OnchainSparseMerkleTreeProof2023="Iden3OnchainSparseMerkleTreeProof2023",i))(A0||{}),BG=(e=>(e.Authentication="Authentication",e))(BG||{}),ZI=(r=>(r.Index="index",r.Value="value",r.None="",r))(ZI||{}),XI=(r=>(r.None="",r.Index="index",r.Value="value",r))(XI||{}),_8=(e=>(e.Iden3RefreshService2023="Iden3RefreshService2023",e))(_8||{}),TG=(r=>(r.Iden3PaymentRequestCryptoV1="Iden3PaymentRequestCryptoV1",r.Iden3PaymentRailsRequestV1="Iden3PaymentRailsRequestV1",r.Iden3PaymentRailsERC20RequestV1="Iden3PaymentRailsERC20RequestV1",r))(TG||{}),PG=(r=>(r.Iden3PaymentCryptoV1="Iden3PaymentCryptoV1",r.Iden3PaymentRailsV1="Iden3PaymentRailsV1",r.Iden3PaymentRailsERC20V1="Iden3PaymentRailsERC20V1",r))(PG||{}),RG=(e=>(e.EthereumEip712Signature2021="EthereumEip712Signature2021",e))(RG||{}),MG=(o=>(o.ETH="ETH",o.ETH_WEI="ETHWEI",o.ETH_GWEI="ETHGWEI",o.MATIC="MATIC",o.POL="POL",o))(MG||{}),FG=(e=>(e.EIP_2612="EIP-2612",e))(FG||{}),_I=(e=>(e.Iden3BasicDisplayMethodV1="Iden3BasicDisplayMethodV1",e))(_I||{}),v0=1e4;var ha=class n{type;issuerData;mtp;coreClaim;constructor(e){this.coreClaim=e.coreClaim,this.issuerData=e.issuerData,this.type="Iden3SparseMerkleTreeProof",this.mtp=e.mtp}toJSON(){return{issuerData:{id:this.issuerData.id.string(),state:{...this.issuerData.state,rootOfRoots:this.issuerData.state.rootOfRoots.hex(),claimsTreeRoot:this.issuerData.state.claimsTreeRoot.hex(),revocationTreeRoot:this.issuerData.state.revocationTreeRoot.hex(),value:this.issuerData.state.value.hex()}},type:this.type,coreClaim:this.coreClaim.hex(),mtp:this.mtp.toJSON()}}static fromJSON(e){let t;if(e?.mtp?.notEmpties&&e?.mtp?.depth&&e?.mtp?.siblings){let r=e?.mtp?.notEmpties,i=r instanceof Uint8Array?r:new Uint8Array(Object.values(r)),o=e?.mtp?.siblings.map(l=>me.fromString(JSON.stringify(l))),s=yt.buildAllSiblings(e?.mtp?.depth,i,o),a=e.mtp.nodeAux||e.mtp.node_aux;a&&(a={key:me.fromString(JSON.stringify(a.key)),value:me.fromString(JSON.stringify(a.value))}),t=new yt({existence:e?.mtp.existence,nodeAux:a,siblings:s})}else t=yt.fromJSON(e.mtp);return new n({coreClaim:new er().fromHex(e.coreClaim),mtp:t,issuerData:{id:Ie.parse(e.issuerData.id),state:{...e.issuerData.state,rootOfRoots:me.fromHex(e.issuerData.state.rootOfRoots),claimsTreeRoot:me.fromHex(e.issuerData.state.claimsTreeRoot),revocationTreeRoot:me.fromHex(e.issuerData.state.revocationTreeRoot),value:me.fromHex(e.issuerData.state.value)}}})}},sd=class n{type;issuerData;signature;coreClaim;constructor(e){this.type="BJJSignature2021",this.issuerData=e.issuerData,this.coreClaim=e.coreClaim,this.signature=e.signature}toJSON(){return{issuerData:{id:this.issuerData.id.string(),state:{...this.issuerData.state,rootOfRoots:this.issuerData.state.rootOfRoots.hex(),claimsTreeRoot:this.issuerData.state.claimsTreeRoot.hex(),revocationTreeRoot:this.issuerData.state.revocationTreeRoot.hex(),value:this.issuerData.state.value.hex()},mtp:this.issuerData.mtp.toJSON(),authCoreClaim:this.issuerData.authCoreClaim.hex(),credentialStatus:this.issuerData.credentialStatus},type:this.type,coreClaim:this.coreClaim.hex(),signature:tn.encodeString(this.signature.compress())}}static fromJSON(e){return new n({issuerData:{id:Ie.parse(e.issuerData.id),mtp:yt.fromJSON(e.issuerData.mtp),state:{...e.issuerData.state,rootOfRoots:me.fromHex(e.issuerData.state.rootOfRoots),claimsTreeRoot:me.fromHex(e.issuerData.state.claimsTreeRoot),revocationTreeRoot:me.fromHex(e.issuerData.state.revocationTreeRoot),value:me.fromHex(e.issuerData.state.value)},credentialStatus:e.issuerData.credentialStatus,authCoreClaim:new er().fromHex(e.issuerData.authCoreClaim)},coreClaim:new er().fromHex(e.coreClaim),signature:pu.newFromCompressed(Uint8Array.from(tn.decodeString(e.signature)).slice(0,64))})}};var lD={};sr(lD,{MerklizationConstants:()=>zt,Merklizer:()=>yc,MtValue:()=>kw,Path:()=>rr,PoseidonHasher:()=>Z9,Temporal:()=>wa,getDocumentLoader:()=>Wi});var ae=$n(kG(),1),Ko=ae.default.BigInt(0),Fy=ae.default.BigInt(1),YS=ae.default.BigInt(2),Vne=ae.default.BigInt(10),Yne=ae.default.BigInt(24),zne=ae.default.BigInt(60),jne=ae.default.BigInt(1e3),_y=ae.default.BigInt(1e6),Ly=ae.default.BigInt(1e9),gN=ae.default.multiply(ae.default.BigInt(3600),Ly),Wne=ae.default.multiply(zne,Ly),fd=ae.default.multiply(gN,Yne);function gl(n){return typeof n=="bigint"?ae.default.BigInt(n.toString(10)):n}function yN(n){return ae.default.equal(ae.default.remainder(n,YS),Ko)}function ih(n){return ae.default.lessThan(n,Ko)?ae.default.unaryMinus(n):n}function tE(n,e){return ae.default.lessThan(n,e)?-1:ae.default.greaterThan(n,e)?1:0}function Iy(n,e){return{quotient:ae.default.divide(n,e),remainder:ae.default.remainder(n,e)}}var OG,GG,it="slot-epochNanoSeconds",ot="slot-iso-date",vn="slot-iso-date-time",On="slot-time",ve="slot-calendar",wN="slot-date-brand",bN="slot-year-month-brand",IN="slot-month-day-brand",Xt="slot-time-zone",Mi="slot-years",Fi="slot-months",co="slot-weeks",ki="slot-days",Oi="slot-hours",Gi="slot-minutes",Ni="slot-seconds",Ui="slot-milliseconds",Hi="slot-microseconds",lo="slot-nanoseconds",EN="date",xN="ym",AN="md",vN="time",CN="datetime",SN="instant",mh="original",L0="timezone-canonical",sS="timezone-original",Ey="calendar-id",DN="locale",aS="options",LN=new WeakMap,cS=Symbol.for("@@Temporal__GetSlots");(OG=globalThis)[cS]||(OG[cS]=function(n){return LN.get(n)});var yE=globalThis[cS],lS=Symbol.for("@@Temporal__CreateSlots");(GG=globalThis)[lS]||(GG[lS]=function(n){LN.set(n,Object.create(null))});var Dl=globalThis[lS];function Vi(n,...e){if(!n||typeof n!="object")return!1;let t=yE(n);return!!t&&e.every(r=>r in t)}function z(n,e){let t=yE(n)?.[e];if(t===void 0)throw new TypeError(`Missing internal slot ${e}`);return t}function wt(n,e,t){let r=yE(n);if(r===void 0)throw new TypeError("Missing slots for the given container");if(r[e])throw new TypeError(`${e} already has set`);r[e]=t}var uS={};function Ll(n,e){Object.defineProperty(n.prototype,Symbol.toStringTag,{value:e,writable:!1,enumerable:!1,configurable:!0});let t=Object.getOwnPropertyNames(n);for(let i=0;i<t.length;i++){let o=t[i],s=Object.getOwnPropertyDescriptor(n,o);s.configurable&&s.enumerable&&(s.enumerable=!1,Object.defineProperty(n,o,s))}let r=Object.getOwnPropertyNames(n.prototype);for(let i=0;i<r.length;i++){let o=r[i],s=Object.getOwnPropertyDescriptor(n.prototype,o);s.configurable&&s.enumerable&&(s.enumerable=!1,Object.defineProperty(n.prototype,o,s))}dS(e,n),dS(`${e}.prototype`,n.prototype)}function dS(n,e){let t=`%${n}%`;if(uS[t]!==void 0)throw new Error(`intrinsic ${n} already exists`);uS[t]=e}function Vr(n){return uS[n]}function T0(n,e){let t=n;if(t===0)return{div:t,mod:t};let r=Math.sign(t);t=Math.abs(t);let i=Math.trunc(1+Math.log10(t));if(e>=i)return{div:0*r,mod:r*t};if(e===0)return{div:r*t,mod:0*r};let o=t.toPrecision(i);return{div:r*Number.parseInt(o.slice(0,i-e),10),mod:r*Number.parseInt(o.slice(i-e),10)}}function tS(n,e,t){let r=n,i=t;if(r===0)return i;let o=Math.sign(r)||Math.sign(i);r=Math.abs(r),i=Math.abs(i);let s=r.toPrecision(Math.trunc(1+Math.log10(r)));if(i===0)return o*Number.parseInt(s+"0".repeat(e),10);let a=s+i.toPrecision(Math.trunc(1+Math.log10(i))).padStart(e,"0");return o*Number.parseInt(a,10)}function wE(n,e){let t=e==="negative";switch(n){case"ceil":return t?"zero":"infinity";case"floor":return t?"infinity":"zero";case"expand":return"infinity";case"trunc":return"zero";case"halfCeil":return t?"half-zero":"half-infinity";case"halfFloor":return t?"half-infinity":"half-zero";case"halfExpand":return"half-infinity";case"halfTrunc":return"half-zero";case"halfEven":return"half-even"}}function bE(n,e,t,r,i){return i==="zero"?n:i==="infinity"?e:t<0?n:t>0?e:i==="half-zero"?n:i==="half-infinity"?e:r?n:e}var dn=class n{constructor(e){this.totalNs=gl(e),this.sec=ae.default.toNumber(ae.default.divide(this.totalNs,Ly)),this.subsec=ae.default.toNumber(ae.default.remainder(this.totalNs,Ly))}static validateNew(e,t){if(ae.default.greaterThan(ih(e),n.MAX))throw new RangeError(`${t} of duration time units cannot exceed ${n.MAX} s`);return new n(e)}static fromEpochNsDiff(e,t){let r=ae.default.subtract(gl(e),gl(t));return new n(r)}static fromComponents(e,t,r,i,o,s){let a=ae.default.add(ae.default.add(ae.default.add(ae.default.add(ae.default.add(ae.default.BigInt(s),ae.default.multiply(ae.default.BigInt(o),jne)),ae.default.multiply(ae.default.BigInt(i),_y)),ae.default.multiply(ae.default.BigInt(r),Ly)),ae.default.multiply(ae.default.BigInt(t),Wne)),ae.default.multiply(ae.default.BigInt(e),gN));return n.validateNew(a,"total")}abs(){return new n(ih(this.totalNs))}add(e){return n.validateNew(ae.default.add(this.totalNs,e.totalNs),"sum")}add24HourDays(e){return n.validateNew(ae.default.add(this.totalNs,ae.default.multiply(ae.default.BigInt(e),fd)),"sum")}addToEpochNs(e){return ae.default.add(gl(e),this.totalNs)}cmp(e){return tE(this.totalNs,e.totalNs)}divmod(e){let{quotient:t,remainder:r}=Iy(this.totalNs,ae.default.BigInt(e));return{quotient:ae.default.toNumber(t),remainder:new n(r)}}fdiv(e){let t=gl(e),r=ae.default.BigInt(t),{quotient:i,remainder:o}=Iy(this.totalNs,r),s=[],a,l=(ae.default.lessThan(this.totalNs,Ko)?-1:1)*Math.sign(ae.default.toNumber(t));for(;!ae.default.equal(o,Ko)&&s.length<50;)o=ae.default.multiply(o,Vne),{quotient:a,remainder:o}=Iy(o,r),s.push(Math.abs(ae.default.toNumber(a)));return l*+(ih(i).toString()+"."+s.join(""))}isZero(){return ae.default.equal(this.totalNs,Ko)}round(e,t){let r=gl(e);if(ae.default.equal(r,Fy))return this;let{quotient:i,remainder:o}=Iy(this.totalNs,r),s=ae.default.lessThan(this.totalNs,Ko)?"negative":"positive",a=ae.default.multiply(ih(i),r),l=ae.default.add(a,r),c=tE(ih(ae.default.multiply(o,YS)),r),u=wE(t,s),d=ae.default.equal(ih(this.totalNs),a)?a:bE(a,l,c,yN(i),u),h=s==="positive"?d:ae.default.unaryMinus(d);return n.validateNew(h,"rounding")}sign(){return this.cmp(new n(Ko))}subtract(e){return n.validateNew(ae.default.subtract(this.totalNs,e.totalNs),"difference")}};dn.MAX=ae.default.BigInt("9007199254740991999999999"),dn.ZERO=new dn(Ko);var NG=/[A-Za-z._][A-Za-z._0-9+-]*/,$y=new RegExp(`(?:${/(?:[+-](?:[01][0-9]|2[0-3])(?::?[0-5][0-9])?)/.source}|(?:${NG.source})(?:\\/(?:${NG.source}))*)`),BN=/(?:[+-]\d{6}|\d{4})/,nE=/(?:0[1-9]|1[0-2])/,fS=/(?:0[1-9]|[12]\d|3[01])/,Zne=new RegExp(`(${BN.source})(?:-(${nE.source})-(${fS.source})|(${nE.source})(${fS.source}))`),TN=/(\d{2})(?::(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?|(\d{2})(?:(\d{2})(?:[.,](\d{1,9}))?)?)?/,PN=/((?:[+-])(?:[01][0-9]|2[0-3])(?::?(?:[0-5][0-9])(?::?(?:[0-5][0-9])(?:[.,](?:\d{1,9}))?)?)?)/,RN=new RegExp(`([zZ])|${PN.source}?`),F0=/\[(!)?([a-z_][a-z0-9_-]*)=([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*)\]/g,Xne=new RegExp([`^${Zne.source}`,`(?:(?:[tT]|\\s+)${TN.source}(?:${RN.source})?)?`,`(?:\\[!?(${$y.source})\\])?`,`((?:${F0.source})*)$`].join("")),_ne=new RegExp([`^[tT]?${TN.source}`,`(?:${RN.source})?`,`(?:\\[!?${$y.source}\\])?`,`((?:${F0.source})*)$`].join("")),$ne=new RegExp(`^(${BN.source})-?(${nE.source})(?:\\[!?${$y.source}\\])?((?:${F0.source})*)$`),ere=new RegExp(`^(?:--)?(${nE.source})-?(${fS.source})(?:\\[!?${$y.source}\\])?((?:${F0.source})*)$`),nS=/(\d+)(?:[.,](\d{1,9}))?/,tre=new RegExp(`(?:${nS.source}H)?(?:${nS.source}M)?(?:${nS.source}S)?`),nre=new RegExp(`^([+-])?P${/(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?/.source}(?:T(?!$)${tre.source})?$`,"i"),hd=864e5,rE=1e6*hd,rre=6e10,MN=1e8*hd,k0=ga(MN),ky=ae.default.unaryMinus(k0),ire=ae.default.add(ae.default.subtract(ky,fd),Fy),ore=ae.default.subtract(ae.default.add(k0,fd),Fy),sre=146097*hd,UG=-271821,HG=275760,By=Date.UTC(1847,0,1),are=["iso8601","hebrew","islamic","islamic-umalqura","islamic-tbla","islamic-civil","islamic-rgsa","islamicc","persian","ethiopic","ethioaa","ethiopic-amete-alem","coptic","chinese","dangi","roc","indian","buddhist","japanese","gregory"],cre=new Set(["ACT","AET","AGT","ART","AST","BET","BST","CAT","CNT","CST","CTT","EAT","ECT","IET","IST","JST","MIT","NET","NST","PLT","PNT","PRT","PST","SST","VST"]);function Gn(n){return typeof n=="object"&&n!==null||typeof n=="function"}function IE(n){if(typeof n=="bigint")throw new TypeError("Cannot convert BigInt to number");return Number(n)}function EE(n){if(typeof n=="symbol")throw new TypeError("Cannot convert a Symbol value to a String");return String(n)}function ut(n){let e=IE(n);if(e===0)return 0;if(Number.isNaN(e)||e===1/0||e===-1/0)throw new RangeError("invalid number value");let t=Math.trunc(e);return t===0?0:t}function KG(n,e){let t=ut(n);if(t<=0)throw e!==void 0?new RangeError(`property '${e}' cannot be a a number less than one`):new RangeError("Cannot convert a number less than one to a positive integer");return t}function pa(n){let e=IE(n);if(Number.isNaN(e))throw new RangeError("not a number");if(e===1/0||e===-1/0)throw new RangeError("infinity is out of range");if(!function(t){if(typeof t!="number"||Number.isNaN(t)||t===1/0||t===-1/0)return!1;let r=Math.abs(t);return Math.floor(r)===r}(e))throw new RangeError(`unsupported fractional value ${n}`);return e===0?0:e}function Oy(n,e){return String(n).padStart(e,"0")}function dr(n){if(typeof n!="string")throw new TypeError(`expected a string, not ${String(n)}`);return n}function hS(n,e){if(Gn(n)){let t=n?.toString();if(typeof t=="string"||typeof t=="number")return t;throw new TypeError("Cannot convert object to primitive value")}return n}var pS=["era","eraYear","year","month","monthCode","day","hour","minute","second","millisecond","microsecond","nanosecond","offset","timeZone"],lre={era:EE,eraYear:ut,year:ut,month:KG,monthCode:function(n){let e=dr(hS(n));if(e.length<3||e.length>4||e[0]!=="M"||"0123456789".indexOf(e[1])===-1||"0123456789".indexOf(e[2])===-1||e[1]+e[2]==="00"&&e[3]!=="L"||e[3]!=="L"&&e[3]!==void 0)throw new RangeError(`bad month code ${e}; must match M01-M99 or M00L-M99L`);return e},day:KG,hour:ut,minute:ut,second:ut,millisecond:ut,microsecond:ut,nanosecond:ut,offset:function(n){let e=dr(hS(n));return Q0(e),e},timeZone:qi},ure={hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0},O0=[["years","year","date"],["months","month","date"],["weeks","week","date"],["days","day","date"],["hours","hour","time"],["minutes","minute","time"],["seconds","second","time"],["milliseconds","millisecond","time"],["microseconds","microsecond","time"],["nanoseconds","nanosecond","time"]],JG=Object.fromEntries(O0.map(n=>[n[0],n[1]])),dre=Object.fromEntries(O0.map(([n,e])=>[e,n])),Ty=O0.map(([,n])=>n),G0={day:rE,hour:36e11,minute:6e10,second:1e9,millisecond:1e6,microsecond:1e3,nanosecond:1},iE=["days","hours","microseconds","milliseconds","minutes","months","nanoseconds","seconds","weeks","years"],fre=Intl.DateTimeFormat,qG=new Map;function FN(n){let e=Ky(n),t=qG.get(e);return t===void 0&&(t=new fre("en-us",{timeZone:e,hour12:!1,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}),qG.set(e,t)),t}function Jr(n){return Vi(n,it)&&!Vi(n,Xt,ve)}function Fn(n){return Vi(n,Mi,Fi,ki,Oi,Gi,Ni,Ui,Hi,lo)}function kn(n){return Vi(n,wN)}function qn(n){return Vi(n,On)}function En(n){return Vi(n,vn)}function qr(n){return Vi(n,bN)}function Ho(n){return Vi(n,IN)}function It(n){return Vi(n,it,Xt,ve)}function de(n,e){if(!e(n))throw new TypeError("invalid receiver: method called with the wrong type of this-object")}function K0(n){if(Vi(n,ve)||Vi(n,Xt))throw new TypeError("with() does not support a calendar or timeZone property");if(qn(n))throw new TypeError("with() does not accept Temporal.PlainTime, use withPlainTime() instead");if(n.calendar!==void 0)throw new TypeError("with() does not support a calendar property");if(n.timeZone!==void 0)throw new TypeError("with() does not support a timeZone property")}function ew(n,e){return e==="never"||e==="auto"&&n==="iso8601"?"":`[${e==="critical"?"!":""}u-ca=${n}]`}function xE(n){let e,t,r=!1;for(F0.lastIndex=0;t=F0.exec(n);){let{1:i,2:o,3:s}=t;if(o==="u-ca"){if(e===void 0)e=s,r=i==="!";else if(i==="!"||r)throw new RangeError(`Invalid annotations in ${n}: more than one u-ca present with critical flag`)}else if(i==="!")throw new RangeError(`Unrecognized annotation: !${o}=${s}`)}return e}function cc(n){let e=Xne.exec(n);if(!e)throw new RangeError(`invalid RFC 9557 string: ${n}`);let t=xE(e[16]),r=e[1];if(r==="-000000")throw new RangeError(`invalid RFC 9557 string: ${n}`);let i=+r,o=+(e[2]??e[4]??1),s=+(e[3]??e[5]??1),a=e[6]!==void 0,l=+(e[6]??0),c=+(e[7]??e[10]??0),u=+(e[8]??e[11]??0);u===60&&(u=59);let d=(e[9]??e[12]??"")+"000000000",h=+d.slice(0,3),f=+d.slice(3,6),p=+d.slice(6,9),w,y=!1;e[13]?(w=void 0,y=!0):e[14]&&(w=e[14]);let v=e[15];return _S(i,o,s,l,c,u,h,f,p),{year:i,month:o,day:s,time:a?{hour:l,minute:c,second:u,millisecond:h,microsecond:f,nanosecond:p}:"start-of-day",tzAnnotation:v,offset:w,z:y,calendar:t}}function kN(n){let e=_ne.exec(n),t,r,i,o,s,a,l;if(e){l=xE(e[10]),t=+(e[1]??0),r=+(e[2]??e[5]??0),i=+(e[3]??e[6]??0),i===60&&(i=59);let c=(e[4]??e[7]??"")+"000000000";if(o=+c.slice(0,3),s=+c.slice(3,6),a=+c.slice(6,9),e[8])throw new RangeError("Z designator not supported for PlainTime")}else{let c,u;if({time:c,z:u,calendar:l}=cc(n),c==="start-of-day")throw new RangeError(`time is missing in string: ${n}`);if(u)throw new RangeError("Z designator not supported for PlainTime");({hour:t,minute:r,second:i,millisecond:o,microsecond:s,nanosecond:a}=c)}if(SE(t,r,i,o,s,a),/[tT ][0-9][0-9]/.test(n))return{hour:t,minute:r,second:i,millisecond:o,microsecond:s,nanosecond:a,calendar:l};try{let{month:c,day:u}=jS(n);lh(1972,c,u)}catch{try{let{year:c,month:u}=zS(n);lh(c,u,1)}catch{return{hour:t,minute:r,second:i,millisecond:o,microsecond:s,nanosecond:a,calendar:l}}}throw new RangeError(`invalid RFC 9557 time-only string ${n}; may need a T prefix`)}function zS(n){let e=$ne.exec(n),t,r,i,o;if(e){i=xE(e[3]);let s=e[1];if(s==="-000000")throw new RangeError(`invalid RFC 9557 string: ${n}`);if(t=+s,r=+e[2],o=1,i!==void 0&&i!=="iso8601")throw new RangeError("YYYY-MM format is only valid with iso8601 calendar")}else{let s;if({year:t,month:r,calendar:i,day:o,z:s}=cc(n),s)throw new RangeError("Z designator not supported for PlainYearMonth")}return{year:t,month:r,calendar:i,referenceISODay:o}}function jS(n){let e=ere.exec(n),t,r,i,o;if(e){if(i=xE(e[3]),t=+e[1],r=+e[2],i!==void 0&&i!=="iso8601")throw new RangeError("MM-DD format is only valid with iso8601 calendar")}else{let s;if({month:t,day:r,calendar:i,year:o,z:s}=cc(n),s)throw new RangeError("Z designator not supported for PlainMonthDay")}return{month:t,day:r,calendar:i,referenceISOYear:o}}var ON=new RegExp(`^${$y.source}$`,"i"),GN=new RegExp(`^${/([+-])([01][0-9]|2[0-3])(?::?([0-5][0-9])?)?/.source}$`);function NN(n){let e=pre.test(n)?"Seconds not allowed in offset time zone":"Invalid time zone";throw new RangeError(`${e}: ${n}`)}function dd(n){return ON.test(n)||NN(n),GN.test(n)?{offsetMinutes:Q0(n)/6e10}:{tzName:n}}function Py(n,e,t,r){let i=n,o=e,s=t;switch(r){case"reject":lh(i,o,s);break;case"constrain":({year:i,month:o,day:s}=tU(i,o,s))}return{year:i,month:o,day:s}}function AE(n,e,t,r,i,o,s){let a=n,l=e,c=t,u=r,d=i,h=o;switch(s){case"reject":SE(a,l,c,u,d,h);break;case"constrain":a=Ki(a,0,23),l=Ki(l,0,59),c=Ki(c,0,59),u=Ki(u,0,999),d=Ki(d,0,999),h=Ki(h,0,999)}return{hour:a,minute:l,second:c,millisecond:u,microsecond:d,nanosecond:h}}function UN(n){if(!Gn(n))throw new TypeError("invalid duration-like");let e={years:void 0,months:void 0,weeks:void 0,days:void 0,hours:void 0,minutes:void 0,seconds:void 0,milliseconds:void 0,microseconds:void 0,nanoseconds:void 0},t=!1;for(let r=0;r<iE.length;r++){let i=iE[r],o=n[i];o!==void 0&&(t=!0,e[i]=pa(o))}if(!t)throw new TypeError("invalid duration-like");return e}function oi({years:n,months:e,weeks:t,days:r},i,o,s){return{years:n,months:s??e,weeks:o??t,days:i??r}}function Ht(n,e){return{isoDate:n,time:e}}function kt(n){return Al(n,"overflow",["constrain","reject"],"constrain")}function Ry(n){return Al(n,"disambiguation",["compatible","earlier","later","reject"],"compatible")}function ya(n,e){return Al(n,"roundingMode",["ceil","floor","expand","trunc","halfCeil","halfFloor","halfExpand","halfTrunc","halfEven"],e)}function eE(n,e){return Al(n,"offset",["prefer","use","ignore","reject"],e)}function tw(n){return Al(n,"calendarName",["auto","always","never","critical"],"auto")}function J0(n){let e=n.roundingIncrement;if(e===void 0)return 1;let t=ut(e);if(t<1||t>1e9)throw new RangeError(`roundingIncrement must be at least 1 and at most 1e9, not ${e}`);return t}function q0(n,e,t){let r=t?e:e-1;if(n>r)throw new RangeError(`roundingIncrement must be at least 1 and less than ${r}, not ${n}`);if(e%n!=0)throw new RangeError(`Rounding increment must divide evenly into ${e}`)}function nw(n){let e=n.fractionalSecondDigits;if(e===void 0)return"auto";if(typeof e!="number"){if(EE(e)!=="auto")throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${e}`);return"auto"}let t=Math.floor(e);if(!Number.isFinite(t)||t<0||t>9)throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${e}`);return t}function rw(n,e){switch(n){case"minute":return{precision:"minute",unit:"minute",increment:1};case"second":return{precision:0,unit:"second",increment:1};case"millisecond":return{precision:3,unit:"millisecond",increment:1};case"microsecond":return{precision:6,unit:"microsecond",increment:1};case"nanosecond":return{precision:9,unit:"nanosecond",increment:1}}switch(e){case"auto":return{precision:e,unit:"nanosecond",increment:1};case 0:return{precision:e,unit:"second",increment:1};case 1:case 2:case 3:return{precision:e,unit:"millisecond",increment:10**(3-e)};case 4:case 5:case 6:return{precision:e,unit:"microsecond",increment:10**(6-e)};case 7:case 8:case 9:return{precision:e,unit:"nanosecond",increment:10**(9-e)};default:throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${e}`)}}var Cl=Symbol("~required~");function fo(n,e,t,r,i=[]){let o=[];for(let c=0;c<O0.length;c++){let u=O0[c],d=u[1],h=u[2];t!=="datetime"&&t!==h||o.push(d)}o=o.concat(i);let s=r;s===Cl?s=void 0:s!==void 0&&o.push(s);let a=[];a=a.concat(o);for(let c=0;c<o.length;c++){let u=o[c],d=dre[u];d!==void 0&&a.push(d)}let l=Al(n,e,a,s);if(l===void 0&&r===Cl)throw new RangeError(`${e} is required`);return l&&l in JG?JG[l]:l}function rS(n){let e=n.relativeTo;if(e===void 0)return{};let t,r,i,o,s,a="option",l=!1;if(Gn(e)){if(It(e))return{zonedRelativeTo:e};if(kn(e))return{plainRelativeTo:e};if(En(e))return{plainRelativeTo:Ji(z(e,vn).isoDate,z(e,ve))};i=cw(e);let c=Vo(i,e,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond","offset","timeZone"],[]);({isoDate:t,time:r}=ow(i,c,"constrain")),{offset:s,timeZone:o}=c,s===void 0&&(a="wall")}else{let c,u,d,h,f;if({year:d,month:h,day:f,time:r,calendar:i,tzAnnotation:c,offset:s,z:u}=cc(dr(e)),c)o=qi(c),u?a="exact":s||(a="wall"),l=!0;else if(u)throw new RangeError("Z designator not supported for PlainDate relativeTo; either remove the Z or add a bracketed time zone");i||(i="iso8601"),i=Yi(i),t={year:d,month:h,day:f}}return o===void 0?{plainRelativeTo:Ji(t,i)}:{zonedRelativeTo:ii(oE(t,r,a,a==="option"?Q0(s):0,o,"compatible","reject",l),o,i)}}function yl(n){return z(n,Mi)!==0?"year":z(n,Fi)!==0?"month":z(n,co)!==0?"week":z(n,ki)!==0?"day":z(n,Oi)!==0?"hour":z(n,Gi)!==0?"minute":z(n,Ni)!==0?"second":z(n,Ui)!==0?"millisecond":z(n,Hi)!==0?"microsecond":"nanosecond"}function El(n,e){return Ty.indexOf(n)>Ty.indexOf(e)?e:n}function tc(n){return n==="year"||n==="month"||n==="week"}function wl(n){return tc(n)||n==="day"?"date":"time"}function gd(n){return Vr("%calendarImpl%")(n)}function iw(n){return Vr("%calendarImpl%")(z(n,ve))}function Qi(n,e,t="date"){let r=Object.create(null),i=gd(n).isoToDate(e,{year:!0,monthCode:!0,day:!0});return r.monthCode=i.monthCode,t!=="month-day"&&t!=="date"||(r.day=i.day),t!=="year-month"&&t!=="date"||(r.year=i.year),r}function Vo(n,e,t,r,i){let o=gd(n).extraFields(t),s=t.concat(r,o),a=Object.create(null),l=!1;s.sort();for(let c=0;c<s.length;c++){let u=s[c],d=e[u];if(d!==void 0)l=!0,a[u]=(0,lre[u])(d);else if(i!=="partial"){if(i.includes(u))throw new TypeError(`required property '${u}' missing or undefined`);a[u]=ure[u]}}if(i==="partial"&&!l)throw new TypeError("no supported properties found");return a}function mS(n,e="complete"){let t=["hour","microsecond","millisecond","minute","nanosecond","second"],r=!1,i=Object.create(null);for(let o=0;o<t.length;o++){let s=t[o],a=n[s];a!==void 0?(i[s]=ut(a),r=!0):e==="complete"&&(i[s]=0)}if(!r)throw new TypeError("invalid time-like");return i}function xy(n,e){if(Gn(n)){if(kn(n))return kt(Qe(e)),Ji(z(n,ot),z(n,ve));if(It(n)){let l=xs(z(n,Xt),z(n,it));return kt(Qe(e)),Ji(l.isoDate,z(n,ve))}if(En(n))return kt(Qe(e)),Ji(z(n,vn).isoDate,z(n,ve));let a=cw(n);return Ji(pd(a,Vo(a,n,["year","month","monthCode","day"],[],[]),kt(Qe(e))),a)}let{year:t,month:r,day:i,calendar:o,z:s}=cc(dr(n));if(s)throw new RangeError("Z designator not supported for PlainDate");return o||(o="iso8601"),o=Yi(o),kt(Qe(e)),Ji({year:t,month:r,day:i},o)}function ow(n,e,t){return Ht(pd(n,e,t),AE(e.hour,e.minute,e.second,e.millisecond,e.microsecond,e.nanosecond,t))}function Ay(n,e){let t,r,i;if(Gn(n)){if(En(n))return kt(Qe(e)),bs(z(n,vn),z(n,ve));if(It(n)){let a=xs(z(n,Xt),z(n,it));return kt(Qe(e)),bs(a,z(n,ve))}if(kn(n))return kt(Qe(e)),bs(Ht(z(n,ot),{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),z(n,ve));i=cw(n);let o=Vo(i,n,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond"],[]),s=kt(Qe(e));({isoDate:t,time:r}=ow(i,o,s))}else{let o,s,a,l;if({year:s,month:a,day:l,time:r,calendar:i,z:o}=cc(dr(n)),o)throw new RangeError("Z designator not supported for PlainDateTime");r==="start-of-day"&&(r={deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),_S(s,a,l,r.hour,r.minute,r.second,r.millisecond,r.microsecond,r.nanosecond),i||(i="iso8601"),i=Yi(i),kt(Qe(e)),t={year:s,month:a,day:l}}return bs(Ht(t,r),i)}function Es(n){let e=Vr("%Temporal.Duration%");if(Fn(n))return new e(z(n,Mi),z(n,Fi),z(n,co),z(n,ki),z(n,Oi),z(n,Gi),z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo));if(!Gn(n))return function(i){let{years:o,months:s,weeks:a,days:l,hours:c,minutes:u,seconds:d,milliseconds:h,microseconds:f,nanoseconds:p}=function(w){let y=nre.exec(w);if(!y)throw new RangeError(`invalid duration: ${w}`);if(y.every((R,J)=>J<2||R===void 0))throw new RangeError(`invalid duration: ${w}`);let v=y[1]==="-"?-1:1,B=y[2]===void 0?0:ut(y[2])*v,U=y[3]===void 0?0:ut(y[3])*v,k=y[4]===void 0?0:ut(y[4])*v,F=y[5]===void 0?0:ut(y[5])*v,P=y[6]===void 0?0:ut(y[6])*v,I=y[7],D=y[8],V=y[9],K=y[10],q=y[11],G=0,x=0,S=0;if(I!==void 0){if(D??V??K??q)throw new RangeError("only the smallest unit can be fractional");S=3600*ut((I+"000000000").slice(0,9))*v}else if(G=D===void 0?0:ut(D)*v,V!==void 0){if(K??q)throw new RangeError("only the smallest unit can be fractional");S=60*ut((V+"000000000").slice(0,9))*v}else x=K===void 0?0:ut(K)*v,q!==void 0&&(S=ut((q+"000000000").slice(0,9))*v);let M=S%1e3,b=Math.trunc(S/1e3)%1e3,A=Math.trunc(S/1e6)%1e3;return x+=Math.trunc(S/1e9)%60,G+=Math.trunc(S/6e10),DE(B,U,k,F,P,G,x,A,b,M),{years:B,months:U,weeks:k,days:F,hours:P,minutes:G,seconds:x,milliseconds:A,microseconds:b,nanoseconds:M}}(i);return new(Vr("%Temporal.Duration%"))(o,s,a,l,c,u,d,h,f,p)}(dr(n));let t={years:0,months:0,weeks:0,days:0,hours:0,minutes:0,seconds:0,milliseconds:0,microseconds:0,nanoseconds:0},r=UN(n);for(let i=0;i<iE.length;i++){let o=iE[i],s=r[o];s!==void 0&&(t[o]=s)}return new e(t.years,t.months,t.weeks,t.days,t.hours,t.minutes,t.seconds,t.milliseconds,t.microseconds,t.nanoseconds)}function vy(n){let e;if(Gn(n)){if(Jr(n)||It(n))return ma(z(n,it));e=hS(n)}else e=n;let{year:t,month:r,day:i,time:o,offset:s,z:a}=function(w){let y=cc(w);if(!y.z&&!y.offset)throw new RangeError("Temporal.Instant requires a time zone offset");return y}(dr(e)),{hour:l=0,minute:c=0,second:u=0,millisecond:d=0,microsecond:h=0,nanosecond:f=0}=o==="start-of-day"?{}:o,p=Hy(t,r,i,l,c,u,d,h,f-(a?0:Q0(s)));return M0(p.isoDate),ma(Qr(p))}function QG(n,e){if(Gn(n)){if(Ho(n))return kt(Qe(e)),P0(z(n,ot),z(n,ve));let a;return Vi(n,ve)?a=z(n,ve):(a=n.calendar,a===void 0&&(a="iso8601"),a=aw(a)),P0(sE(a,Vo(a,n,["year","month","monthCode","day"],[],[]),kt(Qe(e))),a)}let{month:t,day:r,referenceISOYear:i,calendar:o}=jS(dr(n));if(o===void 0&&(o="iso8601"),o=Yi(o),kt(Qe(e)),o==="iso8601")return P0({year:1972,month:t,day:r},o);let s={year:i,month:t,day:r};return gh(s),s=sE(o,Qi(o,s,"month-day"),"constrain"),P0(s,o)}function ld(n,e){let t;if(Gn(n)){if(qn(n))return kt(Qe(e)),bl(z(n,On));if(En(n))return kt(Qe(e)),bl(z(n,vn).time);if(It(n)){let c=xs(z(n,Xt),z(n,it));return kt(Qe(e)),bl(c.time)}let{hour:r,minute:i,second:o,millisecond:s,microsecond:a,nanosecond:l}=mS(n);t=AE(r,i,o,s,a,l,kt(Qe(e)))}else t=kN(dr(n)),kt(Qe(e));return bl(t)}function HN(n){return n===void 0?{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}:z(ld(n),On)}function Cy(n,e){if(Gn(n)){if(qr(n))return kt(Qe(e)),R0(z(n,ot),z(n,ve));let a=cw(n);return R0(Gy(a,Vo(a,n,["year","month","monthCode"],[],[]),kt(Qe(e))),a)}let{year:t,month:r,referenceISODay:i,calendar:o}=zS(dr(n));o===void 0&&(o="iso8601"),o=Yi(o),kt(Qe(e));let s={year:t,month:r,day:i};return $S(s),s=Gy(o,Qi(o,s,"year-month"),"constrain"),R0(s,o)}function oE(n,e,t,r,i,o,s,a){if(e==="start-of-day")return ad(i,n);let l=Ht(n,e);if(t==="wall"||s==="ignore")return si(i,l,o);if(t==="exact"||s==="use"){let d=Hy(n.year,n.month,n.day,e.hour,e.minute,e.second,e.millisecond,e.microsecond,e.nanosecond-r);M0(d.isoDate);let h=Qr(d);return sc(h),h}M0(n);let c=Qr(l),u=Ny(i,l);for(let d=0;d<u.length;d++){let h=u[d],f=ae.default.toNumber(ae.default.subtract(c,h)),p=ud(f,6e10,"halfExpand");if(f===r||a&&p===r)return h}if(s==="reject"){let d=gS(r),h=Uy(l,"iso8601","auto");throw new RangeError(`Offset ${d} is invalid for ${h} in ${i}`)}return WN(u,i,l,o)}function Sy(n,e){let t,r,i,o,s,a,l,c=!1,u="option";if(Gn(n)){if(It(n)){let w=Qe(e);return Ry(w),eE(w,"reject"),kt(w),ii(z(n,it),z(n,Xt),z(n,ve))}s=cw(n);let h=Vo(s,n,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond","offset","timeZone"],["timeZone"]);({offset:o,timeZone:i}=h),o===void 0&&(u="wall");let f=Qe(e);a=Ry(f),l=eE(f,"reject");let p=kt(f);({isoDate:t,time:r}=ow(s,h,p))}else{let h,f,p,w,y;({year:p,month:w,day:y,time:r,tzAnnotation:h,offset:o,z:f,calendar:s}=function(B){let U=cc(B);if(!U.tzAnnotation)throw new RangeError("Temporal.ZonedDateTime requires a time zone ID in brackets");return U}(dr(n))),i=qi(h),f?u="exact":o||(u="wall"),s||(s="iso8601"),s=Yi(s),c=!0;let v=Qe(e);a=Ry(v),l=eE(v,"reject"),kt(v),t={year:p,month:w,day:y}}let d=0;return u==="option"&&(d=Q0(o)),ii(oE(t,r,u,d,i,a,l,c),i,s)}function KN(n,e,t){gh(e),Dl(n),wt(n,ot,e),wt(n,ve,t),wt(n,wN,!0)}function Ji(n,e){let t=Vr("%Temporal.PlainDate%"),r=Object.create(t.prototype);return KN(r,n,e),r}function JN(n,e,t){uh(e),Dl(n),wt(n,vn,e),wt(n,ve,t)}function bs(n,e){let t=Vr("%Temporal.PlainDateTime%"),r=Object.create(t.prototype);return JN(r,n,e),r}function qN(n,e,t){gh(e),Dl(n),wt(n,ot,e),wt(n,ve,t),wt(n,IN,!0)}function P0(n,e){let t=Vr("%Temporal.PlainMonthDay%"),r=Object.create(t.prototype);return qN(r,n,e),r}function QN(n,e){Dl(n),wt(n,On,e)}function bl(n){let e=Vr("%Temporal.PlainTime%"),t=Object.create(e.prototype);return QN(t,n),t}function VN(n,e,t){$S(e),Dl(n),wt(n,ot,e),wt(n,ve,t),wt(n,bN,!0)}function R0(n,e){let t=Vr("%Temporal.PlainYearMonth%"),r=Object.create(t.prototype);return VN(r,n,e),r}function YN(n,e){sc(e),Dl(n),wt(n,it,e)}function ma(n){let e=Vr("%Temporal.Instant%"),t=Object.create(e.prototype);return YN(t,n),t}function zN(n,e,t,r){sc(e),Dl(n),wt(n,it,e),wt(n,Xt,t),wt(n,ve,r)}function ii(n,e,t="iso8601"){let r=Vr("%Temporal.ZonedDateTime%"),i=Object.create(r.prototype);return zN(i,n,e,t),i}function VG(n){return pS.filter(e=>n[e]!==void 0)}function ch(n,e,t){let r=VG(t),i=gd(n).fieldKeysToIgnore(r),o=Object.create(null),s=VG(e);for(let a=0;a<pS.length;a++){let l,c=pS[a];s.includes(c)&&!i.includes(c)&&(l=e[c]),r.includes(c)&&(l=t[c]),l!==void 0&&(o[c]=l)}return o}function qo(n,e,t,r){let i=gd(n).dateAdd(e,t,r);return gh(i),i}function sw(n,e,t,r){return gd(n).dateUntil(e,t,r)}function aw(n){if(Gn(n)&&Vi(n,ve))return z(n,ve);let e=dr(n);try{return Yi(e)}catch{}let t;try{({calendar:t}=cc(e))}catch{try{({calendar:t}=kN(e))}catch{try{({calendar:t}=zS(e))}catch{({calendar:t}=jS(e))}}}return t||(t="iso8601"),Yi(t)}function cw(n){if(Vi(n,ve))return z(n,ve);let{calendar:e}=n;return e===void 0?"iso8601":aw(e)}function oc(n,e){return Yi(n)===Yi(e)}function pd(n,e,t){let r=gd(n);r.resolveFields(e,"date");let i=r.dateToISO(e,t);return gh(i),i}function Gy(n,e,t){let r=gd(n);r.resolveFields(e,"year-month"),e.day=1;let i=r.dateToISO(e,t);return $S(i),i}function sE(n,e,t){let r=gd(n);r.resolveFields(e,"month-day");let i=r.monthDayToISOReferenceDate(e,t);return gh(i),i}function qi(n){if(Gn(n)&&It(n))return z(n,Xt);let e=dr(n);if(e==="UTC")return"UTC";let{tzName:t,offsetMinutes:r}=function(o){let{tzAnnotation:s,offset:a,z:l}=function(c){if(ON.test(c))return{tzAnnotation:c,offset:void 0,z:!1};try{let{tzAnnotation:u,offset:d,z:h}=cc(c);if(h||u||d)return{tzAnnotation:u,offset:d,z:h}}catch{}NN(c)}(o);return s?dd(s):l?dd("UTC"):a?dd(a):void 0}(e);if(r!==void 0)return WS(r);let i=aE(t);if(!i)throw new RangeError(`Unrecognized time zone ${t}`);return i.identifier}function jN(n,e){if(n===e)return!0;let t=dd(n).offsetMinutes,r=dd(e).offsetMinutes;if(t===void 0&&r===void 0){let i=aE(e);if(!i)return!1;let o=aE(n);return!!o&&o.primaryIdentifier===i.primaryIdentifier}return t===r}function Il(n,e){let t=dd(n).offsetMinutes;return t!==void 0?6e10*t:yS(n,e)}function gS(n){let e=n<0?"-":"+",t=Math.abs(n),r=Math.floor(t/36e11),i=Math.floor(t/6e10)%60,o=Math.floor(t/1e9)%60,s=t%1e9;return`${e}${vE(r,i,o,s,o===0&&s===0?"minute":"auto")}`}function xs(n,e){let t=Il(n,e),{isoDate:{year:r,month:i,day:o},time:{hour:s,minute:a,second:l,millisecond:c,microsecond:u,nanosecond:d}}=_N(e);return Hy(r,i,o,s,a,l,c,u,d+t)}function si(n,e,t){return WN(Ny(n,e),n,e,t)}function WN(n,e,t,r){let i=n.length;if(i===1)return n[0];if(i)switch(r){case"compatible":case"earlier":return n[0];case"later":return n[i-1];case"reject":throw new RangeError("multiple instants found")}if(r==="reject")throw new RangeError("multiple instants found");let o=Qr(t),s=ae.default.subtract(o,fd);sc(s);let a=Il(e,s),l=ae.default.add(o,fd);sc(l);let c=Il(e,l)-a;switch(r){case"earlier":{let u=dn.fromComponents(0,0,0,0,0,-c),d=N0(t.time,u);return Ny(e,Ht(ho(t.isoDate.year,t.isoDate.month,t.isoDate.day+d.deltaDays),d))[0]}case"compatible":case"later":{let u=dn.fromComponents(0,0,0,0,0,c),d=N0(t.time,u),h=Ny(e,Ht(ho(t.isoDate.year,t.isoDate.month,t.isoDate.day+d.deltaDays),d));return h[h.length-1]}}}function Ny(n,e){if(n==="UTC")return M0(e.isoDate),[Qr(e)];let t=dd(n).offsetMinutes;if(t!==void 0){let r=Hy(e.isoDate.year,e.isoDate.month,e.isoDate.day,e.time.hour,e.time.minute-t,e.time.second,e.time.millisecond,e.time.microsecond,e.time.nanosecond);M0(r.isoDate);let i=Qr(r);return sc(i),[i]}return M0(e.isoDate),function(r,i){let o=Qr(i),s=ae.default.subtract(o,fd);ae.default.lessThan(s,ky)&&(s=o);let a=ae.default.add(o,fd);ae.default.greaterThan(a,k0)&&(a=o);let l=yS(r,s),c=yS(r,a);return(l===c?[l]:[l,c]).map(d=>{let h=ae.default.subtract(o,ae.default.BigInt(d)),f=function(p,w){let{epochMilliseconds:y,time:{millisecond:v,microsecond:B,nanosecond:U}}=_N(w),{year:k,month:F,day:P,hour:I,minute:D,second:V}=$N(p,y);return Hy(k,F,P,I,D,V,v,B,U)}(r,h);if(U0(i,f)===0)return sc(h),h}).filter(d=>d!==void 0)}(n,e)}function ad(n,e){let t=Ht(e,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),r=Ny(n,t);if(r.length)return r[0];let i=Qr(t),o=ae.default.subtract(i,fd);return sc(o),XS(n,o)}function lw(n){let e;return e=n<0||n>9999?(n<0?"-":"+")+Oy(Math.abs(n),6):Oy(n,4),e}function Qo(n){return Oy(n,2)}function ZN(n,e){let t;if(e==="auto"){if(n===0)return"";t=Oy(n,9).replace(/0+$/,"")}else{if(e===0)return"";t=Oy(n,9).slice(0,e)}return`.${t}`}function vE(n,e,t,r,i){let o=`${Qo(n)}:${Qo(e)}`;return i==="minute"||(o+=`:${Qo(t)}`,o+=ZN(r,i)),o}function YG(n,e,t){let r=e;r===void 0&&(r="UTC");let i=z(n,it),o=Uy(xs(r,i),"iso8601",t,"never"),s="Z";return e!==void 0&&(s=XN(Il(r,i))),`${o}${s}`}function $I(n,e){let t=z(n,Mi),r=z(n,Fi),i=z(n,co),o=z(n,ki),s=z(n,Oi),a=z(n,Gi),l=lE(n),c="";t!==0&&(c+=`${Math.abs(t)}Y`),r!==0&&(c+=`${Math.abs(r)}M`),i!==0&&(c+=`${Math.abs(i)}W`),o!==0&&(c+=`${Math.abs(o)}D`);let u="";s!==0&&(u+=`${Math.abs(s)}H`),a!==0&&(u+=`${Math.abs(a)}M`);let d=dn.fromComponents(0,0,z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo));d.isZero()&&!["second","millisecond","microsecond","nanosecond"].includes(yl(n))&&e==="auto"||(u+=`${Math.abs(d.sec)}${ZN(Math.abs(d.subsec),e)}S`);let h=`${l<0?"-":""}P${c}`;return u&&(h=`${h}T${u}`),h}function zG(n,e="auto"){let{year:t,month:r,day:i}=z(n,ot);return`${lw(t)}-${Qo(r)}-${Qo(i)}${ew(z(n,ve),e)}`}function jG({hour:n,minute:e,second:t,millisecond:r,microsecond:i,nanosecond:o},s){return vE(n,e,t,1e6*r+1e3*i+o,s)}function Uy(n,e,t,r="auto"){let{isoDate:{year:i,month:o,day:s},time:{hour:a,minute:l,second:c,millisecond:u,microsecond:d,nanosecond:h}}=n;return`${lw(i)}-${Qo(o)}-${Qo(s)}T${vE(a,l,c,1e6*u+1e3*d+h,t)}${ew(e,r)}`}function WG(n,e="auto"){let{year:t,month:r,day:i}=z(n,ot),o=`${Qo(r)}-${Qo(i)}`,s=z(n,ve);e!=="always"&&e!=="critical"&&s==="iso8601"||(o=`${lw(t)}-${o}`);let a=ew(s,e);return a&&(o+=a),o}function ZG(n,e="auto"){let{year:t,month:r,day:i}=z(n,ot),o=`${lw(t)}-${Qo(r)}`,s=z(n,ve);e!=="always"&&e!=="critical"&&s==="iso8601"||(o+=`-${Qo(i)}`);let a=ew(s,e);return a&&(o+=a),o}function XG(n,e,t="auto",r="auto",i="auto",o=void 0){let s=z(n,it);if(o){let{unit:u,increment:d,roundingMode:h}=o;s=ES(s,d,u,h)}let a=z(n,Xt),l=Il(a,s),c=Uy(xs(a,s),"iso8601",e,"never");return i!=="never"&&(c+=XN(l)),r!=="never"&&(c+=`[${r==="critical"?"!":""}${a}]`),c+=ew(z(n,ve),t),c}function _G(n){return GN.test(n)}function Q0(n){let e=mre.exec(n);if(!e)throw new RangeError(`invalid time zone offset: ${n}; must match \xB1HH:MM[:SS.SSSSSSSSS]`);return(e[1]==="-"?-1:1)*(1e9*(60*(60*+e[2]+ +(e[3]||0))+ +(e[4]||0))+ +((e[5]||0)+"000000000").slice(0,9))}var yy,hre=Object.assign(Object.create(null),{"/":!0,"-":!0,_:!0});function aE(n){if(yy===void 0){let o=Intl.supportedValuesOf?.("timeZone");if(o){yy=new Map;for(let s=0;s<o.length;s++){let a=o[s];yy.set(Ky(a),a)}}else yy=null}let e=Ky(n),t=yy?.get(e);if(t)return{identifier:t,primaryIdentifier:t};try{t=FN(n).resolvedOptions().timeZone}catch{return}if(e==="antarctica/south_pole"&&(t="Antarctica/McMurdo"),cre.has(n))throw new RangeError(`${n} is a legacy time zone identifier from ICU. Use ${t} instead`);let r=[...e].map((o,s)=>s===0||hre[e[s-1]]?o.toUpperCase():o).join("").split("/");if(r.length===1)return e==="gb-eire"?{identifier:"GB-Eire",primaryIdentifier:t}:{identifier:e.length<=3||/[-0-9]/.test(e)?e.toUpperCase():r[0],primaryIdentifier:t};if(r[0]==="Etc")return{identifier:`Etc/${["Zulu","Greenwich","Universal"].includes(r[1])?r[1]:r[1].toUpperCase()}`,primaryIdentifier:t};if(r[0]==="Us")return{identifier:`US/${r[1]}`,primaryIdentifier:t};let i=new Map([["Act","ACT"],["Lhi","LHI"],["Nsw","NSW"],["Dar_Es_Salaam","Dar_es_Salaam"],["Port_Of_Spain","Port_of_Spain"],["Port-Au-Prince","Port-au-Prince"],["Isle_Of_Man","Isle_of_Man"],["Comodrivadavia","ComodRivadavia"],["Knox_In","Knox_IN"],["Dumontdurville","DumontDUrville"],["Mcmurdo","McMurdo"],["Denoronha","DeNoronha"],["Easterisland","EasterIsland"],["Bajanorte","BajaNorte"],["Bajasur","BajaSur"]]);return r[1]=i.get(r[1])??r[1],r.length>2&&(r[2]=i.get(r[2])??r[2]),{identifier:r.join("/"),primaryIdentifier:t}}function sh(n,e){let{year:t,month:r,day:i,hour:o,minute:s,second:a}=$N(n,e),l=e%1e3;return l<0&&(l+=1e3),1e6*(ZS({isoDate:{year:t,month:r,day:i},time:{hour:o,minute:s,second:a,millisecond:l}})-e)}function yS(n,e){return sh(n,As(e,"floor"))}function WS(n){let e=n<0?"-":"+",t=Math.abs(n);return`${e}${vE(Math.floor(t/60),t%60,0,0,"minute")}`}function XN(n){return WS(ud(n,rre,"halfExpand")/6e10)}function ZS({isoDate:{year:n,month:e,day:t},time:{hour:r,minute:i,second:o,millisecond:s}}){let a=n%400,l=(n-a)/400,c=new Date;return c.setUTCHours(r,i,o,s),c.setUTCFullYear(a,e-1,t),c.getTime()+sre*l}function Qr(n){let e=ZS(n),t=1e3*n.time.microsecond+n.time.nanosecond;return ae.default.add(ga(e),ae.default.BigInt(t))}function _N(n){let e=As(n,"trunc"),t=ae.default.toNumber(ae.default.remainder(n,_y));t<0&&(t+=1e6,e-=1);let r=Math.floor(t/1e3)%1e3,i=t%1e3,o=new Date(e);return{epochMilliseconds:e,isoDate:{year:o.getUTCFullYear(),month:o.getUTCMonth()+1,day:o.getUTCDate()},time:{hour:o.getUTCHours(),minute:o.getUTCMinutes(),second:o.getUTCSeconds(),millisecond:o.getUTCMilliseconds(),microsecond:r,nanosecond:i}}}function XS(n,e){if(n==="UTC")return null;let t=As(e,"floor");if(t<By)return XS(n,ga(By));let r=Date.now(),i=Math.max(t,r)+366*hd*3,o=t,s=sh(n,o),a=o,l=s;for(;s===l&&o<i;){if(a=o+2*hd*7,a>MN)return null;l=sh(n,a),s===l&&(o=a)}return s===l?null:ga(lU(c=>sh(n,c),o,a,s,l))}function wS(n,e){if(n==="UTC")return null;let t=As(e,"ceil"),r=Date.now(),i=r+366*hd*3;if(t>i){let c=wS(n,ga(i));if(c===null||ae.default.lessThan(c,ga(r)))return c}if(n==="Africa/Casablanca"||n==="Africa/El_Aaiun"){let c=Date.UTC(2088,0,1);if(c<t)return wS(n,ga(c))}let o=t-1;if(o<By)return null;let s=sh(n,o),a=o,l=s;for(;s===l&&o>By;){if(a=o-2*hd*7,a<By)return null;l=sh(n,a),s===l&&(o=a)}return s===l?null:ga(lU(c=>sh(n,c),a,o,l,s))}function $N(n,e){return function(t){let r=t.split(/[^\w]+/);if(r.length!==7)throw new RangeError(`expected 7 parts in "${t}`);let i=+r[0],o=+r[1],s=+r[2],a=r[3];if(a[0]==="b"||a[0]==="B")s=1-s;else if(a[0]!=="a"&&a[0]!=="A")throw new RangeError(`Unknown era ${a} in "${t}`);let l=r[4]==="24"?0:+r[4],c=+r[5],u=+r[6];if(!(Number.isFinite(s)&&Number.isFinite(i)&&Number.isFinite(o)&&Number.isFinite(l)&&Number.isFinite(c)&&Number.isFinite(u)))throw new RangeError(`Invalid number in "${t}`);return{year:s,month:i,day:o,hour:l,minute:c,second:u}}(FN(n).format(e))}function cE(n){return n!==void 0&&!(n%4!=0||n%100==0&&n%400!=0)}function ah(n,e){return{standard:[31,28,31,30,31,30,31,31,30,31,30,31],leapyear:[31,29,31,30,31,30,31,31,30,31,30,31]}[cE(n)?"leapyear":"standard"][e-1]}function lE(n){let e=[z(n,Mi),z(n,Fi),z(n,co),z(n,ki),z(n,Oi),z(n,Gi),z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo)];for(let t=0;t<e.length;t++){let r=e[t];if(r!==0)return r<0?-1:1}return 0}function CE(n){let e=["years","months","weeks","days"];for(let t=0;t<e.length;t++){let r=n[e[t]];if(r!==0)return r<0?-1:1}return 0}function eU(n){let e=CE(n.date);return e!==0?e:n.time.sign()}function oh(n,e){let t=n,r=e;if(!Number.isFinite(t)||!Number.isFinite(r))throw new RangeError("infinity is out of range");return r-=1,t+=Math.floor(r/12),r%=12,r<0&&(r+=12),r+=1,{year:t,month:r}}function ho(n,e,t){let r=n,i=e,o=t;if(!Number.isFinite(o))throw new RangeError("infinity is out of range");({year:r,month:i}=oh(r,i));let s=146097;if(Math.abs(o)>s){let c=Math.trunc(o/s);r+=400*c,o-=c*s}let a=0,l=i>2?r:r-1;for(;a=cE(l)?366:365,o<-a;)r-=1,l-=1,o+=a;for(l+=1;a=cE(l)?366:365,o>a;)r+=1,l+=1,o-=a;for(;o<1;)({year:r,month:i}=oh(r,i-1)),o+=ah(r,i);for(;o>ah(r,i);)o-=ah(r,i),{year:r,month:i}=oh(r,i+1);return{year:r,month:i,day:o}}function Hy(n,e,t,r,i,o,s,a,l){let c=cd(r,i,o,s,a,l);return Ht(ho(n,e,t+c.deltaDays),c)}function cd(n,e,t,r,i,o){let s,a=n,l=e,c=t,u=r,d=i,h=o;({div:s,mod:h}=T0(h,3)),d+=s,h<0&&(d-=1,h+=1e3),{div:s,mod:d}=T0(d,3),u+=s,d<0&&(u-=1,d+=1e3),c+=Math.trunc(u/1e3),u%=1e3,u<0&&(c-=1,u+=1e3),l+=Math.trunc(c/60),c%=60,c<0&&(l-=1,c+=60),a+=Math.trunc(l/60),l%=60,l<0&&(a-=1,l+=60);let f=Math.trunc(a/24);return a%=24,a<0&&(f-=1,a+=24),f+=0,a+=0,l+=0,c+=0,u+=0,d+=0,h+=0,{deltaDays:f,hour:a,minute:l,second:c,millisecond:u,microsecond:d,nanosecond:h}}function $G(n,e){let t=oi(n,0);if(CE(t)===0)return n.days;let r=z(e,ot),i=qo(z(e,ve),r,t,"constrain"),o=dh(r.year,r.month-1,r.day),s=dh(i.year,i.month-1,i.day)-o;return n.days+s}function po(n){return new(Vr("%Temporal.Duration%"))(-z(n,Mi),-z(n,Fi),-z(n,co),-z(n,ki),-z(n,Oi),-z(n,Gi),-z(n,Ni),-z(n,Ui),-z(n,Hi),-z(n,lo))}function Ki(n,e,t){return Math.min(t,Math.max(e,n))}function tU(n,e,t){let r=Ki(e,1,12);return{year:n,month:r,day:Ki(t,1,ah(n,r))}}function vr(n,e,t){if(n<e||n>t)throw new RangeError(`value out of range: ${e} <= ${n} <= ${t}`)}function lh(n,e,t){vr(e,1,12),vr(t,1,ah(n,e))}function gh(n){uh(Ht(n,{deltaDays:0,hour:12,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}))}function SE(n,e,t,r,i,o){vr(n,0,23),vr(e,0,59),vr(t,0,59),vr(r,0,999),vr(i,0,999),vr(o,0,999)}function _S(n,e,t,r,i,o,s,a,l){lh(n,e,t),SE(r,i,o,s,a,l)}function uh(n){let e=Qr(n);(ae.default.lessThan(e,ire)||ae.default.greaterThan(e,ore))&&sc(e)}function bS(n){Qr(n)}function sc(n){if(ae.default.lessThan(n,ky)||ae.default.greaterThan(n,k0))throw new RangeError("date/time value is outside of supported range")}function $S({year:n,month:e}){vr(n,UG,HG),n===UG?vr(e,4,12):n===HG&&vr(e,1,9)}function DE(n,e,t,r,i,o,s,a,l,c){let u=0,d=[n,e,t,r,i,o,s,a,l,c];for(let v=0;v<d.length;v++){let B=d[v];if(B===1/0||B===-1/0)throw new RangeError("infinite values not allowed as duration fields");if(B!==0){let U=B<0?-1:1;if(u!==0&&U!==u)throw new RangeError("mixed-sign values not allowed as duration fields");u=U}}if(Math.abs(n)>=2**32||Math.abs(e)>=2**32||Math.abs(t)>=2**32)throw new RangeError("years, months, and weeks must be < 2\xB3\xB2");let h=T0(a,3),f=T0(l,6),p=T0(c,9),w=T0(1e6*h.mod+1e3*f.mod+p.mod,9).div,y=86400*r+3600*i+60*o+s+h.div+f.div+p.div+w;if(!Number.isSafeInteger(y))throw new RangeError("total of duration time units cannot exceed 9007199254740991.999999999 s")}function B0(n){return{date:{years:z(n,Mi),months:z(n,Fi),weeks:z(n,co),days:z(n,ki)},time:dn.fromComponents(z(n,Oi),z(n,Gi),z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo))}}function rc(n){let e=dn.fromComponents(z(n,Oi),z(n,Gi),z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo)).add24HourDays(z(n,ki));return{date:{years:z(n,Mi),months:z(n,Fi),weeks:z(n,co),days:0},time:e}}function nU(n){let e=rc(n),t=Math.trunc(e.time.sec/86400);return DE(e.date.years,e.date.months,e.date.weeks,t,0,0,0,0,0,0),{...e.date,days:t}}function Is(n,e){let t=n.time.sign(),r=n.time.abs().subsec,i=0,o=0,s=n.time.abs().sec,a=0,l=0,c=0;switch(e){case"year":case"month":case"week":case"day":i=Math.trunc(r/1e3),r%=1e3,o=Math.trunc(i/1e3),i%=1e3,s+=Math.trunc(o/1e3),o%=1e3,a=Math.trunc(s/60),s%=60,l=Math.trunc(a/60),a%=60,c=Math.trunc(l/24),l%=24;break;case"hour":i=Math.trunc(r/1e3),r%=1e3,o=Math.trunc(i/1e3),i%=1e3,s+=Math.trunc(o/1e3),o%=1e3,a=Math.trunc(s/60),s%=60,l=Math.trunc(a/60),a%=60;break;case"minute":i=Math.trunc(r/1e3),r%=1e3,o=Math.trunc(i/1e3),i%=1e3,s+=Math.trunc(o/1e3),o%=1e3,a=Math.trunc(s/60),s%=60;break;case"second":i=Math.trunc(r/1e3),r%=1e3,o=Math.trunc(i/1e3),i%=1e3,s+=Math.trunc(o/1e3),o%=1e3;break;case"millisecond":i=Math.trunc(r/1e3),r%=1e3,o=tS(s,3,Math.trunc(i/1e3)),i%=1e3,s=0;break;case"microsecond":i=tS(s,6,Math.trunc(r/1e3)),r%=1e3,s=0;break;case"nanosecond":r=tS(s,9,r),s=0}return new(Vr("%Temporal.Duration%"))(n.date.years,n.date.months,n.date.weeks,n.date.days+t*c,t*l,t*a,t*s,t*o,t*i,t*r)}function xl(n,e){return CE(n),e.sign(),{date:n,time:e}}function dh(n,e,t){return ZS({isoDate:{year:n,month:e+1,day:t},time:{hour:0,minute:0,second:0,millisecond:0}})/hd}function M0({year:n,month:e,day:t}){if(Math.abs(dh(n,e-1,t))>1e8)throw new RangeError("date/time value is outside the supported range")}function e4(n,e){let t=e.hour-n.hour,r=e.minute-n.minute,i=e.second-n.second,o=e.millisecond-n.millisecond,s=e.microsecond-n.microsecond,a=e.nanosecond-n.nanosecond;return dn.fromComponents(t,r,i,o,s,a)}function t4(n,e,t,r,i){let o=dn.fromEpochNsDiff(e,n);return o=uE(o,t,r,i),xl({years:0,months:0,weeks:0,days:0},o)}function rU(n,e,t,r){bS(n),bS(e);let i=e4(n.time,e.time),o=i.sign(),s=ac(n.isoDate,e.isoDate),a=e.isoDate;s===o&&(a=ho(a.year,a.month,a.day+o),i=i.add24HourDays(-o));let l=El("day",r),c=sw(t,n.isoDate,a,l);return r!==l&&(i=i.add24HourDays(c.days),c.days=0),xl(c,i)}function iU(n,e,t,r,i){let o=ae.default.subtract(e,n);if(ae.default.equal(o,Ko))return{date:{years:0,months:0,weeks:0,days:0},time:dn.ZERO};let s=ae.default.lessThan(o,Ko)?-1:1,a=xs(t,n),l=xs(t,e),c,u=0,d=s===1?2:1,h=e4(a.time,l.time);for(h.sign()===-s&&u++;u<=d;u++){c=Ht(ho(l.isoDate.year,l.isoDate.month,l.isoDate.day-u*s),a.time);let p=si(t,c,"compatible");if(h=dn.fromEpochNsDiff(e,p),h.sign()!==-s)break}let f=El("day",i);return xl(sw(r,a.isoDate,c.isoDate,f),h)}function oU(n,e,t,r,i,o,s,a,l){let c,u,d,h,f=e;switch(a){case"year":{let G=ud(f.date.years,s,"trunc");c=G,u=G+s*n,d={years:c,months:0,weeks:0,days:0},h={...d,years:u};break}case"month":{let G=ud(f.date.months,s,"trunc");c=G,u=G+s*n,d=oi(f.date,0,0,c),h=oi(f.date,0,0,u);break}case"week":{let G=oi(f.date,0,0),x=qo(o,r.isoDate,G,"constrain"),S=sw(o,x,ho(x.year,x.month,x.day+f.date.days),"week"),M=ud(f.date.weeks+S.weeks,s,"trunc");c=M,u=M+s*n,d=oi(f.date,0,c),h=oi(f.date,0,u);break}case"day":{let G=ud(f.date.days,s,"trunc");c=G,u=G+s*n,d=oi(f.date,c),h=oi(f.date,u);break}}let p=qo(o,r.isoDate,d,"constrain"),w=qo(o,r.isoDate,h,"constrain"),y,v,B=Ht(p,r.time),U=Ht(w,r.time);i?(y=si(i,B,"compatible"),v=si(i,U,"compatible")):(y=Qr(B),v=Qr(U));let k=dn.fromEpochNsDiff(t,y),F=dn.fromEpochNsDiff(v,y),P=wE(l,n<0?"negative":"positive"),I=k.add(k).abs().subtract(F.abs()).sign(),D=Math.abs(c)/s%2==0,V=k.isZero()?Math.abs(c):k.cmp(F)?bE(Math.abs(c),Math.abs(u),I,D,P):Math.abs(u),K=new dn(ae.default.add(ae.default.multiply(F.totalNs,ae.default.BigInt(c)),ae.default.multiply(k.totalNs,ae.default.BigInt(s*n)))).fdiv(F.totalNs),q=V===Math.abs(u);return f={date:q?h:d,time:dn.ZERO},{nudgeResult:{duration:f,nudgedEpochNs:q?v:y,didExpandCalendarUnit:q},total:K}}function LE(n,e,t,r,i,o,s,a,l){let c=n,u=tc(a)||r&&a==="day",d=eU(c)<0?-1:1,h;return u?{nudgeResult:h}=oU(d,c,e,t,r,i,s,a,l):h=r?function(f,p,w,y,v,B,U,k){let F=p,P=qo(v,w.isoDate,F.date,"constrain"),I=Ht(P,w.time),D=Ht(ho(P.year,P.month,P.day+f),w.time),V=si(y,I,"compatible"),K=si(y,D,"compatible"),q=dn.fromEpochNsDiff(K,V);if(q.sign()!==f)throw new RangeError("time zone returned inconsistent Instants");let G=ae.default.BigInt(G0[U]*B),x=F.time.round(G,k),S=x.subtract(q),M=S.sign()!==-f,b,A;return M?(b=f,x=S.round(G,k),A=x.addToEpochNs(K)):(b=0,A=x.addToEpochNs(V)),{duration:xl(oi(F.date,F.date.days+b),x),nudgedEpochNs:A,didExpandCalendarUnit:M}}(d,c,t,r,i,s,a,l):function(f,p,w,y,v,B){let U=f,k=U.time.add24HourDays(U.date.days),F=k.round(ae.default.BigInt(y*G0[v]),B),P=F.subtract(k),{quotient:I}=k.divmod(rE),{quotient:D}=F.divmod(rE),V=Math.sign(D-I)===k.sign(),K=P.addToEpochNs(p),q=0,G=F;return wl(w)==="date"&&(q=D,G=F.add(dn.fromComponents(24*-D,0,0,0,0,0))),{duration:{date:oi(U.date,q),time:G},nudgedEpochNs:K,didExpandCalendarUnit:V}}(c,e,o,s,a,l),c=h.duration,h.didExpandCalendarUnit&&a!=="week"&&(c=function(f,p,w,y,v,B,U,k){let F=p;if(k===U)return F;let P=Ty.indexOf(U);for(let I=Ty.indexOf(k)-1;I>=P;I--){let D=Ty[I];if(D==="week"&&U!=="week")continue;let V;switch(D){case"year":V={years:F.date.years+f,months:0,weeks:0,days:0};break;case"month":{let G=F.date.months+f;V=oi(F.date,0,0,G);break}case"week":{let G=F.date.weeks+f;V=oi(F.date,0,G);break}}let K=Ht(qo(B,y.isoDate,V,"constrain"),y.time),q;if(q=v?si(v,K,"compatible"):Qr(K),tE(w,q)===-f)break;F={date:V,time:dn.ZERO}}return F}(d,c,h.nudgedEpochNs,t,r,i,o,El(a,"day"))),c}function eN(n,e,t,r,i,o){return tc(o)||r&&o==="day"?oU(eU(n)<0?-1:1,n,e,t,r,i,1,o,"trunc").total:My(n.time.add24HourDays(n.date.days),o)}function sU(n,e,t,r,i,o,s){if(U0(n,e)==0)return{date:{years:0,months:0,weeks:0,days:0},time:dn.ZERO};uh(n),uh(e);let a=rU(n,e,t,r);return o==="nanosecond"&&i===1?a:LE(a,Qr(e),n,null,t,r,i,o,s)}function aU(n,e,t,r,i,o,s,a){if(wl(i)==="time")return t4(n,e,o,s,a);let l=iU(n,e,t,r,i);return s==="nanosecond"&&o===1?l:LE(l,e,xs(t,n),t,r,i,o,s,a)}function V0(n,e,t,r,i,o){let s=O0.reduce((f,p)=>{let w=p[0],y=p[1],v=p[2];return t!=="datetime"&&v!==t||r.includes(y)||f.push(y,w),f},[]),a=fo(e,"largestUnit",t,"auto");if(r.includes(a))throw new RangeError(`largestUnit must be one of ${s.join(", ")}, not ${a}`);let l=J0(e),c=ya(e,"trunc");n==="since"&&(c=function(f){switch(f){case"ceil":return"floor";case"floor":return"ceil";case"halfCeil":return"halfFloor";case"halfFloor":return"halfCeil";default:return f}}(c));let u=fo(e,"smallestUnit",t,i);if(r.includes(u))throw new RangeError(`smallestUnit must be one of ${s.join(", ")}, not ${u}`);let d=El(o,u);if(a==="auto"&&(a=d),El(a,u)!==a)throw new RangeError(`largestUnit ${a} cannot be smaller than smallestUnit ${u}`);let h={hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[u];return h!==void 0&&q0(l,h,!1),{largestUnit:a,roundingIncrement:l,roundingMode:c,smallestUnit:u}}function tN(n,e,t,r){let i=vy(t),o=V0(n,Qe(r),"time",[],"nanosecond","second"),s=Is(t4(z(e,it),z(i,it),o.roundingIncrement,o.smallestUnit,o.roundingMode),o.largestUnit);return n==="since"&&(s=po(s)),s}function nN(n,e,t,r){let i=xy(t),o=z(e,ve),s=z(i,ve);if(!oc(o,s))throw new RangeError(`cannot compute difference between dates of ${o} and ${s} calendars`);let a=V0(n,Qe(r),"date",[],"day","day"),l=Vr("%Temporal.Duration%"),c=z(e,ot),u=z(i,ot);if(ac(c,u)===0)return new l;let d={date:sw(o,c,u,a.largestUnit),time:dn.ZERO};if(a.smallestUnit!=="day"||a.roundingIncrement!==1){let f=Ht(c,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});d=LE(d,Qr(Ht(u,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0})),f,null,o,a.largestUnit,a.roundingIncrement,a.smallestUnit,a.roundingMode)}let h=Is(d,"day");return n==="since"&&(h=po(h)),h}function rN(n,e,t,r){let i=Ay(t),o=z(e,ve),s=z(i,ve);if(!oc(o,s))throw new RangeError(`cannot compute difference between dates of ${o} and ${s} calendars`);let a=V0(n,Qe(r),"datetime",[],"nanosecond","day"),l=Vr("%Temporal.Duration%"),c=z(e,vn),u=z(i,vn);if(U0(c,u)===0)return new l;let d=Is(sU(c,u,o,a.largestUnit,a.roundingIncrement,a.smallestUnit,a.roundingMode),a.largestUnit);return n==="since"&&(d=po(d)),d}function iN(n,e,t,r){let i=ld(t),o=V0(n,Qe(r),"time",[],"nanosecond","hour"),s=e4(z(e,On),z(i,On));s=uE(s,o.roundingIncrement,o.smallestUnit,o.roundingMode);let a=Is(xl({years:0,months:0,weeks:0,days:0},s),o.largestUnit);return n==="since"&&(a=po(a)),a}function oN(n,e,t,r){let i=Cy(t),o=z(e,ve),s=z(i,ve);if(!oc(o,s))throw new RangeError(`cannot compute difference between months of ${o} and ${s} calendars`);let a=V0(n,Qe(r),"date",["week","day"],"month","year"),l=Vr("%Temporal.Duration%");if(ac(z(e,ot),z(i,ot))==0)return new l;let c=Qi(o,z(e,ot),"year-month");c.day=1;let u=pd(o,c,"constrain"),d=Qi(o,z(i,ot),"year-month");d.day=1;let h=pd(o,d,"constrain"),f={date:oi(sw(o,u,h,a.largestUnit),0,0),time:dn.ZERO};if(a.smallestUnit!=="month"||a.roundingIncrement!==1){let w=Ht(u,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});f=LE(f,Qr(Ht(h,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0})),w,null,o,a.largestUnit,a.roundingIncrement,a.smallestUnit,a.roundingMode)}let p=Is(f,"day");return n==="since"&&(p=po(p)),p}function sN(n,e,t,r){let i=Sy(t),o=z(e,ve),s=z(i,ve);if(!oc(o,s))throw new RangeError(`cannot compute difference between dates of ${o} and ${s} calendars`);let a=V0(n,Qe(r),"datetime",[],"nanosecond","hour"),l=z(e,it),c=z(i,it),u=Vr("%Temporal.Duration%"),d;if(wl(a.largestUnit)!=="date")d=Is(t4(l,c,a.roundingIncrement,a.smallestUnit,a.roundingMode),a.largestUnit);else{let h=z(e,Xt);if(!jN(h,z(i,Xt)))throw new RangeError("When calculating difference between time zones, largestUnit must be 'hours' or smaller because day lengths can vary between time zones due to DST or time zone offset changes.");if(ae.default.equal(l,c))return new u;d=Is(aU(l,c,h,o,a.largestUnit,a.roundingIncrement,a.smallestUnit,a.roundingMode),"hour")}return n==="since"&&(d=po(d)),d}function N0({hour:n,minute:e,second:t,millisecond:r,microsecond:i,nanosecond:o},s){let a=t,l=o;return a+=s.sec,l+=s.subsec,cd(n,e,a,r,i,l)}function IS(n,e){let t=e.addToEpochNs(n);return sc(t),t}function Dy(n,e,t,r,i="constrain"){if(CE(r.date)===0)return IS(n,r.time);let o=xs(e,n);return IS(si(e,Ht(qo(t,o.isoDate,r.date,i),o.time),"compatible"),r.time)}function aN(n,e,t){let r=Es(t);n==="subtract"&&(r=po(r));let i=El(yl(e),yl(r));if(tc(i))throw new RangeError("For years, months, or weeks arithmetic, use date arithmetic relative to a starting point");let o=rc(e),s=rc(r);return Is(xl({years:0,months:0,weeks:0,days:0},o.time.add(s.time)),i)}function cN(n,e,t){let r=Es(t);n==="subtract"&&(r=po(r));let i=yl(r);if(wl(i)==="date")throw new RangeError(`Duration field ${i} not supported by Temporal.Instant. Try Temporal.ZonedDateTime instead.`);let o=rc(r);return ma(IS(z(e,it),o.time))}function lN(n,e,t,r){let i=z(e,ve),o=Es(t);n==="subtract"&&(o=po(o));let s=nU(o),a=kt(Qe(r));return Ji(qo(i,z(e,ot),s,a),i)}function uN(n,e,t,r){let i=Es(t);n==="subtract"&&(i=po(i));let o=kt(Qe(r)),s=z(e,ve),a=rc(i),l=z(e,vn),c=N0(l.time,a.time),u=oi(a.date,c.deltaDays);return DE(u.years,u.months,u.weeks,u.days,0,0,0,0,0,0),bs(Ht(qo(s,l.isoDate,u,o),c),s)}function dN(n,e,t){let r=Es(t);n==="subtract"&&(r=po(r));let i=rc(r),{hour:o,minute:s,second:a,millisecond:l,microsecond:c,nanosecond:u}=N0(z(e,On),i.time);return bl(AE(o,s,a,l,c,u,"reject"))}function fN(n,e,t,r){let i=Es(t);n==="subtract"&&(i=po(i));let o=kt(Qe(r)),s=lE(i),a=z(e,ve),l=Qi(a,z(e,ot),"year-month");l.day=1;let c=pd(a,l,"constrain");if(s<0){let d=qo(a,c,{months:1},"constrain");c=ho(d.year,d.month,d.day-1)}let u=nU(i);return gh(c),R0(Gy(a,Qi(a,qo(a,c,u,o),"year-month"),o),a)}function hN(n,e,t,r){let i=Es(t);n==="subtract"&&(i=po(i));let o=kt(Qe(r)),s=z(e,Xt),a=z(e,ve),l=B0(i);return ii(Dy(z(e,it),s,a,l,o),s,a)}function ud(n,e,t){let r=Math.trunc(n/e),i=n%e,o=n<0?"negative":"positive",s=Math.abs(r),a=s+1,l=uo(Math.abs(2*i)-e),c=s%2==0,u=wE(t,o),d=i===0?s:bE(s,a,l,c,u);return e*(o==="positive"?d:-d)}function ES(n,e,t,r){let i=G0[t]*e;return function(o,s,a){let l=gl(o),c=gl(s),u=ae.default.divide(l,c),d=ae.default.remainder(l,c),h=wE(a,"positive"),f,p;ae.default.lessThan(l,Ko)?(f=ae.default.subtract(u,Fy),p=u):(f=u,p=ae.default.add(u,Fy));let w=tE(ih(ae.default.multiply(d,YS)),c)*(ae.default.lessThan(l,Ko)?-1:1)+0,y=ae.default.equal(d,Ko)?u:bE(f,p,w,yN(f),h);return ae.default.multiply(y,c)}(n,ae.default.BigInt(i),r)}function xS(n,e,t,r){bS(n);let{year:i,month:o,day:s}=n.isoDate,a=AS(n.time,e,t,r);return Ht(ho(i,o,s+a.deltaDays),a)}function AS({hour:n,minute:e,second:t,millisecond:r,microsecond:i,nanosecond:o},s,a,l){let c;switch(a){case"day":case"hour":c=1e3*(1e3*(1e3*(60*(60*n+e)+t)+r)+i)+o;break;case"minute":c=1e3*(1e3*(1e3*(60*e+t)+r)+i)+o;break;case"second":c=1e3*(1e3*(1e3*t+r)+i)+o;break;case"millisecond":c=1e3*(1e3*r+i)+o;break;case"microsecond":c=1e3*i+o;break;case"nanosecond":c=o}let u=G0[a],d=ud(c,u*s,l)/u;switch(a){case"day":return{deltaDays:d,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0};case"hour":return cd(d,0,0,0,0,0);case"minute":return cd(n,d,0,0,0,0);case"second":return cd(n,e,d,0,0,0);case"millisecond":return cd(n,e,t,d,0,0);case"microsecond":return cd(n,e,t,r,d,0);case"nanosecond":return cd(n,e,t,r,i,d);default:throw new Error(`Invalid unit ${a}`)}}function uE(n,e,t,r){let i=G0[t];return n.round(ae.default.BigInt(i*e),r)}function My(n,e){let t=G0[e];return n.fdiv(ae.default.BigInt(t))}function ac(n,e){return n.year!==e.year?uo(n.year-e.year):n.month!==e.month?uo(n.month-e.month):n.day!==e.day?uo(n.day-e.day):0}function vS(n,e){return n.hour!==e.hour?uo(n.hour-e.hour):n.minute!==e.minute?uo(n.minute-e.minute):n.second!==e.second?uo(n.second-e.second):n.millisecond!==e.millisecond?uo(n.millisecond-e.millisecond):n.microsecond!==e.microsecond?uo(n.microsecond-e.microsecond):n.nanosecond!==e.nanosecond?uo(n.nanosecond-e.nanosecond):0}function U0(n,e){let t=ac(n.isoDate,e.isoDate);return t!==0?t:vS(n.time,e.time)}function cU(n){let e=dE(n);return globalThis.BigInt!==void 0?globalThis.BigInt(e.toString(10)):e}function As(n,e){let t=gl(n),{quotient:r,remainder:i}=Iy(t,_y),o=ae.default.toNumber(r);return e==="floor"&&ae.default.toNumber(i)<0&&(o-=1),e==="ceil"&&ae.default.toNumber(i)>0&&(o+=1),o}function ga(n){if(!Number.isInteger(n))throw new RangeError("epoch milliseconds must be an integer");return ae.default.multiply(ae.default.BigInt(n),_y)}function dE(n){let e=n;if(typeof n=="object"){let t=n[Symbol.toPrimitive];t&&typeof t=="function"&&(e=t.call(n,"number"))}if(typeof e=="number")throw new TypeError("cannot convert number to bigint");return typeof e=="bigint"?ae.default.BigInt(e.toString(10)):ae.default.BigInt(e)}var CS=(()=>{let n=ae.default.BigInt(Date.now()%1e6);return()=>{let e=Date.now(),t=ae.default.BigInt(e),r=ae.default.add(ga(e),n);return n=ae.default.remainder(t,_y),ae.default.greaterThan(r,k0)?k0:ae.default.lessThan(r,ky)?ky:r}})();function wy(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}function uo(n){return n<0?-1:n>0?1:n}function Qe(n){if(n===void 0)return Object.create(null);if(Gn(n)&&n!==null)return n;throw new TypeError("Options parameter must be an object, not "+(n===null?"null":typeof n))}function fh(n,e){let t=Object.create(null);return t[n]=e,t}function Al(n,e,t,r){let i=n[e];if(i!==void 0){if(i=EE(i),!t.includes(i))throw new RangeError(`${e} must be one of ${t.join(", ")}, not ${i}`);return i}if(r===Cl)throw new RangeError(`${e} option is required`);return r}function Yi(n){let e=Ky(n);if(!are.includes(Ky(e)))throw new RangeError(`invalid calendar identifier ${e}`);switch(e){case"ethiopic-amete-alem":return"ethioaa";case"islamicc":return"islamic-civil"}return e}function Ky(n){let e="";for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);e+=r>=65&&r<=90?String.fromCharCode(r+32):String.fromCharCode(r)}return e}function yd(n){throw new TypeError(`Do not use built-in arithmetic operators with Temporal objects. When comparing, use ${n==="PlainMonthDay"?"Temporal.PlainDate.compare(obj1.toPlainDate(year), obj2.toPlainDate(year))":`Temporal.${n}.compare(obj1, obj2)`}, not obj1 > obj2. When coercing to strings, use \`\${obj}\` or String(obj), not '' + obj. When coercing to numbers, use properties or methods of the object, not \`+obj\`. When concatenating with strings, use \`\${str}\${obj}\` or str.concat(obj), not str + obj. In React, coerce to a string before rendering a Temporal object.`)}var pre=new RegExp(`^${PN.source}$`),mre=new RegExp(`^${/([+-])([01][0-9]|2[0-3])(?::?([0-5][0-9])(?::?([0-5][0-9])(?:[.,](\d{1,9}))?)?)?/.source}$`);function lU(n,e,t,r=n(e),i=n(t)){let o=e,s=t,a=r,l=i;for(;s-o>1;){let c=Math.trunc((o+s)/2),u=n(c);u===a?(o=c,a=u):u===l&&(s=c,l=u)}return s}function uU(n){return[...n]}function dU(n,e){if(n!=="gregory"&&n!=="iso8601")return;let t=uw[n],r=e.year,{dayOfWeek:i,dayOfYear:o,daysInYear:s}=t.isoToDate(e,{dayOfWeek:!0,dayOfYear:!0,daysInYear:!0}),a=t.getFirstDayOfWeek(),l=t.getMinimalDaysInFirstWeek(),c=(i+7-a)%7,u=(i-o+7001-a)%7,d=Math.floor((o-1+u)/7);if(7-u>=l&&++d,d==0)d=function(h,f,p,w){let y=(w-h-p+1)%7;y<0&&(y+=7);let v=Math.floor((p+y-1)/7);return 7-y>=f&&++v,v}(a,l,o+t.isoToDate(t.dateAdd(e,{years:-1},"constrain"),{daysInYear:!0}).daysInYear,i),r--;else if(o>=s-5){let h=(c+s-o)%7;h<0&&(h+=7),6-h>=l&&o+7-c>s&&(d=1,r++)}return{week:d,year:r}}function pN(n,e,t,r,i){if(e!==i.year){if(n*(e-i.year)>0)return!0}else if(t!==i.month){if(n*(t-i.month)>0)return!0}else if(r!==i.day&&n*(r-i.day)>0)return!0;return!1}var uw={};function hh(n){if(!n.startsWith("M"))throw new RangeError(`Invalid month code: ${n}. Month codes must start with M.`);let e=+n.slice(1);if(Number.isNaN(e))throw new RangeError(`Invalid month code: ${n}`);return e}function ic(n,e=!1){return`M${`${n}`.padStart(2,"0")}${e?"L":""}`}function n4(n,e=void 0,t=12){let{month:r,monthCode:i}=n;if(i===void 0){if(r===void 0)throw new TypeError("Either month or monthCode are required");e==="reject"&&vr(r,1,t),e==="constrain"&&(r=Ki(r,1,t)),i=ic(r)}else{let o=hh(i);if(i!==ic(o))throw new RangeError(`Invalid month code: ${i}`);if(r!==void 0&&r!==o)throw new RangeError(`monthCode ${i} and month ${r} must match if both are present`);if(r=o,r<1||r>t)throw new RangeError(`Invalid monthCode: ${i}`)}return{...n,month:r,monthCode:i}}uw.iso8601={resolveFields(n,e){if((e==="date"||e==="year-month")&&n.year===void 0)throw new TypeError("year is required");if((e==="date"||e==="month-day")&&n.day===void 0)throw new TypeError("day is required");Object.assign(n,n4(n))},dateToISO:(n,e)=>Py(n.year,n.month,n.day,e),monthDayToISOReferenceDate(n,e){let{month:t,day:r}=Py(n.year??1972,n.month,n.day,e);return{month:t,day:r,year:1972}},extraFields:()=>[],fieldKeysToIgnore(n){let e=new Set;for(let t=0;t<n.length;t++){let r=n[t];e.add(r),r==="month"?e.add("monthCode"):r==="monthCode"&&e.add("month")}return uU(e)},dateAdd(n,{years:e=0,months:t=0,weeks:r=0,days:i=0},o){let{year:s,month:a,day:l}=n;return s+=e,a+=t,{year:s,month:a}=oh(s,a),{year:s,month:a,day:l}=Py(s,a,l,o),l+=i+7*r,ho(s,a,l)},dateUntil(n,e,t){let r=-ac(n,e);if(r===0)return{years:0,months:0,weeks:0,days:0};let i,o=0,s=0;if(t==="year"||t==="month"){let u=e.year-n.year;for(u!==0&&(u-=r);!pN(r,n.year+u,n.month,n.day,e);)o=u,u+=r;let d=r;for(i=oh(n.year+o,n.month+d);!pN(r,i.year,i.month,n.day,e);)s=d,d+=r,i=oh(i.year,i.month+r);t==="month"&&(s+=12*o,o=0)}i=oh(n.year+o,n.month+s);let a=tU(i.year,i.month,n.day),l=0,c=dh(e.year,e.month-1,e.day)-dh(a.year,a.month-1,a.day);return t==="week"&&(l=Math.trunc(c/7),c%=7),{years:o,months:s,weeks:l,days:c}},isoToDate({year:n,month:e,day:t},r){let i={era:void 0,eraYear:void 0,year:n,month:e,day:t,daysInWeek:7,monthsInYear:12};if(r.monthCode&&(i.monthCode=ic(e)),r.dayOfWeek){let o=e+(e<3?10:-2),s=n-(e<3?1:0),a=Math.floor(s/100),l=s-100*a,c=(t+Math.floor(2.6*o-.2)+(l+Math.floor(l/4))+(Math.floor(a/4)-2*a))%7;i.dayOfWeek=c+(c<=0?7:0)}if(r.dayOfYear){let o=t;for(let s=e-1;s>0;s--)o+=ah(n,s);i.dayOfYear=o}return r.weekOfYear&&(i.weekOfYear=dU("iso8601",{year:n,month:e,day:t})),r.daysInMonth&&(i.daysInMonth=ah(n,e)),(r.daysInYear||r.inLeapYear)&&(i.inLeapYear=cE(n),i.daysInYear=i.inLeapYear?366:365),i},getFirstDayOfWeek:()=>1,getMinimalDaysInFirstWeek:()=>4};var Uo=class n{constructor(e){if(this.map=new Map,this.calls=0,this.hits=0,this.misses=0,e!==void 0){let t=0;for(let r of e.map.entries()){if(++t>n.MAX_CACHE_ENTRIES)break;this.map.set(...r)}}}get(e){let t=this.map.get(e);return t&&(this.hits++,this.report()),this.calls++,t}set(e,t){this.map.set(e,t),this.misses++,this.report()}report(){}setObject(e){if(n.objectMap.get(e))throw new RangeError("object already cached");n.objectMap.set(e,this),this.report()}static getCacheForObject(e){let t=n.objectMap.get(e);return t||(t=new n,n.objectMap.set(e,t)),t}};function fU({isoYear:n,isoMonth:e,isoDay:t}){return`${lw(n)}-${Qo(e)}-${Qo(t)}T00:00Z`}function iS(n,e){return{years:n.year-e.year,months:n.month-e.month,days:n.day-e.day}}Uo.objectMap=new WeakMap,Uo.MAX_CACHE_ENTRIES=1e3;var Sl=class{constructor(){this.eras=[],this.hasEra=!1,this.erasBeginMidYear=!1}getFormatter(){return this.formatter===void 0&&(this.formatter=new Intl.DateTimeFormat(`en-US-u-ca-${this.id}`,{day:"numeric",month:"numeric",year:"numeric",era:"short",timeZone:"UTC"})),this.formatter}getCalendarParts(e){let t=this.getFormatter(),r=new Date(e);if(e==="-271821-04-19T00:00Z"){let i=t.resolvedOptions();t=new Intl.DateTimeFormat(i.locale,{...i,timeZone:"Etc/GMT+1"}),r=new Date("-271821-04-20T00:00Z")}try{return t.formatToParts(r)}catch{throw new RangeError(`Invalid ISO date: ${e}`)}}isoToCalendarDate(e,t){let{year:r,month:i,day:o}=e,s=JSON.stringify({func:"isoToCalendarDate",isoYear:r,isoMonth:i,isoDay:o,id:this.id}),a=t.get(s);if(a)return a;let l=fU({isoYear:r,isoMonth:i,isoDay:o}),c=this.getCalendarParts(l),u={};for(let h=0;h<c.length;h++){let{type:f,value:p}=c[h];if(f!=="year"&&f!=="relatedYear"||(this.hasEra?u.eraYear=+p:u.year=+p),f==="month"){let w=/^([0-9]*)(.*?)$/.exec(p);if(!w||w.length!=3||!w[1]&&!w[2])throw new RangeError(`Unexpected month: ${p}`);if(u.month=w[1]?+w[1]:1,u.month<1)throw new RangeError(`Invalid month ${p} from ${l}[u-ca-${this.id}] (probably due to https://bugs.chromium.org/p/v8/issues/detail?id=10527)`);if(u.month>13)throw new RangeError(`Invalid month ${p} from ${l}[u-ca-${this.id}] (probably due to https://bugs.chromium.org/p/v8/issues/detail?id=10529)`);w[2]&&(u.monthExtra=w[2])}f==="day"&&(u.day=+p),this.hasEra&&f==="era"&&p!=null&&p!==""&&(u.era=p.split(" (")[0].normalize("NFD").replace(/[^-0-9 \p{L}]/gu,"").replace(/ /g,"-").toLowerCase())}if(this.hasEra&&u.eraYear===void 0)throw new RangeError(`Intl.DateTimeFormat.formatToParts lacks relatedYear in ${this.id} calendar. Try Node 14+ or modern browsers.`);if(this.hasEra){let h=this.eras.find(f=>u.era===f.genericName);h&&(u.era=h.code)}if(this.reviseIntlEra){let{era:h,eraYear:f}=this.reviseIntlEra(u,e);u.era=h,u.eraYear=f}this.checkIcuBugs&&this.checkIcuBugs(e);let d=this.adjustCalendarDate(u,t,"constrain",!0);if(d.year===void 0)throw new RangeError(`Missing year converting ${JSON.stringify(e)}`);if(d.month===void 0)throw new RangeError(`Missing month converting ${JSON.stringify(e)}`);if(d.day===void 0)throw new RangeError(`Missing day converting ${JSON.stringify(e)}`);return t.set(s,d),["constrain","reject"].forEach(h=>{let f=JSON.stringify({func:"calendarToIsoDate",year:d.year,month:d.month,day:d.day,overflow:h,id:this.id});t.set(f,e)}),d}validateCalendarDate(e){let{month:t,year:r,day:i,eraYear:o,monthCode:s,monthExtra:a}=e;if(a!==void 0)throw new RangeError("Unexpected `monthExtra` value");if(r===void 0&&o===void 0)throw new TypeError("year or eraYear is required");if(t===void 0&&s===void 0)throw new TypeError("month or monthCode is required");if(i===void 0)throw new RangeError("Missing day");if(s!==void 0){if(typeof s!="string")throw new RangeError("monthCode must be a string, not "+typeof s);if(!/^M([01]?\d)(L?)$/.test(s))throw new RangeError(`Invalid monthCode: ${s}`)}if(this.hasEra&&e.era===void 0!=(e.eraYear===void 0))throw new TypeError("properties era and eraYear must be provided together")}adjustCalendarDate(e,t=void 0,r="constrain",i=!1){if(this.calendarType==="lunisolar")throw new RangeError("Override required for lunisolar calendars");let o=e;this.validateCalendarDate(o);let s=this.monthsInYear(o,t),{month:a,monthCode:l}=o;return{month:a,monthCode:l}=n4(o,r,s),{...o,month:a,monthCode:l}}regulateMonthDayNaive(e,t,r){let i=this.monthsInYear(e,r),{month:o,day:s}=e;return t==="reject"?(vr(o,1,i),vr(s,1,this.maximumMonthLength(e))):(o=Ki(o,1,i),s=Ki(s,1,this.maximumMonthLength({...e,month:o}))),{...e,month:o,day:s}}calendarToIsoDate(e,t="constrain",r){let i=e,o=this.adjustCalendarDate(e,r,t,!1);o=this.regulateMonthDayNaive(o,t,r);let{year:s,month:a,day:l}=o,c=JSON.stringify({func:"calendarToIsoDate",year:s,month:a,day:l,overflow:t,id:this.id}),u,d=r.get(c);if(d||i.year!==void 0&&i.month!==void 0&&i.day!==void 0&&(i.year!==o.year||i.month!==o.month||i.day!==o.day)&&(u=JSON.stringify({func:"calendarToIsoDate",year:i.year,month:i.month,day:i.day,overflow:t,id:this.id}),d=r.get(u),d))return d;let h=this.estimateIsoDate({year:s,month:a,day:l}),f=B=>{let U=this.addDaysIso(h,B);if(o.day>this.minimumMonthLength(o)){let k=this.isoToCalendarDate(U,r);for(;k.month!==a||k.year!==s;){if(t==="reject")throw new RangeError(`day ${l} does not exist in month ${a} of year ${s}`);U=this.addDaysIso(U,-1),k=this.isoToCalendarDate(U,r)}}return U},p=0,w=this.isoToCalendarDate(h,r),y=iS(o,w);if(y.years!==0||y.months!==0||y.days!==0){let B=365*y.years+30*y.months+y.days;h=this.addDaysIso(h,B),w=this.isoToCalendarDate(h,r),y=iS(o,w),y.years===0&&y.months===0?h=f(y.days):p=this.compareCalendarDates(o,w)}let v=8;for(;p;){h=this.addDaysIso(h,p*v);let B=w;w=this.isoToCalendarDate(h,r);let U=p;if(p=this.compareCalendarDates(o,w),p){if(y=iS(o,w),y.years===0&&y.months===0)h=f(y.days),p=0;else if(U&&p!==U)if(v>1)v/=2;else{if(t==="reject")throw new RangeError(`Can't find ISO date from calendar date: ${JSON.stringify({...i})}`);this.compareCalendarDates(w,B)>0&&(h=this.addDaysIso(h,-1)),p=0}}}if(r.set(c,h),u&&r.set(u,h),o.year===void 0||o.month===void 0||o.day===void 0||o.monthCode===void 0||this.hasEra&&(o.era===void 0||o.eraYear===void 0))throw new RangeError("Unexpected missing property");return h}compareCalendarDates(e,t){return e.year!==t.year?uo(e.year-t.year):e.month!==t.month?uo(e.month-t.month):e.day!==t.day?uo(e.day-t.day):0}regulateDate(e,t="constrain",r){let i=this.calendarToIsoDate(e,t,r);return this.isoToCalendarDate(i,r)}addDaysIso(e,t){return ho(e.year,e.month,e.day+t)}addDaysCalendar(e,t,r){let i=this.calendarToIsoDate(e,"constrain",r),o=this.addDaysIso(i,t);return this.isoToCalendarDate(o,r)}addMonthsCalendar(e,t,r,i){let o=e,{day:s}=o;for(let a=0,l=Math.abs(t);a<l;a++){let{month:c}=o,u=o,d=t<0?-Math.max(s,this.daysInPreviousMonth(o,i)):this.daysInMonth(o,i),h=this.calendarToIsoDate(o,"constrain",i),f=this.addDaysIso(h,d);if(o=this.isoToCalendarDate(f,i),t>0){let p=this.monthsInYear(u,i);for(;o.month-1!=c%p;)f=this.addDaysIso(f,-1),o=this.isoToCalendarDate(f,i)}o.day!==s&&(o=this.regulateDate({...o,day:s},"constrain",i))}if(r==="reject"&&o.day!==s)throw new RangeError(`Day ${s} does not exist in resulting calendar month`);return o}addCalendar(e,{years:t=0,months:r=0,weeks:i=0,days:o=0},s,a){let{year:l,day:c,monthCode:u}=e,d=this.adjustCalendarDate({year:l+t,monthCode:u,day:c},a),h=this.addMonthsCalendar(d,r,s,a),f=o+7*i;return this.addDaysCalendar(h,f,a)}untilCalendar(e,t,r,i){let o=0,s=0,a=0,l=0;switch(r){case"day":o=this.calendarDaysUntil(e,t,i);break;case"week":{let c=this.calendarDaysUntil(e,t,i);o=c%7,s=(c-o)/7;break}case"month":case"year":{let c=this.compareCalendarDates(t,e);if(!c)return{years:0,months:0,weeks:0,days:0};let u=t.year-e.year,d=t.day-e.day;if(r==="year"&&u){let p=0;t.monthCode>e.monthCode&&(p=1),t.monthCode<e.monthCode&&(p=-1),p||(p=Math.sign(d)),l=p*c<0?u-c:u}let h,f=l?this.addCalendar(e,{years:l},"constrain",i):e;do a+=c,h=f,f=this.addMonthsCalendar(h,c,"constrain",i),f.day!==e.day&&(f=this.regulateDate({...f,day:e.day},"constrain",i));while(this.compareCalendarDates(t,f)*c>=0);a-=c,o=this.calendarDaysUntil(h,t,i);break}}return{years:l,months:a,weeks:s,days:o}}daysInMonth(e,t){let{day:r}=e,i=this.maximumMonthLength(e),o=this.minimumMonthLength(e);if(o===i)return o;let s=r<=i-o?i:o,a=this.calendarToIsoDate(e,"constrain",t),l=this.addDaysIso(a,s),c=this.isoToCalendarDate(l,t),u=this.addDaysIso(l,-c.day);return this.isoToCalendarDate(u,t).day}daysInPreviousMonth(e,t){let{day:r,month:i,year:o}=e,s={year:i>1?o:o-1,month:i,day:1},a=i>1?i-1:this.monthsInYear(s,t);s={...s,month:a};let l=this.minimumMonthLength(s),c=this.maximumMonthLength(s);if(l===c)return c;let u=this.calendarToIsoDate(e,"constrain",t),d=this.addDaysIso(u,-r);return this.isoToCalendarDate(d,t).day}startOfCalendarYear(e){return{year:e.year,month:1,monthCode:"M01",day:1}}startOfCalendarMonth(e){return{year:e.year,month:e.month,day:1}}calendarDaysUntil(e,t,r){let i=this.calendarToIsoDate(e,"constrain",r),o=this.calendarToIsoDate(t,"constrain",r);return dh(o.year,o.month-1,o.day)-dh(i.year,i.month-1,i.day)}monthDaySearchStartYear(e,t){return 1972}monthDayFromFields(e,t,r){let i,o,s,a,l,{era:c,eraYear:u,year:d,month:h,monthCode:f,day:p}=e;if(h!==void 0&&d===void 0&&(!this.hasEra||c===void 0||u===void 0))throw new TypeError("when month is present, year (or era and eraYear) are required");(f===void 0||d!==void 0||this.hasEra&&u!==void 0)&&({monthCode:f,day:p}=this.isoToCalendarDate(this.calendarToIsoDate(e,t,r),r));let w={year:this.monthDaySearchStartYear(f,p),month:12,day:31},y=this.isoToCalendarDate(w,r),v=y.monthCode>f||y.monthCode===f&&y.day>=p?y.year:y.year-1;for(let B=0;B<20;B++){let U=this.adjustCalendarDate({day:p,monthCode:f,year:v-B},r),k=this.calendarToIsoDate(U,"constrain",r),F=this.isoToCalendarDate(k,r);if({year:i,month:o,day:s}=k,F.monthCode===f&&F.day===p)return{month:o,day:s,year:i};if(t==="constrain"){let P=this.maxLengthOfMonthCodeInAnyYear(F.monthCode);if(F.monthCode===f&&F.day===P&&p>P)return{month:o,day:s,year:i};(a===void 0||F.monthCode===a.monthCode&&F.day>a.day)&&(a=F,l=k)}}if(t==="constrain"&&l!==void 0)return l;throw new RangeError(`No recent ${this.id} year with monthCode ${f} and day ${p}`)}getFirstDayOfWeek(){}getMinimalDaysInFirstWeek(){}},SS=class extends Sl{constructor(){super(...arguments),this.id="hebrew",this.calendarType="lunisolar",this.months={Tishri:{leap:1,regular:1,monthCode:"M01",days:30},Heshvan:{leap:2,regular:2,monthCode:"M02",days:{min:29,max:30}},Kislev:{leap:3,regular:3,monthCode:"M03",days:{min:29,max:30}},Tevet:{leap:4,regular:4,monthCode:"M04",days:29},Shevat:{leap:5,regular:5,monthCode:"M05",days:30},Adar:{leap:void 0,regular:6,monthCode:"M06",days:29},"Adar I":{leap:6,regular:void 0,monthCode:"M05L",days:30},"Adar II":{leap:7,regular:void 0,monthCode:"M06",days:29},Nisan:{leap:8,regular:7,monthCode:"M07",days:30},Iyar:{leap:9,regular:8,monthCode:"M08",days:29},Sivan:{leap:10,regular:9,monthCode:"M09",days:30},Tamuz:{leap:11,regular:10,monthCode:"M10",days:29},Av:{leap:12,regular:11,monthCode:"M11",days:30},Elul:{leap:13,regular:12,monthCode:"M12",days:29}}}inLeapYear(e){let{year:t}=e;return(7*t+1)%19<7}monthsInYear(e){return this.inLeapYear(e)?13:12}minimumMonthLength(e){return this.minMaxMonthLength(e,"min")}maximumMonthLength(e){return this.minMaxMonthLength(e,"max")}minMaxMonthLength(e,t){let{month:r,year:i}=e,o=this.getMonthCode(i,r),s=Object.entries(this.months).find(l=>l[1].monthCode===o);if(s===void 0)throw new RangeError(`unmatched Hebrew month: ${r}`);let a=s[1].days;return typeof a=="number"?a:a[t]}maxLengthOfMonthCodeInAnyYear(e){return["M04","M06","M08","M10","M12"].includes(e)?29:30}estimateIsoDate(e){let{year:t}=e;return{year:t-3760,month:1,day:1}}getMonthCode(e,t){return this.inLeapYear({year:e})?t===6?ic(5,!0):ic(t<6?t:t-1):ic(t)}adjustCalendarDate(e,t,r="constrain",i=!1){let{year:o,month:s,monthCode:a,day:l,monthExtra:c}=e;if(o===void 0)throw new TypeError("Missing property: year");if(i){if(c){let u=this.months[c];if(!u)throw new RangeError(`Unrecognized month from formatToParts: ${c}`);s=this.inLeapYear({year:o})?u.leap:u.regular}return a=this.getMonthCode(o,s),{year:o,month:s,day:l,monthCode:a}}if(this.validateCalendarDate(e),s===void 0)if(a.endsWith("L")){if(a!=="M05L")throw new RangeError(`Hebrew leap month must have monthCode M05L, not ${a}`);if(s=6,!this.inLeapYear({year:o})){if(r==="reject")throw new RangeError(`Hebrew monthCode M05L is invalid in year ${o} which is not a leap year`);s=6,a="M06"}}else{s=hh(a),this.inLeapYear({year:o})&&s>=6&&s++;let u=this.monthsInYear({year:o});if(s<1||s>u)throw new RangeError(`Invalid monthCode: ${a}`)}else if(r==="reject"?(vr(s,1,this.monthsInYear({year:o})),vr(l,1,this.maximumMonthLength({year:o,month:s}))):(s=Ki(s,1,this.monthsInYear({year:o})),l=Ki(l,1,this.maximumMonthLength({year:o,month:s}))),a===void 0)a=this.getMonthCode(o,s);else if(this.getMonthCode(o,s)!==a)throw new RangeError(`monthCode ${a} doesn't correspond to month ${s} in Hebrew year ${o}`);return{...e,day:l,month:s,monthCode:a,year:o}}},md=class extends Sl{constructor(){super(...arguments),this.calendarType="lunar",this.DAYS_PER_ISLAMIC_YEAR=354+11/30,this.DAYS_PER_ISO_YEAR=365.2425}inLeapYear(e,t){let r={year:e.year,month:1,monthCode:"M01",day:1},i={year:e.year+1,month:1,monthCode:"M01",day:1};return this.calendarDaysUntil(r,i,t)===355}monthsInYear(){return 12}minimumMonthLength(){return 29}maximumMonthLength(){return 30}maxLengthOfMonthCodeInAnyYear(){return 30}estimateIsoDate(e){let{year:t}=this.adjustCalendarDate(e);return{year:Math.floor(t*this.DAYS_PER_ISLAMIC_YEAR/this.DAYS_PER_ISO_YEAR)+622,month:1,day:1}}},DS=class extends md{constructor(){super(...arguments),this.id="islamic"}},LS=class extends md{constructor(){super(...arguments),this.id="islamic-umalqura"}},BS=class extends md{constructor(){super(...arguments),this.id="islamic-tbla"}},TS=class extends md{constructor(){super(...arguments),this.id="islamic-civil"}},PS=class extends md{constructor(){super(...arguments),this.id="islamic-rgsa"}},RS=class extends md{constructor(){super(...arguments),this.id="islamicc"}},MS=class extends Sl{constructor(){super(...arguments),this.id="persian",this.calendarType="solar"}inLeapYear(e,t){return this.daysInMonth({year:e.year,month:12,day:1},t)===30}monthsInYear(){return 12}minimumMonthLength(e){let{month:t}=e;return t===12?29:t<=6?31:30}maximumMonthLength(e){let{month:t}=e;return t===12?30:t<=6?31:30}maxLengthOfMonthCodeInAnyYear(e){return hh(e)<=6?31:30}estimateIsoDate(e){let{year:t}=this.adjustCalendarDate(e);return{year:t+621,month:1,day:1}}},FS=class extends Sl{constructor(){super(...arguments),this.id="indian",this.calendarType="solar",this.months={1:{length:30,month:3,day:22,leap:{length:31,month:3,day:21}},2:{length:31,month:4,day:21},3:{length:31,month:5,day:22},4:{length:31,month:6,day:22},5:{length:31,month:7,day:23},6:{length:31,month:8,day:23},7:{length:30,month:9,day:23},8:{length:30,month:10,day:23},9:{length:30,month:11,day:22},10:{length:30,month:12,day:22},11:{length:30,month:1,nextYear:!0,day:21},12:{length:30,month:2,nextYear:!0,day:20}},this.vulnerableToBceBug=new Date("0000-01-01T00:00Z").toLocaleDateString("en-US-u-ca-indian",{timeZone:"UTC"})!=="10/11/-79 Saka"}inLeapYear(e){return r4(e.year+78)}monthsInYear(){return 12}minimumMonthLength(e){return this.getMonthInfo(e).length}maximumMonthLength(e){return this.getMonthInfo(e).length}maxLengthOfMonthCodeInAnyYear(e){let t=hh(e),r=this.months[t];return r=r.leap??r,r.length}getMonthInfo(e){let{month:t}=e,r=this.months[t];if(r===void 0)throw new RangeError(`Invalid month: ${t}`);return this.inLeapYear(e)&&r.leap&&(r=r.leap),r}estimateIsoDate(e){let t=this.adjustCalendarDate(e),r=this.getMonthInfo(t);return ho(t.year+78+(r.nextYear?1:0),r.month,r.day+t.day-1)}checkIcuBugs(e){if(this.vulnerableToBceBug&&e.year<1)throw new RangeError(`calendar '${this.id}' is broken for ISO dates before 0001-01-01 (see https://bugs.chromium.org/p/v8/issues/detail?id=10529)`)}};function r4(n){return n%4==0&&(n%100!=0||n%400==0)}var fE=class extends Sl{constructor(e,t){super(),this.calendarType="solar",this.id=e,this.isoEpoch=t}inLeapYear(e){let{year:t}=this.estimateIsoDate({month:1,day:1,year:e.year});return r4(t)}monthsInYear(){return 12}minimumMonthLength(e){let{month:t}=e;return t===2?this.inLeapYear(e)?29:28:[4,6,9,11].indexOf(t)>=0?30:31}maximumMonthLength(e){return this.minimumMonthLength(e)}maxLengthOfMonthCodeInAnyYear(e){return[31,29,31,30,31,30,31,31,30,31,30,31][hh(e)-1]}estimateIsoDate(e){let t=this.adjustCalendarDate(e);return Py(t.year+this.isoEpoch.year,t.month+this.isoEpoch.month,t.day+this.isoEpoch.day,"constrain")}},hE=class extends Sl{constructor(e,t){super(),this.hasEra=!0,this.calendarType="solar",this.id=e;let{eras:r,anchorEra:i}=function(o){let s,a=o;if(a.length===0)throw new RangeError("Invalid era data: eras are required");if(a.length===1&&a[0].reverseOf)throw new RangeError("Invalid era data: anchor era cannot count years backwards");if(a.length===1&&!a[0].code)throw new RangeError("Invalid era data: at least one named era is required");if(a.filter(c=>c.reverseOf!=null).length>1)throw new RangeError("Invalid era data: only one era can count years backwards");a.forEach(c=>{if(c.isAnchor||!c.anchorEpoch&&!c.reverseOf){if(s)throw new RangeError("Invalid era data: cannot have multiple anchor eras");s=c,c.anchorEpoch={year:c.hasYearZero?0:1}}else if(!c.code)throw new RangeError("If era name is blank, it must be the anchor era")}),a=a.filter(c=>c.code),a.forEach(c=>{let{reverseOf:u}=c;if(u){let d=a.find(h=>h.code===u);if(d===void 0)throw new RangeError(`Invalid era data: unmatched reverseOf era: ${u}`);c.reverseOf=d,c.anchorEpoch=d.anchorEpoch,c.isoEpoch=d.isoEpoch}c.anchorEpoch.month===void 0&&(c.anchorEpoch.month=1),c.anchorEpoch.day===void 0&&(c.anchorEpoch.day=1)}),a.sort((c,u)=>{if(c.reverseOf)return 1;if(u.reverseOf)return-1;if(!c.isoEpoch||!u.isoEpoch)throw new RangeError("Invalid era data: missing ISO epoch");return u.isoEpoch.year-c.isoEpoch.year});let l=a[a.length-1].reverseOf;if(l&&l!==a[a.length-2])throw new RangeError("Invalid era data: invalid reverse-sign era");return a.forEach((c,u)=>{c.genericName="era"+(a.length-1-u)}),{eras:a,anchorEra:s||a[0]}}(t);this.anchorEra=i,this.eras=r}inLeapYear(e){let{year:t}=this.estimateIsoDate({month:1,day:1,year:e.year});return r4(t)}monthsInYear(){return 12}minimumMonthLength(e){let{month:t}=e;return t===2?this.inLeapYear(e)?29:28:[4,6,9,11].indexOf(t)>=0?30:31}maximumMonthLength(e){return this.minimumMonthLength(e)}maxLengthOfMonthCodeInAnyYear(e){return[31,29,31,30,31,30,31,31,30,31,30,31][hh(e)-1]}completeEraYear(e){let t=(a,l,c)=>{let u=e[a];if(u!=null&&u!=l&&!(c||[]).includes(u)){let d=c?.[0];throw new RangeError(`Input ${a} ${u} doesn't match calculated value ${d?`${l} (also called ${d})`:l}`)}},r=a=>{let l,c={...e,year:a},u=this.eras.find((d,h)=>{if(h===this.eras.length-1){if(d.reverseOf){if(a>0)throw new RangeError(`Signed year ${a} is invalid for era ${d.code}`);return l=d.anchorEpoch.year-a,!0}return l=a-d.anchorEpoch.year+(d.hasYearZero?0:1),!0}return this.compareCalendarDates(c,d.anchorEpoch)>=0&&(l=a-d.anchorEpoch.year+(d.hasYearZero?0:1),!0)});if(!u)throw new RangeError(`Year ${a} was not matched by any era`);return{eraYear:l,era:u.code,eraNames:u.names}},{year:i,eraYear:o,era:s}=e;if(i!=null){let a=r(i);({eraYear:o,era:s}=a),t("era",s,a?.eraNames),t("eraYear",o)}else{if(o==null)throw new RangeError("Either year or eraYear and era are required");{if(s===void 0)throw new RangeError("era and eraYear must be provided together");let a=this.eras.find(({code:l,names:c=[]})=>l===s||c.includes(s));if(!a)throw new RangeError(`Era ${s} (ISO year ${o}) was not matched by any era`);i=a.reverseOf?a.anchorEpoch.year-o:o+a.anchorEpoch.year-(a.hasYearZero?0:1),t("year",i),{eraYear:o,era:s}=r(i)}}return{...e,year:i,eraYear:o,era:s}}adjustCalendarDate(e,t,r="constrain"){let i=e,{month:o,monthCode:s}=i;return o===void 0&&(i={...i,month:hh(s)}),this.validateCalendarDate(i),i=this.completeEraYear(i),super.adjustCalendarDate(i,t,r)}estimateIsoDate(e){let t=this.adjustCalendarDate(e),{year:r,month:i,day:o}=t,{anchorEra:s}=this;return Py(r+s.isoEpoch.year-(s.hasYearZero?0:1),i,o,"constrain")}},Jy=class extends hE{constructor(e,t){super(e,t)}isoToCalendarDate(e){let{year:t,month:r,day:i}=e,o=ic(r),s=t-this.anchorEra.isoEpoch.year+1;return this.completeEraYear({year:s,month:r,monthCode:o,day:i})}},nc={inLeapYear(n){let{year:e}=n;return(e+1)%4==0},monthsInYear:()=>13,minimumMonthLength(n){let{month:e}=n;return e===13?this.inLeapYear(n)?6:5:30},maximumMonthLength(n){return this.minimumMonthLength(n)},maxLengthOfMonthCodeInAnyYear:n=>n==="M13"?6:30},kS=class extends fE{constructor(e,t){super(e,t),this.inLeapYear=nc.inLeapYear,this.monthsInYear=nc.monthsInYear,this.minimumMonthLength=nc.minimumMonthLength,this.maximumMonthLength=nc.maximumMonthLength,this.maxLengthOfMonthCodeInAnyYear=nc.maxLengthOfMonthCodeInAnyYear}},pE=class extends hE{constructor(e,t){super(e,t),this.inLeapYear=nc.inLeapYear,this.monthsInYear=nc.monthsInYear,this.minimumMonthLength=nc.minimumMonthLength,this.maximumMonthLength=nc.maximumMonthLength,this.maxLengthOfMonthCodeInAnyYear=nc.maxLengthOfMonthCodeInAnyYear}},OS=class extends kS{constructor(){super("ethioaa",{year:-5492,month:7,day:17})}},GS=class extends pE{constructor(){super("coptic",[{code:"coptic",isoEpoch:{year:284,month:8,day:29}},{code:"coptic-inverse",reverseOf:"coptic"}])}},NS=class extends pE{constructor(){super("ethiopic",[{code:"ethioaa",names:["ethiopic-amete-alem","mundi"],isoEpoch:{year:-5492,month:7,day:17}},{code:"ethiopic",names:["incar"],isoEpoch:{year:8,month:8,day:27},anchorEpoch:{year:5501}}])}},US=class extends Jy{constructor(){super("roc",[{code:"roc",names:["minguo"],isoEpoch:{year:1912,month:1,day:1}},{code:"roc-inverse",names:["before-roc"],reverseOf:"roc"}])}},HS=class extends fE{constructor(){super("buddhist",{year:-543,month:1,day:1})}},KS=class extends Jy{constructor(){super("gregory",[{code:"gregory",names:["ad","ce"],isoEpoch:{year:1,month:1,day:1}},{code:"gregory-inverse",names:["be","bce"],reverseOf:"gregory"}])}reviseIntlEra(e){let{era:t,eraYear:r}=e;return t==="b"&&(t="gregory-inverse"),t==="a"&&(t="gregory"),{era:t,eraYear:r}}getFirstDayOfWeek(){return 1}getMinimalDaysInFirstWeek(){return 1}},JS=class extends Jy{constructor(){super("japanese",[{code:"reiwa",isoEpoch:{year:2019,month:5,day:1},anchorEpoch:{year:2019,month:5,day:1}},{code:"heisei",isoEpoch:{year:1989,month:1,day:8},anchorEpoch:{year:1989,month:1,day:8}},{code:"showa",isoEpoch:{year:1926,month:12,day:25},anchorEpoch:{year:1926,month:12,day:25}},{code:"taisho",isoEpoch:{year:1912,month:7,day:30},anchorEpoch:{year:1912,month:7,day:30}},{code:"meiji",isoEpoch:{year:1868,month:9,day:8},anchorEpoch:{year:1868,month:9,day:8}},{code:"japanese",names:["japanese","gregory","ad","ce"],isoEpoch:{year:1,month:1,day:1}},{code:"japanese-inverse",names:["japanese-inverse","gregory-inverse","bc","bce"],reverseOf:"japanese"}]),this.erasBeginMidYear=!0}reviseIntlEra(e,t){let{era:r,eraYear:i}=e,{year:o}=t;return this.eras.find(s=>s.code===r)?{era:r,eraYear:i}:o<1?{era:"japanese-inverse",eraYear:1-o}:{era:"japanese",eraYear:o}}},mE=class extends Sl{constructor(){super(...arguments),this.calendarType="lunisolar"}inLeapYear(e,t){let r=this.getMonthList(e.year,t);return Object.entries(r).length===13}monthsInYear(e,t){return this.inLeapYear(e,t)?13:12}minimumMonthLength(){return 29}maximumMonthLength(){return 30}maxLengthOfMonthCodeInAnyYear(e){return["M01L","M09L","M10L","M11L","M12L"].includes(e)?29:30}monthDaySearchStartYear(e,t){let r={M01L:[1651,1651],M02L:[1947,1765],M03L:[1966,1955],M04L:[1963,1944],M05L:[1971,1952],M06L:[1960,1941],M07L:[1968,1938],M08L:[1957,1718],M09L:[1832,1832],M10L:[1870,1870],M11L:[1814,1814],M12L:[1890,1890]}[e]??[1972,1972];return t<30?r[0]:r[1]}getMonthList(e,t){if(e===void 0)throw new TypeError("Missing year");let r=JSON.stringify({func:"getMonthList",calendarYear:e,id:this.id}),i=t.get(r);if(i)return i;let o=this.getFormatter(),s=(y,v)=>{let B=fU({isoYear:y,isoMonth:2,isoDay:1}),U=new Date(B);U.setUTCDate(v+1);let k=o.formatToParts(U),F=k.find(V=>V.type==="month").value,P=+k.find(V=>V.type==="day").value,I=k.find(V=>V.type==="relatedYear"),D;if(I===void 0)throw new RangeError(`Intl.DateTimeFormat.formatToParts lacks relatedYear in ${this.id} calendar. Try Node 14+ or modern browsers.`);return D=+I.value,{calendarMonthString:F,calendarDay:P,calendarYearToVerify:D}},a=17,{calendarMonthString:l,calendarDay:c,calendarYearToVerify:u}=s(e,a);l!=="1"&&(a+=29,{calendarMonthString:l,calendarDay:c}=s(e,a)),a-=c-5;let d={},h,f,p=1,w=!1;do({calendarMonthString:l,calendarDay:c,calendarYearToVerify:u}=s(e,a)),h&&(d[f].daysInMonth=h+30-c),u!==e?w=!0:(d[l]={monthIndex:p++},a+=30),h=c,f=l;while(!w);return d[f].daysInMonth=h+30-c,t.set(r,d),d}estimateIsoDate(e){let{year:t,month:r}=e;return{year:t,month:r>=12?12:r+1,day:1}}adjustCalendarDate(e,t,r="constrain",i=!1){let{year:o,month:s,monthExtra:a,day:l,monthCode:c}=e;if(o===void 0)throw new TypeError("Missing property: year");if(i){if(a&&a!=="bis")throw new RangeError(`Unexpected leap month suffix: ${a}`);let u=ic(s,a!==void 0),d=`${s}${a||""}`,h=this.getMonthList(o,t)[d];if(h===void 0)throw new RangeError(`Unmatched month ${d} in Chinese year ${o}`);return s=h.monthIndex,{year:o,month:s,day:l,monthCode:u}}if(this.validateCalendarDate(e),s===void 0){let u=this.getMonthList(o,t),d=c.replace(/^M|L$/g,f=>f==="L"?"bis":"");d[0]==="0"&&(d=d.slice(1));let h=u[d];if(s=h&&h.monthIndex,s===void 0&&c.endsWith("L")&&c!="M13L"&&r==="constrain"){let f=+c.replace(/^M0?|L$/g,"");h=u[f],h&&(s=h.monthIndex,c=ic(f))}if(s===void 0)throw new RangeError(`Unmatched month ${c} in Chinese year ${o}`)}else if(c===void 0){let u=this.getMonthList(o,t),d=Object.entries(u),h=d.length;r==="reject"?(vr(s,1,h),vr(l,1,this.maximumMonthLength())):(s=Ki(s,1,h),l=Ki(l,1,this.maximumMonthLength()));let f=d.find(p=>p[1].monthIndex===s);if(f===void 0)throw new RangeError(`Invalid month ${s} in Chinese year ${o}`);c=ic(+f[0].replace("bis",""),f[0].indexOf("bis")!==-1)}else{let u=this.getMonthList(o,t),d=c.replace(/^M|L$/g,f=>f==="L"?"bis":"");d[0]==="0"&&(d=d.slice(1));let h=u[d];if(!h)throw new RangeError(`Unmatched monthCode ${c} in Chinese year ${o}`);if(s!==h.monthIndex)throw new RangeError(`monthCode ${c} doesn't correspond to month ${s} in Chinese year ${o}`)}return{...e,year:o,month:s,monthCode:c,day:l}}},qS=class extends mE{constructor(){super(...arguments),this.id="chinese"}},QS=class extends mE{constructor(){super(...arguments),this.id="dangi"}},VS=class{constructor(e){this.helper=e}extraFields(e){return this.helper.hasEra&&e.includes("year")?["era","eraYear"]:[]}resolveFields(e){if(this.helper.calendarType!=="lunisolar"){let t=new Uo;n4(e,void 0,this.helper.monthsInYear({year:e.year??1972},t))}}dateToISO(e,t){let r=new Uo,i=this.helper.calendarToIsoDate(e,t,r);return r.setObject(i),i}monthDayToISOReferenceDate(e,t){let r=new Uo,i=this.helper.monthDayFromFields(e,t,r);return r.setObject(i),i}fieldKeysToIgnore(e){let t=new Set;for(let r=0;r<e.length;r++){let i=e[r];switch(t.add(i),i){case"era":t.add("eraYear"),t.add("year");break;case"eraYear":t.add("era"),t.add("year");break;case"year":t.add("era"),t.add("eraYear");break;case"month":t.add("monthCode"),this.helper.erasBeginMidYear&&(t.add("era"),t.add("eraYear"));break;case"monthCode":t.add("month"),this.helper.erasBeginMidYear&&(t.add("era"),t.add("eraYear"));break;case"day":this.helper.erasBeginMidYear&&(t.add("era"),t.add("eraYear"))}}return uU(t)}dateAdd(e,{years:t,months:r,weeks:i,days:o},s){let a=Uo.getCacheForObject(e),l=this.helper.isoToCalendarDate(e,a),c=this.helper.addCalendar(l,{years:t,months:r,weeks:i,days:o},s,a),u=this.helper.calendarToIsoDate(c,"constrain",a);return Uo.getCacheForObject(u)||new Uo(a).setObject(u),u}dateUntil(e,t,r){let i=Uo.getCacheForObject(e),o=Uo.getCacheForObject(t),s=this.helper.isoToCalendarDate(e,i),a=this.helper.isoToCalendarDate(t,o);return this.helper.untilCalendar(s,a,r,i)}isoToDate(e,t){let r=Uo.getCacheForObject(e),i=this.helper.isoToCalendarDate(e,r);if(t.dayOfWeek&&(i.dayOfWeek=uw.iso8601.isoToDate(e,{dayOfWeek:!0}).dayOfWeek),t.dayOfYear){let o=this.helper.startOfCalendarYear(i),s=this.helper.calendarDaysUntil(o,i,r);i.dayOfYear=s+1}if(t.weekOfYear&&(i.weekOfYear=dU(this.helper.id,e)),i.daysInWeek=7,t.daysInMonth&&(i.daysInMonth=this.helper.daysInMonth(i,r)),t.daysInYear){let o=this.helper.startOfCalendarYear(i),s=this.helper.addCalendar(o,{years:1},"constrain",r);i.daysInYear=this.helper.calendarDaysUntil(o,s,r)}return t.monthsInYear&&(i.monthsInYear=this.helper.monthsInYear(i,r)),t.inLeapYear&&(i.inLeapYear=this.helper.inLeapYear(i,r)),i}getFirstDayOfWeek(){return this.helper.getFirstDayOfWeek()}getMinimalDaysInFirstWeek(){return this.helper.getMinimalDaysInFirstWeek()}};for(let n of[SS,MS,NS,OS,GS,qS,QS,US,FS,HS,KS,JS,DS,LS,BS,TS,PS,RS]){let e=new n;uw[e.id]=new VS(e)}dS("calendarImpl",function(n){return uw[n]});var qy=Intl.DateTimeFormat;function C0(n,e){let t=z(n,e);return typeof t=="function"&&(t=new qy(z(n,DN),t(z(n,aS))),function(r,i,o){let s=yE(r);if(s===void 0)throw new TypeError("Missing slots for the given container");if(s[i]===void 0)throw new TypeError(`tried to reset ${i} which was not set`);s[i]=o}(n,e,t)),t}function by(n){return Vi(n,mh)}var ph=class{constructor(e=void 0,t=void 0){(function(r,i,o){let s=o!==void 0,a;if(s){let d=["localeMatcher","calendar","numberingSystem","hour12","hourCycle","timeZone","weekday","era","year","month","day","dayPeriod","hour","minute","second","fractionalSecondDigits","timeZoneName","formatMatcher","dateStyle","timeStyle"];a=function(f){if(f==null)throw new TypeError(`Expected object not ${f}`);return Object(f)}(o);let h=Object.create(null);for(let f=0;f<d.length;f++){let p=d[f];Object.prototype.hasOwnProperty.call(a,p)&&(h[p]=a[p])}a=h}else a=Object.create(null);let l=new qy(i,a),c=l.resolvedOptions();if(Dl(r),s){let d=Object.assign(Object.create(null),c);for(let h in d)Object.prototype.hasOwnProperty.call(a,h)||delete d[h];d.hour12=a.hour12,d.hourCycle=a.hourCycle,wt(r,aS,d)}else wt(r,aS,a);wt(r,DN,c.locale),wt(r,mh,l),wt(r,L0,c.timeZone),wt(r,Ey,c.calendar),wt(r,EN,vre),wt(r,xN,xre),wt(r,AN,Are),wt(r,vN,Ere),wt(r,CN,Cre),wt(r,SN,Sre);let u=s?a.timeZone:void 0;if(u===void 0)wt(r,sS,c.timeZone);else{let d=EE(u);if(d.startsWith("\u2212"))throw new RangeError("Unicode minus (U+2212) is not supported in time zone offsets");wt(r,sS,qi(d))}})(this,e,t)}get format(){de(this,by);let e=yre.bind(this);return Object.defineProperties(e,{length:{value:1,enumerable:!1,writable:!1,configurable:!0},name:{value:"",enumerable:!1,writable:!1,configurable:!0}}),e}formatRange(e,t){return de(this,by),bre.call(this,e,t)}formatToParts(e,...t){return de(this,by),wre.call(this,e,...t)}formatRangeToParts(e,t){return de(this,by),Ire.call(this,e,t)}resolvedOptions(){return de(this,by),gre.call(this)}};"formatToParts"in qy.prototype||delete ph.prototype.formatToParts,"formatRangeToParts"in qy.prototype||delete ph.prototype.formatRangeToParts;var Jo=function(n=void 0,e=void 0){return new ph(n,e)};function gre(){let n=z(this,mh).resolvedOptions();return n.timeZone=z(this,sS),n}function yre(n,...e){let t,r,i=H0(n,this);return i.formatter?(t=i.formatter,r=[As(i.epochNs,"floor")]):(t=z(this,mh),r=[n,...e]),t.format(...r)}function wre(n,...e){let t,r,i=H0(n,this);return i.formatter?(t=i.formatter,r=[As(i.epochNs,"floor")]):(t=z(this,mh),r=[n,...e]),t.formatToParts(...r)}function bre(n,e){if(n===void 0||e===void 0)throw new TypeError("Intl.DateTimeFormat.formatRange requires two values");let t=gE(n),r=gE(e),i,o=[t,r];if(vl(t)!==vl(r))throw new TypeError("Intl.DateTimeFormat.formatRange accepts two values of the same type");if(vl(t)){if(!hU(t,r))throw new TypeError("Intl.DateTimeFormat.formatRange accepts two values of the same type");let{epochNs:s,formatter:a}=H0(t,this),{epochNs:l,formatter:c}=H0(r,this);a&&(i=a,o=[As(s,"floor"),As(l,"floor")])}return i||(i=z(this,mh)),i.formatRange(...o)}function Ire(n,e){if(n===void 0||e===void 0)throw new TypeError("Intl.DateTimeFormat.formatRange requires two values");let t=gE(n),r=gE(e),i,o=[t,r];if(vl(t)!==vl(r))throw new TypeError("Intl.DateTimeFormat.formatRangeToParts accepts two values of the same type");if(vl(t)){if(!hU(t,r))throw new TypeError("Intl.DateTimeFormat.formatRangeToParts accepts two values of the same type");let{epochNs:s,formatter:a}=H0(t,this),{epochNs:l,formatter:c}=H0(r,this);a&&(i=a,o=[As(s,"floor"),As(l,"floor")])}return i||(i=z(this,mh)),i.formatRangeToParts(...o)}function dw(n={},e={}){let t=Object.assign({},n),r=["year","month","day","hour","minute","second","weekday","dayPeriod","timeZoneName","dateStyle","timeStyle"];for(let i=0;i<r.length;i++){let o=r[i];t[o]=o in e?e[o]:t[o],t[o]!==!1&&t[o]!==void 0||delete t[o]}return t}function Ere(n){let e=dw(n,{year:!1,month:!1,day:!1,weekday:!1,timeZoneName:!1,dateStyle:!1});if(e.timeStyle!=="long"&&e.timeStyle!=="full"||(delete e.timeStyle,Object.assign(e,{hour:"numeric",minute:"2-digit",second:"2-digit"})),!TE(e)){if(fw(n))throw new TypeError(`cannot format Temporal.PlainTime with options [${Object.keys(n)}]`);Object.assign(e,{hour:"numeric",minute:"numeric",second:"numeric"})}return e}function xre(n){let e={short:{year:"2-digit",month:"numeric"},medium:{year:"numeric",month:"short"},long:{year:"numeric",month:"long"},full:{year:"numeric",month:"long"}},t=dw(n,{day:!1,hour:!1,minute:!1,second:!1,weekday:!1,dayPeriod:!1,timeZoneName:!1,timeStyle:!1});if("dateStyle"in t&&t.dateStyle){let r=t.dateStyle;delete t.dateStyle,Object.assign(t,e[r])}if(!("year"in t||"month"in t||"era"in t)){if(fw(n))throw new TypeError(`cannot format PlainYearMonth with options [${Object.keys(n)}]`);Object.assign(t,{year:"numeric",month:"numeric"})}return t}function Are(n){let e={short:{month:"numeric",day:"numeric"},medium:{month:"short",day:"numeric"},long:{month:"long",day:"numeric"},full:{month:"long",day:"numeric"}},t=dw(n,{year:!1,hour:!1,minute:!1,second:!1,weekday:!1,dayPeriod:!1,timeZoneName:!1,timeStyle:!1});if("dateStyle"in t&&t.dateStyle){let r=t.dateStyle;delete t.dateStyle,Object.assign(t,e[r])}if(!("month"in t)&&!("day"in t)){if(fw(n))throw new TypeError(`cannot format PlainMonthDay with options [${Object.keys(n)}]`);Object.assign(t,{month:"numeric",day:"numeric"})}return t}function vre(n){let e=dw(n,{hour:!1,minute:!1,second:!1,dayPeriod:!1,timeZoneName:!1,timeStyle:!1});if(!BE(e)){if(fw(n))throw new TypeError(`cannot format PlainDate with options [${Object.keys(n)}]`);Object.assign(e,{year:"numeric",month:"numeric",day:"numeric"})}return e}function Cre(n){let e=dw(n,{timeZoneName:!1});if((e.timeStyle==="long"||e.timeStyle==="full")&&(delete e.timeStyle,Object.assign(e,{hour:"numeric",minute:"2-digit",second:"2-digit"}),e.dateStyle)&&(Object.assign(e,{short:{year:"numeric",month:"numeric",day:"numeric"},medium:{year:"numeric",month:"short",day:"numeric"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}}[e.dateStyle]),delete e.dateStyle),!TE(e)&&!BE(e)){if(fw(n))throw new TypeError(`cannot format PlainDateTime with options [${Object.keys(n)}]`);Object.assign(e,{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})}return e}function Sre(n){let e=n;return TE(e)||BE(e)||(e=Object.assign({},e,{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),e}function BE(n){return"year"in n||"month"in n||"day"in n||"weekday"in n||"dateStyle"in n||"era"in n}function TE(n){return"hour"in n||"minute"in n||"second"in n||"timeStyle"in n||"dayPeriod"in n||"fractionalSecondDigits"in n}function fw(n){return BE(n)||TE(n)||"dateStyle"in n||"timeStyle"in n||"timeZoneName"in n}function vl(n){return kn(n)||qn(n)||En(n)||It(n)||qr(n)||Ho(n)||Jr(n)}function gE(n){return vl(n)?n:IE(n)}function hU(n,e){return!(!vl(n)||!vl(e)||qn(n)&&!qn(e)||kn(n)&&!kn(e)||En(n)&&!En(e)||It(n)&&!It(e)||qr(n)&&!qr(e)||Ho(n)&&!Ho(e)||Jr(n)&&!Jr(e))}function H0(n,e){if(qn(n)){let t={isoDate:{year:1970,month:1,day:1},time:z(n,On)};return{epochNs:si(z(e,L0),t,"compatible"),formatter:C0(e,vN)}}if(qr(n)){let t=z(n,ve),r=z(e,Ey);if(t!==r)throw new RangeError(`cannot format PlainYearMonth with calendar ${t} in locale with calendar ${r}`);let i=Ht(z(n,ot),{deltaDays:0,hour:12,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});return{epochNs:si(z(e,L0),i,"compatible"),formatter:C0(e,xN)}}if(Ho(n)){let t=z(n,ve),r=z(e,Ey);if(t!==r)throw new RangeError(`cannot format PlainMonthDay with calendar ${t} in locale with calendar ${r}`);let i=Ht(z(n,ot),{deltaDays:0,hour:12,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});return{epochNs:si(z(e,L0),i,"compatible"),formatter:C0(e,AN)}}if(kn(n)){let t=z(n,ve),r=z(e,Ey);if(t!=="iso8601"&&t!==r)throw new RangeError(`cannot format PlainDate with calendar ${t} in locale with calendar ${r}`);let i=Ht(z(n,ot),{deltaDays:0,hour:12,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});return{epochNs:si(z(e,L0),i,"compatible"),formatter:C0(e,EN)}}if(En(n)){let t=z(n,ve),r=z(e,Ey);if(t!=="iso8601"&&t!==r)throw new RangeError(`cannot format PlainDateTime with calendar ${t} in locale with calendar ${r}`);let i=z(n,vn);return{epochNs:si(z(e,L0),i,"compatible"),formatter:C0(e,CN)}}if(It(n))throw new TypeError("Temporal.ZonedDateTime not supported in DateTimeFormat methods. Use toLocaleString() instead.");return Jr(n)?{epochNs:z(n,it),formatter:C0(e,SN)}:{}}function pU(n){let e=Object.create(null);return e.years=z(n,Mi),e.months=z(n,Fi),e.weeks=z(n,co),e.days=z(n,ki),e.hours=z(n,Oi),e.minutes=z(n,Gi),e.seconds=z(n,Ni),e.milliseconds=z(n,Ui),e.microseconds=z(n,Hi),e.nanoseconds=z(n,lo),e}ph.prototype.constructor=Jo,Object.defineProperty(Jo,"prototype",{value:ph.prototype,writable:!1,enumerable:!1,configurable:!1}),Jo.supportedLocalesOf=qy.supportedLocalesOf,Ll(Jo,"Intl.DateTimeFormat");var{format:Dre,formatToParts:Lre}=Intl.DurationFormat?.prototype??Object.create(null);function i4(n){Intl.DurationFormat.prototype.resolvedOptions.call(this);let e=pU(Es(n));return Dre.call(this,e)}Intl.DurationFormat?.prototype&&(Intl.DurationFormat.prototype.format=i4,Intl.DurationFormat.prototype.formatToParts=function(n){Intl.DurationFormat.prototype.resolvedOptions.call(this);let e=pU(Es(n));return Lre.call(this,e)});var l6e=Object.freeze({__proto__:null,DateTimeFormat:Jo,ModifiedIntlDurationFormatPrototypeFormat:i4}),Qy=class{constructor(e){if(arguments.length<1)throw new TypeError("missing argument: epochNanoseconds is required");YN(this,dE(e))}get epochMilliseconds(){return de(this,Jr),As(z(this,it),"floor")}get epochNanoseconds(){return de(this,Jr),cU(ae.default.BigInt(z(this,it)))}add(e){return de(this,Jr),cN("add",this,e)}subtract(e){return de(this,Jr),cN("subtract",this,e)}until(e,t=void 0){return de(this,Jr),tN("until",this,e,t)}since(e,t=void 0){return de(this,Jr),tN("since",this,e,t)}round(e){if(de(this,Jr),e===void 0)throw new TypeError("options parameter is required");let t=typeof e=="string"?fh("smallestUnit",e):Qe(e),r=J0(t),i=ya(t,"halfExpand"),o=fo(t,"smallestUnit","time",Cl);return q0(r,{hour:24,minute:1440,second:86400,millisecond:864e5,microsecond:864e8,nanosecond:864e11}[o],!0),ma(ES(z(this,it),r,o,i))}equals(e){de(this,Jr);let t=vy(e),r=z(this,it),i=z(t,it);return ae.default.equal(ae.default.BigInt(r),ae.default.BigInt(i))}toString(e=void 0){de(this,Jr);let t=Qe(e),r=nw(t),i=ya(t,"trunc"),o=fo(t,"smallestUnit","time",void 0);if(o==="hour")throw new RangeError('smallestUnit must be a time unit other than "hour"');let s=t.timeZone;s!==void 0&&(s=qi(s));let{precision:a,unit:l,increment:c}=rw(o,r);return YG(ma(ES(z(this,it),c,l,i)),s,a)}toJSON(){return de(this,Jr),YG(this,void 0,"auto")}toLocaleString(e=void 0,t=void 0){return de(this,Jr),new Jo(e,t).format(this)}valueOf(){yd("Instant")}toZonedDateTimeISO(e){de(this,Jr);let t=qi(e);return ii(z(this,it),t,"iso8601")}static fromEpochMilliseconds(e){return ma(ga(IE(e)))}static fromEpochNanoseconds(e){return ma(dE(e))}static from(e){return vy(e)}static compare(e,t){let r=vy(e),i=vy(t),o=z(r,it),s=z(i,it);return ae.default.lessThan(o,s)?-1:ae.default.greaterThan(o,s)?1:0}};Ll(Qy,"Temporal.Instant");var Vy=class{constructor(e,t,r,i="iso8601"){let o=ut(e),s=ut(t),a=ut(r),l=Yi(i===void 0?"iso8601":dr(i));lh(o,s,a),KN(this,{year:o,month:s,day:a},l)}get calendarId(){return de(this,kn),z(this,ve)}get era(){return Ti(this,"era")}get eraYear(){return Ti(this,"eraYear")}get year(){return Ti(this,"year")}get month(){return Ti(this,"month")}get monthCode(){return Ti(this,"monthCode")}get day(){return Ti(this,"day")}get dayOfWeek(){return Ti(this,"dayOfWeek")}get dayOfYear(){return Ti(this,"dayOfYear")}get weekOfYear(){return Ti(this,"weekOfYear")?.week}get yearOfWeek(){return Ti(this,"weekOfYear")?.year}get daysInWeek(){return Ti(this,"daysInWeek")}get daysInMonth(){return Ti(this,"daysInMonth")}get daysInYear(){return Ti(this,"daysInYear")}get monthsInYear(){return Ti(this,"monthsInYear")}get inLeapYear(){return Ti(this,"inLeapYear")}with(e,t=void 0){if(de(this,kn),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=z(this,ve),i=Qi(r,z(this,ot));return i=ch(r,i,Vo(r,e,["year","month","monthCode","day"],[],"partial")),Ji(pd(r,i,kt(Qe(t))),r)}withCalendar(e){de(this,kn);let t=aw(e);return Ji(z(this,ot),t)}add(e,t=void 0){return de(this,kn),lN("add",this,e,t)}subtract(e,t=void 0){return de(this,kn),lN("subtract",this,e,t)}until(e,t=void 0){return de(this,kn),nN("until",this,e,t)}since(e,t=void 0){return de(this,kn),nN("since",this,e,t)}equals(e){de(this,kn);let t=xy(e);return ac(z(this,ot),z(t,ot))===0&&oc(z(this,ve),z(t,ve))}toString(e=void 0){return de(this,kn),zG(this,tw(Qe(e)))}toJSON(){return de(this,kn),zG(this)}toLocaleString(e=void 0,t=void 0){return de(this,kn),new Jo(e,t).format(this)}valueOf(){yd("PlainDate")}toPlainDateTime(e=void 0){de(this,kn);let t=HN(e);return bs(Ht(z(this,ot),t),z(this,ve))}toZonedDateTime(e){let t,r;if(de(this,kn),Gn(e)){let s=e.timeZone;s===void 0?t=qi(e):(t=qi(s),r=e.plainTime)}else t=qi(e);let i=z(this,ot),o;return r===void 0?o=ad(t,i):(r=ld(r),o=si(t,Ht(i,z(r,On)),"compatible")),ii(o,t,z(this,ve))}toPlainYearMonth(){de(this,kn);let e=z(this,ve);return R0(Gy(e,Qi(e,z(this,ot)),"constrain"),e)}toPlainMonthDay(){de(this,kn);let e=z(this,ve);return P0(sE(e,Qi(e,z(this,ot)),"constrain"),e)}static from(e,t=void 0){return xy(e,t)}static compare(e,t){let r=xy(e),i=xy(t);return ac(z(r,ot),z(i,ot))}};function Ti(n,e){de(n,kn);let t=z(n,ot);return iw(n).isoToDate(t,{[e]:!0})[e]}Ll(Vy,"Temporal.PlainDate");var Yy=class{constructor(e,t,r,i=0,o=0,s=0,a=0,l=0,c=0,u="iso8601"){let d=ut(e),h=ut(t),f=ut(r),p=i===void 0?0:ut(i),w=o===void 0?0:ut(o),y=s===void 0?0:ut(s),v=a===void 0?0:ut(a),B=l===void 0?0:ut(l),U=c===void 0?0:ut(c),k=Yi(u===void 0?"iso8601":dr(u));_S(d,h,f,p,w,y,v,B,U),JN(this,{isoDate:{year:d,month:h,day:f},time:{hour:p,minute:w,second:y,millisecond:v,microsecond:B,nanosecond:U}},k)}get calendarId(){return de(this,En),z(this,ve)}get year(){return Pi(this,"year")}get month(){return Pi(this,"month")}get monthCode(){return Pi(this,"monthCode")}get day(){return Pi(this,"day")}get hour(){return S0(this,"hour")}get minute(){return S0(this,"minute")}get second(){return S0(this,"second")}get millisecond(){return S0(this,"millisecond")}get microsecond(){return S0(this,"microsecond")}get nanosecond(){return S0(this,"nanosecond")}get era(){return Pi(this,"era")}get eraYear(){return Pi(this,"eraYear")}get dayOfWeek(){return Pi(this,"dayOfWeek")}get dayOfYear(){return Pi(this,"dayOfYear")}get weekOfYear(){return Pi(this,"weekOfYear")?.week}get yearOfWeek(){return Pi(this,"weekOfYear")?.year}get daysInWeek(){return Pi(this,"daysInWeek")}get daysInYear(){return Pi(this,"daysInYear")}get daysInMonth(){return Pi(this,"daysInMonth")}get monthsInYear(){return Pi(this,"monthsInYear")}get inLeapYear(){return Pi(this,"inLeapYear")}with(e,t=void 0){if(de(this,En),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=z(this,ve),i=z(this,vn),o={...Qi(r,i.isoDate),...i.time};return o=ch(r,o,Vo(r,e,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond"],"partial")),bs(ow(r,o,kt(Qe(t))),r)}withPlainTime(e=void 0){de(this,En);let t=HN(e);return bs(Ht(z(this,vn).isoDate,t),z(this,ve))}withCalendar(e){de(this,En);let t=aw(e);return bs(z(this,vn),t)}add(e,t=void 0){return de(this,En),uN("add",this,e,t)}subtract(e,t=void 0){return de(this,En),uN("subtract",this,e,t)}until(e,t=void 0){return de(this,En),rN("until",this,e,t)}since(e,t=void 0){return de(this,En),rN("since",this,e,t)}round(e){if(de(this,En),e===void 0)throw new TypeError("options parameter is required");let t=typeof e=="string"?fh("smallestUnit",e):Qe(e),r=J0(t),i=ya(t,"halfExpand"),o=fo(t,"smallestUnit","time",Cl,["day"]),s={day:1,hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[o];q0(r,s,s===1);let a=z(this,vn);return bs(r===1&&o==="nanosecond"?a:xS(a,r,o,i),z(this,ve))}equals(e){de(this,En);let t=Ay(e);return U0(z(this,vn),z(t,vn))===0&&oc(z(this,ve),z(t,ve))}toString(e=void 0){de(this,En);let t=Qe(e),r=tw(t),i=nw(t),o=ya(t,"trunc"),s=fo(t,"smallestUnit","time",void 0);if(s==="hour")throw new RangeError('smallestUnit must be a time unit other than "hour"');let{precision:a,unit:l,increment:c}=rw(s,i),u=xS(z(this,vn),c,l,o);return uh(u),Uy(u,z(this,ve),a,r)}toJSON(){return de(this,En),Uy(z(this,vn),z(this,ve),"auto")}toLocaleString(e=void 0,t=void 0){return de(this,En),new Jo(e,t).format(this)}valueOf(){yd("PlainDateTime")}toZonedDateTime(e,t=void 0){de(this,En);let r=qi(e),i=Ry(Qe(t));return ii(si(r,z(this,vn),i),r,z(this,ve))}toPlainDate(){return de(this,En),Ji(z(this,vn).isoDate,z(this,ve))}toPlainTime(){return de(this,En),bl(z(this,vn).time)}static from(e,t=void 0){return Ay(e,t)}static compare(e,t){let r=Ay(e),i=Ay(t);return U0(z(r,vn),z(i,vn))}};function Pi(n,e){de(n,En);let t=z(n,vn).isoDate;return iw(n).isoToDate(t,{[e]:!0})[e]}function S0(n,e){return de(n,En),z(n,vn).time[e]}Ll(Yy,"Temporal.PlainDateTime");var zy=class n{constructor(e=0,t=0,r=0,i=0,o=0,s=0,a=0,l=0,c=0,u=0){let d=e===void 0?0:pa(e),h=t===void 0?0:pa(t),f=r===void 0?0:pa(r),p=i===void 0?0:pa(i),w=o===void 0?0:pa(o),y=s===void 0?0:pa(s),v=a===void 0?0:pa(a),B=l===void 0?0:pa(l),U=c===void 0?0:pa(c),k=u===void 0?0:pa(u);DE(d,h,f,p,w,y,v,B,U,k),Dl(this),wt(this,Mi,d),wt(this,Fi,h),wt(this,co,f),wt(this,ki,p),wt(this,Oi,w),wt(this,Gi,y),wt(this,Ni,v),wt(this,Ui,B),wt(this,Hi,U),wt(this,lo,k)}get years(){return de(this,Fn),z(this,Mi)}get months(){return de(this,Fn),z(this,Fi)}get weeks(){return de(this,Fn),z(this,co)}get days(){return de(this,Fn),z(this,ki)}get hours(){return de(this,Fn),z(this,Oi)}get minutes(){return de(this,Fn),z(this,Gi)}get seconds(){return de(this,Fn),z(this,Ni)}get milliseconds(){return de(this,Fn),z(this,Ui)}get microseconds(){return de(this,Fn),z(this,Hi)}get nanoseconds(){return de(this,Fn),z(this,lo)}get sign(){return de(this,Fn),lE(this)}get blank(){return de(this,Fn),lE(this)===0}with(e){de(this,Fn);let t=UN(e),{years:r=z(this,Mi),months:i=z(this,Fi),weeks:o=z(this,co),days:s=z(this,ki),hours:a=z(this,Oi),minutes:l=z(this,Gi),seconds:c=z(this,Ni),milliseconds:u=z(this,Ui),microseconds:d=z(this,Hi),nanoseconds:h=z(this,lo)}=t;return new n(r,i,o,s,a,l,c,u,d,h)}negated(){return de(this,Fn),po(this)}abs(){return de(this,Fn),new n(Math.abs(z(this,Mi)),Math.abs(z(this,Fi)),Math.abs(z(this,co)),Math.abs(z(this,ki)),Math.abs(z(this,Oi)),Math.abs(z(this,Gi)),Math.abs(z(this,Ni)),Math.abs(z(this,Ui)),Math.abs(z(this,Hi)),Math.abs(z(this,lo)))}add(e){return de(this,Fn),aN("add",this,e)}subtract(e){return de(this,Fn),aN("subtract",this,e)}round(e){if(de(this,Fn),e===void 0)throw new TypeError("options parameter is required");let t=yl(this),r=typeof e=="string"?fh("smallestUnit",e):Qe(e),i=fo(r,"largestUnit","datetime",void 0,["auto"]),{plainRelativeTo:o,zonedRelativeTo:s}=rS(r),a=J0(r),l=ya(r,"halfExpand"),c=fo(r,"smallestUnit","datetime",void 0),u=!0;c||(u=!1,c="nanosecond");let d=El(t,c),h=!0;if(i||(h=!1,i=d),i==="auto"&&(i=d),!u&&!h)throw new RangeError("at least one of smallestUnit or largestUnit is required");if(El(i,c)!==i)throw new RangeError(`largestUnit ${i} cannot be smaller than smallestUnit ${c}`);let f={hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[c];if(f!==void 0&&q0(a,f,!1),a>1&&wl(c)==="date"&&i!==c)throw new RangeError("For calendar units with roundingIncrement > 1, use largestUnit = smallestUnit");if(s){let w=B0(this),y=z(s,Xt),v=z(s,ve),B=z(s,it);return w=aU(B,Dy(B,y,v,w),y,v,i,a,c,l),wl(i)==="date"&&(i="hour"),Is(w,i)}if(o){let w=rc(this),y=N0({deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0},w.time),v=z(o,ot),B=z(o,ve),U=qo(B,v,oi(w.date,y.deltaDays),"constrain");return w=sU(Ht(v,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),Ht(U,y),B,i,a,c,l),Is(w,i)}if(tc(t))throw new RangeError(`a starting point is required for ${t}s balancing`);if(tc(i))throw new RangeError(`a starting point is required for ${i}s balancing`);let p=rc(this);if(c==="day"){let{quotient:w,remainder:y}=p.time.divmod(rE),v=p.date.days+w+My(y,"day");v=ud(v,a,l),p=xl({years:0,months:0,weeks:0,days:v},dn.ZERO)}else p=xl({years:0,months:0,weeks:0,days:0},uE(p.time,a,c,l));return Is(p,i)}total(e){if(de(this,Fn),e===void 0)throw new TypeError("options argument is required");let t=typeof e=="string"?fh("unit",e):Qe(e),{plainRelativeTo:r,zonedRelativeTo:i}=rS(t),o=fo(t,"unit","datetime",Cl);if(i){let a=B0(this),l=z(i,Xt),c=z(i,ve),u=z(i,it);return function(d,h,f,p,w){return wl(w)==="time"?My(dn.fromEpochNsDiff(h,d),w):eN(iU(d,h,f,p,w),h,xs(f,d),f,p,w)}(u,Dy(u,l,c,a),l,c,o)}if(r){let a=rc(this),l=N0({deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0},a.time),c=z(r,ot),u=z(r,ve),d=qo(u,c,oi(a.date,l.deltaDays),"constrain");return function(h,f,p,w){if(U0(h,f)==0)return 0;uh(h),uh(f);let y=rU(h,f,p,w);return w==="nanosecond"?ae.default.toNumber(y.time.totalNs):eN(y,Qr(f),h,null,p,w)}(Ht(c,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),Ht(d,l),u,o)}let s=yl(this);if(tc(s))throw new RangeError(`a starting point is required for ${s}s total`);if(tc(o))throw new RangeError(`a starting point is required for ${o}s total`);return My(rc(this).time,o)}toString(e=void 0){de(this,Fn);let t=Qe(e),r=nw(t),i=ya(t,"trunc"),o=fo(t,"smallestUnit","time",void 0);if(o==="hour"||o==="minute")throw new RangeError('smallestUnit must be a time unit other than "hours" or "minutes"');let{precision:s,unit:a,increment:l}=rw(o,r);if(a==="nanosecond"&&l===1)return $I(this,s);let c=yl(this),u=B0(this),d=uE(u.time,l,a,i);return u=xl(u.date,d),$I(Is(u,El(c,"second")),s)}toJSON(){return de(this,Fn),$I(this,"auto")}toLocaleString(e=void 0,t=void 0){if(de(this,Fn),typeof Intl.DurationFormat=="function"){let r=new Intl.DurationFormat(e,t);return i4.call(r,this)}return console.warn("Temporal.Duration.prototype.toLocaleString() requires Intl.DurationFormat."),$I(this,"auto")}valueOf(){yd("Duration")}static from(e){return Es(e)}static compare(e,t,r=void 0){let i=Es(e),o=Es(t),s=Qe(r),{plainRelativeTo:a,zonedRelativeTo:l}=rS(s);if(z(i,Mi)===z(o,Mi)&&z(i,Fi)===z(o,Fi)&&z(i,co)===z(o,co)&&z(i,ki)===z(o,ki)&&z(i,Oi)===z(o,Oi)&&z(i,Gi)===z(o,Gi)&&z(i,Ni)===z(o,Ni)&&z(i,Ui)===z(o,Ui)&&z(i,Hi)===z(o,Hi)&&z(i,lo)===z(o,lo))return 0;let c=yl(i),u=yl(o),d=B0(i),h=B0(o);if(l&&(wl(c)==="date"||wl(u)==="date")){let v=z(l,Xt),B=z(l,ve),U=z(l,it),k=Dy(U,v,B,d),F=Dy(U,v,B,h);return uo(ae.default.toNumber(ae.default.subtract(k,F)))}let f=d.date.days,p=h.date.days;if(tc(c)||tc(u)){if(!a)throw new RangeError("A starting point is required for years, months, or weeks comparison");f=$G(d.date,a),p=$G(h.date,a)}let w=d.time.add24HourDays(f),y=h.time.add24HourDays(p);return w.cmp(y)}};Ll(zy,"Temporal.Duration");var jy=class{constructor(e,t,r="iso8601",i=1972){let o=ut(e),s=ut(t),a=Yi(r===void 0?"iso8601":dr(r)),l=ut(i);lh(l,o,s),qN(this,{year:l,month:o,day:s},a)}get monthCode(){return mN(this,"monthCode")}get day(){return mN(this,"day")}get calendarId(){return de(this,Ho),z(this,ve)}with(e,t=void 0){if(de(this,Ho),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=z(this,ve),i=Qi(r,z(this,ot),"month-day");return i=ch(r,i,Vo(r,e,["year","month","monthCode","day"],[],"partial")),P0(sE(r,i,kt(Qe(t))),r)}equals(e){de(this,Ho);let t=QG(e);return ac(z(this,ot),z(t,ot))===0&&oc(z(this,ve),z(t,ve))}toString(e=void 0){return de(this,Ho),WG(this,tw(Qe(e)))}toJSON(){return de(this,Ho),WG(this)}toLocaleString(e=void 0,t=void 0){return de(this,Ho),new Jo(e,t).format(this)}valueOf(){yd("PlainMonthDay")}toPlainDate(e){if(de(this,Ho),!Gn(e))throw new TypeError("argument should be an object");let t=z(this,ve);return Ji(pd(t,ch(t,Qi(t,z(this,ot),"month-day"),Vo(t,e,["year"],[],[])),"constrain"),t)}static from(e,t=void 0){return QG(e,t)}};function mN(n,e){de(n,Ho);let t=z(n,ot);return iw(n).isoToDate(t,{[e]:!0})[e]}function oS(n){return xs(n,CS())}Ll(jy,"Temporal.PlainMonthDay");var mU={instant:()=>ma(CS()),plainDateTimeISO:(n=wy())=>bs(oS(qi(n)),"iso8601"),plainDateISO:(n=wy())=>Ji(oS(qi(n)).isoDate,"iso8601"),plainTimeISO:(n=wy())=>bl(oS(qi(n)).time),timeZoneId:()=>wy(),zonedDateTimeISO:(n=wy())=>{let e=qi(n);return ii(CS(),e,"iso8601")},[Symbol.toStringTag]:"Temporal.Now"};Object.defineProperty(mU,Symbol.toStringTag,{value:"Temporal.Now",writable:!1,enumerable:!1,configurable:!0});var Wy=class n{constructor(e=0,t=0,r=0,i=0,o=0,s=0){let a=e===void 0?0:ut(e),l=t===void 0?0:ut(t),c=r===void 0?0:ut(r),u=i===void 0?0:ut(i),d=o===void 0?0:ut(o),h=s===void 0?0:ut(s);SE(a,l,c,u,d,h),QN(this,{hour:a,minute:l,second:c,millisecond:u,microsecond:d,nanosecond:h})}get hour(){return de(this,qn),z(this,On).hour}get minute(){return de(this,qn),z(this,On).minute}get second(){return de(this,qn),z(this,On).second}get millisecond(){return de(this,qn),z(this,On).millisecond}get microsecond(){return de(this,qn),z(this,On).microsecond}get nanosecond(){return de(this,qn),z(this,On).nanosecond}with(e,t=void 0){if(de(this,qn),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=mS(e,"partial"),i=mS(this),{hour:o,minute:s,second:a,millisecond:l,microsecond:c,nanosecond:u}=Object.assign(i,r),d=kt(Qe(t));return{hour:o,minute:s,second:a,millisecond:l,microsecond:c,nanosecond:u}=AE(o,s,a,l,c,u,d),new n(o,s,a,l,c,u)}add(e){return de(this,qn),dN("add",this,e)}subtract(e){return de(this,qn),dN("subtract",this,e)}until(e,t=void 0){return de(this,qn),iN("until",this,e,t)}since(e,t=void 0){return de(this,qn),iN("since",this,e,t)}round(e){if(de(this,qn),e===void 0)throw new TypeError("options parameter is required");let t=typeof e=="string"?fh("smallestUnit",e):Qe(e),r=J0(t),i=ya(t,"halfExpand"),o=fo(t,"smallestUnit","time",Cl);return q0(r,{hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[o],!1),bl(AS(z(this,On),r,o,i))}equals(e){de(this,qn);let t=ld(e);return vS(z(this,On),z(t,On))===0}toString(e=void 0){de(this,qn);let t=Qe(e),r=nw(t),i=ya(t,"trunc"),o=fo(t,"smallestUnit","time",void 0);if(o==="hour")throw new RangeError('smallestUnit must be a time unit other than "hour"');let{precision:s,unit:a,increment:l}=rw(o,r);return jG(AS(z(this,On),l,a,i),s)}toJSON(){return de(this,qn),jG(z(this,On),"auto")}toLocaleString(e=void 0,t=void 0){return de(this,qn),new Jo(e,t).format(this)}valueOf(){yd("PlainTime")}static from(e,t=void 0){return ld(e,t)}static compare(e,t){let r=ld(e),i=ld(t);return vS(z(r,On),z(i,On))}};Ll(Wy,"Temporal.PlainTime");var Zy=class{constructor(e,t,r="iso8601",i=1){let o=ut(e),s=ut(t),a=Yi(r===void 0?"iso8601":dr(r)),l=ut(i);lh(o,s,l),VN(this,{year:o,month:s,day:l},a)}get year(){return ml(this,"year")}get month(){return ml(this,"month")}get monthCode(){return ml(this,"monthCode")}get calendarId(){return de(this,qr),z(this,ve)}get era(){return ml(this,"era")}get eraYear(){return ml(this,"eraYear")}get daysInMonth(){return ml(this,"daysInMonth")}get daysInYear(){return ml(this,"daysInYear")}get monthsInYear(){return ml(this,"monthsInYear")}get inLeapYear(){return ml(this,"inLeapYear")}with(e,t=void 0){if(de(this,qr),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=z(this,ve),i=Qi(r,z(this,ot),"year-month");return i=ch(r,i,Vo(r,e,["year","month","monthCode"],[],"partial")),R0(Gy(r,i,kt(Qe(t))),r)}add(e,t=void 0){return de(this,qr),fN("add",this,e,t)}subtract(e,t=void 0){return de(this,qr),fN("subtract",this,e,t)}until(e,t=void 0){return de(this,qr),oN("until",this,e,t)}since(e,t=void 0){return de(this,qr),oN("since",this,e,t)}equals(e){de(this,qr);let t=Cy(e);return ac(z(this,ot),z(t,ot))===0&&oc(z(this,ve),z(t,ve))}toString(e=void 0){return de(this,qr),ZG(this,tw(Qe(e)))}toJSON(){return de(this,qr),ZG(this)}toLocaleString(e=void 0,t=void 0){return de(this,qr),new Jo(e,t).format(this)}valueOf(){yd("PlainYearMonth")}toPlainDate(e){if(de(this,qr),!Gn(e))throw new TypeError("argument should be an object");let t=z(this,ve);return Ji(pd(t,ch(t,Qi(t,z(this,ot),"year-month"),Vo(t,e,["day"],[],[])),"constrain"),t)}static from(e,t=void 0){return Cy(e,t)}static compare(e,t){let r=Cy(e),i=Cy(t);return ac(z(r,ot),z(i,ot))}};function ml(n,e){de(n,qr);let t=z(n,ot);return iw(n).isoToDate(t,{[e]:!0})[e]}Ll(Zy,"Temporal.PlainYearMonth");var Bre=Jo.prototype.resolvedOptions,Xy=class{constructor(e,t,r="iso8601"){if(arguments.length<1)throw new TypeError("missing argument: epochNanoseconds is required");let i=dE(e),o=dr(t),{tzName:s,offsetMinutes:a}=dd(o);if(a===void 0){let l=aE(s);if(!l)throw new RangeError(`unknown time zone ${s}`);o=l.identifier}else o=WS(a);zN(this,i,o,Yi(r===void 0?"iso8601":dr(r)))}get calendarId(){return de(this,It),z(this,ve)}get timeZoneId(){return de(this,It),z(this,Xt)}get year(){return Ri(this,"year")}get month(){return Ri(this,"month")}get monthCode(){return Ri(this,"monthCode")}get day(){return Ri(this,"day")}get hour(){return D0(this,"hour")}get minute(){return D0(this,"minute")}get second(){return D0(this,"second")}get millisecond(){return D0(this,"millisecond")}get microsecond(){return D0(this,"microsecond")}get nanosecond(){return D0(this,"nanosecond")}get era(){return Ri(this,"era")}get eraYear(){return Ri(this,"eraYear")}get epochMilliseconds(){return de(this,It),As(z(this,it),"floor")}get epochNanoseconds(){return de(this,It),cU(z(this,it))}get dayOfWeek(){return Ri(this,"dayOfWeek")}get dayOfYear(){return Ri(this,"dayOfYear")}get weekOfYear(){return Ri(this,"weekOfYear")?.week}get yearOfWeek(){return Ri(this,"weekOfYear")?.year}get hoursInDay(){de(this,It);let e=z(this,Xt),t=ec(this).isoDate,r=ho(t.year,t.month,t.day+1),i=ad(e,t),o=ad(e,r);return My(dn.fromEpochNsDiff(o,i),"hour")}get daysInWeek(){return Ri(this,"daysInWeek")}get daysInMonth(){return Ri(this,"daysInMonth")}get daysInYear(){return Ri(this,"daysInYear")}get monthsInYear(){return Ri(this,"monthsInYear")}get inLeapYear(){return Ri(this,"inLeapYear")}get offset(){return de(this,It),gS(Il(z(this,Xt),z(this,it)))}get offsetNanoseconds(){return de(this,It),Il(z(this,Xt),z(this,it))}with(e,t=void 0){if(de(this,It),!Gn(e))throw new TypeError("invalid zoned-date-time-like");K0(e);let r=z(this,ve),i=z(this,Xt),o=Il(i,z(this,it)),s=ec(this),a={...Qi(r,s.isoDate),...s.time,offset:gS(o)};a=ch(r,a,Vo(r,e,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond","offset"],"partial"));let l=Qe(t),c=Ry(l),u=eE(l,"prefer"),d=ow(r,a,kt(l)),h=Q0(a.offset);return ii(oE(d.isoDate,d.time,"option",h,i,c,u,!1),i,r)}withPlainTime(e=void 0){de(this,It);let t=z(this,Xt),r=z(this,ve),i=ec(this).isoDate,o;return o=e===void 0?ad(t,i):si(t,Ht(i,z(ld(e),On)),"compatible"),ii(o,t,r)}withTimeZone(e){de(this,It);let t=qi(e);return ii(z(this,it),t,z(this,ve))}withCalendar(e){de(this,It);let t=aw(e);return ii(z(this,it),z(this,Xt),t)}add(e,t=void 0){return de(this,It),hN("add",this,e,t)}subtract(e,t=void 0){return de(this,It),hN("subtract",this,e,t)}until(e,t=void 0){return de(this,It),sN("until",this,e,t)}since(e,t=void 0){return de(this,It),sN("since",this,e,t)}round(e){if(de(this,It),e===void 0)throw new TypeError("options parameter is required");let t=typeof e=="string"?fh("smallestUnit",e):Qe(e),r=J0(t),i=ya(t,"halfExpand"),o=fo(t,"smallestUnit","time",Cl,["day"]),s={day:1,hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[o];if(q0(r,s,s===1),o==="nanosecond"&&r===1)return ii(z(this,it),z(this,Xt),z(this,ve));let a=z(this,Xt),l=z(this,it),c=ec(this),u;if(o==="day"){let d=c.isoDate,h=ho(d.year,d.month,d.day+1),f=ad(a,d),p=ad(a,h),w=ae.default.subtract(p,f);u=dn.fromEpochNsDiff(l,f).round(w,i).addToEpochNs(f)}else{let d=xS(c,r,o,i),h=Il(a,l);u=oE(d.isoDate,d.time,"option",h,a,"compatible","prefer",!1)}return ii(u,a,z(this,ve))}equals(e){de(this,It);let t=Sy(e),r=z(this,it),i=z(t,it);return!!ae.default.equal(ae.default.BigInt(r),ae.default.BigInt(i))&&!!jN(z(this,Xt),z(t,Xt))&&oc(z(this,ve),z(t,ve))}toString(e=void 0){de(this,It);let t=Qe(e),r=tw(t),i=nw(t),o=function(h){return Al(h,"offset",["auto","never"],"auto")}(t),s=ya(t,"trunc"),a=fo(t,"smallestUnit","time",void 0);if(a==="hour")throw new RangeError('smallestUnit must be a time unit other than "hour"');let l=function(h){return Al(h,"timeZoneName",["auto","never","critical"],"auto")}(t),{precision:c,unit:u,increment:d}=rw(a,i);return XG(this,c,r,l,o,{unit:u,increment:d,roundingMode:s})}toLocaleString(e=void 0,t=void 0){de(this,It);let r=Qe(t),i=Object.create(null);if(function(l,c,u,d){if(c==null)return;let h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){let p=h[f];if(!u.some(w=>Object.is(w,p))&&Object.prototype.propertyIsEnumerable.call(c,p)){let w=c[p];l[p]=w}}}(i,r,["timeZone"]),r.timeZone!==void 0)throw new TypeError("ZonedDateTime toLocaleString does not accept a timeZone option");if(i.year===void 0&&i.month===void 0&&i.day===void 0&&i.era===void 0&&i.weekday===void 0&&i.dateStyle===void 0&&i.hour===void 0&&i.minute===void 0&&i.second===void 0&&i.fractionalSecondDigits===void 0&&i.timeStyle===void 0&&i.dayPeriod===void 0&&i.timeZoneName===void 0&&(i.timeZoneName="short"),i.timeZone=z(this,Xt),_G(i.timeZone))throw new RangeError("toLocaleString does not currently support offset time zones");let o=new Jo(e,i),s=Bre.call(o).calendar,a=z(this,ve);if(a!=="iso8601"&&s!=="iso8601"&&!oc(s,a))throw new RangeError(`cannot format ZonedDateTime with calendar ${a} in locale with calendar ${s}`);return o.format(ma(z(this,it)))}toJSON(){return de(this,It),XG(this,"auto")}valueOf(){yd("ZonedDateTime")}startOfDay(){de(this,It);let e=z(this,Xt);return ii(ad(e,ec(this).isoDate),e,z(this,ve))}getTimeZoneTransition(e){de(this,It);let t=z(this,Xt);if(e===void 0)throw new TypeError("options parameter is required");let r=Al(typeof e=="string"?fh("direction",e):Qe(e),"direction",["next","previous"],Cl);if(r===void 0)throw new TypeError("direction option is required");if(_G(t)||t==="UTC")return null;let i=z(this,it),o=r==="next"?XS(t,i):wS(t,i);return o===null?null:ii(o,t,z(this,ve))}toInstant(){return de(this,It),ma(z(this,it))}toPlainDate(){return de(this,It),Ji(ec(this).isoDate,z(this,ve))}toPlainTime(){return de(this,It),bl(ec(this).time)}toPlainDateTime(){return de(this,It),bs(ec(this),z(this,ve))}static from(e,t=void 0){return Sy(e,t)}static compare(e,t){let r=Sy(e),i=Sy(t),o=z(r,it),s=z(i,it);return ae.default.lessThan(ae.default.BigInt(o),ae.default.BigInt(s))?-1:ae.default.greaterThan(ae.default.BigInt(o),ae.default.BigInt(s))?1:0}};function ec(n){return xs(z(n,Xt),z(n,it))}function Ri(n,e){de(n,It);let t=ec(n).isoDate;return iw(n).isoToDate(t,{[e]:!0})[e]}function D0(n,e){return de(n,It),ec(n).time[e]}Ll(Xy,"Temporal.ZonedDateTime");var wa=Object.freeze({__proto__:null,Duration:zy,Instant:Qy,Now:mU,PlainDate:Vy,PlainDateTime:Yy,PlainMonthDay:jy,PlainTime:Wy,PlainYearMonth:Zy,ZonedDateTime:Xy}),u6e=class{toTemporalInstant(){return ma(ga(Date.prototype.valueOf.call(this)))}}.prototype.toTemporalInstant,Tre=[Qy,Vy,Yy,zy,jy,Wy,Zy,Xy];for(let n of Tre){let e=Object.getOwnPropertyDescriptor(n,"prototype");(e.configurable||e.enumerable||e.writable)&&(e.configurable=!1,e.enumerable=!1,e.writable=!1,Object.defineProperty(n,"prototype",e))}var eH=$n(vd(),1);var U9=$n(G9());var Bw="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Tw="http://www.w3.org/2001/XMLSchema#",ex="http://www.w3.org/2000/10/swap/",Io={xsd:{decimal:`${Tw}decimal`,boolean:`${Tw}boolean`,double:`${Tw}double`,integer:`${Tw}integer`,string:`${Tw}string`},rdf:{type:`${Bw}type`,nil:`${Bw}nil`,first:`${Bw}first`,rest:`${Bw}rest`,langString:`${Bw}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${ex}reify#forSome`,forAll:`${ex}reify#forAll`},log:{implies:`${ex}log#implies`,isImpliedBy:`${ex}log#isImpliedBy`}};var{xsd:tx}=Io,use=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,N9={"\\":"\\","'":"'",'"':'"',n:`
36
+ `;var N8={...A8,...v8,...C8,...S8,...D8,...L8,...B8,...T8,...P8,...R8},HDe={...O8,...G8};function CO(n,e,t,r){return{name:n,prefix:e,encoder:{name:n,prefix:e,encode:t},decoder:{decode:r}}}var vO=CO("utf8","u",n=>"u"+new TextDecoder("utf8").decode(n),n=>new TextEncoder().encode(n.substring(1))),U8=CO("ascii","a",n=>{let e="a";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return e},n=>{n=n.substring(1);let e=ay(n.length);for(let t=0;t<n.length;t++)e[t]=n.charCodeAt(t);return e}),Ete={utf8:vO,"utf-8":vO,hex:N8.base16,latin1:U8,ascii:U8,binary:U8,...N8},NI=Ete;function dy(n,e="utf8"){let t=NI[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?_f(globalThis.Buffer.from(n,"utf-8")):t.decoder.decode(`${t.prefix}${n}`)}function UI(n,e="utf8"){let t=NI[e];if(!t)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(n.buffer,n.byteOffset,n.byteLength).toString("utf8"):t.encoder.encode(n).substring(1)}var j8=$n(UO(),1);var HO={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},KO={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},JO={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},Yte=Hr(HO.p),zte=Hr(KO.p),jte=Hr(JO.p);var qO=g0({...HO,Fp:Yte,lowS:!1},c0);var yLe=g0({...KO,Fp:zte,lowS:!1},Lk);var wLe=g0({...JO,Fp:jte,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},LI);var JI=qO;var QO=c0;var Wte=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),YO=Uint8Array.from(new Array(16).fill(0).map((n,e)=>e)),Zte=YO.map(n=>(9*n+5)%16),zO=(()=>{let t=[[YO],[Zte]];for(let r=0;r<4;r++)for(let i of t)i.push(i[r].map(o=>Wte[o]));return t})(),jO=zO[0],WO=zO[1],ZO=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(n=>Uint8Array.from(n)),Xte=jO.map((n,e)=>n.map(t=>ZO[e][t])),_te=WO.map((n,e)=>n.map(t=>ZO[e][t])),$te=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),ene=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function VO(n,e,t,r){return n===0?e^t^r:n===1?e&t|~e&r:n===2?(e|~t)^r:n===3?e&r|t&~r:e^(t|~r)}var qI=new Uint32Array(16),QI=class extends Yf{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){let{h0:e,h1:t,h2:r,h3:i,h4:o}=this;return[e,t,r,i,o]}set(e,t,r,i,o){this.h0=e|0,this.h1=t|0,this.h2=r|0,this.h3=i|0,this.h4=o|0}process(e,t){for(let f=0;f<16;f++,t+=4)qI[f]=e.getUint32(t,!0);let r=this.h0|0,i=r,o=this.h1|0,s=o,a=this.h2|0,l=a,c=this.h3|0,u=c,d=this.h4|0,h=d;for(let f=0;f<5;f++){let p=4-f,w=$te[f],y=ene[f],v=jO[f],B=WO[f],U=Xte[f],k=_te[f];for(let F=0;F<16;F++){let P=$g(r+VO(f,o,a,c)+qI[v[F]]+w,U[F])+d|0;r=d,d=c,c=$g(a,10)|0,a=o,o=P}for(let F=0;F<16;F++){let P=$g(i+VO(p,s,l,u)+qI[B[F]]+y,k[F])+h|0;i=h,h=u,u=$g(l,10)|0,l=s,s=P}}this.set(this.h1+a+u|0,this.h2+c+h|0,this.h3+d+i|0,this.h4+r+s|0,this.h0+o+l|0)}roundClean(){Li(qI)}destroy(){this.destroyed=!0,Li(this.buffer),this.set(0,0,0,0,0)}},XO=Zu(()=>new QI);var K8=XO;var tne=BigInt(0),hy=BigInt(1),nne=BigInt(2),rne=BigInt(7),ine=BigInt(256),one=BigInt(113),eG=[],tG=[],nG=[];for(let n=0,e=hy,t=1,r=0;n<24;n++){[t,r]=[r,(2*t+3*r)%5],eG.push(2*(5*r+t)),tG.push((n+1)*(n+2)/2%64);let i=tne;for(let o=0;o<7;o++)e=(e<<hy^(e>>rne)*one)%ine,e&nne&&(i^=hy<<(hy<<BigInt(o))-hy);nG.push(i)}var rG=CI(nG,!0),sne=rG[0],ane=rG[1],_O=(n,e,t)=>t>32?bk(n,e,t):yk(n,e,t),$O=(n,e,t)=>t>32?Ik(n,e,t):wk(n,e,t);function cne(n,e=24){let t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let s=0;s<10;s++)t[s]=n[s]^n[s+10]^n[s+20]^n[s+30]^n[s+40];for(let s=0;s<10;s+=2){let a=(s+8)%10,l=(s+2)%10,c=t[l],u=t[l+1],d=_O(c,u,1)^t[a],h=$O(c,u,1)^t[a+1];for(let f=0;f<50;f+=10)n[s+f]^=d,n[s+f+1]^=h}let i=n[2],o=n[3];for(let s=0;s<24;s++){let a=tG[s],l=_O(i,o,a),c=$O(i,o,a),u=eG[s];i=n[u],o=n[u+1],n[u]=l,n[u+1]=c}for(let s=0;s<50;s+=10){for(let a=0;a<10;a++)t[a]=n[s+a];for(let a=0;a<10;a++)n[s+a]^=~t[(a+2)%10]&t[(a+4)%10]}n[0]^=sne[r],n[1]^=ane[r]}Li(t)}var J8=class n extends Wu{constructor(e,t,r,i=!1,o=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=i,this.rounds=o,ju(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=pk(this.state)}clone(){return this._cloneInto()}keccak(){VC(this.state32),cne(this.state32,this.rounds),VC(this.state32),this.posOut=0,this.pos=0}update(e){nl(this),e=Vf(e),An(e);let{blockLen:t,state:r}=this,i=e.length;for(let o=0;o<i;){let s=Math.min(t-this.pos,i-o);for(let a=0;a<s;a++)r[this.pos++]^=e[o++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:t,pos:r,blockLen:i}=this;e[r]^=t,(t&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){nl(this,!1),An(e),this.finish();let t=this.state,{blockLen:r}=this;for(let i=0,o=e.length;i<o;){this.posOut>=r&&this.keccak();let s=Math.min(r-this.posOut,o-i);e.set(t.subarray(this.posOut,this.posOut+s),i),this.posOut+=s,i+=s}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ju(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(xI(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Li(this.state)}_cloneInto(e){let{blockLen:t,suffix:r,outputLen:i,rounds:o,enableXOF:s}=this;return e||(e=new n(t,r,i,s,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=i,e.enableXOF=s,e.destroyed=this.destroyed,e}},lne=(n,e,t)=>Zu(()=>new J8(e,n,t));var iG=lne(1,136,256/8);var Cne=$n(sG(),1);var une="(?:%[0-9a-fA-F]{2})",aG=`(?:[a-zA-Z0-9._-]|${une})`,dne="([a-z0-9]+)",fne=`((?:${aG}*:)*(${aG}+))`,cG="[a-zA-Z0-9_.:%-]",hne=`;${cG}+=${cG}*`,pne=`((${hne})*)`,mne="(/[^#?]*)?",gne="([?][^#]*)?",yne="(#.*)?",wne=new RegExp(`^did:${dne}:${fne}${pne}${mne}${gne}${yne}$`);function lG(n){if(n===""||!n)return null;let e=n.match(wne);if(e){let t={did:`did:${e[1]}:${e[2]}`,method:e[1],id:e[2],didUrl:n};if(e[4]){let r=e[4].slice(1).split(";");t.params={};for(let i of r){let o=i.split("=");t.params[o[0]]=o[1]}}return e[6]&&(t.path=e[6]),e[7]&&(t.query=e[7].slice(1)),e[8]&&(t.fragment=e[8].slice(1)),t}return null}function hG(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function pG(n,e){return Array.isArray(e)?e.length===0?!0:n?e.every(t=>typeof t=="string"):e.every(t=>Number.isSafeInteger(t)):!1}function bne(n){if(typeof n!="function")throw new Error("function expected");return!0}function my(n,e){if(typeof e!="string")throw new Error(`${n}: string expected`);return!0}function mG(n){if(!Number.isSafeInteger(n))throw new Error(`invalid integer: ${n}`)}function q8(n){if(!Array.isArray(n))throw new Error("array expected")}function gG(n,e){if(!pG(!0,e))throw new Error(`${n}: array of strings expected`)}function yG(n,e){if(!pG(!1,e))throw new Error(`${n}: array of numbers expected`)}function Ine(...n){let e=o=>o,t=(o,s)=>a=>o(s(a)),r=n.map(o=>o.encode).reduceRight(t,e),i=n.map(o=>o.decode).reduce(t,e);return{encode:r,decode:i}}function Ene(n){let e=typeof n=="string"?n.split(""):n,t=e.length;gG("alphabet",e);let r=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(q8(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=t)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${n}`);return e[o]})),decode:i=>(q8(i),i.map(o=>{my("alphabet.decode",o);let s=r.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${n}`);return s}))}}function xne(n=""){return my("join",n),{encode:e=>(gG("join.decode",e),e.join(n)),decode:e=>(my("join.decode",e),e.split(n))}}var wG=(n,e)=>e===0?n:wG(e,n%e),YI=(n,e)=>n+(e-wG(n,e)),VI=(()=>{let n=[];for(let e=0;e<40;e++)n.push(2**e);return n})();function Q8(n,e,t,r){if(q8(n),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(t<=0||t>32)throw new Error(`convertRadix2: wrong to=${t}`);if(YI(e,t)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${t} carryBits=${YI(e,t)}`);let i=0,o=0,s=VI[e],a=VI[t]-1,l=[];for(let c of n){if(mG(c),c>=s)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(i=i<<e|c,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=t;o-=t)l.push((i>>o-t&a)>>>0);let u=VI[o];if(u===void 0)throw new Error("invalid carry");i&=u-1}if(i=i<<t-o&a,!r&&o>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&o>0&&l.push(i>>>0),l}function Ane(n,e=!1){if(mG(n),n<=0||n>32)throw new Error("radix2: bits should be in (0..32]");if(YI(8,n)>32||YI(n,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!hG(t))throw new Error("radix2.encode input should be Uint8Array");return Q8(Array.from(t),8,n,!e)},decode:t=>(yG("radix2.decode",t),Uint8Array.from(Q8(t,n,8,e)))}}function uG(n){return bne(n),function(...e){try{return n.apply(null,e)}catch{}}}var V8=Ine(Ene("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),xne("")),dG=[996825010,642813549,513874426,1027748829,705979059];function py(n){let e=n>>25,t=(n&33554431)<<5;for(let r=0;r<dG.length;r++)(e>>r&1)===1&&(t^=dG[r]);return t}function fG(n,e,t=1){let r=n.length,i=1;for(let o=0;o<r;o++){let s=n.charCodeAt(o);if(s<33||s>126)throw new Error(`Invalid prefix (${n})`);i=py(i)^s>>5}i=py(i);for(let o=0;o<r;o++)i=py(i)^n.charCodeAt(o)&31;for(let o of e)i=py(i)^o;for(let o=0;o<6;o++)i=py(i);return i^=t,V8.encode(Q8([i%VI[30]],30,5,!1))}function vne(n){let e=n==="bech32"?1:734539939,t=Ane(5),r=t.decode,i=t.encode,o=uG(r);function s(d,h,f=90){my("bech32.encode prefix",d),hG(h)&&(h=Array.from(h)),yG("bech32.encode",h);let p=d.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);let w=p+7+h.length;if(f!==!1&&w>f)throw new TypeError(`Length ${w} exceeds limit ${f}`);let y=d.toLowerCase(),v=fG(y,h,e);return`${y}1${V8.encode(h)}${v}`}function a(d,h=90){my("bech32.decode input",d);let f=d.length;if(f<8||h!==!1&&f>h)throw new TypeError(`invalid string length: ${f} (${d}). Expected (8..${h})`);let p=d.toLowerCase();if(d!==p&&d!==d.toUpperCase())throw new Error("String must be lowercase or uppercase");let w=p.lastIndexOf("1");if(w===0||w===-1)throw new Error('Letter "1" must be present between prefix and data only');let y=p.slice(0,w),v=p.slice(w+1);if(v.length<6)throw new Error("Data must be at least 6 characters long");let B=V8.decode(v).slice(0,-6),U=fG(y,B,e);if(!v.endsWith(U))throw new Error(`Invalid checksum in ${d}: expected "${U}"`);return{prefix:y,words:B}}let l=uG(a);function c(d){let{prefix:h,words:f}=a(d,!1);return{prefix:h,words:f,bytes:r(f)}}function u(d,h){return s(d,i(h))}return{encode:s,decode:a,encodeFromBytes:u,decodeToBytes:c,decodeUnsafe:l,fromWords:r,fromWordsUnsafe:o,toWords:i}}var Y8=vne("bech32");var fa={toString:UI,fromString:dy,concat:w8};function Sne(n){return fa.toString(n,"base64url")}function ws(n){let e=n.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");return fa.fromString(e,"base64url")}function AG(n){return fa.fromString(n,"base58btc")}function Dne(n){return fa.toString(n,"base58btc")}var zI={Secp256k1SignatureVerificationKey2018:"Secp256k1",Secp256k1VerificationKey2018:"Secp256k1",EcdsaSecp256k1VerificationKey2019:"Secp256k1",EcdsaPublicKeySecp256k1:"Secp256k1",EcdsaSecp256k1RecoveryMethod2020:"Secp256k1",EcdsaSecp256r1VerificationKey2019:"P-256",Ed25519VerificationKey2018:"Ed25519",Ed25519VerificationKey2020:"Ed25519",ED25519SignatureVerification:"Ed25519",X25519KeyAgreementKey2019:"X25519",X25519KeyAgreementKey2020:"X25519",ConditionalProof2022:void 0,JsonWebKey2020:void 0,Multikey:void 0},Lne={"ed25519-pub":237,"x25519-pub":236,"secp256k1-pub":231,"bls12_381-g1-pub":234,"bls12_381-g2-pub":235,"p256-pub":4608},Bne={"bls12_381-g1-pub":"Bls12381G1","bls12_381-g2-pub":"Bls12381G2","ed25519-pub":"Ed25519","p256-pub":"P-256","secp256k1-pub":"Secp256k1","x25519-pub":"X25519"};function WI(n){if(n.publicKeyBase58)return{keyBytes:AG(n.publicKeyBase58),keyType:zI[n.type]};if(n.publicKeyBase64)return{keyBytes:ws(n.publicKeyBase64),keyType:zI[n.type]};if(n.publicKeyHex)return{keyBytes:x0(n.publicKeyHex),keyType:zI[n.type]};if(n.publicKeyJwk&&n.publicKeyJwk.crv==="secp256k1"&&n.publicKeyJwk.x&&n.publicKeyJwk.y)return{keyBytes:No.ProjectivePoint.fromAffine({x:jI(ws(n.publicKeyJwk.x)),y:jI(ws(n.publicKeyJwk.y))}).toRawBytes(!1),keyType:"Secp256k1"};if(n.publicKeyJwk&&n.publicKeyJwk.crv==="P-256"&&n.publicKeyJwk.x&&n.publicKeyJwk.y)return{keyBytes:JI.ProjectivePoint.fromAffine({x:jI(ws(n.publicKeyJwk.x)),y:jI(ws(n.publicKeyJwk.y))}).toRawBytes(!1),keyType:"P-256"};if(n.publicKeyJwk&&n.publicKeyJwk.kty==="OKP"&&["Ed25519","X25519"].includes(n.publicKeyJwk.crv??"")&&n.publicKeyJwk.x)return{keyBytes:ws(n.publicKeyJwk.x),keyType:n.publicKeyJwk.crv};if(n.publicKeyMultibase){let{keyBytes:e,keyType:t}=Tne(n.publicKeyMultibase);return{keyBytes:e,keyType:t??zI[n.type]}}return{keyBytes:new Uint8Array}}function Tne(n){let e=(0,j8.decode)(n);if([32,33,48,64,65,96].includes(e.length))return{keyBytes:e};try{let[t,r]=th.decode(e),i=Object.entries(Lne).filter(([,o])=>o===t)?.[0][0]??"";return{keyBytes:e.slice(r),keyType:Bne[i]}}catch{return{keyBytes:e}}}function x0(n,e){let t=n.startsWith("0x")?n.substring(2):n;if(t.length%2!==0&&(t=`0${t}`),e){let r=Math.max(t.length,e*2);t=t.padStart(r,"00")}return fa.fromString(t.toLowerCase(),"base16")}function Pne(n){return fa.toString(ws(n))}function id(n){return fa.toString(n,"base16")}function jI(n){return BigInt("0x"+fa.toString(n,"base16"))}function Rne(n){return fa.fromString(n,"utf-8")}function W8({r:n,s:e,recoveryParam:t},r){let i=new Uint8Array(r?65:64);if(i.set(fa.fromString(n,"base16"),0),i.set(fa.fromString(e,"base16"),32),r){if(typeof t>"u")throw new Error("Signer did not return a recoveryParam");i[64]=t}return Sne(i)}function Mne(n){let e=ws(n);if(e.length<64||e.length>65)throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${e.length}`);let t=id(e.slice(0,32)),r=id(e.slice(32,64)),i=e.length===65?e[64]:void 0;return{r:t,s:r,recoveryParam:i}}function bG(n,e=64){return n.length===e?n:"0".repeat(e-n.length)+n}function od(n){let e=typeof n=="string"?dy(n):n;return QO(e)}var Fne=iG;function vG(n){let e=dy(n.slice(2),"base16");return`0x${UI(Fne(e).slice(-20),"base16")}`}function CG(n,e=!1){let t=n;if(t.length!==32)throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${t.length}`);return function(r){try{let i=No.sign(od(r),t);return Promise.resolve(W8({r:bG(i.r.toString(16)),s:bG(i.s.toString(16)),recoveryParam:i.recovery},e))}catch(i){return Promise.reject(i)}}}function Z8(n){return typeof n=="object"&&"r"in n&&"s"in n}function kne(){return function(e,t){try{return Promise.resolve(t(e)).then(function(r){return Z8(r)?W8(r):r})}catch(r){return Promise.reject(r)}}}function IG(n){return function(t,r){try{return Promise.resolve(r(t)).then(function(i){if(Z8(i))return W8(i,n);if(n&&typeof Mne(i).recoveryParam>"u")throw new Error("not_supported: ES256K-R not supported when signer doesn't provide a recovery param");return i})}catch(i){return Promise.reject(i)}}}function EG(){return function(e,t){try{return Promise.resolve(t(e)).then(function(r){if(Z8(r))throw new Error("invalid_config: expected a signer function that returns a string instead of signature object");return r})}catch(r){return Promise.reject(r)}}}var WLe={ES256:kne(),ES256K:IG(),"ES256K-R":IG(!0),Ed25519:EG(),EdDSA:EG()};function One(n,e){let t=id(AG(e).slice(0,1)),r=x0(n),i=K8(od(r)),o=t+id(i),s=od(x0(o)),a=od(s),l=id(a).substring(0,8),c=o+l;return Dne(x0(c))}function Gne(n,e){let t=No.ProjectivePoint.fromHex(n).toRawBytes(),r=K8(od(t)),i=Y8.toWords(r);return Y8.encode(e,i).replace(e,"")}function Nne(n,e){if(e){let t=e.split(":");switch(t[0]){case"bip122":t[t.length-1]=One(n,t[t.length-1]);break;case"cosmos":t[t.length-1]=Gne(n,t[1]);break;case"eip155":t[t.length-1]=vG(n);break;default:return!1}return t.join(":").toLowerCase()===e.toLowerCase()}return!1}function Une(n,e=!1){let t=ws(n);if(t.length!==(e?65:64))throw new Error("wrong signature length");let r=id(t.slice(0,32)),i=id(t.slice(32,64)),o={r,s:i};return e&&(o.recoveryParam=t[64]),o}function z8(n,e=!1){let t=ws(n);if(t.length!==(e?65:64))throw new Error("wrong signature length");return{compact:t.slice(0,64),recovery:t[64]}}function Hne(n,e,t){let r=od(n),i=JI.Signature.fromCompact(z8(e).compact),s=t.filter(a=>!a.ethereumAddress&&!a.blockchainAccountId).find(a=>{try{let{keyBytes:l}=WI(a);return JI.verify(i,r,l)}catch{return!1}});if(!s)throw new Error("invalid_signature: Signature invalid for JWT");return s}function Kne(n,e,t){let r=od(n),i=No.Signature.fromCompact(ws(e)).normalizeS(),o=t.filter(l=>!l.ethereumAddress&&!l.blockchainAccountId),s=t.filter(l=>l.ethereumAddress||l.blockchainAccountId),a=o.find(l=>{try{let{keyBytes:c}=WI(l);return No.verify(i,r,c)}catch{return!1}});if(!a&&s.length>0&&(a=SG(n,e,s)),!a)throw new Error("invalid_signature: Signature invalid for JWT");return a}function SG(n,e,t){let r=[];if(e.length>86)r.push(z8(e,!0));else{let s=z8(e,!1);r.push({...s,recovery:0}),r.push({...s,recovery:1})}let i=od(n),o=s=>{let l=No.Signature.fromCompact(s.compact).addRecoveryBit(s.recovery||0).recoverPublicKey(i),c=vG(l.toHex(!1)).toLowerCase(),u=l.toHex(!1),d=l.toHex(!0);return t.find(h=>{let{keyBytes:f}=WI(h),p=id(f);return p===u||p===d||h.ethereumAddress?.toLowerCase()===c||h.blockchainAccountId?.split("@eip155")?.[0].toLowerCase()===c||Nne(u,h.blockchainAccountId)})};for(let s of r){let a=o(s);if(a)return a}throw new Error("invalid_signature: Signature invalid for JWT")}function xG(n,e,t){let r=Rne(n),i=ws(e),o=t.find(s=>{let{keyBytes:a,keyType:l}=WI(s);return l==="Ed25519"?Ar.verify(i,r,a):!1});if(!o)throw new Error("invalid_signature: Signature invalid for JWT");return o}var Jne={ES256:Hne,ES256K:Kne,"ES256K-R":SG,Ed25519:xG,EdDSA:xG};function DG(n){let e=Jne[n];if(!e)throw new Error(`not_supported: Unsupported algorithm ${n}`);return e}DG.toSignatureObject=Une;var ZLe=typeof Symbol<"u"?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function qne(n){let e=n.match(/^([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)\.([a-zA-Z0-9_-]+)$/);if(e)return{header:JSON.parse(Pne(e[1])),payload:e[2],signature:e[3],data:`${e[1]}.${e[2]}`};throw new Error("invalid_argument: Incorrect format JWS")}function Qne({header:n,data:e,signature:t},r){return Array.isArray(r)||(r=[r]),DG(n.alg)(e,t,r)}function LG(n,e){let t=qne(n);return Qne(t,e)}var XLe=typeof Symbol<"u"?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";var X8=class{keyType;_keyStore;constructor(e,t){if(e!=="Secp256k1")throw new Error("Key type must be Secp256k1");this.keyType=e,this._keyStore=t}async list(){return(await this._keyStore.list()).filter(t=>t.alias.startsWith(this.keyType))}async newPrivateKeyFromSeed(e){if(e.length!==32)throw new Error("Seed should be 32 bytes");let t=No.getPublicKey(e),r={type:this.keyType,id:qs(this.keyType,xi(t))};return await this._keyStore.importKey({alias:r.id,key:xi(e).padStart(64,"0")}),r}async publicKey(e){let t=await this.privateKey(e),r=No.getPublicKey(t,!1);return xi(r)}async sign(e,t,r={alg:"ES256K"}){let i=await this.privateKey(e),o=await CG(x0(i),r.alg==="ES256K-R")(t);if(typeof o!="string")throw new Error("signatureBase64 must be a string");return jd(o)}async verify(e,t,r){let i=await this.publicKey(r);return No.verify(t,Pc(e),i)}async privateKey(e){return this._keyStore.get({alias:e.id})}};var Fe=Object.freeze({ERRORS:{FiELD_IS_EMPTY:"fieldPath is empty",CONTEXT_TYPE_IS_EMPTY:"ctxType is empty",IDENTITY_DOES_NOT_EXIST:"Identity does not exist",IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR:"IdentityDoesNotExist",NO_AUTH_CRED_FOUND:"no auth credentials found",STATE_DOES_NOT_EXIST:"State does not exist",STATE_DOES_NOT_EXIST_CUSTOM_ERROR:"StateDoesNotExist",ROOT_DOES_NOT_EXIST:"Root does not exist",ROOT_DOES_NOT_EXIST_CUSTOM_ERROR:"RootDoesNotExist",ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY:"no credential satisfied query",ID_WALLET_SIGNER_IS_REQUIRED:"Ethereum signer is required to create Ethereum identities in order to transit state",ID_WALLET_PROVER_IS_REQUIRED:"prover is required to generate proofs for non ethereum identities",ID_WALLET_CORE_CLAIM_REQUIRED_IN_SIG_PROOF:"credential must have coreClaim representation in the signature proof",ID_WALLET_CORE_CLAIM_REQUIRED_IN_ANY_PROOF:"credential must have coreClaim representation in proofs",ID_WALLET_CORE_CLAIM_MISMATCH:"core claim representations is set in both proofs but they are not equal",ID_WALLET_CORE_CLAIM_IS_NOT_SET:"core claim is not set in credential proofs",ID_WALLET_PROFILE_OR_IDENTITY_NOT_FOUND:"profile or identity not found",ID_WALLET_PROFILE_ALREADY_EXISTS:"profile with given nonce or verifier already exists",ID_WALLET_PROFILE_ALREADY_EXISTS_VERIFIER_TAGS:"profile with given verifier and tags already exists",ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_ANY_PROOF:"issuer auth credential must have proof",ID_WALLET_ISSUER_AUTH_BJJ_CRED_MUST_HAVE_MTP_PROOF:"mtp is required for auth bjj key to issue new credentials",PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE:"no credentials belong to did or its profiles",PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY:"credential not found for query",PROOF_SERVICE_PROFILE_GENESIS_DID_MISMATCH:"subject and auth profiles are not derived from the same did",PROOF_SERVICE_NO_QUERIES_IN_ZKP_REQUEST:"no queries in zkp request",CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED:"all claims are revoked"},CREDENTIAL_TYPE:{W3C_VERIFIABLE_CREDENTIAL:"VerifiableCredential",W3C_VERIFIABLE_PRESENTATION:"VerifiablePresentation"},CREDENTIAL_SUBJECT_PATH:"https://www.w3.org/2018/credentials#credentialSubject",JSONLD_SCHEMA:{IDEN3_CREDENTIAL:"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld",IDEN3_DISPLAY_METHOD:"https://schema.iden3.io/core/jsonld/displayMethod.jsonld",W3C_CREDENTIAL_2018:"https://www.w3.org/2018/credentials/v1",W3C_VC_DOCUMENT_2018:'{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","VerifiableCredential":{"@id":"https://www.w3.org/2018/credentials#VerifiableCredential","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","credentialSchema":{"@id":"cred:credentialSchema","@type":"@id","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","JsonSchemaValidator2018":"cred:JsonSchemaValidator2018"}},"credentialStatus":{"@id":"cred:credentialStatus","@type":"@id"},"credentialSubject":{"@id":"cred:credentialSubject","@type":"@id"},"evidence":{"@id":"cred:evidence","@type":"@id"},"expirationDate":{"@id":"cred:expirationDate","@type":"xsd:dateTime"},"holder":{"@id":"cred:holder","@type":"@id"},"issued":{"@id":"cred:issued","@type":"xsd:dateTime"},"issuer":{"@id":"cred:issuer","@type":"@id"},"issuanceDate":{"@id":"cred:issuanceDate","@type":"xsd:dateTime"},"proof":{"@id":"sec:proof","@type":"@id","@container":"@graph"},"refreshService":{"@id":"cred:refreshService","@type":"@id","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","ManualRefreshService2018":"cred:ManualRefreshService2018"}},"termsOfUse":{"@id":"cred:termsOfUse","@type":"@id"},"validFrom":{"@id":"cred:validFrom","@type":"xsd:dateTime"},"validUntil":{"@id":"cred:validUntil","@type":"xsd:dateTime"}}},"VerifiablePresentation":{"@id":"https://www.w3.org/2018/credentials#VerifiablePresentation","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","cred":"https://www.w3.org/2018/credentials#","sec":"https://w3id.org/security#","holder":{"@id":"cred:holder","@type":"@id"},"proof":{"@id":"sec:proof","@type":"@id","@container":"@graph"},"verifiableCredential":{"@id":"cred:verifiableCredential","@type":"@id","@container":"@graph"}}},"EcdsaSecp256k1Signature2019":{"@id":"https://w3id.org/security#EcdsaSecp256k1Signature2019","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"EcdsaSecp256r1Signature2019":{"@id":"https://w3id.org/security#EcdsaSecp256r1Signature2019","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"Ed25519Signature2018":{"@id":"https://w3id.org/security#Ed25519Signature2018","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","xsd":"http://www.w3.org/2001/XMLSchema#","challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"RsaSignature2018":{"@id":"https://w3id.org/security#RsaSignature2018","@context":{"@version":1.1,"@protected":true,"challenge":"sec:challenge","created":{"@id":"http://purl.org/dc/terms/created","@type":"xsd:dateTime"},"domain":"sec:domain","expires":{"@id":"sec:expiration","@type":"xsd:dateTime"},"jws":"sec:jws","nonce":"sec:nonce","proofPurpose":{"@id":"sec:proofPurpose","@type":"@vocab","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","assertionMethod":{"@id":"sec:assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"sec:authenticationMethod","@type":"@id","@container":"@set"}}},"proofValue":"sec:proofValue","verificationMethod":{"@id":"sec:verificationMethod","@type":"@id"}}},"proof":{"@id":"https://w3id.org/security#proof","@type":"@id","@container":"@graph"}}}',IDEN3_PROOFS_DEFINITION_DOCUMENT:'{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","Iden3SparseMerkleTreeProof":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3SparseMerkleTreeProof","@context":{"@version":1.1,"@protected":true,"@propagate":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","@vocab":"https://schema.iden3.io/core/vocab/Iden3SparseMerkleTreeProof.md#","xsd":"http://www.w3.org/2001/XMLSchema#","mtp":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#SparseMerkleTreeProof","@type":"SparseMerkleTreeProof"},"coreClaim":{"@id":"coreClaim","@type":"xsd:string"},"issuerData":{"@id":"issuerData","@context":{"@version":1.1,"state":{"@id":"state","@context":{"txId":{"@id":"txId","@type":"xsd:string"},"blockTimestamp":{"@id":"blockTimestamp","@type":"xsd:integer"},"blockNumber":{"@id":"blockNumber","@type":"xsd:integer"},"rootOfRoots":{"@id":"rootOfRoots","@type":"xsd:string"},"claimsTreeRoot":{"@id":"claimsTreeRoot","@type":"xsd:string"},"revocationTreeRoot":{"@id":"revocationTreeRoot","@type":"xsd:string"},"authCoreClaim":{"@id":"authCoreClaim","@type":"xsd:string"},"value":{"@id":"value","@type":"xsd:string"}}}}}}},"SparseMerkleTreeProof":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#SparseMerkleTreeProof","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","sec":"https://w3id.org/security#","smt-proof-vocab":"https://schema.iden3.io/core/vocab/SparseMerkleTreeProof.md#","xsd":"http://www.w3.org/2001/XMLSchema#","existence":{"@id":"smt-proof-vocab:existence","@type":"xsd:boolean"},"revocationNonce":{"@id":"smt-proof-vocab:revocationNonce","@type":"xsd:number"},"siblings":{"@id":"smt-proof-vocab:siblings","@container":"@list"},"nodeAux":"@nest","hIndex":{"@id":"smt-proof-vocab:hIndex","@nest":"nodeAux","@type":"xsd:string"},"hValue":{"@id":"smt-proof-vocab:hValue","@nest":"nodeAux","@type":"xsd:string"}}},"BJJSignature2021":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#BJJSignature2021","@context":{"@version":1.1,"@protected":true,"id":"@id","@vocab":"https://schema.iden3.io/core/vocab/BJJSignature2021.md#","@propagate":true,"type":"@type","xsd":"http://www.w3.org/2001/XMLSchema#","coreClaim":{"@id":"coreClaim","@type":"xsd:string"},"issuerData":{"@id":"issuerData","@context":{"@version":1.1,"authCoreClaim":{"@id":"authCoreClaim","@type":"xsd:string"},"mtp":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#SparseMerkleTreeProof","@type":"SparseMerkleTreeProof"},"revocationStatus":{"@id":"revocationStatus","@type":"@id"},"state":{"@id":"state","@context":{"@version":1.1,"rootOfRoots":{"@id":"rootOfRoots","@type":"xsd:string"},"claimsTreeRoot":{"@id":"claimsTreeRoot","@type":"xsd:string"},"revocationTreeRoot":{"@id":"revocationTreeRoot","@type":"xsd:string"},"value":{"@id":"value","@type":"xsd:string"}}}}},"signature":{"@id":"signature","@type":"https://w3id.org/security#multibase"},"domain":"https://w3id.org/security#domain","creator":{"@id":"creator","@type":"http://www.w3.org/2001/XMLSchema#string"},"challenge":"https://w3id.org/security#challenge","created":{"@id":"created","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},"expires":{"@id":"https://w3id.org/security#expiration","@type":"http://www.w3.org/2001/XMLSchema#dateTime"},"nonce":"https://w3id.org/security#nonce","proofPurpose":{"@id":"https://w3id.org/security#proofPurpose","@type":"@vocab","@context":{"@protected":true,"id":"@id","type":"@type","assertionMethod":{"@id":"https://w3id.org/security#assertionMethod","@type":"@id","@container":"@set"},"authentication":{"@id":"https://w3id.org/security#authenticationMethod","@type":"@id","@container":"@set"},"capabilityInvocation":{"@id":"https://w3id.org/security#capabilityInvocationMethod","@type":"@id","@container":"@set"},"capabilityDelegation":{"@id":"https://w3id.org/security#capabilityDelegationMethod","@type":"@id","@container":"@set"},"keyAgreement":{"@id":"https://w3id.org/security#keyAgreementMethod","@type":"@id","@container":"@set"}}},"proofValue":{"@id":"https://w3id.org/security#proofValue","@type":"https://w3id.org/security#multibase"},"verificationMethod":{"@id":"https://w3id.org/security#verificationMethod","@type":"@id"}}},"Iden3ReverseSparseMerkleTreeProof":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3ReverseSparseMerkleTreeProof","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3-reverse-sparse-merkle-tree-proof-vocab":"https://schema.iden3.io/core/vocab/Iden3ReverseSparseMerkleTreeProof.md#","xsd":"http://www.w3.org/2001/XMLSchema#","revocationNonce":{"@id":"iden3-reverse-sparse-merkle-tree-proof-vocab:revocationNonce","@type":"xsd:integer"},"statusIssuer":{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type"},"@id":"iden3-reverse-sparse-merkle-tree-proof-vocab:statusIssuer"}}},"Iden3commRevocationStatusV1.0":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3commRevocationStatusV1.0","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3-comm-revocation-statusV1.0-vocab":"https://schema.iden3.io/core/vocab/Iden3commRevocationStatusV1.0.md#","xsd":"http://www.w3.org/2001/XMLSchema#","revocationNonce":{"@id":"iden3-comm-revocation-statusV1.0-vocab:revocationNonce","@type":"xsd:integer"},"statusIssuer":{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type"},"@id":"iden3-comm-revocation-statusV1.0-vocab:statusIssuer"}}},"Iden3OnchainSparseMerkleTreeProof2023":{"@id":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3OnchainSparseMerkleTreeProof2023","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3-onchain-sparse-merkle-tree-proof-2023-vocab":"https://schema.iden3.io/core/vocab/Iden3OnchainSparseMerkleTreeProof2023.md#","xsd":"http://www.w3.org/2001/XMLSchema#","revocationNonce":{"@id":"iden3-onchain-sparse-merkle-tree-proof-2023-vocab:revocationNonce","@type":"xsd:integer"},"statusIssuer":{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type"},"@id":"iden3-onchain-sparse-merkle-tree-proof-2023-vocab:statusIssuer"}}},"JsonSchema2023":"https://www.w3.org/ns/credentials#JsonSchema2023","Iden3RefreshService2023":"https://schema.iden3.io/core/jsonld/iden3proofs.jsonld#Iden3RefreshService2023"}}',IDEN3_DISPLAY_METHOD_DEFINITION_DOCUMENT:'{"@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","displayMethod":{"@id":"https://schema.iden3.io/core/vocab/displayMethod.md#displayMethod","@type":"@id","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","Iden3BasicDisplayMethodV1":"https://schema.iden3.io/core/vocab/displayMethod.md#Iden3BasicDisplayMethodV1"}}}}'},JSON_SCHEMA_VALIDATOR:"JsonSchema2023",SERVICE_TYPE:{IDEN3_COMM:"iden3-communication",PUSH_NOTIFICATION:"push-notification"},AUTH:{AUTH_BJJ_CREDENTIAL_HASH:"013fd3f623559d850fb5b02ff012d0e2",AUTH_BJJ_CREDENTIAL_SCHEMA_JSON_URL:"https://schema.iden3.io/core/json/auth.json",AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL:"https://schema.iden3.io/core/jsonld/auth.jsonld",AUTH_BJJ_CREDENTIAL_TYPE:"AuthBJJCredential",AUTH_BJJ_CREDENTIAL_SCHEMA_JSON:'{"$schema":"http://json-schema.org/draft-07/schema#","$metadata":{"uris":{"jsonLdContext":"https://schema.iden3.io/core/jsonld/auth.jsonld","jsonSchema":"https://schema.iden3.io/core/json/auth.json"},"serialization":{"indexDataSlotA":"x","indexDataSlotB":"y"}},"type":"object","required":["@context","id","type","issuanceDate","credentialSubject","credentialSchema","credentialStatus","issuer"],"properties":{"@context":{"type":["string","array","object"]},"id":{"type":"string"},"type":{"type":["string","array"],"items":{"type":"string"}},"issuer":{"type":["string","object"],"format":"uri","required":["id"],"properties":{"id":{"type":"string","format":"uri"}}},"issuanceDate":{"type":"string","format":"date-time"},"expirationDate":{"type":"string","format":"date-time"},"credentialSchema":{"type":"object","required":["id","type"],"properties":{"id":{"type":"string","format":"uri"},"type":{"type":"string"}}},"credentialSubject":{"type":"object","required":["x","y"],"properties":{"id":{"title":"Credential Subject ID","type":"string","format":"uri"},"x":{"type":"string"},"y":{"type":"string"}}}}}',AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD:'{"@context":[{"@version":1.1,"@protected":true,"id":"@id","type":"@type","AuthBJJCredential":{"@id":"https://schema.iden3.io/core/jsonld/auth.jsonld#AuthBJJCredential","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","iden3_serialization":"iden3:v1:slotIndexA=x&slotIndexB=y","xsd":"http://www.w3.org/2001/XMLSchema#","auth-vocab":"https://schema.iden3.io/core/vocab/auth.md#","x":{"@id":"auth-vocab:x","@type":"xsd:positiveInteger"},"y":{"@id":"auth-vocab:y","@type":"xsd:positiveInteger"}}},"Iden3StateInfo2023":{"@id":"https://schema.iden3.io/core/jsonld/auth.jsonld#Iden3StateInfo2023","@context":{"@version":1.1,"@protected":true,"id":"@id","type":"@type","xsd":"http://www.w3.org/2001/XMLSchema#","@vocab":"https://schema.iden3.io/core/vocab/state-info.md#","@propagate":true,"stateContractAddress":{"@id":"stateContractAddress","@type":"xsd:string"},"published":{"@id":"published","@type":"xsd:boolean"},"info":{"@id":"info","@type":"@id","@context":{"@protected":true,"id":{"@id":"id","@type":"xsd:string"},"state":{"@id":"state","@type":"xsd:string"},"replacedByState":{"@id":"replacedByState","@type":"xsd:string"},"createdAtTimestamp":{"@id":"createdAtTimestamp","@type":"xsd:string"},"replacedAtTimestamp":{"@id":"replacedAtTimestamp","@type":"xsd:string"},"createdAtBlock":{"@id":"createdAtBlock","@type":"xsd:string"},"replacedAtBlock":{"@id":"replacedAtBlock","@type":"xsd:string"}}},"global":{"@id":"global","@type":"@id","@context":{"@protected":true,"sec":"https://w3id.org/security#","root":{"@id":"root","@type":"xsd:string"},"replacedByRoot":{"@id":"replacedByRoot","@type":"xsd:string"},"createdAtTimestamp":{"@id":"createdAtTimestamp","@type":"xsd:string"},"replacedAtTimestamp":{"@id":"replacedAtTimestamp","@type":"xsd:string"},"createdAtBlock":{"@id":"createdAtBlock","@type":"xsd:string"},"replacedAtBlock":{"@id":"replacedAtBlock","@type":"xsd:string"},"proof":{"@id":"sec:proof","@type":"@id","@container":"@graph"}}}}}}]}'}}),gy=(t=>(t.BJJSignature="BJJSignature2021",t.Iden3SparseMerkleTreeProof="Iden3SparseMerkleTreeProof",t))(gy||{}),A0=(i=>(i.SparseMerkleTreeProof="SparseMerkleTreeProof",i.Iden3ReverseSparseMerkleTreeProof="Iden3ReverseSparseMerkleTreeProof",i.Iden3commRevocationStatusV1="Iden3commRevocationStatusV1.0",i.Iden3OnchainSparseMerkleTreeProof2023="Iden3OnchainSparseMerkleTreeProof2023",i))(A0||{}),BG=(e=>(e.Authentication="Authentication",e))(BG||{}),ZI=(r=>(r.Index="index",r.Value="value",r.None="",r))(ZI||{}),XI=(r=>(r.None="",r.Index="index",r.Value="value",r))(XI||{}),_8=(e=>(e.Iden3RefreshService2023="Iden3RefreshService2023",e))(_8||{}),TG=(r=>(r.Iden3PaymentRequestCryptoV1="Iden3PaymentRequestCryptoV1",r.Iden3PaymentRailsRequestV1="Iden3PaymentRailsRequestV1",r.Iden3PaymentRailsERC20RequestV1="Iden3PaymentRailsERC20RequestV1",r))(TG||{}),PG=(r=>(r.Iden3PaymentCryptoV1="Iden3PaymentCryptoV1",r.Iden3PaymentRailsV1="Iden3PaymentRailsV1",r.Iden3PaymentRailsERC20V1="Iden3PaymentRailsERC20V1",r))(PG||{}),RG=(e=>(e.EthereumEip712Signature2021="EthereumEip712Signature2021",e))(RG||{}),MG=(o=>(o.ETH="ETH",o.ETH_WEI="ETHWEI",o.ETH_GWEI="ETHGWEI",o.MATIC="MATIC",o.POL="POL",o))(MG||{}),FG=(e=>(e.EIP_2612="EIP-2612",e))(FG||{}),_I=(e=>(e.Iden3BasicDisplayMethodV1="Iden3BasicDisplayMethodV1",e))(_I||{}),v0=1e4;var ha=class n{type;issuerData;mtp;coreClaim;constructor(e){this.coreClaim=e.coreClaim,this.issuerData=e.issuerData,this.type="Iden3SparseMerkleTreeProof",this.mtp=e.mtp}toJSON(){return{issuerData:{id:this.issuerData.id.string(),state:{...this.issuerData.state,rootOfRoots:this.issuerData.state.rootOfRoots.hex(),claimsTreeRoot:this.issuerData.state.claimsTreeRoot.hex(),revocationTreeRoot:this.issuerData.state.revocationTreeRoot.hex(),value:this.issuerData.state.value.hex()}},type:this.type,coreClaim:this.coreClaim.hex(),mtp:this.mtp.toJSON()}}static fromJSON(e){let t;if(e?.mtp?.notEmpties&&e?.mtp?.depth&&e?.mtp?.siblings){let r=e?.mtp?.notEmpties,i=r instanceof Uint8Array?r:new Uint8Array(Object.values(r)),o=e?.mtp?.siblings.map(l=>me.fromString(JSON.stringify(l))),s=yt.buildAllSiblings(e?.mtp?.depth,i,o),a=e.mtp.nodeAux||e.mtp.node_aux;a&&(a={key:me.fromString(JSON.stringify(a.key)),value:me.fromString(JSON.stringify(a.value))}),t=new yt({existence:e?.mtp.existence,nodeAux:a,siblings:s})}else t=yt.fromJSON(e.mtp);return new n({coreClaim:new er().fromHex(e.coreClaim),mtp:t,issuerData:{id:Ie.parse(e.issuerData.id),state:{...e.issuerData.state,rootOfRoots:me.fromHex(e.issuerData.state.rootOfRoots),claimsTreeRoot:me.fromHex(e.issuerData.state.claimsTreeRoot),revocationTreeRoot:me.fromHex(e.issuerData.state.revocationTreeRoot),value:me.fromHex(e.issuerData.state.value)}}})}},sd=class n{type;issuerData;signature;coreClaim;constructor(e){this.type="BJJSignature2021",this.issuerData=e.issuerData,this.coreClaim=e.coreClaim,this.signature=e.signature}toJSON(){return{issuerData:{id:this.issuerData.id.string(),state:{...this.issuerData.state,rootOfRoots:this.issuerData.state.rootOfRoots.hex(),claimsTreeRoot:this.issuerData.state.claimsTreeRoot.hex(),revocationTreeRoot:this.issuerData.state.revocationTreeRoot.hex(),value:this.issuerData.state.value.hex()},mtp:this.issuerData.mtp.toJSON(),authCoreClaim:this.issuerData.authCoreClaim.hex(),credentialStatus:this.issuerData.credentialStatus},type:this.type,coreClaim:this.coreClaim.hex(),signature:tn.encodeString(this.signature.compress())}}static fromJSON(e){return new n({issuerData:{id:Ie.parse(e.issuerData.id),mtp:yt.fromJSON(e.issuerData.mtp),state:{...e.issuerData.state,rootOfRoots:me.fromHex(e.issuerData.state.rootOfRoots),claimsTreeRoot:me.fromHex(e.issuerData.state.claimsTreeRoot),revocationTreeRoot:me.fromHex(e.issuerData.state.revocationTreeRoot),value:me.fromHex(e.issuerData.state.value)},credentialStatus:e.issuerData.credentialStatus,authCoreClaim:new er().fromHex(e.issuerData.authCoreClaim)},coreClaim:new er().fromHex(e.coreClaim),signature:pu.newFromCompressed(Uint8Array.from(tn.decodeString(e.signature)).slice(0,64))})}};var lD={};sr(lD,{MerklizationConstants:()=>zt,Merklizer:()=>yc,MtValue:()=>kw,Path:()=>rr,PoseidonHasher:()=>Z9,Temporal:()=>wa,getDocumentLoader:()=>Wi});var ae=$n(kG(),1),Ko=ae.default.BigInt(0),Fy=ae.default.BigInt(1),YS=ae.default.BigInt(2),Vne=ae.default.BigInt(10),Yne=ae.default.BigInt(24),zne=ae.default.BigInt(60),jne=ae.default.BigInt(1e3),_y=ae.default.BigInt(1e6),Ly=ae.default.BigInt(1e9),gN=ae.default.multiply(ae.default.BigInt(3600),Ly),Wne=ae.default.multiply(zne,Ly),fd=ae.default.multiply(gN,Yne);function gl(n){return typeof n=="bigint"?ae.default.BigInt(n.toString(10)):n}function yN(n){return ae.default.equal(ae.default.remainder(n,YS),Ko)}function ih(n){return ae.default.lessThan(n,Ko)?ae.default.unaryMinus(n):n}function tE(n,e){return ae.default.lessThan(n,e)?-1:ae.default.greaterThan(n,e)?1:0}function Iy(n,e){return{quotient:ae.default.divide(n,e),remainder:ae.default.remainder(n,e)}}var OG,GG,it="slot-epochNanoSeconds",ot="slot-iso-date",vn="slot-iso-date-time",On="slot-time",ve="slot-calendar",wN="slot-date-brand",bN="slot-year-month-brand",IN="slot-month-day-brand",Xt="slot-time-zone",Mi="slot-years",Fi="slot-months",co="slot-weeks",ki="slot-days",Oi="slot-hours",Gi="slot-minutes",Ni="slot-seconds",Ui="slot-milliseconds",Hi="slot-microseconds",lo="slot-nanoseconds",EN="date",xN="ym",AN="md",vN="time",CN="datetime",SN="instant",mh="original",L0="timezone-canonical",sS="timezone-original",Ey="calendar-id",DN="locale",aS="options",LN=new WeakMap,cS=Symbol.for("@@Temporal__GetSlots");(OG=globalThis)[cS]||(OG[cS]=function(n){return LN.get(n)});var yE=globalThis[cS],lS=Symbol.for("@@Temporal__CreateSlots");(GG=globalThis)[lS]||(GG[lS]=function(n){LN.set(n,Object.create(null))});var Dl=globalThis[lS];function Vi(n,...e){if(!n||typeof n!="object")return!1;let t=yE(n);return!!t&&e.every(r=>r in t)}function z(n,e){let t=yE(n)?.[e];if(t===void 0)throw new TypeError(`Missing internal slot ${e}`);return t}function wt(n,e,t){let r=yE(n);if(r===void 0)throw new TypeError("Missing slots for the given container");if(r[e])throw new TypeError(`${e} already has set`);r[e]=t}var uS={};function Ll(n,e){Object.defineProperty(n.prototype,Symbol.toStringTag,{value:e,writable:!1,enumerable:!1,configurable:!0});let t=Object.getOwnPropertyNames(n);for(let i=0;i<t.length;i++){let o=t[i],s=Object.getOwnPropertyDescriptor(n,o);s.configurable&&s.enumerable&&(s.enumerable=!1,Object.defineProperty(n,o,s))}let r=Object.getOwnPropertyNames(n.prototype);for(let i=0;i<r.length;i++){let o=r[i],s=Object.getOwnPropertyDescriptor(n.prototype,o);s.configurable&&s.enumerable&&(s.enumerable=!1,Object.defineProperty(n.prototype,o,s))}dS(e,n),dS(`${e}.prototype`,n.prototype)}function dS(n,e){let t=`%${n}%`;if(uS[t]!==void 0)throw new Error(`intrinsic ${n} already exists`);uS[t]=e}function Vr(n){return uS[n]}function T0(n,e){let t=n;if(t===0)return{div:t,mod:t};let r=Math.sign(t);t=Math.abs(t);let i=Math.trunc(1+Math.log10(t));if(e>=i)return{div:0*r,mod:r*t};if(e===0)return{div:r*t,mod:0*r};let o=t.toPrecision(i);return{div:r*Number.parseInt(o.slice(0,i-e),10),mod:r*Number.parseInt(o.slice(i-e),10)}}function tS(n,e,t){let r=n,i=t;if(r===0)return i;let o=Math.sign(r)||Math.sign(i);r=Math.abs(r),i=Math.abs(i);let s=r.toPrecision(Math.trunc(1+Math.log10(r)));if(i===0)return o*Number.parseInt(s+"0".repeat(e),10);let a=s+i.toPrecision(Math.trunc(1+Math.log10(i))).padStart(e,"0");return o*Number.parseInt(a,10)}function wE(n,e){let t=e==="negative";switch(n){case"ceil":return t?"zero":"infinity";case"floor":return t?"infinity":"zero";case"expand":return"infinity";case"trunc":return"zero";case"halfCeil":return t?"half-zero":"half-infinity";case"halfFloor":return t?"half-infinity":"half-zero";case"halfExpand":return"half-infinity";case"halfTrunc":return"half-zero";case"halfEven":return"half-even"}}function bE(n,e,t,r,i){return i==="zero"?n:i==="infinity"?e:t<0?n:t>0?e:i==="half-zero"?n:i==="half-infinity"?e:r?n:e}var dn=class n{constructor(e){this.totalNs=gl(e),this.sec=ae.default.toNumber(ae.default.divide(this.totalNs,Ly)),this.subsec=ae.default.toNumber(ae.default.remainder(this.totalNs,Ly))}static validateNew(e,t){if(ae.default.greaterThan(ih(e),n.MAX))throw new RangeError(`${t} of duration time units cannot exceed ${n.MAX} s`);return new n(e)}static fromEpochNsDiff(e,t){let r=ae.default.subtract(gl(e),gl(t));return new n(r)}static fromComponents(e,t,r,i,o,s){let a=ae.default.add(ae.default.add(ae.default.add(ae.default.add(ae.default.add(ae.default.BigInt(s),ae.default.multiply(ae.default.BigInt(o),jne)),ae.default.multiply(ae.default.BigInt(i),_y)),ae.default.multiply(ae.default.BigInt(r),Ly)),ae.default.multiply(ae.default.BigInt(t),Wne)),ae.default.multiply(ae.default.BigInt(e),gN));return n.validateNew(a,"total")}abs(){return new n(ih(this.totalNs))}add(e){return n.validateNew(ae.default.add(this.totalNs,e.totalNs),"sum")}add24HourDays(e){return n.validateNew(ae.default.add(this.totalNs,ae.default.multiply(ae.default.BigInt(e),fd)),"sum")}addToEpochNs(e){return ae.default.add(gl(e),this.totalNs)}cmp(e){return tE(this.totalNs,e.totalNs)}divmod(e){let{quotient:t,remainder:r}=Iy(this.totalNs,ae.default.BigInt(e));return{quotient:ae.default.toNumber(t),remainder:new n(r)}}fdiv(e){let t=gl(e),r=ae.default.BigInt(t),{quotient:i,remainder:o}=Iy(this.totalNs,r),s=[],a,l=(ae.default.lessThan(this.totalNs,Ko)?-1:1)*Math.sign(ae.default.toNumber(t));for(;!ae.default.equal(o,Ko)&&s.length<50;)o=ae.default.multiply(o,Vne),{quotient:a,remainder:o}=Iy(o,r),s.push(Math.abs(ae.default.toNumber(a)));return l*+(ih(i).toString()+"."+s.join(""))}isZero(){return ae.default.equal(this.totalNs,Ko)}round(e,t){let r=gl(e);if(ae.default.equal(r,Fy))return this;let{quotient:i,remainder:o}=Iy(this.totalNs,r),s=ae.default.lessThan(this.totalNs,Ko)?"negative":"positive",a=ae.default.multiply(ih(i),r),l=ae.default.add(a,r),c=tE(ih(ae.default.multiply(o,YS)),r),u=wE(t,s),d=ae.default.equal(ih(this.totalNs),a)?a:bE(a,l,c,yN(i),u),h=s==="positive"?d:ae.default.unaryMinus(d);return n.validateNew(h,"rounding")}sign(){return this.cmp(new n(Ko))}subtract(e){return n.validateNew(ae.default.subtract(this.totalNs,e.totalNs),"difference")}};dn.MAX=ae.default.BigInt("9007199254740991999999999"),dn.ZERO=new dn(Ko);var NG=/[A-Za-z._][A-Za-z._0-9+-]*/,$y=new RegExp(`(?:${/(?:[+-](?:[01][0-9]|2[0-3])(?::?[0-5][0-9])?)/.source}|(?:${NG.source})(?:\\/(?:${NG.source}))*)`),BN=/(?:[+-]\d{6}|\d{4})/,nE=/(?:0[1-9]|1[0-2])/,fS=/(?:0[1-9]|[12]\d|3[01])/,Zne=new RegExp(`(${BN.source})(?:-(${nE.source})-(${fS.source})|(${nE.source})(${fS.source}))`),TN=/(\d{2})(?::(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?|(\d{2})(?:(\d{2})(?:[.,](\d{1,9}))?)?)?/,PN=/((?:[+-])(?:[01][0-9]|2[0-3])(?::?(?:[0-5][0-9])(?::?(?:[0-5][0-9])(?:[.,](?:\d{1,9}))?)?)?)/,RN=new RegExp(`([zZ])|${PN.source}?`),F0=/\[(!)?([a-z_][a-z0-9_-]*)=([A-Za-z0-9]+(?:-[A-Za-z0-9]+)*)\]/g,Xne=new RegExp([`^${Zne.source}`,`(?:(?:[tT]|\\s+)${TN.source}(?:${RN.source})?)?`,`(?:\\[!?(${$y.source})\\])?`,`((?:${F0.source})*)$`].join("")),_ne=new RegExp([`^[tT]?${TN.source}`,`(?:${RN.source})?`,`(?:\\[!?${$y.source}\\])?`,`((?:${F0.source})*)$`].join("")),$ne=new RegExp(`^(${BN.source})-?(${nE.source})(?:\\[!?${$y.source}\\])?((?:${F0.source})*)$`),ere=new RegExp(`^(?:--)?(${nE.source})-?(${fS.source})(?:\\[!?${$y.source}\\])?((?:${F0.source})*)$`),nS=/(\d+)(?:[.,](\d{1,9}))?/,tre=new RegExp(`(?:${nS.source}H)?(?:${nS.source}M)?(?:${nS.source}S)?`),nre=new RegExp(`^([+-])?P${/(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?/.source}(?:T(?!$)${tre.source})?$`,"i"),hd=864e5,rE=1e6*hd,rre=6e10,MN=1e8*hd,k0=ga(MN),ky=ae.default.unaryMinus(k0),ire=ae.default.add(ae.default.subtract(ky,fd),Fy),ore=ae.default.subtract(ae.default.add(k0,fd),Fy),sre=146097*hd,UG=-271821,HG=275760,By=Date.UTC(1847,0,1),are=["iso8601","hebrew","islamic","islamic-umalqura","islamic-tbla","islamic-civil","islamic-rgsa","islamicc","persian","ethiopic","ethioaa","ethiopic-amete-alem","coptic","chinese","dangi","roc","indian","buddhist","japanese","gregory"],cre=new Set(["ACT","AET","AGT","ART","AST","BET","BST","CAT","CNT","CST","CTT","EAT","ECT","IET","IST","JST","MIT","NET","NST","PLT","PNT","PRT","PST","SST","VST"]);function Gn(n){return typeof n=="object"&&n!==null||typeof n=="function"}function IE(n){if(typeof n=="bigint")throw new TypeError("Cannot convert BigInt to number");return Number(n)}function EE(n){if(typeof n=="symbol")throw new TypeError("Cannot convert a Symbol value to a String");return String(n)}function ut(n){let e=IE(n);if(e===0)return 0;if(Number.isNaN(e)||e===1/0||e===-1/0)throw new RangeError("invalid number value");let t=Math.trunc(e);return t===0?0:t}function KG(n,e){let t=ut(n);if(t<=0)throw e!==void 0?new RangeError(`property '${e}' cannot be a a number less than one`):new RangeError("Cannot convert a number less than one to a positive integer");return t}function pa(n){let e=IE(n);if(Number.isNaN(e))throw new RangeError("not a number");if(e===1/0||e===-1/0)throw new RangeError("infinity is out of range");if(!function(t){if(typeof t!="number"||Number.isNaN(t)||t===1/0||t===-1/0)return!1;let r=Math.abs(t);return Math.floor(r)===r}(e))throw new RangeError(`unsupported fractional value ${n}`);return e===0?0:e}function Oy(n,e){return String(n).padStart(e,"0")}function dr(n){if(typeof n!="string")throw new TypeError(`expected a string, not ${String(n)}`);return n}function hS(n,e){if(Gn(n)){let t=n?.toString();if(typeof t=="string"||typeof t=="number")return t;throw new TypeError("Cannot convert object to primitive value")}return n}var pS=["era","eraYear","year","month","monthCode","day","hour","minute","second","millisecond","microsecond","nanosecond","offset","timeZone"],lre={era:EE,eraYear:ut,year:ut,month:KG,monthCode:function(n){let e=dr(hS(n));if(e.length<3||e.length>4||e[0]!=="M"||"0123456789".indexOf(e[1])===-1||"0123456789".indexOf(e[2])===-1||e[1]+e[2]==="00"&&e[3]!=="L"||e[3]!=="L"&&e[3]!==void 0)throw new RangeError(`bad month code ${e}; must match M01-M99 or M00L-M99L`);return e},day:KG,hour:ut,minute:ut,second:ut,millisecond:ut,microsecond:ut,nanosecond:ut,offset:function(n){let e=dr(hS(n));return Q0(e),e},timeZone:qi},ure={hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0},O0=[["years","year","date"],["months","month","date"],["weeks","week","date"],["days","day","date"],["hours","hour","time"],["minutes","minute","time"],["seconds","second","time"],["milliseconds","millisecond","time"],["microseconds","microsecond","time"],["nanoseconds","nanosecond","time"]],JG=Object.fromEntries(O0.map(n=>[n[0],n[1]])),dre=Object.fromEntries(O0.map(([n,e])=>[e,n])),Ty=O0.map(([,n])=>n),G0={day:rE,hour:36e11,minute:6e10,second:1e9,millisecond:1e6,microsecond:1e3,nanosecond:1},iE=["days","hours","microseconds","milliseconds","minutes","months","nanoseconds","seconds","weeks","years"],fre=Intl.DateTimeFormat,qG=new Map;function FN(n){let e=Ky(n),t=qG.get(e);return t===void 0&&(t=new fre("en-us",{timeZone:e,hour12:!1,era:"short",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"}),qG.set(e,t)),t}function Jr(n){return Vi(n,it)&&!Vi(n,Xt,ve)}function Fn(n){return Vi(n,Mi,Fi,ki,Oi,Gi,Ni,Ui,Hi,lo)}function kn(n){return Vi(n,wN)}function qn(n){return Vi(n,On)}function En(n){return Vi(n,vn)}function qr(n){return Vi(n,bN)}function Ho(n){return Vi(n,IN)}function It(n){return Vi(n,it,Xt,ve)}function de(n,e){if(!e(n))throw new TypeError("invalid receiver: method called with the wrong type of this-object")}function K0(n){if(Vi(n,ve)||Vi(n,Xt))throw new TypeError("with() does not support a calendar or timeZone property");if(qn(n))throw new TypeError("with() does not accept Temporal.PlainTime, use withPlainTime() instead");if(n.calendar!==void 0)throw new TypeError("with() does not support a calendar property");if(n.timeZone!==void 0)throw new TypeError("with() does not support a timeZone property")}function ew(n,e){return e==="never"||e==="auto"&&n==="iso8601"?"":`[${e==="critical"?"!":""}u-ca=${n}]`}function xE(n){let e,t,r=!1;for(F0.lastIndex=0;t=F0.exec(n);){let{1:i,2:o,3:s}=t;if(o==="u-ca"){if(e===void 0)e=s,r=i==="!";else if(i==="!"||r)throw new RangeError(`Invalid annotations in ${n}: more than one u-ca present with critical flag`)}else if(i==="!")throw new RangeError(`Unrecognized annotation: !${o}=${s}`)}return e}function cc(n){let e=Xne.exec(n);if(!e)throw new RangeError(`invalid RFC 9557 string: ${n}`);let t=xE(e[16]),r=e[1];if(r==="-000000")throw new RangeError(`invalid RFC 9557 string: ${n}`);let i=+r,o=+(e[2]??e[4]??1),s=+(e[3]??e[5]??1),a=e[6]!==void 0,l=+(e[6]??0),c=+(e[7]??e[10]??0),u=+(e[8]??e[11]??0);u===60&&(u=59);let d=(e[9]??e[12]??"")+"000000000",h=+d.slice(0,3),f=+d.slice(3,6),p=+d.slice(6,9),w,y=!1;e[13]?(w=void 0,y=!0):e[14]&&(w=e[14]);let v=e[15];return _S(i,o,s,l,c,u,h,f,p),{year:i,month:o,day:s,time:a?{hour:l,minute:c,second:u,millisecond:h,microsecond:f,nanosecond:p}:"start-of-day",tzAnnotation:v,offset:w,z:y,calendar:t}}function kN(n){let e=_ne.exec(n),t,r,i,o,s,a,l;if(e){l=xE(e[10]),t=+(e[1]??0),r=+(e[2]??e[5]??0),i=+(e[3]??e[6]??0),i===60&&(i=59);let c=(e[4]??e[7]??"")+"000000000";if(o=+c.slice(0,3),s=+c.slice(3,6),a=+c.slice(6,9),e[8])throw new RangeError("Z designator not supported for PlainTime")}else{let c,u;if({time:c,z:u,calendar:l}=cc(n),c==="start-of-day")throw new RangeError(`time is missing in string: ${n}`);if(u)throw new RangeError("Z designator not supported for PlainTime");({hour:t,minute:r,second:i,millisecond:o,microsecond:s,nanosecond:a}=c)}if(SE(t,r,i,o,s,a),/[tT ][0-9][0-9]/.test(n))return{hour:t,minute:r,second:i,millisecond:o,microsecond:s,nanosecond:a,calendar:l};try{let{month:c,day:u}=jS(n);lh(1972,c,u)}catch{try{let{year:c,month:u}=zS(n);lh(c,u,1)}catch{return{hour:t,minute:r,second:i,millisecond:o,microsecond:s,nanosecond:a,calendar:l}}}throw new RangeError(`invalid RFC 9557 time-only string ${n}; may need a T prefix`)}function zS(n){let e=$ne.exec(n),t,r,i,o;if(e){i=xE(e[3]);let s=e[1];if(s==="-000000")throw new RangeError(`invalid RFC 9557 string: ${n}`);if(t=+s,r=+e[2],o=1,i!==void 0&&i!=="iso8601")throw new RangeError("YYYY-MM format is only valid with iso8601 calendar")}else{let s;if({year:t,month:r,calendar:i,day:o,z:s}=cc(n),s)throw new RangeError("Z designator not supported for PlainYearMonth")}return{year:t,month:r,calendar:i,referenceISODay:o}}function jS(n){let e=ere.exec(n),t,r,i,o;if(e){if(i=xE(e[3]),t=+e[1],r=+e[2],i!==void 0&&i!=="iso8601")throw new RangeError("MM-DD format is only valid with iso8601 calendar")}else{let s;if({month:t,day:r,calendar:i,year:o,z:s}=cc(n),s)throw new RangeError("Z designator not supported for PlainMonthDay")}return{month:t,day:r,calendar:i,referenceISOYear:o}}var ON=new RegExp(`^${$y.source}$`,"i"),GN=new RegExp(`^${/([+-])([01][0-9]|2[0-3])(?::?([0-5][0-9])?)?/.source}$`);function NN(n){let e=pre.test(n)?"Seconds not allowed in offset time zone":"Invalid time zone";throw new RangeError(`${e}: ${n}`)}function dd(n){return ON.test(n)||NN(n),GN.test(n)?{offsetMinutes:Q0(n)/6e10}:{tzName:n}}function Py(n,e,t,r){let i=n,o=e,s=t;switch(r){case"reject":lh(i,o,s);break;case"constrain":({year:i,month:o,day:s}=tU(i,o,s))}return{year:i,month:o,day:s}}function AE(n,e,t,r,i,o,s){let a=n,l=e,c=t,u=r,d=i,h=o;switch(s){case"reject":SE(a,l,c,u,d,h);break;case"constrain":a=Ki(a,0,23),l=Ki(l,0,59),c=Ki(c,0,59),u=Ki(u,0,999),d=Ki(d,0,999),h=Ki(h,0,999)}return{hour:a,minute:l,second:c,millisecond:u,microsecond:d,nanosecond:h}}function UN(n){if(!Gn(n))throw new TypeError("invalid duration-like");let e={years:void 0,months:void 0,weeks:void 0,days:void 0,hours:void 0,minutes:void 0,seconds:void 0,milliseconds:void 0,microseconds:void 0,nanoseconds:void 0},t=!1;for(let r=0;r<iE.length;r++){let i=iE[r],o=n[i];o!==void 0&&(t=!0,e[i]=pa(o))}if(!t)throw new TypeError("invalid duration-like");return e}function oi({years:n,months:e,weeks:t,days:r},i,o,s){return{years:n,months:s??e,weeks:o??t,days:i??r}}function Ht(n,e){return{isoDate:n,time:e}}function kt(n){return Al(n,"overflow",["constrain","reject"],"constrain")}function Ry(n){return Al(n,"disambiguation",["compatible","earlier","later","reject"],"compatible")}function ya(n,e){return Al(n,"roundingMode",["ceil","floor","expand","trunc","halfCeil","halfFloor","halfExpand","halfTrunc","halfEven"],e)}function eE(n,e){return Al(n,"offset",["prefer","use","ignore","reject"],e)}function tw(n){return Al(n,"calendarName",["auto","always","never","critical"],"auto")}function J0(n){let e=n.roundingIncrement;if(e===void 0)return 1;let t=ut(e);if(t<1||t>1e9)throw new RangeError(`roundingIncrement must be at least 1 and at most 1e9, not ${e}`);return t}function q0(n,e,t){let r=t?e:e-1;if(n>r)throw new RangeError(`roundingIncrement must be at least 1 and less than ${r}, not ${n}`);if(e%n!=0)throw new RangeError(`Rounding increment must divide evenly into ${e}`)}function nw(n){let e=n.fractionalSecondDigits;if(e===void 0)return"auto";if(typeof e!="number"){if(EE(e)!=="auto")throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${e}`);return"auto"}let t=Math.floor(e);if(!Number.isFinite(t)||t<0||t>9)throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${e}`);return t}function rw(n,e){switch(n){case"minute":return{precision:"minute",unit:"minute",increment:1};case"second":return{precision:0,unit:"second",increment:1};case"millisecond":return{precision:3,unit:"millisecond",increment:1};case"microsecond":return{precision:6,unit:"microsecond",increment:1};case"nanosecond":return{precision:9,unit:"nanosecond",increment:1}}switch(e){case"auto":return{precision:e,unit:"nanosecond",increment:1};case 0:return{precision:e,unit:"second",increment:1};case 1:case 2:case 3:return{precision:e,unit:"millisecond",increment:10**(3-e)};case 4:case 5:case 6:return{precision:e,unit:"microsecond",increment:10**(6-e)};case 7:case 8:case 9:return{precision:e,unit:"nanosecond",increment:10**(9-e)};default:throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${e}`)}}var Cl=Symbol("~required~");function fo(n,e,t,r,i=[]){let o=[];for(let c=0;c<O0.length;c++){let u=O0[c],d=u[1],h=u[2];t!=="datetime"&&t!==h||o.push(d)}o=o.concat(i);let s=r;s===Cl?s=void 0:s!==void 0&&o.push(s);let a=[];a=a.concat(o);for(let c=0;c<o.length;c++){let u=o[c],d=dre[u];d!==void 0&&a.push(d)}let l=Al(n,e,a,s);if(l===void 0&&r===Cl)throw new RangeError(`${e} is required`);return l&&l in JG?JG[l]:l}function rS(n){let e=n.relativeTo;if(e===void 0)return{};let t,r,i,o,s,a="option",l=!1;if(Gn(e)){if(It(e))return{zonedRelativeTo:e};if(kn(e))return{plainRelativeTo:e};if(En(e))return{plainRelativeTo:Ji(z(e,vn).isoDate,z(e,ve))};i=cw(e);let c=Vo(i,e,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond","offset","timeZone"],[]);({isoDate:t,time:r}=ow(i,c,"constrain")),{offset:s,timeZone:o}=c,s===void 0&&(a="wall")}else{let c,u,d,h,f;if({year:d,month:h,day:f,time:r,calendar:i,tzAnnotation:c,offset:s,z:u}=cc(dr(e)),c)o=qi(c),u?a="exact":s||(a="wall"),l=!0;else if(u)throw new RangeError("Z designator not supported for PlainDate relativeTo; either remove the Z or add a bracketed time zone");i||(i="iso8601"),i=Yi(i),t={year:d,month:h,day:f}}return o===void 0?{plainRelativeTo:Ji(t,i)}:{zonedRelativeTo:ii(oE(t,r,a,a==="option"?Q0(s):0,o,"compatible","reject",l),o,i)}}function yl(n){return z(n,Mi)!==0?"year":z(n,Fi)!==0?"month":z(n,co)!==0?"week":z(n,ki)!==0?"day":z(n,Oi)!==0?"hour":z(n,Gi)!==0?"minute":z(n,Ni)!==0?"second":z(n,Ui)!==0?"millisecond":z(n,Hi)!==0?"microsecond":"nanosecond"}function El(n,e){return Ty.indexOf(n)>Ty.indexOf(e)?e:n}function tc(n){return n==="year"||n==="month"||n==="week"}function wl(n){return tc(n)||n==="day"?"date":"time"}function gd(n){return Vr("%calendarImpl%")(n)}function iw(n){return Vr("%calendarImpl%")(z(n,ve))}function Qi(n,e,t="date"){let r=Object.create(null),i=gd(n).isoToDate(e,{year:!0,monthCode:!0,day:!0});return r.monthCode=i.monthCode,t!=="month-day"&&t!=="date"||(r.day=i.day),t!=="year-month"&&t!=="date"||(r.year=i.year),r}function Vo(n,e,t,r,i){let o=gd(n).extraFields(t),s=t.concat(r,o),a=Object.create(null),l=!1;s.sort();for(let c=0;c<s.length;c++){let u=s[c],d=e[u];if(d!==void 0)l=!0,a[u]=(0,lre[u])(d);else if(i!=="partial"){if(i.includes(u))throw new TypeError(`required property '${u}' missing or undefined`);a[u]=ure[u]}}if(i==="partial"&&!l)throw new TypeError("no supported properties found");return a}function mS(n,e="complete"){let t=["hour","microsecond","millisecond","minute","nanosecond","second"],r=!1,i=Object.create(null);for(let o=0;o<t.length;o++){let s=t[o],a=n[s];a!==void 0?(i[s]=ut(a),r=!0):e==="complete"&&(i[s]=0)}if(!r)throw new TypeError("invalid time-like");return i}function xy(n,e){if(Gn(n)){if(kn(n))return kt(Qe(e)),Ji(z(n,ot),z(n,ve));if(It(n)){let l=xs(z(n,Xt),z(n,it));return kt(Qe(e)),Ji(l.isoDate,z(n,ve))}if(En(n))return kt(Qe(e)),Ji(z(n,vn).isoDate,z(n,ve));let a=cw(n);return Ji(pd(a,Vo(a,n,["year","month","monthCode","day"],[],[]),kt(Qe(e))),a)}let{year:t,month:r,day:i,calendar:o,z:s}=cc(dr(n));if(s)throw new RangeError("Z designator not supported for PlainDate");return o||(o="iso8601"),o=Yi(o),kt(Qe(e)),Ji({year:t,month:r,day:i},o)}function ow(n,e,t){return Ht(pd(n,e,t),AE(e.hour,e.minute,e.second,e.millisecond,e.microsecond,e.nanosecond,t))}function Ay(n,e){let t,r,i;if(Gn(n)){if(En(n))return kt(Qe(e)),bs(z(n,vn),z(n,ve));if(It(n)){let a=xs(z(n,Xt),z(n,it));return kt(Qe(e)),bs(a,z(n,ve))}if(kn(n))return kt(Qe(e)),bs(Ht(z(n,ot),{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),z(n,ve));i=cw(n);let o=Vo(i,n,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond"],[]),s=kt(Qe(e));({isoDate:t,time:r}=ow(i,o,s))}else{let o,s,a,l;if({year:s,month:a,day:l,time:r,calendar:i,z:o}=cc(dr(n)),o)throw new RangeError("Z designator not supported for PlainDateTime");r==="start-of-day"&&(r={deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),_S(s,a,l,r.hour,r.minute,r.second,r.millisecond,r.microsecond,r.nanosecond),i||(i="iso8601"),i=Yi(i),kt(Qe(e)),t={year:s,month:a,day:l}}return bs(Ht(t,r),i)}function Es(n){let e=Vr("%Temporal.Duration%");if(Fn(n))return new e(z(n,Mi),z(n,Fi),z(n,co),z(n,ki),z(n,Oi),z(n,Gi),z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo));if(!Gn(n))return function(i){let{years:o,months:s,weeks:a,days:l,hours:c,minutes:u,seconds:d,milliseconds:h,microseconds:f,nanoseconds:p}=function(w){let y=nre.exec(w);if(!y)throw new RangeError(`invalid duration: ${w}`);if(y.every((R,J)=>J<2||R===void 0))throw new RangeError(`invalid duration: ${w}`);let v=y[1]==="-"?-1:1,B=y[2]===void 0?0:ut(y[2])*v,U=y[3]===void 0?0:ut(y[3])*v,k=y[4]===void 0?0:ut(y[4])*v,F=y[5]===void 0?0:ut(y[5])*v,P=y[6]===void 0?0:ut(y[6])*v,I=y[7],D=y[8],V=y[9],K=y[10],q=y[11],G=0,x=0,S=0;if(I!==void 0){if(D??V??K??q)throw new RangeError("only the smallest unit can be fractional");S=3600*ut((I+"000000000").slice(0,9))*v}else if(G=D===void 0?0:ut(D)*v,V!==void 0){if(K??q)throw new RangeError("only the smallest unit can be fractional");S=60*ut((V+"000000000").slice(0,9))*v}else x=K===void 0?0:ut(K)*v,q!==void 0&&(S=ut((q+"000000000").slice(0,9))*v);let M=S%1e3,b=Math.trunc(S/1e3)%1e3,A=Math.trunc(S/1e6)%1e3;return x+=Math.trunc(S/1e9)%60,G+=Math.trunc(S/6e10),DE(B,U,k,F,P,G,x,A,b,M),{years:B,months:U,weeks:k,days:F,hours:P,minutes:G,seconds:x,milliseconds:A,microseconds:b,nanoseconds:M}}(i);return new(Vr("%Temporal.Duration%"))(o,s,a,l,c,u,d,h,f,p)}(dr(n));let t={years:0,months:0,weeks:0,days:0,hours:0,minutes:0,seconds:0,milliseconds:0,microseconds:0,nanoseconds:0},r=UN(n);for(let i=0;i<iE.length;i++){let o=iE[i],s=r[o];s!==void 0&&(t[o]=s)}return new e(t.years,t.months,t.weeks,t.days,t.hours,t.minutes,t.seconds,t.milliseconds,t.microseconds,t.nanoseconds)}function vy(n){let e;if(Gn(n)){if(Jr(n)||It(n))return ma(z(n,it));e=hS(n)}else e=n;let{year:t,month:r,day:i,time:o,offset:s,z:a}=function(w){let y=cc(w);if(!y.z&&!y.offset)throw new RangeError("Temporal.Instant requires a time zone offset");return y}(dr(e)),{hour:l=0,minute:c=0,second:u=0,millisecond:d=0,microsecond:h=0,nanosecond:f=0}=o==="start-of-day"?{}:o,p=Hy(t,r,i,l,c,u,d,h,f-(a?0:Q0(s)));return M0(p.isoDate),ma(Qr(p))}function QG(n,e){if(Gn(n)){if(Ho(n))return kt(Qe(e)),P0(z(n,ot),z(n,ve));let a;return Vi(n,ve)?a=z(n,ve):(a=n.calendar,a===void 0&&(a="iso8601"),a=aw(a)),P0(sE(a,Vo(a,n,["year","month","monthCode","day"],[],[]),kt(Qe(e))),a)}let{month:t,day:r,referenceISOYear:i,calendar:o}=jS(dr(n));if(o===void 0&&(o="iso8601"),o=Yi(o),kt(Qe(e)),o==="iso8601")return P0({year:1972,month:t,day:r},o);let s={year:i,month:t,day:r};return gh(s),s=sE(o,Qi(o,s,"month-day"),"constrain"),P0(s,o)}function ld(n,e){let t;if(Gn(n)){if(qn(n))return kt(Qe(e)),bl(z(n,On));if(En(n))return kt(Qe(e)),bl(z(n,vn).time);if(It(n)){let c=xs(z(n,Xt),z(n,it));return kt(Qe(e)),bl(c.time)}let{hour:r,minute:i,second:o,millisecond:s,microsecond:a,nanosecond:l}=mS(n);t=AE(r,i,o,s,a,l,kt(Qe(e)))}else t=kN(dr(n)),kt(Qe(e));return bl(t)}function HN(n){return n===void 0?{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}:z(ld(n),On)}function Cy(n,e){if(Gn(n)){if(qr(n))return kt(Qe(e)),R0(z(n,ot),z(n,ve));let a=cw(n);return R0(Gy(a,Vo(a,n,["year","month","monthCode"],[],[]),kt(Qe(e))),a)}let{year:t,month:r,referenceISODay:i,calendar:o}=zS(dr(n));o===void 0&&(o="iso8601"),o=Yi(o),kt(Qe(e));let s={year:t,month:r,day:i};return $S(s),s=Gy(o,Qi(o,s,"year-month"),"constrain"),R0(s,o)}function oE(n,e,t,r,i,o,s,a){if(e==="start-of-day")return ad(i,n);let l=Ht(n,e);if(t==="wall"||s==="ignore")return si(i,l,o);if(t==="exact"||s==="use"){let d=Hy(n.year,n.month,n.day,e.hour,e.minute,e.second,e.millisecond,e.microsecond,e.nanosecond-r);M0(d.isoDate);let h=Qr(d);return sc(h),h}M0(n);let c=Qr(l),u=Ny(i,l);for(let d=0;d<u.length;d++){let h=u[d],f=ae.default.toNumber(ae.default.subtract(c,h)),p=ud(f,6e10,"halfExpand");if(f===r||a&&p===r)return h}if(s==="reject"){let d=gS(r),h=Uy(l,"iso8601","auto");throw new RangeError(`Offset ${d} is invalid for ${h} in ${i}`)}return WN(u,i,l,o)}function Sy(n,e){let t,r,i,o,s,a,l,c=!1,u="option";if(Gn(n)){if(It(n)){let w=Qe(e);return Ry(w),eE(w,"reject"),kt(w),ii(z(n,it),z(n,Xt),z(n,ve))}s=cw(n);let h=Vo(s,n,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond","offset","timeZone"],["timeZone"]);({offset:o,timeZone:i}=h),o===void 0&&(u="wall");let f=Qe(e);a=Ry(f),l=eE(f,"reject");let p=kt(f);({isoDate:t,time:r}=ow(s,h,p))}else{let h,f,p,w,y;({year:p,month:w,day:y,time:r,tzAnnotation:h,offset:o,z:f,calendar:s}=function(B){let U=cc(B);if(!U.tzAnnotation)throw new RangeError("Temporal.ZonedDateTime requires a time zone ID in brackets");return U}(dr(n))),i=qi(h),f?u="exact":o||(u="wall"),s||(s="iso8601"),s=Yi(s),c=!0;let v=Qe(e);a=Ry(v),l=eE(v,"reject"),kt(v),t={year:p,month:w,day:y}}let d=0;return u==="option"&&(d=Q0(o)),ii(oE(t,r,u,d,i,a,l,c),i,s)}function KN(n,e,t){gh(e),Dl(n),wt(n,ot,e),wt(n,ve,t),wt(n,wN,!0)}function Ji(n,e){let t=Vr("%Temporal.PlainDate%"),r=Object.create(t.prototype);return KN(r,n,e),r}function JN(n,e,t){uh(e),Dl(n),wt(n,vn,e),wt(n,ve,t)}function bs(n,e){let t=Vr("%Temporal.PlainDateTime%"),r=Object.create(t.prototype);return JN(r,n,e),r}function qN(n,e,t){gh(e),Dl(n),wt(n,ot,e),wt(n,ve,t),wt(n,IN,!0)}function P0(n,e){let t=Vr("%Temporal.PlainMonthDay%"),r=Object.create(t.prototype);return qN(r,n,e),r}function QN(n,e){Dl(n),wt(n,On,e)}function bl(n){let e=Vr("%Temporal.PlainTime%"),t=Object.create(e.prototype);return QN(t,n),t}function VN(n,e,t){$S(e),Dl(n),wt(n,ot,e),wt(n,ve,t),wt(n,bN,!0)}function R0(n,e){let t=Vr("%Temporal.PlainYearMonth%"),r=Object.create(t.prototype);return VN(r,n,e),r}function YN(n,e){sc(e),Dl(n),wt(n,it,e)}function ma(n){let e=Vr("%Temporal.Instant%"),t=Object.create(e.prototype);return YN(t,n),t}function zN(n,e,t,r){sc(e),Dl(n),wt(n,it,e),wt(n,Xt,t),wt(n,ve,r)}function ii(n,e,t="iso8601"){let r=Vr("%Temporal.ZonedDateTime%"),i=Object.create(r.prototype);return zN(i,n,e,t),i}function VG(n){return pS.filter(e=>n[e]!==void 0)}function ch(n,e,t){let r=VG(t),i=gd(n).fieldKeysToIgnore(r),o=Object.create(null),s=VG(e);for(let a=0;a<pS.length;a++){let l,c=pS[a];s.includes(c)&&!i.includes(c)&&(l=e[c]),r.includes(c)&&(l=t[c]),l!==void 0&&(o[c]=l)}return o}function qo(n,e,t,r){let i=gd(n).dateAdd(e,t,r);return gh(i),i}function sw(n,e,t,r){return gd(n).dateUntil(e,t,r)}function aw(n){if(Gn(n)&&Vi(n,ve))return z(n,ve);let e=dr(n);try{return Yi(e)}catch{}let t;try{({calendar:t}=cc(e))}catch{try{({calendar:t}=kN(e))}catch{try{({calendar:t}=zS(e))}catch{({calendar:t}=jS(e))}}}return t||(t="iso8601"),Yi(t)}function cw(n){if(Vi(n,ve))return z(n,ve);let{calendar:e}=n;return e===void 0?"iso8601":aw(e)}function oc(n,e){return Yi(n)===Yi(e)}function pd(n,e,t){let r=gd(n);r.resolveFields(e,"date");let i=r.dateToISO(e,t);return gh(i),i}function Gy(n,e,t){let r=gd(n);r.resolveFields(e,"year-month"),e.day=1;let i=r.dateToISO(e,t);return $S(i),i}function sE(n,e,t){let r=gd(n);r.resolveFields(e,"month-day");let i=r.monthDayToISOReferenceDate(e,t);return gh(i),i}function qi(n){if(Gn(n)&&It(n))return z(n,Xt);let e=dr(n);if(e==="UTC")return"UTC";let{tzName:t,offsetMinutes:r}=function(o){let{tzAnnotation:s,offset:a,z:l}=function(c){if(ON.test(c))return{tzAnnotation:c,offset:void 0,z:!1};try{let{tzAnnotation:u,offset:d,z:h}=cc(c);if(h||u||d)return{tzAnnotation:u,offset:d,z:h}}catch{}NN(c)}(o);return s?dd(s):l?dd("UTC"):a?dd(a):void 0}(e);if(r!==void 0)return WS(r);let i=aE(t);if(!i)throw new RangeError(`Unrecognized time zone ${t}`);return i.identifier}function jN(n,e){if(n===e)return!0;let t=dd(n).offsetMinutes,r=dd(e).offsetMinutes;if(t===void 0&&r===void 0){let i=aE(e);if(!i)return!1;let o=aE(n);return!!o&&o.primaryIdentifier===i.primaryIdentifier}return t===r}function Il(n,e){let t=dd(n).offsetMinutes;return t!==void 0?6e10*t:yS(n,e)}function gS(n){let e=n<0?"-":"+",t=Math.abs(n),r=Math.floor(t/36e11),i=Math.floor(t/6e10)%60,o=Math.floor(t/1e9)%60,s=t%1e9;return`${e}${vE(r,i,o,s,o===0&&s===0?"minute":"auto")}`}function xs(n,e){let t=Il(n,e),{isoDate:{year:r,month:i,day:o},time:{hour:s,minute:a,second:l,millisecond:c,microsecond:u,nanosecond:d}}=_N(e);return Hy(r,i,o,s,a,l,c,u,d+t)}function si(n,e,t){return WN(Ny(n,e),n,e,t)}function WN(n,e,t,r){let i=n.length;if(i===1)return n[0];if(i)switch(r){case"compatible":case"earlier":return n[0];case"later":return n[i-1];case"reject":throw new RangeError("multiple instants found")}if(r==="reject")throw new RangeError("multiple instants found");let o=Qr(t),s=ae.default.subtract(o,fd);sc(s);let a=Il(e,s),l=ae.default.add(o,fd);sc(l);let c=Il(e,l)-a;switch(r){case"earlier":{let u=dn.fromComponents(0,0,0,0,0,-c),d=N0(t.time,u);return Ny(e,Ht(ho(t.isoDate.year,t.isoDate.month,t.isoDate.day+d.deltaDays),d))[0]}case"compatible":case"later":{let u=dn.fromComponents(0,0,0,0,0,c),d=N0(t.time,u),h=Ny(e,Ht(ho(t.isoDate.year,t.isoDate.month,t.isoDate.day+d.deltaDays),d));return h[h.length-1]}}}function Ny(n,e){if(n==="UTC")return M0(e.isoDate),[Qr(e)];let t=dd(n).offsetMinutes;if(t!==void 0){let r=Hy(e.isoDate.year,e.isoDate.month,e.isoDate.day,e.time.hour,e.time.minute-t,e.time.second,e.time.millisecond,e.time.microsecond,e.time.nanosecond);M0(r.isoDate);let i=Qr(r);return sc(i),[i]}return M0(e.isoDate),function(r,i){let o=Qr(i),s=ae.default.subtract(o,fd);ae.default.lessThan(s,ky)&&(s=o);let a=ae.default.add(o,fd);ae.default.greaterThan(a,k0)&&(a=o);let l=yS(r,s),c=yS(r,a);return(l===c?[l]:[l,c]).map(d=>{let h=ae.default.subtract(o,ae.default.BigInt(d)),f=function(p,w){let{epochMilliseconds:y,time:{millisecond:v,microsecond:B,nanosecond:U}}=_N(w),{year:k,month:F,day:P,hour:I,minute:D,second:V}=$N(p,y);return Hy(k,F,P,I,D,V,v,B,U)}(r,h);if(U0(i,f)===0)return sc(h),h}).filter(d=>d!==void 0)}(n,e)}function ad(n,e){let t=Ht(e,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),r=Ny(n,t);if(r.length)return r[0];let i=Qr(t),o=ae.default.subtract(i,fd);return sc(o),XS(n,o)}function lw(n){let e;return e=n<0||n>9999?(n<0?"-":"+")+Oy(Math.abs(n),6):Oy(n,4),e}function Qo(n){return Oy(n,2)}function ZN(n,e){let t;if(e==="auto"){if(n===0)return"";t=Oy(n,9).replace(/0+$/,"")}else{if(e===0)return"";t=Oy(n,9).slice(0,e)}return`.${t}`}function vE(n,e,t,r,i){let o=`${Qo(n)}:${Qo(e)}`;return i==="minute"||(o+=`:${Qo(t)}`,o+=ZN(r,i)),o}function YG(n,e,t){let r=e;r===void 0&&(r="UTC");let i=z(n,it),o=Uy(xs(r,i),"iso8601",t,"never"),s="Z";return e!==void 0&&(s=XN(Il(r,i))),`${o}${s}`}function $I(n,e){let t=z(n,Mi),r=z(n,Fi),i=z(n,co),o=z(n,ki),s=z(n,Oi),a=z(n,Gi),l=lE(n),c="";t!==0&&(c+=`${Math.abs(t)}Y`),r!==0&&(c+=`${Math.abs(r)}M`),i!==0&&(c+=`${Math.abs(i)}W`),o!==0&&(c+=`${Math.abs(o)}D`);let u="";s!==0&&(u+=`${Math.abs(s)}H`),a!==0&&(u+=`${Math.abs(a)}M`);let d=dn.fromComponents(0,0,z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo));d.isZero()&&!["second","millisecond","microsecond","nanosecond"].includes(yl(n))&&e==="auto"||(u+=`${Math.abs(d.sec)}${ZN(Math.abs(d.subsec),e)}S`);let h=`${l<0?"-":""}P${c}`;return u&&(h=`${h}T${u}`),h}function zG(n,e="auto"){let{year:t,month:r,day:i}=z(n,ot);return`${lw(t)}-${Qo(r)}-${Qo(i)}${ew(z(n,ve),e)}`}function jG({hour:n,minute:e,second:t,millisecond:r,microsecond:i,nanosecond:o},s){return vE(n,e,t,1e6*r+1e3*i+o,s)}function Uy(n,e,t,r="auto"){let{isoDate:{year:i,month:o,day:s},time:{hour:a,minute:l,second:c,millisecond:u,microsecond:d,nanosecond:h}}=n;return`${lw(i)}-${Qo(o)}-${Qo(s)}T${vE(a,l,c,1e6*u+1e3*d+h,t)}${ew(e,r)}`}function WG(n,e="auto"){let{year:t,month:r,day:i}=z(n,ot),o=`${Qo(r)}-${Qo(i)}`,s=z(n,ve);e!=="always"&&e!=="critical"&&s==="iso8601"||(o=`${lw(t)}-${o}`);let a=ew(s,e);return a&&(o+=a),o}function ZG(n,e="auto"){let{year:t,month:r,day:i}=z(n,ot),o=`${lw(t)}-${Qo(r)}`,s=z(n,ve);e!=="always"&&e!=="critical"&&s==="iso8601"||(o+=`-${Qo(i)}`);let a=ew(s,e);return a&&(o+=a),o}function XG(n,e,t="auto",r="auto",i="auto",o=void 0){let s=z(n,it);if(o){let{unit:u,increment:d,roundingMode:h}=o;s=ES(s,d,u,h)}let a=z(n,Xt),l=Il(a,s),c=Uy(xs(a,s),"iso8601",e,"never");return i!=="never"&&(c+=XN(l)),r!=="never"&&(c+=`[${r==="critical"?"!":""}${a}]`),c+=ew(z(n,ve),t),c}function _G(n){return GN.test(n)}function Q0(n){let e=mre.exec(n);if(!e)throw new RangeError(`invalid time zone offset: ${n}; must match \xB1HH:MM[:SS.SSSSSSSSS]`);return(e[1]==="-"?-1:1)*(1e9*(60*(60*+e[2]+ +(e[3]||0))+ +(e[4]||0))+ +((e[5]||0)+"000000000").slice(0,9))}var yy,hre=Object.assign(Object.create(null),{"/":!0,"-":!0,_:!0});function aE(n){if(yy===void 0){let o=Intl.supportedValuesOf?.("timeZone");if(o){yy=new Map;for(let s=0;s<o.length;s++){let a=o[s];yy.set(Ky(a),a)}}else yy=null}let e=Ky(n),t=yy?.get(e);if(t)return{identifier:t,primaryIdentifier:t};try{t=FN(n).resolvedOptions().timeZone}catch{return}if(e==="antarctica/south_pole"&&(t="Antarctica/McMurdo"),cre.has(n))throw new RangeError(`${n} is a legacy time zone identifier from ICU. Use ${t} instead`);let r=[...e].map((o,s)=>s===0||hre[e[s-1]]?o.toUpperCase():o).join("").split("/");if(r.length===1)return e==="gb-eire"?{identifier:"GB-Eire",primaryIdentifier:t}:{identifier:e.length<=3||/[-0-9]/.test(e)?e.toUpperCase():r[0],primaryIdentifier:t};if(r[0]==="Etc")return{identifier:`Etc/${["Zulu","Greenwich","Universal"].includes(r[1])?r[1]:r[1].toUpperCase()}`,primaryIdentifier:t};if(r[0]==="Us")return{identifier:`US/${r[1]}`,primaryIdentifier:t};let i=new Map([["Act","ACT"],["Lhi","LHI"],["Nsw","NSW"],["Dar_Es_Salaam","Dar_es_Salaam"],["Port_Of_Spain","Port_of_Spain"],["Port-Au-Prince","Port-au-Prince"],["Isle_Of_Man","Isle_of_Man"],["Comodrivadavia","ComodRivadavia"],["Knox_In","Knox_IN"],["Dumontdurville","DumontDUrville"],["Mcmurdo","McMurdo"],["Denoronha","DeNoronha"],["Easterisland","EasterIsland"],["Bajanorte","BajaNorte"],["Bajasur","BajaSur"]]);return r[1]=i.get(r[1])??r[1],r.length>2&&(r[2]=i.get(r[2])??r[2]),{identifier:r.join("/"),primaryIdentifier:t}}function sh(n,e){let{year:t,month:r,day:i,hour:o,minute:s,second:a}=$N(n,e),l=e%1e3;return l<0&&(l+=1e3),1e6*(ZS({isoDate:{year:t,month:r,day:i},time:{hour:o,minute:s,second:a,millisecond:l}})-e)}function yS(n,e){return sh(n,As(e,"floor"))}function WS(n){let e=n<0?"-":"+",t=Math.abs(n);return`${e}${vE(Math.floor(t/60),t%60,0,0,"minute")}`}function XN(n){return WS(ud(n,rre,"halfExpand")/6e10)}function ZS({isoDate:{year:n,month:e,day:t},time:{hour:r,minute:i,second:o,millisecond:s}}){let a=n%400,l=(n-a)/400,c=new Date;return c.setUTCHours(r,i,o,s),c.setUTCFullYear(a,e-1,t),c.getTime()+sre*l}function Qr(n){let e=ZS(n),t=1e3*n.time.microsecond+n.time.nanosecond;return ae.default.add(ga(e),ae.default.BigInt(t))}function _N(n){let e=As(n,"trunc"),t=ae.default.toNumber(ae.default.remainder(n,_y));t<0&&(t+=1e6,e-=1);let r=Math.floor(t/1e3)%1e3,i=t%1e3,o=new Date(e);return{epochMilliseconds:e,isoDate:{year:o.getUTCFullYear(),month:o.getUTCMonth()+1,day:o.getUTCDate()},time:{hour:o.getUTCHours(),minute:o.getUTCMinutes(),second:o.getUTCSeconds(),millisecond:o.getUTCMilliseconds(),microsecond:r,nanosecond:i}}}function XS(n,e){if(n==="UTC")return null;let t=As(e,"floor");if(t<By)return XS(n,ga(By));let r=Date.now(),i=Math.max(t,r)+366*hd*3,o=t,s=sh(n,o),a=o,l=s;for(;s===l&&o<i;){if(a=o+2*hd*7,a>MN)return null;l=sh(n,a),s===l&&(o=a)}return s===l?null:ga(lU(c=>sh(n,c),o,a,s,l))}function wS(n,e){if(n==="UTC")return null;let t=As(e,"ceil"),r=Date.now(),i=r+366*hd*3;if(t>i){let c=wS(n,ga(i));if(c===null||ae.default.lessThan(c,ga(r)))return c}if(n==="Africa/Casablanca"||n==="Africa/El_Aaiun"){let c=Date.UTC(2088,0,1);if(c<t)return wS(n,ga(c))}let o=t-1;if(o<By)return null;let s=sh(n,o),a=o,l=s;for(;s===l&&o>By;){if(a=o-2*hd*7,a<By)return null;l=sh(n,a),s===l&&(o=a)}return s===l?null:ga(lU(c=>sh(n,c),a,o,l,s))}function $N(n,e){return function(t){let r=t.split(/[^\w]+/);if(r.length!==7)throw new RangeError(`expected 7 parts in "${t}`);let i=+r[0],o=+r[1],s=+r[2],a=r[3];if(a[0]==="b"||a[0]==="B")s=1-s;else if(a[0]!=="a"&&a[0]!=="A")throw new RangeError(`Unknown era ${a} in "${t}`);let l=r[4]==="24"?0:+r[4],c=+r[5],u=+r[6];if(!(Number.isFinite(s)&&Number.isFinite(i)&&Number.isFinite(o)&&Number.isFinite(l)&&Number.isFinite(c)&&Number.isFinite(u)))throw new RangeError(`Invalid number in "${t}`);return{year:s,month:i,day:o,hour:l,minute:c,second:u}}(FN(n).format(e))}function cE(n){return n!==void 0&&!(n%4!=0||n%100==0&&n%400!=0)}function ah(n,e){return{standard:[31,28,31,30,31,30,31,31,30,31,30,31],leapyear:[31,29,31,30,31,30,31,31,30,31,30,31]}[cE(n)?"leapyear":"standard"][e-1]}function lE(n){let e=[z(n,Mi),z(n,Fi),z(n,co),z(n,ki),z(n,Oi),z(n,Gi),z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo)];for(let t=0;t<e.length;t++){let r=e[t];if(r!==0)return r<0?-1:1}return 0}function CE(n){let e=["years","months","weeks","days"];for(let t=0;t<e.length;t++){let r=n[e[t]];if(r!==0)return r<0?-1:1}return 0}function eU(n){let e=CE(n.date);return e!==0?e:n.time.sign()}function oh(n,e){let t=n,r=e;if(!Number.isFinite(t)||!Number.isFinite(r))throw new RangeError("infinity is out of range");return r-=1,t+=Math.floor(r/12),r%=12,r<0&&(r+=12),r+=1,{year:t,month:r}}function ho(n,e,t){let r=n,i=e,o=t;if(!Number.isFinite(o))throw new RangeError("infinity is out of range");({year:r,month:i}=oh(r,i));let s=146097;if(Math.abs(o)>s){let c=Math.trunc(o/s);r+=400*c,o-=c*s}let a=0,l=i>2?r:r-1;for(;a=cE(l)?366:365,o<-a;)r-=1,l-=1,o+=a;for(l+=1;a=cE(l)?366:365,o>a;)r+=1,l+=1,o-=a;for(;o<1;)({year:r,month:i}=oh(r,i-1)),o+=ah(r,i);for(;o>ah(r,i);)o-=ah(r,i),{year:r,month:i}=oh(r,i+1);return{year:r,month:i,day:o}}function Hy(n,e,t,r,i,o,s,a,l){let c=cd(r,i,o,s,a,l);return Ht(ho(n,e,t+c.deltaDays),c)}function cd(n,e,t,r,i,o){let s,a=n,l=e,c=t,u=r,d=i,h=o;({div:s,mod:h}=T0(h,3)),d+=s,h<0&&(d-=1,h+=1e3),{div:s,mod:d}=T0(d,3),u+=s,d<0&&(u-=1,d+=1e3),c+=Math.trunc(u/1e3),u%=1e3,u<0&&(c-=1,u+=1e3),l+=Math.trunc(c/60),c%=60,c<0&&(l-=1,c+=60),a+=Math.trunc(l/60),l%=60,l<0&&(a-=1,l+=60);let f=Math.trunc(a/24);return a%=24,a<0&&(f-=1,a+=24),f+=0,a+=0,l+=0,c+=0,u+=0,d+=0,h+=0,{deltaDays:f,hour:a,minute:l,second:c,millisecond:u,microsecond:d,nanosecond:h}}function $G(n,e){let t=oi(n,0);if(CE(t)===0)return n.days;let r=z(e,ot),i=qo(z(e,ve),r,t,"constrain"),o=dh(r.year,r.month-1,r.day),s=dh(i.year,i.month-1,i.day)-o;return n.days+s}function po(n){return new(Vr("%Temporal.Duration%"))(-z(n,Mi),-z(n,Fi),-z(n,co),-z(n,ki),-z(n,Oi),-z(n,Gi),-z(n,Ni),-z(n,Ui),-z(n,Hi),-z(n,lo))}function Ki(n,e,t){return Math.min(t,Math.max(e,n))}function tU(n,e,t){let r=Ki(e,1,12);return{year:n,month:r,day:Ki(t,1,ah(n,r))}}function vr(n,e,t){if(n<e||n>t)throw new RangeError(`value out of range: ${e} <= ${n} <= ${t}`)}function lh(n,e,t){vr(e,1,12),vr(t,1,ah(n,e))}function gh(n){uh(Ht(n,{deltaDays:0,hour:12,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}))}function SE(n,e,t,r,i,o){vr(n,0,23),vr(e,0,59),vr(t,0,59),vr(r,0,999),vr(i,0,999),vr(o,0,999)}function _S(n,e,t,r,i,o,s,a,l){lh(n,e,t),SE(r,i,o,s,a,l)}function uh(n){let e=Qr(n);(ae.default.lessThan(e,ire)||ae.default.greaterThan(e,ore))&&sc(e)}function bS(n){Qr(n)}function sc(n){if(ae.default.lessThan(n,ky)||ae.default.greaterThan(n,k0))throw new RangeError("date/time value is outside of supported range")}function $S({year:n,month:e}){vr(n,UG,HG),n===UG?vr(e,4,12):n===HG&&vr(e,1,9)}function DE(n,e,t,r,i,o,s,a,l,c){let u=0,d=[n,e,t,r,i,o,s,a,l,c];for(let v=0;v<d.length;v++){let B=d[v];if(B===1/0||B===-1/0)throw new RangeError("infinite values not allowed as duration fields");if(B!==0){let U=B<0?-1:1;if(u!==0&&U!==u)throw new RangeError("mixed-sign values not allowed as duration fields");u=U}}if(Math.abs(n)>=2**32||Math.abs(e)>=2**32||Math.abs(t)>=2**32)throw new RangeError("years, months, and weeks must be < 2\xB3\xB2");let h=T0(a,3),f=T0(l,6),p=T0(c,9),w=T0(1e6*h.mod+1e3*f.mod+p.mod,9).div,y=86400*r+3600*i+60*o+s+h.div+f.div+p.div+w;if(!Number.isSafeInteger(y))throw new RangeError("total of duration time units cannot exceed 9007199254740991.999999999 s")}function B0(n){return{date:{years:z(n,Mi),months:z(n,Fi),weeks:z(n,co),days:z(n,ki)},time:dn.fromComponents(z(n,Oi),z(n,Gi),z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo))}}function rc(n){let e=dn.fromComponents(z(n,Oi),z(n,Gi),z(n,Ni),z(n,Ui),z(n,Hi),z(n,lo)).add24HourDays(z(n,ki));return{date:{years:z(n,Mi),months:z(n,Fi),weeks:z(n,co),days:0},time:e}}function nU(n){let e=rc(n),t=Math.trunc(e.time.sec/86400);return DE(e.date.years,e.date.months,e.date.weeks,t,0,0,0,0,0,0),{...e.date,days:t}}function Is(n,e){let t=n.time.sign(),r=n.time.abs().subsec,i=0,o=0,s=n.time.abs().sec,a=0,l=0,c=0;switch(e){case"year":case"month":case"week":case"day":i=Math.trunc(r/1e3),r%=1e3,o=Math.trunc(i/1e3),i%=1e3,s+=Math.trunc(o/1e3),o%=1e3,a=Math.trunc(s/60),s%=60,l=Math.trunc(a/60),a%=60,c=Math.trunc(l/24),l%=24;break;case"hour":i=Math.trunc(r/1e3),r%=1e3,o=Math.trunc(i/1e3),i%=1e3,s+=Math.trunc(o/1e3),o%=1e3,a=Math.trunc(s/60),s%=60,l=Math.trunc(a/60),a%=60;break;case"minute":i=Math.trunc(r/1e3),r%=1e3,o=Math.trunc(i/1e3),i%=1e3,s+=Math.trunc(o/1e3),o%=1e3,a=Math.trunc(s/60),s%=60;break;case"second":i=Math.trunc(r/1e3),r%=1e3,o=Math.trunc(i/1e3),i%=1e3,s+=Math.trunc(o/1e3),o%=1e3;break;case"millisecond":i=Math.trunc(r/1e3),r%=1e3,o=tS(s,3,Math.trunc(i/1e3)),i%=1e3,s=0;break;case"microsecond":i=tS(s,6,Math.trunc(r/1e3)),r%=1e3,s=0;break;case"nanosecond":r=tS(s,9,r),s=0}return new(Vr("%Temporal.Duration%"))(n.date.years,n.date.months,n.date.weeks,n.date.days+t*c,t*l,t*a,t*s,t*o,t*i,t*r)}function xl(n,e){return CE(n),e.sign(),{date:n,time:e}}function dh(n,e,t){return ZS({isoDate:{year:n,month:e+1,day:t},time:{hour:0,minute:0,second:0,millisecond:0}})/hd}function M0({year:n,month:e,day:t}){if(Math.abs(dh(n,e-1,t))>1e8)throw new RangeError("date/time value is outside the supported range")}function e4(n,e){let t=e.hour-n.hour,r=e.minute-n.minute,i=e.second-n.second,o=e.millisecond-n.millisecond,s=e.microsecond-n.microsecond,a=e.nanosecond-n.nanosecond;return dn.fromComponents(t,r,i,o,s,a)}function t4(n,e,t,r,i){let o=dn.fromEpochNsDiff(e,n);return o=uE(o,t,r,i),xl({years:0,months:0,weeks:0,days:0},o)}function rU(n,e,t,r){bS(n),bS(e);let i=e4(n.time,e.time),o=i.sign(),s=ac(n.isoDate,e.isoDate),a=e.isoDate;s===o&&(a=ho(a.year,a.month,a.day+o),i=i.add24HourDays(-o));let l=El("day",r),c=sw(t,n.isoDate,a,l);return r!==l&&(i=i.add24HourDays(c.days),c.days=0),xl(c,i)}function iU(n,e,t,r,i){let o=ae.default.subtract(e,n);if(ae.default.equal(o,Ko))return{date:{years:0,months:0,weeks:0,days:0},time:dn.ZERO};let s=ae.default.lessThan(o,Ko)?-1:1,a=xs(t,n),l=xs(t,e),c,u=0,d=s===1?2:1,h=e4(a.time,l.time);for(h.sign()===-s&&u++;u<=d;u++){c=Ht(ho(l.isoDate.year,l.isoDate.month,l.isoDate.day-u*s),a.time);let p=si(t,c,"compatible");if(h=dn.fromEpochNsDiff(e,p),h.sign()!==-s)break}let f=El("day",i);return xl(sw(r,a.isoDate,c.isoDate,f),h)}function oU(n,e,t,r,i,o,s,a,l){let c,u,d,h,f=e;switch(a){case"year":{let G=ud(f.date.years,s,"trunc");c=G,u=G+s*n,d={years:c,months:0,weeks:0,days:0},h={...d,years:u};break}case"month":{let G=ud(f.date.months,s,"trunc");c=G,u=G+s*n,d=oi(f.date,0,0,c),h=oi(f.date,0,0,u);break}case"week":{let G=oi(f.date,0,0),x=qo(o,r.isoDate,G,"constrain"),S=sw(o,x,ho(x.year,x.month,x.day+f.date.days),"week"),M=ud(f.date.weeks+S.weeks,s,"trunc");c=M,u=M+s*n,d=oi(f.date,0,c),h=oi(f.date,0,u);break}case"day":{let G=ud(f.date.days,s,"trunc");c=G,u=G+s*n,d=oi(f.date,c),h=oi(f.date,u);break}}let p=qo(o,r.isoDate,d,"constrain"),w=qo(o,r.isoDate,h,"constrain"),y,v,B=Ht(p,r.time),U=Ht(w,r.time);i?(y=si(i,B,"compatible"),v=si(i,U,"compatible")):(y=Qr(B),v=Qr(U));let k=dn.fromEpochNsDiff(t,y),F=dn.fromEpochNsDiff(v,y),P=wE(l,n<0?"negative":"positive"),I=k.add(k).abs().subtract(F.abs()).sign(),D=Math.abs(c)/s%2==0,V=k.isZero()?Math.abs(c):k.cmp(F)?bE(Math.abs(c),Math.abs(u),I,D,P):Math.abs(u),K=new dn(ae.default.add(ae.default.multiply(F.totalNs,ae.default.BigInt(c)),ae.default.multiply(k.totalNs,ae.default.BigInt(s*n)))).fdiv(F.totalNs),q=V===Math.abs(u);return f={date:q?h:d,time:dn.ZERO},{nudgeResult:{duration:f,nudgedEpochNs:q?v:y,didExpandCalendarUnit:q},total:K}}function LE(n,e,t,r,i,o,s,a,l){let c=n,u=tc(a)||r&&a==="day",d=eU(c)<0?-1:1,h;return u?{nudgeResult:h}=oU(d,c,e,t,r,i,s,a,l):h=r?function(f,p,w,y,v,B,U,k){let F=p,P=qo(v,w.isoDate,F.date,"constrain"),I=Ht(P,w.time),D=Ht(ho(P.year,P.month,P.day+f),w.time),V=si(y,I,"compatible"),K=si(y,D,"compatible"),q=dn.fromEpochNsDiff(K,V);if(q.sign()!==f)throw new RangeError("time zone returned inconsistent Instants");let G=ae.default.BigInt(G0[U]*B),x=F.time.round(G,k),S=x.subtract(q),M=S.sign()!==-f,b,A;return M?(b=f,x=S.round(G,k),A=x.addToEpochNs(K)):(b=0,A=x.addToEpochNs(V)),{duration:xl(oi(F.date,F.date.days+b),x),nudgedEpochNs:A,didExpandCalendarUnit:M}}(d,c,t,r,i,s,a,l):function(f,p,w,y,v,B){let U=f,k=U.time.add24HourDays(U.date.days),F=k.round(ae.default.BigInt(y*G0[v]),B),P=F.subtract(k),{quotient:I}=k.divmod(rE),{quotient:D}=F.divmod(rE),V=Math.sign(D-I)===k.sign(),K=P.addToEpochNs(p),q=0,G=F;return wl(w)==="date"&&(q=D,G=F.add(dn.fromComponents(24*-D,0,0,0,0,0))),{duration:{date:oi(U.date,q),time:G},nudgedEpochNs:K,didExpandCalendarUnit:V}}(c,e,o,s,a,l),c=h.duration,h.didExpandCalendarUnit&&a!=="week"&&(c=function(f,p,w,y,v,B,U,k){let F=p;if(k===U)return F;let P=Ty.indexOf(U);for(let I=Ty.indexOf(k)-1;I>=P;I--){let D=Ty[I];if(D==="week"&&U!=="week")continue;let V;switch(D){case"year":V={years:F.date.years+f,months:0,weeks:0,days:0};break;case"month":{let G=F.date.months+f;V=oi(F.date,0,0,G);break}case"week":{let G=F.date.weeks+f;V=oi(F.date,0,G);break}}let K=Ht(qo(B,y.isoDate,V,"constrain"),y.time),q;if(q=v?si(v,K,"compatible"):Qr(K),tE(w,q)===-f)break;F={date:V,time:dn.ZERO}}return F}(d,c,h.nudgedEpochNs,t,r,i,o,El(a,"day"))),c}function eN(n,e,t,r,i,o){return tc(o)||r&&o==="day"?oU(eU(n)<0?-1:1,n,e,t,r,i,1,o,"trunc").total:My(n.time.add24HourDays(n.date.days),o)}function sU(n,e,t,r,i,o,s){if(U0(n,e)==0)return{date:{years:0,months:0,weeks:0,days:0},time:dn.ZERO};uh(n),uh(e);let a=rU(n,e,t,r);return o==="nanosecond"&&i===1?a:LE(a,Qr(e),n,null,t,r,i,o,s)}function aU(n,e,t,r,i,o,s,a){if(wl(i)==="time")return t4(n,e,o,s,a);let l=iU(n,e,t,r,i);return s==="nanosecond"&&o===1?l:LE(l,e,xs(t,n),t,r,i,o,s,a)}function V0(n,e,t,r,i,o){let s=O0.reduce((f,p)=>{let w=p[0],y=p[1],v=p[2];return t!=="datetime"&&v!==t||r.includes(y)||f.push(y,w),f},[]),a=fo(e,"largestUnit",t,"auto");if(r.includes(a))throw new RangeError(`largestUnit must be one of ${s.join(", ")}, not ${a}`);let l=J0(e),c=ya(e,"trunc");n==="since"&&(c=function(f){switch(f){case"ceil":return"floor";case"floor":return"ceil";case"halfCeil":return"halfFloor";case"halfFloor":return"halfCeil";default:return f}}(c));let u=fo(e,"smallestUnit",t,i);if(r.includes(u))throw new RangeError(`smallestUnit must be one of ${s.join(", ")}, not ${u}`);let d=El(o,u);if(a==="auto"&&(a=d),El(a,u)!==a)throw new RangeError(`largestUnit ${a} cannot be smaller than smallestUnit ${u}`);let h={hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[u];return h!==void 0&&q0(l,h,!1),{largestUnit:a,roundingIncrement:l,roundingMode:c,smallestUnit:u}}function tN(n,e,t,r){let i=vy(t),o=V0(n,Qe(r),"time",[],"nanosecond","second"),s=Is(t4(z(e,it),z(i,it),o.roundingIncrement,o.smallestUnit,o.roundingMode),o.largestUnit);return n==="since"&&(s=po(s)),s}function nN(n,e,t,r){let i=xy(t),o=z(e,ve),s=z(i,ve);if(!oc(o,s))throw new RangeError(`cannot compute difference between dates of ${o} and ${s} calendars`);let a=V0(n,Qe(r),"date",[],"day","day"),l=Vr("%Temporal.Duration%"),c=z(e,ot),u=z(i,ot);if(ac(c,u)===0)return new l;let d={date:sw(o,c,u,a.largestUnit),time:dn.ZERO};if(a.smallestUnit!=="day"||a.roundingIncrement!==1){let f=Ht(c,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});d=LE(d,Qr(Ht(u,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0})),f,null,o,a.largestUnit,a.roundingIncrement,a.smallestUnit,a.roundingMode)}let h=Is(d,"day");return n==="since"&&(h=po(h)),h}function rN(n,e,t,r){let i=Ay(t),o=z(e,ve),s=z(i,ve);if(!oc(o,s))throw new RangeError(`cannot compute difference between dates of ${o} and ${s} calendars`);let a=V0(n,Qe(r),"datetime",[],"nanosecond","day"),l=Vr("%Temporal.Duration%"),c=z(e,vn),u=z(i,vn);if(U0(c,u)===0)return new l;let d=Is(sU(c,u,o,a.largestUnit,a.roundingIncrement,a.smallestUnit,a.roundingMode),a.largestUnit);return n==="since"&&(d=po(d)),d}function iN(n,e,t,r){let i=ld(t),o=V0(n,Qe(r),"time",[],"nanosecond","hour"),s=e4(z(e,On),z(i,On));s=uE(s,o.roundingIncrement,o.smallestUnit,o.roundingMode);let a=Is(xl({years:0,months:0,weeks:0,days:0},s),o.largestUnit);return n==="since"&&(a=po(a)),a}function oN(n,e,t,r){let i=Cy(t),o=z(e,ve),s=z(i,ve);if(!oc(o,s))throw new RangeError(`cannot compute difference between months of ${o} and ${s} calendars`);let a=V0(n,Qe(r),"date",["week","day"],"month","year"),l=Vr("%Temporal.Duration%");if(ac(z(e,ot),z(i,ot))==0)return new l;let c=Qi(o,z(e,ot),"year-month");c.day=1;let u=pd(o,c,"constrain"),d=Qi(o,z(i,ot),"year-month");d.day=1;let h=pd(o,d,"constrain"),f={date:oi(sw(o,u,h,a.largestUnit),0,0),time:dn.ZERO};if(a.smallestUnit!=="month"||a.roundingIncrement!==1){let w=Ht(u,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});f=LE(f,Qr(Ht(h,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0})),w,null,o,a.largestUnit,a.roundingIncrement,a.smallestUnit,a.roundingMode)}let p=Is(f,"day");return n==="since"&&(p=po(p)),p}function sN(n,e,t,r){let i=Sy(t),o=z(e,ve),s=z(i,ve);if(!oc(o,s))throw new RangeError(`cannot compute difference between dates of ${o} and ${s} calendars`);let a=V0(n,Qe(r),"datetime",[],"nanosecond","hour"),l=z(e,it),c=z(i,it),u=Vr("%Temporal.Duration%"),d;if(wl(a.largestUnit)!=="date")d=Is(t4(l,c,a.roundingIncrement,a.smallestUnit,a.roundingMode),a.largestUnit);else{let h=z(e,Xt);if(!jN(h,z(i,Xt)))throw new RangeError("When calculating difference between time zones, largestUnit must be 'hours' or smaller because day lengths can vary between time zones due to DST or time zone offset changes.");if(ae.default.equal(l,c))return new u;d=Is(aU(l,c,h,o,a.largestUnit,a.roundingIncrement,a.smallestUnit,a.roundingMode),"hour")}return n==="since"&&(d=po(d)),d}function N0({hour:n,minute:e,second:t,millisecond:r,microsecond:i,nanosecond:o},s){let a=t,l=o;return a+=s.sec,l+=s.subsec,cd(n,e,a,r,i,l)}function IS(n,e){let t=e.addToEpochNs(n);return sc(t),t}function Dy(n,e,t,r,i="constrain"){if(CE(r.date)===0)return IS(n,r.time);let o=xs(e,n);return IS(si(e,Ht(qo(t,o.isoDate,r.date,i),o.time),"compatible"),r.time)}function aN(n,e,t){let r=Es(t);n==="subtract"&&(r=po(r));let i=El(yl(e),yl(r));if(tc(i))throw new RangeError("For years, months, or weeks arithmetic, use date arithmetic relative to a starting point");let o=rc(e),s=rc(r);return Is(xl({years:0,months:0,weeks:0,days:0},o.time.add(s.time)),i)}function cN(n,e,t){let r=Es(t);n==="subtract"&&(r=po(r));let i=yl(r);if(wl(i)==="date")throw new RangeError(`Duration field ${i} not supported by Temporal.Instant. Try Temporal.ZonedDateTime instead.`);let o=rc(r);return ma(IS(z(e,it),o.time))}function lN(n,e,t,r){let i=z(e,ve),o=Es(t);n==="subtract"&&(o=po(o));let s=nU(o),a=kt(Qe(r));return Ji(qo(i,z(e,ot),s,a),i)}function uN(n,e,t,r){let i=Es(t);n==="subtract"&&(i=po(i));let o=kt(Qe(r)),s=z(e,ve),a=rc(i),l=z(e,vn),c=N0(l.time,a.time),u=oi(a.date,c.deltaDays);return DE(u.years,u.months,u.weeks,u.days,0,0,0,0,0,0),bs(Ht(qo(s,l.isoDate,u,o),c),s)}function dN(n,e,t){let r=Es(t);n==="subtract"&&(r=po(r));let i=rc(r),{hour:o,minute:s,second:a,millisecond:l,microsecond:c,nanosecond:u}=N0(z(e,On),i.time);return bl(AE(o,s,a,l,c,u,"reject"))}function fN(n,e,t,r){let i=Es(t);n==="subtract"&&(i=po(i));let o=kt(Qe(r)),s=lE(i),a=z(e,ve),l=Qi(a,z(e,ot),"year-month");l.day=1;let c=pd(a,l,"constrain");if(s<0){let d=qo(a,c,{months:1},"constrain");c=ho(d.year,d.month,d.day-1)}let u=nU(i);return gh(c),R0(Gy(a,Qi(a,qo(a,c,u,o),"year-month"),o),a)}function hN(n,e,t,r){let i=Es(t);n==="subtract"&&(i=po(i));let o=kt(Qe(r)),s=z(e,Xt),a=z(e,ve),l=B0(i);return ii(Dy(z(e,it),s,a,l,o),s,a)}function ud(n,e,t){let r=Math.trunc(n/e),i=n%e,o=n<0?"negative":"positive",s=Math.abs(r),a=s+1,l=uo(Math.abs(2*i)-e),c=s%2==0,u=wE(t,o),d=i===0?s:bE(s,a,l,c,u);return e*(o==="positive"?d:-d)}function ES(n,e,t,r){let i=G0[t]*e;return function(o,s,a){let l=gl(o),c=gl(s),u=ae.default.divide(l,c),d=ae.default.remainder(l,c),h=wE(a,"positive"),f,p;ae.default.lessThan(l,Ko)?(f=ae.default.subtract(u,Fy),p=u):(f=u,p=ae.default.add(u,Fy));let w=tE(ih(ae.default.multiply(d,YS)),c)*(ae.default.lessThan(l,Ko)?-1:1)+0,y=ae.default.equal(d,Ko)?u:bE(f,p,w,yN(f),h);return ae.default.multiply(y,c)}(n,ae.default.BigInt(i),r)}function xS(n,e,t,r){bS(n);let{year:i,month:o,day:s}=n.isoDate,a=AS(n.time,e,t,r);return Ht(ho(i,o,s+a.deltaDays),a)}function AS({hour:n,minute:e,second:t,millisecond:r,microsecond:i,nanosecond:o},s,a,l){let c;switch(a){case"day":case"hour":c=1e3*(1e3*(1e3*(60*(60*n+e)+t)+r)+i)+o;break;case"minute":c=1e3*(1e3*(1e3*(60*e+t)+r)+i)+o;break;case"second":c=1e3*(1e3*(1e3*t+r)+i)+o;break;case"millisecond":c=1e3*(1e3*r+i)+o;break;case"microsecond":c=1e3*i+o;break;case"nanosecond":c=o}let u=G0[a],d=ud(c,u*s,l)/u;switch(a){case"day":return{deltaDays:d,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0};case"hour":return cd(d,0,0,0,0,0);case"minute":return cd(n,d,0,0,0,0);case"second":return cd(n,e,d,0,0,0);case"millisecond":return cd(n,e,t,d,0,0);case"microsecond":return cd(n,e,t,r,d,0);case"nanosecond":return cd(n,e,t,r,i,d);default:throw new Error(`Invalid unit ${a}`)}}function uE(n,e,t,r){let i=G0[t];return n.round(ae.default.BigInt(i*e),r)}function My(n,e){let t=G0[e];return n.fdiv(ae.default.BigInt(t))}function ac(n,e){return n.year!==e.year?uo(n.year-e.year):n.month!==e.month?uo(n.month-e.month):n.day!==e.day?uo(n.day-e.day):0}function vS(n,e){return n.hour!==e.hour?uo(n.hour-e.hour):n.minute!==e.minute?uo(n.minute-e.minute):n.second!==e.second?uo(n.second-e.second):n.millisecond!==e.millisecond?uo(n.millisecond-e.millisecond):n.microsecond!==e.microsecond?uo(n.microsecond-e.microsecond):n.nanosecond!==e.nanosecond?uo(n.nanosecond-e.nanosecond):0}function U0(n,e){let t=ac(n.isoDate,e.isoDate);return t!==0?t:vS(n.time,e.time)}function cU(n){let e=dE(n);return globalThis.BigInt!==void 0?globalThis.BigInt(e.toString(10)):e}function As(n,e){let t=gl(n),{quotient:r,remainder:i}=Iy(t,_y),o=ae.default.toNumber(r);return e==="floor"&&ae.default.toNumber(i)<0&&(o-=1),e==="ceil"&&ae.default.toNumber(i)>0&&(o+=1),o}function ga(n){if(!Number.isInteger(n))throw new RangeError("epoch milliseconds must be an integer");return ae.default.multiply(ae.default.BigInt(n),_y)}function dE(n){let e=n;if(typeof n=="object"){let t=n[Symbol.toPrimitive];t&&typeof t=="function"&&(e=t.call(n,"number"))}if(typeof e=="number")throw new TypeError("cannot convert number to bigint");return typeof e=="bigint"?ae.default.BigInt(e.toString(10)):ae.default.BigInt(e)}var CS=(()=>{let n=ae.default.BigInt(Date.now()%1e6);return()=>{let e=Date.now(),t=ae.default.BigInt(e),r=ae.default.add(ga(e),n);return n=ae.default.remainder(t,_y),ae.default.greaterThan(r,k0)?k0:ae.default.lessThan(r,ky)?ky:r}})();function wy(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}function uo(n){return n<0?-1:n>0?1:n}function Qe(n){if(n===void 0)return Object.create(null);if(Gn(n)&&n!==null)return n;throw new TypeError("Options parameter must be an object, not "+(n===null?"null":typeof n))}function fh(n,e){let t=Object.create(null);return t[n]=e,t}function Al(n,e,t,r){let i=n[e];if(i!==void 0){if(i=EE(i),!t.includes(i))throw new RangeError(`${e} must be one of ${t.join(", ")}, not ${i}`);return i}if(r===Cl)throw new RangeError(`${e} option is required`);return r}function Yi(n){let e=Ky(n);if(!are.includes(Ky(e)))throw new RangeError(`invalid calendar identifier ${e}`);switch(e){case"ethiopic-amete-alem":return"ethioaa";case"islamicc":return"islamic-civil"}return e}function Ky(n){let e="";for(let t=0;t<n.length;t++){let r=n.charCodeAt(t);e+=r>=65&&r<=90?String.fromCharCode(r+32):String.fromCharCode(r)}return e}function yd(n){throw new TypeError(`Do not use built-in arithmetic operators with Temporal objects. When comparing, use ${n==="PlainMonthDay"?"Temporal.PlainDate.compare(obj1.toPlainDate(year), obj2.toPlainDate(year))":`Temporal.${n}.compare(obj1, obj2)`}, not obj1 > obj2. When coercing to strings, use \`\${obj}\` or String(obj), not '' + obj. When coercing to numbers, use properties or methods of the object, not \`+obj\`. When concatenating with strings, use \`\${str}\${obj}\` or str.concat(obj), not str + obj. In React, coerce to a string before rendering a Temporal object.`)}var pre=new RegExp(`^${PN.source}$`),mre=new RegExp(`^${/([+-])([01][0-9]|2[0-3])(?::?([0-5][0-9])(?::?([0-5][0-9])(?:[.,](\d{1,9}))?)?)?/.source}$`);function lU(n,e,t,r=n(e),i=n(t)){let o=e,s=t,a=r,l=i;for(;s-o>1;){let c=Math.trunc((o+s)/2),u=n(c);u===a?(o=c,a=u):u===l&&(s=c,l=u)}return s}function uU(n){return[...n]}function dU(n,e){if(n!=="gregory"&&n!=="iso8601")return;let t=uw[n],r=e.year,{dayOfWeek:i,dayOfYear:o,daysInYear:s}=t.isoToDate(e,{dayOfWeek:!0,dayOfYear:!0,daysInYear:!0}),a=t.getFirstDayOfWeek(),l=t.getMinimalDaysInFirstWeek(),c=(i+7-a)%7,u=(i-o+7001-a)%7,d=Math.floor((o-1+u)/7);if(7-u>=l&&++d,d==0)d=function(h,f,p,w){let y=(w-h-p+1)%7;y<0&&(y+=7);let v=Math.floor((p+y-1)/7);return 7-y>=f&&++v,v}(a,l,o+t.isoToDate(t.dateAdd(e,{years:-1},"constrain"),{daysInYear:!0}).daysInYear,i),r--;else if(o>=s-5){let h=(c+s-o)%7;h<0&&(h+=7),6-h>=l&&o+7-c>s&&(d=1,r++)}return{week:d,year:r}}function pN(n,e,t,r,i){if(e!==i.year){if(n*(e-i.year)>0)return!0}else if(t!==i.month){if(n*(t-i.month)>0)return!0}else if(r!==i.day&&n*(r-i.day)>0)return!0;return!1}var uw={};function hh(n){if(!n.startsWith("M"))throw new RangeError(`Invalid month code: ${n}. Month codes must start with M.`);let e=+n.slice(1);if(Number.isNaN(e))throw new RangeError(`Invalid month code: ${n}`);return e}function ic(n,e=!1){return`M${`${n}`.padStart(2,"0")}${e?"L":""}`}function n4(n,e=void 0,t=12){let{month:r,monthCode:i}=n;if(i===void 0){if(r===void 0)throw new TypeError("Either month or monthCode are required");e==="reject"&&vr(r,1,t),e==="constrain"&&(r=Ki(r,1,t)),i=ic(r)}else{let o=hh(i);if(i!==ic(o))throw new RangeError(`Invalid month code: ${i}`);if(r!==void 0&&r!==o)throw new RangeError(`monthCode ${i} and month ${r} must match if both are present`);if(r=o,r<1||r>t)throw new RangeError(`Invalid monthCode: ${i}`)}return{...n,month:r,monthCode:i}}uw.iso8601={resolveFields(n,e){if((e==="date"||e==="year-month")&&n.year===void 0)throw new TypeError("year is required");if((e==="date"||e==="month-day")&&n.day===void 0)throw new TypeError("day is required");Object.assign(n,n4(n))},dateToISO:(n,e)=>Py(n.year,n.month,n.day,e),monthDayToISOReferenceDate(n,e){let{month:t,day:r}=Py(n.year??1972,n.month,n.day,e);return{month:t,day:r,year:1972}},extraFields:()=>[],fieldKeysToIgnore(n){let e=new Set;for(let t=0;t<n.length;t++){let r=n[t];e.add(r),r==="month"?e.add("monthCode"):r==="monthCode"&&e.add("month")}return uU(e)},dateAdd(n,{years:e=0,months:t=0,weeks:r=0,days:i=0},o){let{year:s,month:a,day:l}=n;return s+=e,a+=t,{year:s,month:a}=oh(s,a),{year:s,month:a,day:l}=Py(s,a,l,o),l+=i+7*r,ho(s,a,l)},dateUntil(n,e,t){let r=-ac(n,e);if(r===0)return{years:0,months:0,weeks:0,days:0};let i,o=0,s=0;if(t==="year"||t==="month"){let u=e.year-n.year;for(u!==0&&(u-=r);!pN(r,n.year+u,n.month,n.day,e);)o=u,u+=r;let d=r;for(i=oh(n.year+o,n.month+d);!pN(r,i.year,i.month,n.day,e);)s=d,d+=r,i=oh(i.year,i.month+r);t==="month"&&(s+=12*o,o=0)}i=oh(n.year+o,n.month+s);let a=tU(i.year,i.month,n.day),l=0,c=dh(e.year,e.month-1,e.day)-dh(a.year,a.month-1,a.day);return t==="week"&&(l=Math.trunc(c/7),c%=7),{years:o,months:s,weeks:l,days:c}},isoToDate({year:n,month:e,day:t},r){let i={era:void 0,eraYear:void 0,year:n,month:e,day:t,daysInWeek:7,monthsInYear:12};if(r.monthCode&&(i.monthCode=ic(e)),r.dayOfWeek){let o=e+(e<3?10:-2),s=n-(e<3?1:0),a=Math.floor(s/100),l=s-100*a,c=(t+Math.floor(2.6*o-.2)+(l+Math.floor(l/4))+(Math.floor(a/4)-2*a))%7;i.dayOfWeek=c+(c<=0?7:0)}if(r.dayOfYear){let o=t;for(let s=e-1;s>0;s--)o+=ah(n,s);i.dayOfYear=o}return r.weekOfYear&&(i.weekOfYear=dU("iso8601",{year:n,month:e,day:t})),r.daysInMonth&&(i.daysInMonth=ah(n,e)),(r.daysInYear||r.inLeapYear)&&(i.inLeapYear=cE(n),i.daysInYear=i.inLeapYear?366:365),i},getFirstDayOfWeek:()=>1,getMinimalDaysInFirstWeek:()=>4};var Uo=class n{constructor(e){if(this.map=new Map,this.calls=0,this.hits=0,this.misses=0,e!==void 0){let t=0;for(let r of e.map.entries()){if(++t>n.MAX_CACHE_ENTRIES)break;this.map.set(...r)}}}get(e){let t=this.map.get(e);return t&&(this.hits++,this.report()),this.calls++,t}set(e,t){this.map.set(e,t),this.misses++,this.report()}report(){}setObject(e){if(n.objectMap.get(e))throw new RangeError("object already cached");n.objectMap.set(e,this),this.report()}static getCacheForObject(e){let t=n.objectMap.get(e);return t||(t=new n,n.objectMap.set(e,t)),t}};function fU({isoYear:n,isoMonth:e,isoDay:t}){return`${lw(n)}-${Qo(e)}-${Qo(t)}T00:00Z`}function iS(n,e){return{years:n.year-e.year,months:n.month-e.month,days:n.day-e.day}}Uo.objectMap=new WeakMap,Uo.MAX_CACHE_ENTRIES=1e3;var Sl=class{constructor(){this.eras=[],this.hasEra=!1,this.erasBeginMidYear=!1}getFormatter(){return this.formatter===void 0&&(this.formatter=new Intl.DateTimeFormat(`en-US-u-ca-${this.id}`,{day:"numeric",month:"numeric",year:"numeric",era:"short",timeZone:"UTC"})),this.formatter}getCalendarParts(e){let t=this.getFormatter(),r=new Date(e);if(e==="-271821-04-19T00:00Z"){let i=t.resolvedOptions();t=new Intl.DateTimeFormat(i.locale,{...i,timeZone:"Etc/GMT+1"}),r=new Date("-271821-04-20T00:00Z")}try{return t.formatToParts(r)}catch{throw new RangeError(`Invalid ISO date: ${e}`)}}isoToCalendarDate(e,t){let{year:r,month:i,day:o}=e,s=JSON.stringify({func:"isoToCalendarDate",isoYear:r,isoMonth:i,isoDay:o,id:this.id}),a=t.get(s);if(a)return a;let l=fU({isoYear:r,isoMonth:i,isoDay:o}),c=this.getCalendarParts(l),u={};for(let h=0;h<c.length;h++){let{type:f,value:p}=c[h];if(f!=="year"&&f!=="relatedYear"||(this.hasEra?u.eraYear=+p:u.year=+p),f==="month"){let w=/^([0-9]*)(.*?)$/.exec(p);if(!w||w.length!=3||!w[1]&&!w[2])throw new RangeError(`Unexpected month: ${p}`);if(u.month=w[1]?+w[1]:1,u.month<1)throw new RangeError(`Invalid month ${p} from ${l}[u-ca-${this.id}] (probably due to https://bugs.chromium.org/p/v8/issues/detail?id=10527)`);if(u.month>13)throw new RangeError(`Invalid month ${p} from ${l}[u-ca-${this.id}] (probably due to https://bugs.chromium.org/p/v8/issues/detail?id=10529)`);w[2]&&(u.monthExtra=w[2])}f==="day"&&(u.day=+p),this.hasEra&&f==="era"&&p!=null&&p!==""&&(u.era=p.split(" (")[0].normalize("NFD").replace(/[^-0-9 \p{L}]/gu,"").replace(/ /g,"-").toLowerCase())}if(this.hasEra&&u.eraYear===void 0)throw new RangeError(`Intl.DateTimeFormat.formatToParts lacks relatedYear in ${this.id} calendar. Try Node 14+ or modern browsers.`);if(this.hasEra){let h=this.eras.find(f=>u.era===f.genericName);h&&(u.era=h.code)}if(this.reviseIntlEra){let{era:h,eraYear:f}=this.reviseIntlEra(u,e);u.era=h,u.eraYear=f}this.checkIcuBugs&&this.checkIcuBugs(e);let d=this.adjustCalendarDate(u,t,"constrain",!0);if(d.year===void 0)throw new RangeError(`Missing year converting ${JSON.stringify(e)}`);if(d.month===void 0)throw new RangeError(`Missing month converting ${JSON.stringify(e)}`);if(d.day===void 0)throw new RangeError(`Missing day converting ${JSON.stringify(e)}`);return t.set(s,d),["constrain","reject"].forEach(h=>{let f=JSON.stringify({func:"calendarToIsoDate",year:d.year,month:d.month,day:d.day,overflow:h,id:this.id});t.set(f,e)}),d}validateCalendarDate(e){let{month:t,year:r,day:i,eraYear:o,monthCode:s,monthExtra:a}=e;if(a!==void 0)throw new RangeError("Unexpected `monthExtra` value");if(r===void 0&&o===void 0)throw new TypeError("year or eraYear is required");if(t===void 0&&s===void 0)throw new TypeError("month or monthCode is required");if(i===void 0)throw new RangeError("Missing day");if(s!==void 0){if(typeof s!="string")throw new RangeError("monthCode must be a string, not "+typeof s);if(!/^M([01]?\d)(L?)$/.test(s))throw new RangeError(`Invalid monthCode: ${s}`)}if(this.hasEra&&e.era===void 0!=(e.eraYear===void 0))throw new TypeError("properties era and eraYear must be provided together")}adjustCalendarDate(e,t=void 0,r="constrain",i=!1){if(this.calendarType==="lunisolar")throw new RangeError("Override required for lunisolar calendars");let o=e;this.validateCalendarDate(o);let s=this.monthsInYear(o,t),{month:a,monthCode:l}=o;return{month:a,monthCode:l}=n4(o,r,s),{...o,month:a,monthCode:l}}regulateMonthDayNaive(e,t,r){let i=this.monthsInYear(e,r),{month:o,day:s}=e;return t==="reject"?(vr(o,1,i),vr(s,1,this.maximumMonthLength(e))):(o=Ki(o,1,i),s=Ki(s,1,this.maximumMonthLength({...e,month:o}))),{...e,month:o,day:s}}calendarToIsoDate(e,t="constrain",r){let i=e,o=this.adjustCalendarDate(e,r,t,!1);o=this.regulateMonthDayNaive(o,t,r);let{year:s,month:a,day:l}=o,c=JSON.stringify({func:"calendarToIsoDate",year:s,month:a,day:l,overflow:t,id:this.id}),u,d=r.get(c);if(d||i.year!==void 0&&i.month!==void 0&&i.day!==void 0&&(i.year!==o.year||i.month!==o.month||i.day!==o.day)&&(u=JSON.stringify({func:"calendarToIsoDate",year:i.year,month:i.month,day:i.day,overflow:t,id:this.id}),d=r.get(u),d))return d;let h=this.estimateIsoDate({year:s,month:a,day:l}),f=B=>{let U=this.addDaysIso(h,B);if(o.day>this.minimumMonthLength(o)){let k=this.isoToCalendarDate(U,r);for(;k.month!==a||k.year!==s;){if(t==="reject")throw new RangeError(`day ${l} does not exist in month ${a} of year ${s}`);U=this.addDaysIso(U,-1),k=this.isoToCalendarDate(U,r)}}return U},p=0,w=this.isoToCalendarDate(h,r),y=iS(o,w);if(y.years!==0||y.months!==0||y.days!==0){let B=365*y.years+30*y.months+y.days;h=this.addDaysIso(h,B),w=this.isoToCalendarDate(h,r),y=iS(o,w),y.years===0&&y.months===0?h=f(y.days):p=this.compareCalendarDates(o,w)}let v=8;for(;p;){h=this.addDaysIso(h,p*v);let B=w;w=this.isoToCalendarDate(h,r);let U=p;if(p=this.compareCalendarDates(o,w),p){if(y=iS(o,w),y.years===0&&y.months===0)h=f(y.days),p=0;else if(U&&p!==U)if(v>1)v/=2;else{if(t==="reject")throw new RangeError(`Can't find ISO date from calendar date: ${JSON.stringify({...i})}`);this.compareCalendarDates(w,B)>0&&(h=this.addDaysIso(h,-1)),p=0}}}if(r.set(c,h),u&&r.set(u,h),o.year===void 0||o.month===void 0||o.day===void 0||o.monthCode===void 0||this.hasEra&&(o.era===void 0||o.eraYear===void 0))throw new RangeError("Unexpected missing property");return h}compareCalendarDates(e,t){return e.year!==t.year?uo(e.year-t.year):e.month!==t.month?uo(e.month-t.month):e.day!==t.day?uo(e.day-t.day):0}regulateDate(e,t="constrain",r){let i=this.calendarToIsoDate(e,t,r);return this.isoToCalendarDate(i,r)}addDaysIso(e,t){return ho(e.year,e.month,e.day+t)}addDaysCalendar(e,t,r){let i=this.calendarToIsoDate(e,"constrain",r),o=this.addDaysIso(i,t);return this.isoToCalendarDate(o,r)}addMonthsCalendar(e,t,r,i){let o=e,{day:s}=o;for(let a=0,l=Math.abs(t);a<l;a++){let{month:c}=o,u=o,d=t<0?-Math.max(s,this.daysInPreviousMonth(o,i)):this.daysInMonth(o,i),h=this.calendarToIsoDate(o,"constrain",i),f=this.addDaysIso(h,d);if(o=this.isoToCalendarDate(f,i),t>0){let p=this.monthsInYear(u,i);for(;o.month-1!=c%p;)f=this.addDaysIso(f,-1),o=this.isoToCalendarDate(f,i)}o.day!==s&&(o=this.regulateDate({...o,day:s},"constrain",i))}if(r==="reject"&&o.day!==s)throw new RangeError(`Day ${s} does not exist in resulting calendar month`);return o}addCalendar(e,{years:t=0,months:r=0,weeks:i=0,days:o=0},s,a){let{year:l,day:c,monthCode:u}=e,d=this.adjustCalendarDate({year:l+t,monthCode:u,day:c},a),h=this.addMonthsCalendar(d,r,s,a),f=o+7*i;return this.addDaysCalendar(h,f,a)}untilCalendar(e,t,r,i){let o=0,s=0,a=0,l=0;switch(r){case"day":o=this.calendarDaysUntil(e,t,i);break;case"week":{let c=this.calendarDaysUntil(e,t,i);o=c%7,s=(c-o)/7;break}case"month":case"year":{let c=this.compareCalendarDates(t,e);if(!c)return{years:0,months:0,weeks:0,days:0};let u=t.year-e.year,d=t.day-e.day;if(r==="year"&&u){let p=0;t.monthCode>e.monthCode&&(p=1),t.monthCode<e.monthCode&&(p=-1),p||(p=Math.sign(d)),l=p*c<0?u-c:u}let h,f=l?this.addCalendar(e,{years:l},"constrain",i):e;do a+=c,h=f,f=this.addMonthsCalendar(h,c,"constrain",i),f.day!==e.day&&(f=this.regulateDate({...f,day:e.day},"constrain",i));while(this.compareCalendarDates(t,f)*c>=0);a-=c,o=this.calendarDaysUntil(h,t,i);break}}return{years:l,months:a,weeks:s,days:o}}daysInMonth(e,t){let{day:r}=e,i=this.maximumMonthLength(e),o=this.minimumMonthLength(e);if(o===i)return o;let s=r<=i-o?i:o,a=this.calendarToIsoDate(e,"constrain",t),l=this.addDaysIso(a,s),c=this.isoToCalendarDate(l,t),u=this.addDaysIso(l,-c.day);return this.isoToCalendarDate(u,t).day}daysInPreviousMonth(e,t){let{day:r,month:i,year:o}=e,s={year:i>1?o:o-1,month:i,day:1},a=i>1?i-1:this.monthsInYear(s,t);s={...s,month:a};let l=this.minimumMonthLength(s),c=this.maximumMonthLength(s);if(l===c)return c;let u=this.calendarToIsoDate(e,"constrain",t),d=this.addDaysIso(u,-r);return this.isoToCalendarDate(d,t).day}startOfCalendarYear(e){return{year:e.year,month:1,monthCode:"M01",day:1}}startOfCalendarMonth(e){return{year:e.year,month:e.month,day:1}}calendarDaysUntil(e,t,r){let i=this.calendarToIsoDate(e,"constrain",r),o=this.calendarToIsoDate(t,"constrain",r);return dh(o.year,o.month-1,o.day)-dh(i.year,i.month-1,i.day)}monthDaySearchStartYear(e,t){return 1972}monthDayFromFields(e,t,r){let i,o,s,a,l,{era:c,eraYear:u,year:d,month:h,monthCode:f,day:p}=e;if(h!==void 0&&d===void 0&&(!this.hasEra||c===void 0||u===void 0))throw new TypeError("when month is present, year (or era and eraYear) are required");(f===void 0||d!==void 0||this.hasEra&&u!==void 0)&&({monthCode:f,day:p}=this.isoToCalendarDate(this.calendarToIsoDate(e,t,r),r));let w={year:this.monthDaySearchStartYear(f,p),month:12,day:31},y=this.isoToCalendarDate(w,r),v=y.monthCode>f||y.monthCode===f&&y.day>=p?y.year:y.year-1;for(let B=0;B<20;B++){let U=this.adjustCalendarDate({day:p,monthCode:f,year:v-B},r),k=this.calendarToIsoDate(U,"constrain",r),F=this.isoToCalendarDate(k,r);if({year:i,month:o,day:s}=k,F.monthCode===f&&F.day===p)return{month:o,day:s,year:i};if(t==="constrain"){let P=this.maxLengthOfMonthCodeInAnyYear(F.monthCode);if(F.monthCode===f&&F.day===P&&p>P)return{month:o,day:s,year:i};(a===void 0||F.monthCode===a.monthCode&&F.day>a.day)&&(a=F,l=k)}}if(t==="constrain"&&l!==void 0)return l;throw new RangeError(`No recent ${this.id} year with monthCode ${f} and day ${p}`)}getFirstDayOfWeek(){}getMinimalDaysInFirstWeek(){}},SS=class extends Sl{constructor(){super(...arguments),this.id="hebrew",this.calendarType="lunisolar",this.months={Tishri:{leap:1,regular:1,monthCode:"M01",days:30},Heshvan:{leap:2,regular:2,monthCode:"M02",days:{min:29,max:30}},Kislev:{leap:3,regular:3,monthCode:"M03",days:{min:29,max:30}},Tevet:{leap:4,regular:4,monthCode:"M04",days:29},Shevat:{leap:5,regular:5,monthCode:"M05",days:30},Adar:{leap:void 0,regular:6,monthCode:"M06",days:29},"Adar I":{leap:6,regular:void 0,monthCode:"M05L",days:30},"Adar II":{leap:7,regular:void 0,monthCode:"M06",days:29},Nisan:{leap:8,regular:7,monthCode:"M07",days:30},Iyar:{leap:9,regular:8,monthCode:"M08",days:29},Sivan:{leap:10,regular:9,monthCode:"M09",days:30},Tamuz:{leap:11,regular:10,monthCode:"M10",days:29},Av:{leap:12,regular:11,monthCode:"M11",days:30},Elul:{leap:13,regular:12,monthCode:"M12",days:29}}}inLeapYear(e){let{year:t}=e;return(7*t+1)%19<7}monthsInYear(e){return this.inLeapYear(e)?13:12}minimumMonthLength(e){return this.minMaxMonthLength(e,"min")}maximumMonthLength(e){return this.minMaxMonthLength(e,"max")}minMaxMonthLength(e,t){let{month:r,year:i}=e,o=this.getMonthCode(i,r),s=Object.entries(this.months).find(l=>l[1].monthCode===o);if(s===void 0)throw new RangeError(`unmatched Hebrew month: ${r}`);let a=s[1].days;return typeof a=="number"?a:a[t]}maxLengthOfMonthCodeInAnyYear(e){return["M04","M06","M08","M10","M12"].includes(e)?29:30}estimateIsoDate(e){let{year:t}=e;return{year:t-3760,month:1,day:1}}getMonthCode(e,t){return this.inLeapYear({year:e})?t===6?ic(5,!0):ic(t<6?t:t-1):ic(t)}adjustCalendarDate(e,t,r="constrain",i=!1){let{year:o,month:s,monthCode:a,day:l,monthExtra:c}=e;if(o===void 0)throw new TypeError("Missing property: year");if(i){if(c){let u=this.months[c];if(!u)throw new RangeError(`Unrecognized month from formatToParts: ${c}`);s=this.inLeapYear({year:o})?u.leap:u.regular}return a=this.getMonthCode(o,s),{year:o,month:s,day:l,monthCode:a}}if(this.validateCalendarDate(e),s===void 0)if(a.endsWith("L")){if(a!=="M05L")throw new RangeError(`Hebrew leap month must have monthCode M05L, not ${a}`);if(s=6,!this.inLeapYear({year:o})){if(r==="reject")throw new RangeError(`Hebrew monthCode M05L is invalid in year ${o} which is not a leap year`);s=6,a="M06"}}else{s=hh(a),this.inLeapYear({year:o})&&s>=6&&s++;let u=this.monthsInYear({year:o});if(s<1||s>u)throw new RangeError(`Invalid monthCode: ${a}`)}else if(r==="reject"?(vr(s,1,this.monthsInYear({year:o})),vr(l,1,this.maximumMonthLength({year:o,month:s}))):(s=Ki(s,1,this.monthsInYear({year:o})),l=Ki(l,1,this.maximumMonthLength({year:o,month:s}))),a===void 0)a=this.getMonthCode(o,s);else if(this.getMonthCode(o,s)!==a)throw new RangeError(`monthCode ${a} doesn't correspond to month ${s} in Hebrew year ${o}`);return{...e,day:l,month:s,monthCode:a,year:o}}},md=class extends Sl{constructor(){super(...arguments),this.calendarType="lunar",this.DAYS_PER_ISLAMIC_YEAR=354+11/30,this.DAYS_PER_ISO_YEAR=365.2425}inLeapYear(e,t){let r={year:e.year,month:1,monthCode:"M01",day:1},i={year:e.year+1,month:1,monthCode:"M01",day:1};return this.calendarDaysUntil(r,i,t)===355}monthsInYear(){return 12}minimumMonthLength(){return 29}maximumMonthLength(){return 30}maxLengthOfMonthCodeInAnyYear(){return 30}estimateIsoDate(e){let{year:t}=this.adjustCalendarDate(e);return{year:Math.floor(t*this.DAYS_PER_ISLAMIC_YEAR/this.DAYS_PER_ISO_YEAR)+622,month:1,day:1}}},DS=class extends md{constructor(){super(...arguments),this.id="islamic"}},LS=class extends md{constructor(){super(...arguments),this.id="islamic-umalqura"}},BS=class extends md{constructor(){super(...arguments),this.id="islamic-tbla"}},TS=class extends md{constructor(){super(...arguments),this.id="islamic-civil"}},PS=class extends md{constructor(){super(...arguments),this.id="islamic-rgsa"}},RS=class extends md{constructor(){super(...arguments),this.id="islamicc"}},MS=class extends Sl{constructor(){super(...arguments),this.id="persian",this.calendarType="solar"}inLeapYear(e,t){return this.daysInMonth({year:e.year,month:12,day:1},t)===30}monthsInYear(){return 12}minimumMonthLength(e){let{month:t}=e;return t===12?29:t<=6?31:30}maximumMonthLength(e){let{month:t}=e;return t===12?30:t<=6?31:30}maxLengthOfMonthCodeInAnyYear(e){return hh(e)<=6?31:30}estimateIsoDate(e){let{year:t}=this.adjustCalendarDate(e);return{year:t+621,month:1,day:1}}},FS=class extends Sl{constructor(){super(...arguments),this.id="indian",this.calendarType="solar",this.months={1:{length:30,month:3,day:22,leap:{length:31,month:3,day:21}},2:{length:31,month:4,day:21},3:{length:31,month:5,day:22},4:{length:31,month:6,day:22},5:{length:31,month:7,day:23},6:{length:31,month:8,day:23},7:{length:30,month:9,day:23},8:{length:30,month:10,day:23},9:{length:30,month:11,day:22},10:{length:30,month:12,day:22},11:{length:30,month:1,nextYear:!0,day:21},12:{length:30,month:2,nextYear:!0,day:20}},this.vulnerableToBceBug=new Date("0000-01-01T00:00Z").toLocaleDateString("en-US-u-ca-indian",{timeZone:"UTC"})!=="10/11/-79 Saka"}inLeapYear(e){return r4(e.year+78)}monthsInYear(){return 12}minimumMonthLength(e){return this.getMonthInfo(e).length}maximumMonthLength(e){return this.getMonthInfo(e).length}maxLengthOfMonthCodeInAnyYear(e){let t=hh(e),r=this.months[t];return r=r.leap??r,r.length}getMonthInfo(e){let{month:t}=e,r=this.months[t];if(r===void 0)throw new RangeError(`Invalid month: ${t}`);return this.inLeapYear(e)&&r.leap&&(r=r.leap),r}estimateIsoDate(e){let t=this.adjustCalendarDate(e),r=this.getMonthInfo(t);return ho(t.year+78+(r.nextYear?1:0),r.month,r.day+t.day-1)}checkIcuBugs(e){if(this.vulnerableToBceBug&&e.year<1)throw new RangeError(`calendar '${this.id}' is broken for ISO dates before 0001-01-01 (see https://bugs.chromium.org/p/v8/issues/detail?id=10529)`)}};function r4(n){return n%4==0&&(n%100!=0||n%400==0)}var fE=class extends Sl{constructor(e,t){super(),this.calendarType="solar",this.id=e,this.isoEpoch=t}inLeapYear(e){let{year:t}=this.estimateIsoDate({month:1,day:1,year:e.year});return r4(t)}monthsInYear(){return 12}minimumMonthLength(e){let{month:t}=e;return t===2?this.inLeapYear(e)?29:28:[4,6,9,11].indexOf(t)>=0?30:31}maximumMonthLength(e){return this.minimumMonthLength(e)}maxLengthOfMonthCodeInAnyYear(e){return[31,29,31,30,31,30,31,31,30,31,30,31][hh(e)-1]}estimateIsoDate(e){let t=this.adjustCalendarDate(e);return Py(t.year+this.isoEpoch.year,t.month+this.isoEpoch.month,t.day+this.isoEpoch.day,"constrain")}},hE=class extends Sl{constructor(e,t){super(),this.hasEra=!0,this.calendarType="solar",this.id=e;let{eras:r,anchorEra:i}=function(o){let s,a=o;if(a.length===0)throw new RangeError("Invalid era data: eras are required");if(a.length===1&&a[0].reverseOf)throw new RangeError("Invalid era data: anchor era cannot count years backwards");if(a.length===1&&!a[0].code)throw new RangeError("Invalid era data: at least one named era is required");if(a.filter(c=>c.reverseOf!=null).length>1)throw new RangeError("Invalid era data: only one era can count years backwards");a.forEach(c=>{if(c.isAnchor||!c.anchorEpoch&&!c.reverseOf){if(s)throw new RangeError("Invalid era data: cannot have multiple anchor eras");s=c,c.anchorEpoch={year:c.hasYearZero?0:1}}else if(!c.code)throw new RangeError("If era name is blank, it must be the anchor era")}),a=a.filter(c=>c.code),a.forEach(c=>{let{reverseOf:u}=c;if(u){let d=a.find(h=>h.code===u);if(d===void 0)throw new RangeError(`Invalid era data: unmatched reverseOf era: ${u}`);c.reverseOf=d,c.anchorEpoch=d.anchorEpoch,c.isoEpoch=d.isoEpoch}c.anchorEpoch.month===void 0&&(c.anchorEpoch.month=1),c.anchorEpoch.day===void 0&&(c.anchorEpoch.day=1)}),a.sort((c,u)=>{if(c.reverseOf)return 1;if(u.reverseOf)return-1;if(!c.isoEpoch||!u.isoEpoch)throw new RangeError("Invalid era data: missing ISO epoch");return u.isoEpoch.year-c.isoEpoch.year});let l=a[a.length-1].reverseOf;if(l&&l!==a[a.length-2])throw new RangeError("Invalid era data: invalid reverse-sign era");return a.forEach((c,u)=>{c.genericName="era"+(a.length-1-u)}),{eras:a,anchorEra:s||a[0]}}(t);this.anchorEra=i,this.eras=r}inLeapYear(e){let{year:t}=this.estimateIsoDate({month:1,day:1,year:e.year});return r4(t)}monthsInYear(){return 12}minimumMonthLength(e){let{month:t}=e;return t===2?this.inLeapYear(e)?29:28:[4,6,9,11].indexOf(t)>=0?30:31}maximumMonthLength(e){return this.minimumMonthLength(e)}maxLengthOfMonthCodeInAnyYear(e){return[31,29,31,30,31,30,31,31,30,31,30,31][hh(e)-1]}completeEraYear(e){let t=(a,l,c)=>{let u=e[a];if(u!=null&&u!=l&&!(c||[]).includes(u)){let d=c?.[0];throw new RangeError(`Input ${a} ${u} doesn't match calculated value ${d?`${l} (also called ${d})`:l}`)}},r=a=>{let l,c={...e,year:a},u=this.eras.find((d,h)=>{if(h===this.eras.length-1){if(d.reverseOf){if(a>0)throw new RangeError(`Signed year ${a} is invalid for era ${d.code}`);return l=d.anchorEpoch.year-a,!0}return l=a-d.anchorEpoch.year+(d.hasYearZero?0:1),!0}return this.compareCalendarDates(c,d.anchorEpoch)>=0&&(l=a-d.anchorEpoch.year+(d.hasYearZero?0:1),!0)});if(!u)throw new RangeError(`Year ${a} was not matched by any era`);return{eraYear:l,era:u.code,eraNames:u.names}},{year:i,eraYear:o,era:s}=e;if(i!=null){let a=r(i);({eraYear:o,era:s}=a),t("era",s,a?.eraNames),t("eraYear",o)}else{if(o==null)throw new RangeError("Either year or eraYear and era are required");{if(s===void 0)throw new RangeError("era and eraYear must be provided together");let a=this.eras.find(({code:l,names:c=[]})=>l===s||c.includes(s));if(!a)throw new RangeError(`Era ${s} (ISO year ${o}) was not matched by any era`);i=a.reverseOf?a.anchorEpoch.year-o:o+a.anchorEpoch.year-(a.hasYearZero?0:1),t("year",i),{eraYear:o,era:s}=r(i)}}return{...e,year:i,eraYear:o,era:s}}adjustCalendarDate(e,t,r="constrain"){let i=e,{month:o,monthCode:s}=i;return o===void 0&&(i={...i,month:hh(s)}),this.validateCalendarDate(i),i=this.completeEraYear(i),super.adjustCalendarDate(i,t,r)}estimateIsoDate(e){let t=this.adjustCalendarDate(e),{year:r,month:i,day:o}=t,{anchorEra:s}=this;return Py(r+s.isoEpoch.year-(s.hasYearZero?0:1),i,o,"constrain")}},Jy=class extends hE{constructor(e,t){super(e,t)}isoToCalendarDate(e){let{year:t,month:r,day:i}=e,o=ic(r),s=t-this.anchorEra.isoEpoch.year+1;return this.completeEraYear({year:s,month:r,monthCode:o,day:i})}},nc={inLeapYear(n){let{year:e}=n;return(e+1)%4==0},monthsInYear:()=>13,minimumMonthLength(n){let{month:e}=n;return e===13?this.inLeapYear(n)?6:5:30},maximumMonthLength(n){return this.minimumMonthLength(n)},maxLengthOfMonthCodeInAnyYear:n=>n==="M13"?6:30},kS=class extends fE{constructor(e,t){super(e,t),this.inLeapYear=nc.inLeapYear,this.monthsInYear=nc.monthsInYear,this.minimumMonthLength=nc.minimumMonthLength,this.maximumMonthLength=nc.maximumMonthLength,this.maxLengthOfMonthCodeInAnyYear=nc.maxLengthOfMonthCodeInAnyYear}},pE=class extends hE{constructor(e,t){super(e,t),this.inLeapYear=nc.inLeapYear,this.monthsInYear=nc.monthsInYear,this.minimumMonthLength=nc.minimumMonthLength,this.maximumMonthLength=nc.maximumMonthLength,this.maxLengthOfMonthCodeInAnyYear=nc.maxLengthOfMonthCodeInAnyYear}},OS=class extends kS{constructor(){super("ethioaa",{year:-5492,month:7,day:17})}},GS=class extends pE{constructor(){super("coptic",[{code:"coptic",isoEpoch:{year:284,month:8,day:29}},{code:"coptic-inverse",reverseOf:"coptic"}])}},NS=class extends pE{constructor(){super("ethiopic",[{code:"ethioaa",names:["ethiopic-amete-alem","mundi"],isoEpoch:{year:-5492,month:7,day:17}},{code:"ethiopic",names:["incar"],isoEpoch:{year:8,month:8,day:27},anchorEpoch:{year:5501}}])}},US=class extends Jy{constructor(){super("roc",[{code:"roc",names:["minguo"],isoEpoch:{year:1912,month:1,day:1}},{code:"roc-inverse",names:["before-roc"],reverseOf:"roc"}])}},HS=class extends fE{constructor(){super("buddhist",{year:-543,month:1,day:1})}},KS=class extends Jy{constructor(){super("gregory",[{code:"gregory",names:["ad","ce"],isoEpoch:{year:1,month:1,day:1}},{code:"gregory-inverse",names:["be","bce"],reverseOf:"gregory"}])}reviseIntlEra(e){let{era:t,eraYear:r}=e;return t==="b"&&(t="gregory-inverse"),t==="a"&&(t="gregory"),{era:t,eraYear:r}}getFirstDayOfWeek(){return 1}getMinimalDaysInFirstWeek(){return 1}},JS=class extends Jy{constructor(){super("japanese",[{code:"reiwa",isoEpoch:{year:2019,month:5,day:1},anchorEpoch:{year:2019,month:5,day:1}},{code:"heisei",isoEpoch:{year:1989,month:1,day:8},anchorEpoch:{year:1989,month:1,day:8}},{code:"showa",isoEpoch:{year:1926,month:12,day:25},anchorEpoch:{year:1926,month:12,day:25}},{code:"taisho",isoEpoch:{year:1912,month:7,day:30},anchorEpoch:{year:1912,month:7,day:30}},{code:"meiji",isoEpoch:{year:1868,month:9,day:8},anchorEpoch:{year:1868,month:9,day:8}},{code:"japanese",names:["japanese","gregory","ad","ce"],isoEpoch:{year:1,month:1,day:1}},{code:"japanese-inverse",names:["japanese-inverse","gregory-inverse","bc","bce"],reverseOf:"japanese"}]),this.erasBeginMidYear=!0}reviseIntlEra(e,t){let{era:r,eraYear:i}=e,{year:o}=t;return this.eras.find(s=>s.code===r)?{era:r,eraYear:i}:o<1?{era:"japanese-inverse",eraYear:1-o}:{era:"japanese",eraYear:o}}},mE=class extends Sl{constructor(){super(...arguments),this.calendarType="lunisolar"}inLeapYear(e,t){let r=this.getMonthList(e.year,t);return Object.entries(r).length===13}monthsInYear(e,t){return this.inLeapYear(e,t)?13:12}minimumMonthLength(){return 29}maximumMonthLength(){return 30}maxLengthOfMonthCodeInAnyYear(e){return["M01L","M09L","M10L","M11L","M12L"].includes(e)?29:30}monthDaySearchStartYear(e,t){let r={M01L:[1651,1651],M02L:[1947,1765],M03L:[1966,1955],M04L:[1963,1944],M05L:[1971,1952],M06L:[1960,1941],M07L:[1968,1938],M08L:[1957,1718],M09L:[1832,1832],M10L:[1870,1870],M11L:[1814,1814],M12L:[1890,1890]}[e]??[1972,1972];return t<30?r[0]:r[1]}getMonthList(e,t){if(e===void 0)throw new TypeError("Missing year");let r=JSON.stringify({func:"getMonthList",calendarYear:e,id:this.id}),i=t.get(r);if(i)return i;let o=this.getFormatter(),s=(y,v)=>{let B=fU({isoYear:y,isoMonth:2,isoDay:1}),U=new Date(B);U.setUTCDate(v+1);let k=o.formatToParts(U),F=k.find(V=>V.type==="month").value,P=+k.find(V=>V.type==="day").value,I=k.find(V=>V.type==="relatedYear"),D;if(I===void 0)throw new RangeError(`Intl.DateTimeFormat.formatToParts lacks relatedYear in ${this.id} calendar. Try Node 14+ or modern browsers.`);return D=+I.value,{calendarMonthString:F,calendarDay:P,calendarYearToVerify:D}},a=17,{calendarMonthString:l,calendarDay:c,calendarYearToVerify:u}=s(e,a);l!=="1"&&(a+=29,{calendarMonthString:l,calendarDay:c}=s(e,a)),a-=c-5;let d={},h,f,p=1,w=!1;do({calendarMonthString:l,calendarDay:c,calendarYearToVerify:u}=s(e,a)),h&&(d[f].daysInMonth=h+30-c),u!==e?w=!0:(d[l]={monthIndex:p++},a+=30),h=c,f=l;while(!w);return d[f].daysInMonth=h+30-c,t.set(r,d),d}estimateIsoDate(e){let{year:t,month:r}=e;return{year:t,month:r>=12?12:r+1,day:1}}adjustCalendarDate(e,t,r="constrain",i=!1){let{year:o,month:s,monthExtra:a,day:l,monthCode:c}=e;if(o===void 0)throw new TypeError("Missing property: year");if(i){if(a&&a!=="bis")throw new RangeError(`Unexpected leap month suffix: ${a}`);let u=ic(s,a!==void 0),d=`${s}${a||""}`,h=this.getMonthList(o,t)[d];if(h===void 0)throw new RangeError(`Unmatched month ${d} in Chinese year ${o}`);return s=h.monthIndex,{year:o,month:s,day:l,monthCode:u}}if(this.validateCalendarDate(e),s===void 0){let u=this.getMonthList(o,t),d=c.replace(/^M|L$/g,f=>f==="L"?"bis":"");d[0]==="0"&&(d=d.slice(1));let h=u[d];if(s=h&&h.monthIndex,s===void 0&&c.endsWith("L")&&c!="M13L"&&r==="constrain"){let f=+c.replace(/^M0?|L$/g,"");h=u[f],h&&(s=h.monthIndex,c=ic(f))}if(s===void 0)throw new RangeError(`Unmatched month ${c} in Chinese year ${o}`)}else if(c===void 0){let u=this.getMonthList(o,t),d=Object.entries(u),h=d.length;r==="reject"?(vr(s,1,h),vr(l,1,this.maximumMonthLength())):(s=Ki(s,1,h),l=Ki(l,1,this.maximumMonthLength()));let f=d.find(p=>p[1].monthIndex===s);if(f===void 0)throw new RangeError(`Invalid month ${s} in Chinese year ${o}`);c=ic(+f[0].replace("bis",""),f[0].indexOf("bis")!==-1)}else{let u=this.getMonthList(o,t),d=c.replace(/^M|L$/g,f=>f==="L"?"bis":"");d[0]==="0"&&(d=d.slice(1));let h=u[d];if(!h)throw new RangeError(`Unmatched monthCode ${c} in Chinese year ${o}`);if(s!==h.monthIndex)throw new RangeError(`monthCode ${c} doesn't correspond to month ${s} in Chinese year ${o}`)}return{...e,year:o,month:s,monthCode:c,day:l}}},qS=class extends mE{constructor(){super(...arguments),this.id="chinese"}},QS=class extends mE{constructor(){super(...arguments),this.id="dangi"}},VS=class{constructor(e){this.helper=e}extraFields(e){return this.helper.hasEra&&e.includes("year")?["era","eraYear"]:[]}resolveFields(e){if(this.helper.calendarType!=="lunisolar"){let t=new Uo;n4(e,void 0,this.helper.monthsInYear({year:e.year??1972},t))}}dateToISO(e,t){let r=new Uo,i=this.helper.calendarToIsoDate(e,t,r);return r.setObject(i),i}monthDayToISOReferenceDate(e,t){let r=new Uo,i=this.helper.monthDayFromFields(e,t,r);return r.setObject(i),i}fieldKeysToIgnore(e){let t=new Set;for(let r=0;r<e.length;r++){let i=e[r];switch(t.add(i),i){case"era":t.add("eraYear"),t.add("year");break;case"eraYear":t.add("era"),t.add("year");break;case"year":t.add("era"),t.add("eraYear");break;case"month":t.add("monthCode"),this.helper.erasBeginMidYear&&(t.add("era"),t.add("eraYear"));break;case"monthCode":t.add("month"),this.helper.erasBeginMidYear&&(t.add("era"),t.add("eraYear"));break;case"day":this.helper.erasBeginMidYear&&(t.add("era"),t.add("eraYear"))}}return uU(t)}dateAdd(e,{years:t,months:r,weeks:i,days:o},s){let a=Uo.getCacheForObject(e),l=this.helper.isoToCalendarDate(e,a),c=this.helper.addCalendar(l,{years:t,months:r,weeks:i,days:o},s,a),u=this.helper.calendarToIsoDate(c,"constrain",a);return Uo.getCacheForObject(u)||new Uo(a).setObject(u),u}dateUntil(e,t,r){let i=Uo.getCacheForObject(e),o=Uo.getCacheForObject(t),s=this.helper.isoToCalendarDate(e,i),a=this.helper.isoToCalendarDate(t,o);return this.helper.untilCalendar(s,a,r,i)}isoToDate(e,t){let r=Uo.getCacheForObject(e),i=this.helper.isoToCalendarDate(e,r);if(t.dayOfWeek&&(i.dayOfWeek=uw.iso8601.isoToDate(e,{dayOfWeek:!0}).dayOfWeek),t.dayOfYear){let o=this.helper.startOfCalendarYear(i),s=this.helper.calendarDaysUntil(o,i,r);i.dayOfYear=s+1}if(t.weekOfYear&&(i.weekOfYear=dU(this.helper.id,e)),i.daysInWeek=7,t.daysInMonth&&(i.daysInMonth=this.helper.daysInMonth(i,r)),t.daysInYear){let o=this.helper.startOfCalendarYear(i),s=this.helper.addCalendar(o,{years:1},"constrain",r);i.daysInYear=this.helper.calendarDaysUntil(o,s,r)}return t.monthsInYear&&(i.monthsInYear=this.helper.monthsInYear(i,r)),t.inLeapYear&&(i.inLeapYear=this.helper.inLeapYear(i,r)),i}getFirstDayOfWeek(){return this.helper.getFirstDayOfWeek()}getMinimalDaysInFirstWeek(){return this.helper.getMinimalDaysInFirstWeek()}};for(let n of[SS,MS,NS,OS,GS,qS,QS,US,FS,HS,KS,JS,DS,LS,BS,TS,PS,RS]){let e=new n;uw[e.id]=new VS(e)}dS("calendarImpl",function(n){return uw[n]});var qy=Intl.DateTimeFormat;function C0(n,e){let t=z(n,e);return typeof t=="function"&&(t=new qy(z(n,DN),t(z(n,aS))),function(r,i,o){let s=yE(r);if(s===void 0)throw new TypeError("Missing slots for the given container");if(s[i]===void 0)throw new TypeError(`tried to reset ${i} which was not set`);s[i]=o}(n,e,t)),t}function by(n){return Vi(n,mh)}var ph=class{constructor(e=void 0,t=void 0){(function(r,i,o){let s=o!==void 0,a;if(s){let d=["localeMatcher","calendar","numberingSystem","hour12","hourCycle","timeZone","weekday","era","year","month","day","dayPeriod","hour","minute","second","fractionalSecondDigits","timeZoneName","formatMatcher","dateStyle","timeStyle"];a=function(f){if(f==null)throw new TypeError(`Expected object not ${f}`);return Object(f)}(o);let h=Object.create(null);for(let f=0;f<d.length;f++){let p=d[f];Object.prototype.hasOwnProperty.call(a,p)&&(h[p]=a[p])}a=h}else a=Object.create(null);let l=new qy(i,a),c=l.resolvedOptions();if(Dl(r),s){let d=Object.assign(Object.create(null),c);for(let h in d)Object.prototype.hasOwnProperty.call(a,h)||delete d[h];d.hour12=a.hour12,d.hourCycle=a.hourCycle,wt(r,aS,d)}else wt(r,aS,a);wt(r,DN,c.locale),wt(r,mh,l),wt(r,L0,c.timeZone),wt(r,Ey,c.calendar),wt(r,EN,vre),wt(r,xN,xre),wt(r,AN,Are),wt(r,vN,Ere),wt(r,CN,Cre),wt(r,SN,Sre);let u=s?a.timeZone:void 0;if(u===void 0)wt(r,sS,c.timeZone);else{let d=EE(u);if(d.startsWith("\u2212"))throw new RangeError("Unicode minus (U+2212) is not supported in time zone offsets");wt(r,sS,qi(d))}})(this,e,t)}get format(){de(this,by);let e=yre.bind(this);return Object.defineProperties(e,{length:{value:1,enumerable:!1,writable:!1,configurable:!0},name:{value:"",enumerable:!1,writable:!1,configurable:!0}}),e}formatRange(e,t){return de(this,by),bre.call(this,e,t)}formatToParts(e,...t){return de(this,by),wre.call(this,e,...t)}formatRangeToParts(e,t){return de(this,by),Ire.call(this,e,t)}resolvedOptions(){return de(this,by),gre.call(this)}};"formatToParts"in qy.prototype||delete ph.prototype.formatToParts,"formatRangeToParts"in qy.prototype||delete ph.prototype.formatRangeToParts;var Jo=function(n=void 0,e=void 0){return new ph(n,e)};function gre(){let n=z(this,mh).resolvedOptions();return n.timeZone=z(this,sS),n}function yre(n,...e){let t,r,i=H0(n,this);return i.formatter?(t=i.formatter,r=[As(i.epochNs,"floor")]):(t=z(this,mh),r=[n,...e]),t.format(...r)}function wre(n,...e){let t,r,i=H0(n,this);return i.formatter?(t=i.formatter,r=[As(i.epochNs,"floor")]):(t=z(this,mh),r=[n,...e]),t.formatToParts(...r)}function bre(n,e){if(n===void 0||e===void 0)throw new TypeError("Intl.DateTimeFormat.formatRange requires two values");let t=gE(n),r=gE(e),i,o=[t,r];if(vl(t)!==vl(r))throw new TypeError("Intl.DateTimeFormat.formatRange accepts two values of the same type");if(vl(t)){if(!hU(t,r))throw new TypeError("Intl.DateTimeFormat.formatRange accepts two values of the same type");let{epochNs:s,formatter:a}=H0(t,this),{epochNs:l,formatter:c}=H0(r,this);a&&(i=a,o=[As(s,"floor"),As(l,"floor")])}return i||(i=z(this,mh)),i.formatRange(...o)}function Ire(n,e){if(n===void 0||e===void 0)throw new TypeError("Intl.DateTimeFormat.formatRange requires two values");let t=gE(n),r=gE(e),i,o=[t,r];if(vl(t)!==vl(r))throw new TypeError("Intl.DateTimeFormat.formatRangeToParts accepts two values of the same type");if(vl(t)){if(!hU(t,r))throw new TypeError("Intl.DateTimeFormat.formatRangeToParts accepts two values of the same type");let{epochNs:s,formatter:a}=H0(t,this),{epochNs:l,formatter:c}=H0(r,this);a&&(i=a,o=[As(s,"floor"),As(l,"floor")])}return i||(i=z(this,mh)),i.formatRangeToParts(...o)}function dw(n={},e={}){let t=Object.assign({},n),r=["year","month","day","hour","minute","second","weekday","dayPeriod","timeZoneName","dateStyle","timeStyle"];for(let i=0;i<r.length;i++){let o=r[i];t[o]=o in e?e[o]:t[o],t[o]!==!1&&t[o]!==void 0||delete t[o]}return t}function Ere(n){let e=dw(n,{year:!1,month:!1,day:!1,weekday:!1,timeZoneName:!1,dateStyle:!1});if(e.timeStyle!=="long"&&e.timeStyle!=="full"||(delete e.timeStyle,Object.assign(e,{hour:"numeric",minute:"2-digit",second:"2-digit"})),!TE(e)){if(fw(n))throw new TypeError(`cannot format Temporal.PlainTime with options [${Object.keys(n)}]`);Object.assign(e,{hour:"numeric",minute:"numeric",second:"numeric"})}return e}function xre(n){let e={short:{year:"2-digit",month:"numeric"},medium:{year:"numeric",month:"short"},long:{year:"numeric",month:"long"},full:{year:"numeric",month:"long"}},t=dw(n,{day:!1,hour:!1,minute:!1,second:!1,weekday:!1,dayPeriod:!1,timeZoneName:!1,timeStyle:!1});if("dateStyle"in t&&t.dateStyle){let r=t.dateStyle;delete t.dateStyle,Object.assign(t,e[r])}if(!("year"in t||"month"in t||"era"in t)){if(fw(n))throw new TypeError(`cannot format PlainYearMonth with options [${Object.keys(n)}]`);Object.assign(t,{year:"numeric",month:"numeric"})}return t}function Are(n){let e={short:{month:"numeric",day:"numeric"},medium:{month:"short",day:"numeric"},long:{month:"long",day:"numeric"},full:{month:"long",day:"numeric"}},t=dw(n,{year:!1,hour:!1,minute:!1,second:!1,weekday:!1,dayPeriod:!1,timeZoneName:!1,timeStyle:!1});if("dateStyle"in t&&t.dateStyle){let r=t.dateStyle;delete t.dateStyle,Object.assign(t,e[r])}if(!("month"in t)&&!("day"in t)){if(fw(n))throw new TypeError(`cannot format PlainMonthDay with options [${Object.keys(n)}]`);Object.assign(t,{month:"numeric",day:"numeric"})}return t}function vre(n){let e=dw(n,{hour:!1,minute:!1,second:!1,dayPeriod:!1,timeZoneName:!1,timeStyle:!1});if(!BE(e)){if(fw(n))throw new TypeError(`cannot format PlainDate with options [${Object.keys(n)}]`);Object.assign(e,{year:"numeric",month:"numeric",day:"numeric"})}return e}function Cre(n){let e=dw(n,{timeZoneName:!1});if((e.timeStyle==="long"||e.timeStyle==="full")&&(delete e.timeStyle,Object.assign(e,{hour:"numeric",minute:"2-digit",second:"2-digit"}),e.dateStyle)&&(Object.assign(e,{short:{year:"numeric",month:"numeric",day:"numeric"},medium:{year:"numeric",month:"short",day:"numeric"},long:{year:"numeric",month:"long",day:"numeric"},full:{year:"numeric",month:"long",day:"numeric",weekday:"long"}}[e.dateStyle]),delete e.dateStyle),!TE(e)&&!BE(e)){if(fw(n))throw new TypeError(`cannot format PlainDateTime with options [${Object.keys(n)}]`);Object.assign(e,{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})}return e}function Sre(n){let e=n;return TE(e)||BE(e)||(e=Object.assign({},e,{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})),e}function BE(n){return"year"in n||"month"in n||"day"in n||"weekday"in n||"dateStyle"in n||"era"in n}function TE(n){return"hour"in n||"minute"in n||"second"in n||"timeStyle"in n||"dayPeriod"in n||"fractionalSecondDigits"in n}function fw(n){return BE(n)||TE(n)||"dateStyle"in n||"timeStyle"in n||"timeZoneName"in n}function vl(n){return kn(n)||qn(n)||En(n)||It(n)||qr(n)||Ho(n)||Jr(n)}function gE(n){return vl(n)?n:IE(n)}function hU(n,e){return!(!vl(n)||!vl(e)||qn(n)&&!qn(e)||kn(n)&&!kn(e)||En(n)&&!En(e)||It(n)&&!It(e)||qr(n)&&!qr(e)||Ho(n)&&!Ho(e)||Jr(n)&&!Jr(e))}function H0(n,e){if(qn(n)){let t={isoDate:{year:1970,month:1,day:1},time:z(n,On)};return{epochNs:si(z(e,L0),t,"compatible"),formatter:C0(e,vN)}}if(qr(n)){let t=z(n,ve),r=z(e,Ey);if(t!==r)throw new RangeError(`cannot format PlainYearMonth with calendar ${t} in locale with calendar ${r}`);let i=Ht(z(n,ot),{deltaDays:0,hour:12,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});return{epochNs:si(z(e,L0),i,"compatible"),formatter:C0(e,xN)}}if(Ho(n)){let t=z(n,ve),r=z(e,Ey);if(t!==r)throw new RangeError(`cannot format PlainMonthDay with calendar ${t} in locale with calendar ${r}`);let i=Ht(z(n,ot),{deltaDays:0,hour:12,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});return{epochNs:si(z(e,L0),i,"compatible"),formatter:C0(e,AN)}}if(kn(n)){let t=z(n,ve),r=z(e,Ey);if(t!=="iso8601"&&t!==r)throw new RangeError(`cannot format PlainDate with calendar ${t} in locale with calendar ${r}`);let i=Ht(z(n,ot),{deltaDays:0,hour:12,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0});return{epochNs:si(z(e,L0),i,"compatible"),formatter:C0(e,EN)}}if(En(n)){let t=z(n,ve),r=z(e,Ey);if(t!=="iso8601"&&t!==r)throw new RangeError(`cannot format PlainDateTime with calendar ${t} in locale with calendar ${r}`);let i=z(n,vn);return{epochNs:si(z(e,L0),i,"compatible"),formatter:C0(e,CN)}}if(It(n))throw new TypeError("Temporal.ZonedDateTime not supported in DateTimeFormat methods. Use toLocaleString() instead.");return Jr(n)?{epochNs:z(n,it),formatter:C0(e,SN)}:{}}function pU(n){let e=Object.create(null);return e.years=z(n,Mi),e.months=z(n,Fi),e.weeks=z(n,co),e.days=z(n,ki),e.hours=z(n,Oi),e.minutes=z(n,Gi),e.seconds=z(n,Ni),e.milliseconds=z(n,Ui),e.microseconds=z(n,Hi),e.nanoseconds=z(n,lo),e}ph.prototype.constructor=Jo,Object.defineProperty(Jo,"prototype",{value:ph.prototype,writable:!1,enumerable:!1,configurable:!1}),Jo.supportedLocalesOf=qy.supportedLocalesOf,Ll(Jo,"Intl.DateTimeFormat");var{format:Dre,formatToParts:Lre}=Intl.DurationFormat?.prototype??Object.create(null);function i4(n){Intl.DurationFormat.prototype.resolvedOptions.call(this);let e=pU(Es(n));return Dre.call(this,e)}Intl.DurationFormat?.prototype&&(Intl.DurationFormat.prototype.format=i4,Intl.DurationFormat.prototype.formatToParts=function(n){Intl.DurationFormat.prototype.resolvedOptions.call(this);let e=pU(Es(n));return Lre.call(this,e)});var l6e=Object.freeze({__proto__:null,DateTimeFormat:Jo,ModifiedIntlDurationFormatPrototypeFormat:i4}),Qy=class{constructor(e){if(arguments.length<1)throw new TypeError("missing argument: epochNanoseconds is required");YN(this,dE(e))}get epochMilliseconds(){return de(this,Jr),As(z(this,it),"floor")}get epochNanoseconds(){return de(this,Jr),cU(ae.default.BigInt(z(this,it)))}add(e){return de(this,Jr),cN("add",this,e)}subtract(e){return de(this,Jr),cN("subtract",this,e)}until(e,t=void 0){return de(this,Jr),tN("until",this,e,t)}since(e,t=void 0){return de(this,Jr),tN("since",this,e,t)}round(e){if(de(this,Jr),e===void 0)throw new TypeError("options parameter is required");let t=typeof e=="string"?fh("smallestUnit",e):Qe(e),r=J0(t),i=ya(t,"halfExpand"),o=fo(t,"smallestUnit","time",Cl);return q0(r,{hour:24,minute:1440,second:86400,millisecond:864e5,microsecond:864e8,nanosecond:864e11}[o],!0),ma(ES(z(this,it),r,o,i))}equals(e){de(this,Jr);let t=vy(e),r=z(this,it),i=z(t,it);return ae.default.equal(ae.default.BigInt(r),ae.default.BigInt(i))}toString(e=void 0){de(this,Jr);let t=Qe(e),r=nw(t),i=ya(t,"trunc"),o=fo(t,"smallestUnit","time",void 0);if(o==="hour")throw new RangeError('smallestUnit must be a time unit other than "hour"');let s=t.timeZone;s!==void 0&&(s=qi(s));let{precision:a,unit:l,increment:c}=rw(o,r);return YG(ma(ES(z(this,it),c,l,i)),s,a)}toJSON(){return de(this,Jr),YG(this,void 0,"auto")}toLocaleString(e=void 0,t=void 0){return de(this,Jr),new Jo(e,t).format(this)}valueOf(){yd("Instant")}toZonedDateTimeISO(e){de(this,Jr);let t=qi(e);return ii(z(this,it),t,"iso8601")}static fromEpochMilliseconds(e){return ma(ga(IE(e)))}static fromEpochNanoseconds(e){return ma(dE(e))}static from(e){return vy(e)}static compare(e,t){let r=vy(e),i=vy(t),o=z(r,it),s=z(i,it);return ae.default.lessThan(o,s)?-1:ae.default.greaterThan(o,s)?1:0}};Ll(Qy,"Temporal.Instant");var Vy=class{constructor(e,t,r,i="iso8601"){let o=ut(e),s=ut(t),a=ut(r),l=Yi(i===void 0?"iso8601":dr(i));lh(o,s,a),KN(this,{year:o,month:s,day:a},l)}get calendarId(){return de(this,kn),z(this,ve)}get era(){return Ti(this,"era")}get eraYear(){return Ti(this,"eraYear")}get year(){return Ti(this,"year")}get month(){return Ti(this,"month")}get monthCode(){return Ti(this,"monthCode")}get day(){return Ti(this,"day")}get dayOfWeek(){return Ti(this,"dayOfWeek")}get dayOfYear(){return Ti(this,"dayOfYear")}get weekOfYear(){return Ti(this,"weekOfYear")?.week}get yearOfWeek(){return Ti(this,"weekOfYear")?.year}get daysInWeek(){return Ti(this,"daysInWeek")}get daysInMonth(){return Ti(this,"daysInMonth")}get daysInYear(){return Ti(this,"daysInYear")}get monthsInYear(){return Ti(this,"monthsInYear")}get inLeapYear(){return Ti(this,"inLeapYear")}with(e,t=void 0){if(de(this,kn),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=z(this,ve),i=Qi(r,z(this,ot));return i=ch(r,i,Vo(r,e,["year","month","monthCode","day"],[],"partial")),Ji(pd(r,i,kt(Qe(t))),r)}withCalendar(e){de(this,kn);let t=aw(e);return Ji(z(this,ot),t)}add(e,t=void 0){return de(this,kn),lN("add",this,e,t)}subtract(e,t=void 0){return de(this,kn),lN("subtract",this,e,t)}until(e,t=void 0){return de(this,kn),nN("until",this,e,t)}since(e,t=void 0){return de(this,kn),nN("since",this,e,t)}equals(e){de(this,kn);let t=xy(e);return ac(z(this,ot),z(t,ot))===0&&oc(z(this,ve),z(t,ve))}toString(e=void 0){return de(this,kn),zG(this,tw(Qe(e)))}toJSON(){return de(this,kn),zG(this)}toLocaleString(e=void 0,t=void 0){return de(this,kn),new Jo(e,t).format(this)}valueOf(){yd("PlainDate")}toPlainDateTime(e=void 0){de(this,kn);let t=HN(e);return bs(Ht(z(this,ot),t),z(this,ve))}toZonedDateTime(e){let t,r;if(de(this,kn),Gn(e)){let s=e.timeZone;s===void 0?t=qi(e):(t=qi(s),r=e.plainTime)}else t=qi(e);let i=z(this,ot),o;return r===void 0?o=ad(t,i):(r=ld(r),o=si(t,Ht(i,z(r,On)),"compatible")),ii(o,t,z(this,ve))}toPlainYearMonth(){de(this,kn);let e=z(this,ve);return R0(Gy(e,Qi(e,z(this,ot)),"constrain"),e)}toPlainMonthDay(){de(this,kn);let e=z(this,ve);return P0(sE(e,Qi(e,z(this,ot)),"constrain"),e)}static from(e,t=void 0){return xy(e,t)}static compare(e,t){let r=xy(e),i=xy(t);return ac(z(r,ot),z(i,ot))}};function Ti(n,e){de(n,kn);let t=z(n,ot);return iw(n).isoToDate(t,{[e]:!0})[e]}Ll(Vy,"Temporal.PlainDate");var Yy=class{constructor(e,t,r,i=0,o=0,s=0,a=0,l=0,c=0,u="iso8601"){let d=ut(e),h=ut(t),f=ut(r),p=i===void 0?0:ut(i),w=o===void 0?0:ut(o),y=s===void 0?0:ut(s),v=a===void 0?0:ut(a),B=l===void 0?0:ut(l),U=c===void 0?0:ut(c),k=Yi(u===void 0?"iso8601":dr(u));_S(d,h,f,p,w,y,v,B,U),JN(this,{isoDate:{year:d,month:h,day:f},time:{hour:p,minute:w,second:y,millisecond:v,microsecond:B,nanosecond:U}},k)}get calendarId(){return de(this,En),z(this,ve)}get year(){return Pi(this,"year")}get month(){return Pi(this,"month")}get monthCode(){return Pi(this,"monthCode")}get day(){return Pi(this,"day")}get hour(){return S0(this,"hour")}get minute(){return S0(this,"minute")}get second(){return S0(this,"second")}get millisecond(){return S0(this,"millisecond")}get microsecond(){return S0(this,"microsecond")}get nanosecond(){return S0(this,"nanosecond")}get era(){return Pi(this,"era")}get eraYear(){return Pi(this,"eraYear")}get dayOfWeek(){return Pi(this,"dayOfWeek")}get dayOfYear(){return Pi(this,"dayOfYear")}get weekOfYear(){return Pi(this,"weekOfYear")?.week}get yearOfWeek(){return Pi(this,"weekOfYear")?.year}get daysInWeek(){return Pi(this,"daysInWeek")}get daysInYear(){return Pi(this,"daysInYear")}get daysInMonth(){return Pi(this,"daysInMonth")}get monthsInYear(){return Pi(this,"monthsInYear")}get inLeapYear(){return Pi(this,"inLeapYear")}with(e,t=void 0){if(de(this,En),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=z(this,ve),i=z(this,vn),o={...Qi(r,i.isoDate),...i.time};return o=ch(r,o,Vo(r,e,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond"],"partial")),bs(ow(r,o,kt(Qe(t))),r)}withPlainTime(e=void 0){de(this,En);let t=HN(e);return bs(Ht(z(this,vn).isoDate,t),z(this,ve))}withCalendar(e){de(this,En);let t=aw(e);return bs(z(this,vn),t)}add(e,t=void 0){return de(this,En),uN("add",this,e,t)}subtract(e,t=void 0){return de(this,En),uN("subtract",this,e,t)}until(e,t=void 0){return de(this,En),rN("until",this,e,t)}since(e,t=void 0){return de(this,En),rN("since",this,e,t)}round(e){if(de(this,En),e===void 0)throw new TypeError("options parameter is required");let t=typeof e=="string"?fh("smallestUnit",e):Qe(e),r=J0(t),i=ya(t,"halfExpand"),o=fo(t,"smallestUnit","time",Cl,["day"]),s={day:1,hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[o];q0(r,s,s===1);let a=z(this,vn);return bs(r===1&&o==="nanosecond"?a:xS(a,r,o,i),z(this,ve))}equals(e){de(this,En);let t=Ay(e);return U0(z(this,vn),z(t,vn))===0&&oc(z(this,ve),z(t,ve))}toString(e=void 0){de(this,En);let t=Qe(e),r=tw(t),i=nw(t),o=ya(t,"trunc"),s=fo(t,"smallestUnit","time",void 0);if(s==="hour")throw new RangeError('smallestUnit must be a time unit other than "hour"');let{precision:a,unit:l,increment:c}=rw(s,i),u=xS(z(this,vn),c,l,o);return uh(u),Uy(u,z(this,ve),a,r)}toJSON(){return de(this,En),Uy(z(this,vn),z(this,ve),"auto")}toLocaleString(e=void 0,t=void 0){return de(this,En),new Jo(e,t).format(this)}valueOf(){yd("PlainDateTime")}toZonedDateTime(e,t=void 0){de(this,En);let r=qi(e),i=Ry(Qe(t));return ii(si(r,z(this,vn),i),r,z(this,ve))}toPlainDate(){return de(this,En),Ji(z(this,vn).isoDate,z(this,ve))}toPlainTime(){return de(this,En),bl(z(this,vn).time)}static from(e,t=void 0){return Ay(e,t)}static compare(e,t){let r=Ay(e),i=Ay(t);return U0(z(r,vn),z(i,vn))}};function Pi(n,e){de(n,En);let t=z(n,vn).isoDate;return iw(n).isoToDate(t,{[e]:!0})[e]}function S0(n,e){return de(n,En),z(n,vn).time[e]}Ll(Yy,"Temporal.PlainDateTime");var zy=class n{constructor(e=0,t=0,r=0,i=0,o=0,s=0,a=0,l=0,c=0,u=0){let d=e===void 0?0:pa(e),h=t===void 0?0:pa(t),f=r===void 0?0:pa(r),p=i===void 0?0:pa(i),w=o===void 0?0:pa(o),y=s===void 0?0:pa(s),v=a===void 0?0:pa(a),B=l===void 0?0:pa(l),U=c===void 0?0:pa(c),k=u===void 0?0:pa(u);DE(d,h,f,p,w,y,v,B,U,k),Dl(this),wt(this,Mi,d),wt(this,Fi,h),wt(this,co,f),wt(this,ki,p),wt(this,Oi,w),wt(this,Gi,y),wt(this,Ni,v),wt(this,Ui,B),wt(this,Hi,U),wt(this,lo,k)}get years(){return de(this,Fn),z(this,Mi)}get months(){return de(this,Fn),z(this,Fi)}get weeks(){return de(this,Fn),z(this,co)}get days(){return de(this,Fn),z(this,ki)}get hours(){return de(this,Fn),z(this,Oi)}get minutes(){return de(this,Fn),z(this,Gi)}get seconds(){return de(this,Fn),z(this,Ni)}get milliseconds(){return de(this,Fn),z(this,Ui)}get microseconds(){return de(this,Fn),z(this,Hi)}get nanoseconds(){return de(this,Fn),z(this,lo)}get sign(){return de(this,Fn),lE(this)}get blank(){return de(this,Fn),lE(this)===0}with(e){de(this,Fn);let t=UN(e),{years:r=z(this,Mi),months:i=z(this,Fi),weeks:o=z(this,co),days:s=z(this,ki),hours:a=z(this,Oi),minutes:l=z(this,Gi),seconds:c=z(this,Ni),milliseconds:u=z(this,Ui),microseconds:d=z(this,Hi),nanoseconds:h=z(this,lo)}=t;return new n(r,i,o,s,a,l,c,u,d,h)}negated(){return de(this,Fn),po(this)}abs(){return de(this,Fn),new n(Math.abs(z(this,Mi)),Math.abs(z(this,Fi)),Math.abs(z(this,co)),Math.abs(z(this,ki)),Math.abs(z(this,Oi)),Math.abs(z(this,Gi)),Math.abs(z(this,Ni)),Math.abs(z(this,Ui)),Math.abs(z(this,Hi)),Math.abs(z(this,lo)))}add(e){return de(this,Fn),aN("add",this,e)}subtract(e){return de(this,Fn),aN("subtract",this,e)}round(e){if(de(this,Fn),e===void 0)throw new TypeError("options parameter is required");let t=yl(this),r=typeof e=="string"?fh("smallestUnit",e):Qe(e),i=fo(r,"largestUnit","datetime",void 0,["auto"]),{plainRelativeTo:o,zonedRelativeTo:s}=rS(r),a=J0(r),l=ya(r,"halfExpand"),c=fo(r,"smallestUnit","datetime",void 0),u=!0;c||(u=!1,c="nanosecond");let d=El(t,c),h=!0;if(i||(h=!1,i=d),i==="auto"&&(i=d),!u&&!h)throw new RangeError("at least one of smallestUnit or largestUnit is required");if(El(i,c)!==i)throw new RangeError(`largestUnit ${i} cannot be smaller than smallestUnit ${c}`);let f={hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[c];if(f!==void 0&&q0(a,f,!1),a>1&&wl(c)==="date"&&i!==c)throw new RangeError("For calendar units with roundingIncrement > 1, use largestUnit = smallestUnit");if(s){let w=B0(this),y=z(s,Xt),v=z(s,ve),B=z(s,it);return w=aU(B,Dy(B,y,v,w),y,v,i,a,c,l),wl(i)==="date"&&(i="hour"),Is(w,i)}if(o){let w=rc(this),y=N0({deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0},w.time),v=z(o,ot),B=z(o,ve),U=qo(B,v,oi(w.date,y.deltaDays),"constrain");return w=sU(Ht(v,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),Ht(U,y),B,i,a,c,l),Is(w,i)}if(tc(t))throw new RangeError(`a starting point is required for ${t}s balancing`);if(tc(i))throw new RangeError(`a starting point is required for ${i}s balancing`);let p=rc(this);if(c==="day"){let{quotient:w,remainder:y}=p.time.divmod(rE),v=p.date.days+w+My(y,"day");v=ud(v,a,l),p=xl({years:0,months:0,weeks:0,days:v},dn.ZERO)}else p=xl({years:0,months:0,weeks:0,days:0},uE(p.time,a,c,l));return Is(p,i)}total(e){if(de(this,Fn),e===void 0)throw new TypeError("options argument is required");let t=typeof e=="string"?fh("unit",e):Qe(e),{plainRelativeTo:r,zonedRelativeTo:i}=rS(t),o=fo(t,"unit","datetime",Cl);if(i){let a=B0(this),l=z(i,Xt),c=z(i,ve),u=z(i,it);return function(d,h,f,p,w){return wl(w)==="time"?My(dn.fromEpochNsDiff(h,d),w):eN(iU(d,h,f,p,w),h,xs(f,d),f,p,w)}(u,Dy(u,l,c,a),l,c,o)}if(r){let a=rc(this),l=N0({deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0},a.time),c=z(r,ot),u=z(r,ve),d=qo(u,c,oi(a.date,l.deltaDays),"constrain");return function(h,f,p,w){if(U0(h,f)==0)return 0;uh(h),uh(f);let y=rU(h,f,p,w);return w==="nanosecond"?ae.default.toNumber(y.time.totalNs):eN(y,Qr(f),h,null,p,w)}(Ht(c,{deltaDays:0,hour:0,minute:0,second:0,millisecond:0,microsecond:0,nanosecond:0}),Ht(d,l),u,o)}let s=yl(this);if(tc(s))throw new RangeError(`a starting point is required for ${s}s total`);if(tc(o))throw new RangeError(`a starting point is required for ${o}s total`);return My(rc(this).time,o)}toString(e=void 0){de(this,Fn);let t=Qe(e),r=nw(t),i=ya(t,"trunc"),o=fo(t,"smallestUnit","time",void 0);if(o==="hour"||o==="minute")throw new RangeError('smallestUnit must be a time unit other than "hours" or "minutes"');let{precision:s,unit:a,increment:l}=rw(o,r);if(a==="nanosecond"&&l===1)return $I(this,s);let c=yl(this),u=B0(this),d=uE(u.time,l,a,i);return u=xl(u.date,d),$I(Is(u,El(c,"second")),s)}toJSON(){return de(this,Fn),$I(this,"auto")}toLocaleString(e=void 0,t=void 0){if(de(this,Fn),typeof Intl.DurationFormat=="function"){let r=new Intl.DurationFormat(e,t);return i4.call(r,this)}return console.warn("Temporal.Duration.prototype.toLocaleString() requires Intl.DurationFormat."),$I(this,"auto")}valueOf(){yd("Duration")}static from(e){return Es(e)}static compare(e,t,r=void 0){let i=Es(e),o=Es(t),s=Qe(r),{plainRelativeTo:a,zonedRelativeTo:l}=rS(s);if(z(i,Mi)===z(o,Mi)&&z(i,Fi)===z(o,Fi)&&z(i,co)===z(o,co)&&z(i,ki)===z(o,ki)&&z(i,Oi)===z(o,Oi)&&z(i,Gi)===z(o,Gi)&&z(i,Ni)===z(o,Ni)&&z(i,Ui)===z(o,Ui)&&z(i,Hi)===z(o,Hi)&&z(i,lo)===z(o,lo))return 0;let c=yl(i),u=yl(o),d=B0(i),h=B0(o);if(l&&(wl(c)==="date"||wl(u)==="date")){let v=z(l,Xt),B=z(l,ve),U=z(l,it),k=Dy(U,v,B,d),F=Dy(U,v,B,h);return uo(ae.default.toNumber(ae.default.subtract(k,F)))}let f=d.date.days,p=h.date.days;if(tc(c)||tc(u)){if(!a)throw new RangeError("A starting point is required for years, months, or weeks comparison");f=$G(d.date,a),p=$G(h.date,a)}let w=d.time.add24HourDays(f),y=h.time.add24HourDays(p);return w.cmp(y)}};Ll(zy,"Temporal.Duration");var jy=class{constructor(e,t,r="iso8601",i=1972){let o=ut(e),s=ut(t),a=Yi(r===void 0?"iso8601":dr(r)),l=ut(i);lh(l,o,s),qN(this,{year:l,month:o,day:s},a)}get monthCode(){return mN(this,"monthCode")}get day(){return mN(this,"day")}get calendarId(){return de(this,Ho),z(this,ve)}with(e,t=void 0){if(de(this,Ho),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=z(this,ve),i=Qi(r,z(this,ot),"month-day");return i=ch(r,i,Vo(r,e,["year","month","monthCode","day"],[],"partial")),P0(sE(r,i,kt(Qe(t))),r)}equals(e){de(this,Ho);let t=QG(e);return ac(z(this,ot),z(t,ot))===0&&oc(z(this,ve),z(t,ve))}toString(e=void 0){return de(this,Ho),WG(this,tw(Qe(e)))}toJSON(){return de(this,Ho),WG(this)}toLocaleString(e=void 0,t=void 0){return de(this,Ho),new Jo(e,t).format(this)}valueOf(){yd("PlainMonthDay")}toPlainDate(e){if(de(this,Ho),!Gn(e))throw new TypeError("argument should be an object");let t=z(this,ve);return Ji(pd(t,ch(t,Qi(t,z(this,ot),"month-day"),Vo(t,e,["year"],[],[])),"constrain"),t)}static from(e,t=void 0){return QG(e,t)}};function mN(n,e){de(n,Ho);let t=z(n,ot);return iw(n).isoToDate(t,{[e]:!0})[e]}function oS(n){return xs(n,CS())}Ll(jy,"Temporal.PlainMonthDay");var mU={instant:()=>ma(CS()),plainDateTimeISO:(n=wy())=>bs(oS(qi(n)),"iso8601"),plainDateISO:(n=wy())=>Ji(oS(qi(n)).isoDate,"iso8601"),plainTimeISO:(n=wy())=>bl(oS(qi(n)).time),timeZoneId:()=>wy(),zonedDateTimeISO:(n=wy())=>{let e=qi(n);return ii(CS(),e,"iso8601")},[Symbol.toStringTag]:"Temporal.Now"};Object.defineProperty(mU,Symbol.toStringTag,{value:"Temporal.Now",writable:!1,enumerable:!1,configurable:!0});var Wy=class n{constructor(e=0,t=0,r=0,i=0,o=0,s=0){let a=e===void 0?0:ut(e),l=t===void 0?0:ut(t),c=r===void 0?0:ut(r),u=i===void 0?0:ut(i),d=o===void 0?0:ut(o),h=s===void 0?0:ut(s);SE(a,l,c,u,d,h),QN(this,{hour:a,minute:l,second:c,millisecond:u,microsecond:d,nanosecond:h})}get hour(){return de(this,qn),z(this,On).hour}get minute(){return de(this,qn),z(this,On).minute}get second(){return de(this,qn),z(this,On).second}get millisecond(){return de(this,qn),z(this,On).millisecond}get microsecond(){return de(this,qn),z(this,On).microsecond}get nanosecond(){return de(this,qn),z(this,On).nanosecond}with(e,t=void 0){if(de(this,qn),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=mS(e,"partial"),i=mS(this),{hour:o,minute:s,second:a,millisecond:l,microsecond:c,nanosecond:u}=Object.assign(i,r),d=kt(Qe(t));return{hour:o,minute:s,second:a,millisecond:l,microsecond:c,nanosecond:u}=AE(o,s,a,l,c,u,d),new n(o,s,a,l,c,u)}add(e){return de(this,qn),dN("add",this,e)}subtract(e){return de(this,qn),dN("subtract",this,e)}until(e,t=void 0){return de(this,qn),iN("until",this,e,t)}since(e,t=void 0){return de(this,qn),iN("since",this,e,t)}round(e){if(de(this,qn),e===void 0)throw new TypeError("options parameter is required");let t=typeof e=="string"?fh("smallestUnit",e):Qe(e),r=J0(t),i=ya(t,"halfExpand"),o=fo(t,"smallestUnit","time",Cl);return q0(r,{hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[o],!1),bl(AS(z(this,On),r,o,i))}equals(e){de(this,qn);let t=ld(e);return vS(z(this,On),z(t,On))===0}toString(e=void 0){de(this,qn);let t=Qe(e),r=nw(t),i=ya(t,"trunc"),o=fo(t,"smallestUnit","time",void 0);if(o==="hour")throw new RangeError('smallestUnit must be a time unit other than "hour"');let{precision:s,unit:a,increment:l}=rw(o,r);return jG(AS(z(this,On),l,a,i),s)}toJSON(){return de(this,qn),jG(z(this,On),"auto")}toLocaleString(e=void 0,t=void 0){return de(this,qn),new Jo(e,t).format(this)}valueOf(){yd("PlainTime")}static from(e,t=void 0){return ld(e,t)}static compare(e,t){let r=ld(e),i=ld(t);return vS(z(r,On),z(i,On))}};Ll(Wy,"Temporal.PlainTime");var Zy=class{constructor(e,t,r="iso8601",i=1){let o=ut(e),s=ut(t),a=Yi(r===void 0?"iso8601":dr(r)),l=ut(i);lh(o,s,l),VN(this,{year:o,month:s,day:l},a)}get year(){return ml(this,"year")}get month(){return ml(this,"month")}get monthCode(){return ml(this,"monthCode")}get calendarId(){return de(this,qr),z(this,ve)}get era(){return ml(this,"era")}get eraYear(){return ml(this,"eraYear")}get daysInMonth(){return ml(this,"daysInMonth")}get daysInYear(){return ml(this,"daysInYear")}get monthsInYear(){return ml(this,"monthsInYear")}get inLeapYear(){return ml(this,"inLeapYear")}with(e,t=void 0){if(de(this,qr),!Gn(e))throw new TypeError("invalid argument");K0(e);let r=z(this,ve),i=Qi(r,z(this,ot),"year-month");return i=ch(r,i,Vo(r,e,["year","month","monthCode"],[],"partial")),R0(Gy(r,i,kt(Qe(t))),r)}add(e,t=void 0){return de(this,qr),fN("add",this,e,t)}subtract(e,t=void 0){return de(this,qr),fN("subtract",this,e,t)}until(e,t=void 0){return de(this,qr),oN("until",this,e,t)}since(e,t=void 0){return de(this,qr),oN("since",this,e,t)}equals(e){de(this,qr);let t=Cy(e);return ac(z(this,ot),z(t,ot))===0&&oc(z(this,ve),z(t,ve))}toString(e=void 0){return de(this,qr),ZG(this,tw(Qe(e)))}toJSON(){return de(this,qr),ZG(this)}toLocaleString(e=void 0,t=void 0){return de(this,qr),new Jo(e,t).format(this)}valueOf(){yd("PlainYearMonth")}toPlainDate(e){if(de(this,qr),!Gn(e))throw new TypeError("argument should be an object");let t=z(this,ve);return Ji(pd(t,ch(t,Qi(t,z(this,ot),"year-month"),Vo(t,e,["day"],[],[])),"constrain"),t)}static from(e,t=void 0){return Cy(e,t)}static compare(e,t){let r=Cy(e),i=Cy(t);return ac(z(r,ot),z(i,ot))}};function ml(n,e){de(n,qr);let t=z(n,ot);return iw(n).isoToDate(t,{[e]:!0})[e]}Ll(Zy,"Temporal.PlainYearMonth");var Bre=Jo.prototype.resolvedOptions,Xy=class{constructor(e,t,r="iso8601"){if(arguments.length<1)throw new TypeError("missing argument: epochNanoseconds is required");let i=dE(e),o=dr(t),{tzName:s,offsetMinutes:a}=dd(o);if(a===void 0){let l=aE(s);if(!l)throw new RangeError(`unknown time zone ${s}`);o=l.identifier}else o=WS(a);zN(this,i,o,Yi(r===void 0?"iso8601":dr(r)))}get calendarId(){return de(this,It),z(this,ve)}get timeZoneId(){return de(this,It),z(this,Xt)}get year(){return Ri(this,"year")}get month(){return Ri(this,"month")}get monthCode(){return Ri(this,"monthCode")}get day(){return Ri(this,"day")}get hour(){return D0(this,"hour")}get minute(){return D0(this,"minute")}get second(){return D0(this,"second")}get millisecond(){return D0(this,"millisecond")}get microsecond(){return D0(this,"microsecond")}get nanosecond(){return D0(this,"nanosecond")}get era(){return Ri(this,"era")}get eraYear(){return Ri(this,"eraYear")}get epochMilliseconds(){return de(this,It),As(z(this,it),"floor")}get epochNanoseconds(){return de(this,It),cU(z(this,it))}get dayOfWeek(){return Ri(this,"dayOfWeek")}get dayOfYear(){return Ri(this,"dayOfYear")}get weekOfYear(){return Ri(this,"weekOfYear")?.week}get yearOfWeek(){return Ri(this,"weekOfYear")?.year}get hoursInDay(){de(this,It);let e=z(this,Xt),t=ec(this).isoDate,r=ho(t.year,t.month,t.day+1),i=ad(e,t),o=ad(e,r);return My(dn.fromEpochNsDiff(o,i),"hour")}get daysInWeek(){return Ri(this,"daysInWeek")}get daysInMonth(){return Ri(this,"daysInMonth")}get daysInYear(){return Ri(this,"daysInYear")}get monthsInYear(){return Ri(this,"monthsInYear")}get inLeapYear(){return Ri(this,"inLeapYear")}get offset(){return de(this,It),gS(Il(z(this,Xt),z(this,it)))}get offsetNanoseconds(){return de(this,It),Il(z(this,Xt),z(this,it))}with(e,t=void 0){if(de(this,It),!Gn(e))throw new TypeError("invalid zoned-date-time-like");K0(e);let r=z(this,ve),i=z(this,Xt),o=Il(i,z(this,it)),s=ec(this),a={...Qi(r,s.isoDate),...s.time,offset:gS(o)};a=ch(r,a,Vo(r,e,["year","month","monthCode","day"],["hour","minute","second","millisecond","microsecond","nanosecond","offset"],"partial"));let l=Qe(t),c=Ry(l),u=eE(l,"prefer"),d=ow(r,a,kt(l)),h=Q0(a.offset);return ii(oE(d.isoDate,d.time,"option",h,i,c,u,!1),i,r)}withPlainTime(e=void 0){de(this,It);let t=z(this,Xt),r=z(this,ve),i=ec(this).isoDate,o;return o=e===void 0?ad(t,i):si(t,Ht(i,z(ld(e),On)),"compatible"),ii(o,t,r)}withTimeZone(e){de(this,It);let t=qi(e);return ii(z(this,it),t,z(this,ve))}withCalendar(e){de(this,It);let t=aw(e);return ii(z(this,it),z(this,Xt),t)}add(e,t=void 0){return de(this,It),hN("add",this,e,t)}subtract(e,t=void 0){return de(this,It),hN("subtract",this,e,t)}until(e,t=void 0){return de(this,It),sN("until",this,e,t)}since(e,t=void 0){return de(this,It),sN("since",this,e,t)}round(e){if(de(this,It),e===void 0)throw new TypeError("options parameter is required");let t=typeof e=="string"?fh("smallestUnit",e):Qe(e),r=J0(t),i=ya(t,"halfExpand"),o=fo(t,"smallestUnit","time",Cl,["day"]),s={day:1,hour:24,minute:60,second:60,millisecond:1e3,microsecond:1e3,nanosecond:1e3}[o];if(q0(r,s,s===1),o==="nanosecond"&&r===1)return ii(z(this,it),z(this,Xt),z(this,ve));let a=z(this,Xt),l=z(this,it),c=ec(this),u;if(o==="day"){let d=c.isoDate,h=ho(d.year,d.month,d.day+1),f=ad(a,d),p=ad(a,h),w=ae.default.subtract(p,f);u=dn.fromEpochNsDiff(l,f).round(w,i).addToEpochNs(f)}else{let d=xS(c,r,o,i),h=Il(a,l);u=oE(d.isoDate,d.time,"option",h,a,"compatible","prefer",!1)}return ii(u,a,z(this,ve))}equals(e){de(this,It);let t=Sy(e),r=z(this,it),i=z(t,it);return!!ae.default.equal(ae.default.BigInt(r),ae.default.BigInt(i))&&!!jN(z(this,Xt),z(t,Xt))&&oc(z(this,ve),z(t,ve))}toString(e=void 0){de(this,It);let t=Qe(e),r=tw(t),i=nw(t),o=function(h){return Al(h,"offset",["auto","never"],"auto")}(t),s=ya(t,"trunc"),a=fo(t,"smallestUnit","time",void 0);if(a==="hour")throw new RangeError('smallestUnit must be a time unit other than "hour"');let l=function(h){return Al(h,"timeZoneName",["auto","never","critical"],"auto")}(t),{precision:c,unit:u,increment:d}=rw(a,i);return XG(this,c,r,l,o,{unit:u,increment:d,roundingMode:s})}toLocaleString(e=void 0,t=void 0){de(this,It);let r=Qe(t),i=Object.create(null);if(function(l,c,u,d){if(c==null)return;let h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){let p=h[f];if(!u.some(w=>Object.is(w,p))&&Object.prototype.propertyIsEnumerable.call(c,p)){let w=c[p];l[p]=w}}}(i,r,["timeZone"]),r.timeZone!==void 0)throw new TypeError("ZonedDateTime toLocaleString does not accept a timeZone option");if(i.year===void 0&&i.month===void 0&&i.day===void 0&&i.era===void 0&&i.weekday===void 0&&i.dateStyle===void 0&&i.hour===void 0&&i.minute===void 0&&i.second===void 0&&i.fractionalSecondDigits===void 0&&i.timeStyle===void 0&&i.dayPeriod===void 0&&i.timeZoneName===void 0&&(i.timeZoneName="short"),i.timeZone=z(this,Xt),_G(i.timeZone))throw new RangeError("toLocaleString does not currently support offset time zones");let o=new Jo(e,i),s=Bre.call(o).calendar,a=z(this,ve);if(a!=="iso8601"&&s!=="iso8601"&&!oc(s,a))throw new RangeError(`cannot format ZonedDateTime with calendar ${a} in locale with calendar ${s}`);return o.format(ma(z(this,it)))}toJSON(){return de(this,It),XG(this,"auto")}valueOf(){yd("ZonedDateTime")}startOfDay(){de(this,It);let e=z(this,Xt);return ii(ad(e,ec(this).isoDate),e,z(this,ve))}getTimeZoneTransition(e){de(this,It);let t=z(this,Xt);if(e===void 0)throw new TypeError("options parameter is required");let r=Al(typeof e=="string"?fh("direction",e):Qe(e),"direction",["next","previous"],Cl);if(r===void 0)throw new TypeError("direction option is required");if(_G(t)||t==="UTC")return null;let i=z(this,it),o=r==="next"?XS(t,i):wS(t,i);return o===null?null:ii(o,t,z(this,ve))}toInstant(){return de(this,It),ma(z(this,it))}toPlainDate(){return de(this,It),Ji(ec(this).isoDate,z(this,ve))}toPlainTime(){return de(this,It),bl(ec(this).time)}toPlainDateTime(){return de(this,It),bs(ec(this),z(this,ve))}static from(e,t=void 0){return Sy(e,t)}static compare(e,t){let r=Sy(e),i=Sy(t),o=z(r,it),s=z(i,it);return ae.default.lessThan(ae.default.BigInt(o),ae.default.BigInt(s))?-1:ae.default.greaterThan(ae.default.BigInt(o),ae.default.BigInt(s))?1:0}};function ec(n){return xs(z(n,Xt),z(n,it))}function Ri(n,e){de(n,It);let t=ec(n).isoDate;return iw(n).isoToDate(t,{[e]:!0})[e]}function D0(n,e){return de(n,It),ec(n).time[e]}Ll(Xy,"Temporal.ZonedDateTime");var wa=Object.freeze({__proto__:null,Duration:zy,Instant:Qy,Now:mU,PlainDate:Vy,PlainDateTime:Yy,PlainMonthDay:jy,PlainTime:Wy,PlainYearMonth:Zy,ZonedDateTime:Xy}),u6e=class{toTemporalInstant(){return ma(ga(Date.prototype.valueOf.call(this)))}}.prototype.toTemporalInstant,Tre=[Qy,Vy,Yy,zy,jy,Wy,Zy,Xy];for(let n of Tre){let e=Object.getOwnPropertyDescriptor(n,"prototype");(e.configurable||e.enumerable||e.writable)&&(e.configurable=!1,e.enumerable=!1,e.writable=!1,Object.defineProperty(n,"prototype",e))}var eH=$n(vd(),1);var U9=$n(G9());var Bw="http://www.w3.org/1999/02/22-rdf-syntax-ns#",Tw="http://www.w3.org/2001/XMLSchema#",ex="http://www.w3.org/2000/10/swap/",Io={xsd:{decimal:`${Tw}decimal`,boolean:`${Tw}boolean`,double:`${Tw}double`,integer:`${Tw}integer`,string:`${Tw}string`},rdf:{type:`${Bw}type`,nil:`${Bw}nil`,first:`${Bw}first`,rest:`${Bw}rest`,langString:`${Bw}langString`},owl:{sameAs:"http://www.w3.org/2002/07/owl#sameAs"},r:{forSome:`${ex}reify#forSome`,forAll:`${ex}reify#forAll`},log:{implies:`${ex}log#implies`,isImpliedBy:`${ex}log#isImpliedBy`}};var{xsd:tx}=Io,use=/\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{8})|\\([^])/g,N9={"\\":"\\","'":"'",'"':'"',n:`
37
37
  `,r:"\r",t:" ",f:"\f",b:"\b",_:"_","~":"~",".":".","-":"-","!":"!",$:"$","&":"&","(":"(",")":")","*":"*","+":"+",",":",",";":";","=":"=","/":"/","?":"?","#":"#","@":"@","%":"%"},dse=/[\x00-\x20<>\\"\{\}\|\^\`]/,fse={_iri:!0,_unescapedIri:!0,_simpleQuotedString:!0,_langcode:!0,_blank:!0,_newline:!0,_comment:!0,_whitespace:!0,_endOfFile:!0},hse=/$0^/,Pw=class{constructor(e){if(this._iri=/^<((?:[^ <>{}\\]|\\[uU])+)>[ \t]*/,this._unescapedIri=/^<([^\x00-\x20<>\\"\{\}\|\^\`]*)>[ \t]*/,this._simpleQuotedString=/^"([^"\\\r\n]*)"(?=[^"])/,this._simpleApostropheString=/^'([^'\\\r\n]*)'(?=[^'])/,this._langcode=/^@([a-z]+(?:-[a-z0-9]+)*)(?=[^a-z0-9\-])/i,this._prefix=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:(?=[#\s<])/,this._prefixed=/^((?:[A-Za-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)?:((?:(?:[0-:A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])(?:(?:[\.\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~])*(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff]|%[0-9a-fA-F]{2}|\\[!#-\/;=?\-@_~]))?)?)(?:[ \t]+|(?=\.?[,;!\^\s#()\[\]\{\}"'<>]))/,this._variable=/^\?(?:(?:[A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:[\-0-:A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?=[.,;!\^\s#()\[\]\{\}"'<>])/,this._blank=/^_:((?:[0-9A-Z_a-z\xc0-\xd6\xd8-\xf6\xf8-\u02ff\u0370-\u037d\u037f-\u1fff\u200c\u200d\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])(?:\.?[\-0-9A-Z_a-z\xb7\xc0-\xd6\xd8-\xf6\xf8-\u037d\u037f-\u1fff\u200c\u200d\u203f\u2040\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff\uf900-\ufdcf\ufdf0-\ufffd]|[\ud800-\udb7f][\udc00-\udfff])*)(?:[ \t]+|(?=\.?[,;:\s#()\[\]\{\}"'<>]))/,this._number=/^[\-+]?(?:(\d+\.\d*|\.?\d+)[eE][\-+]?|\d*(\.)?)\d+(?=\.?[,;:\s#()\[\]\{\}"'<>])/,this._boolean=/^(?:true|false)(?=[.,;\s#()\[\]\{\}"'<>])/,this._keyword=/^@[a-z]+(?=[\s#<:])/i,this._sparqlKeyword=/^(?:PREFIX|BASE|GRAPH)(?=[\s#<])/i,this._shortPredicates=/^a(?=[\s#()\[\]\{\}"'<>])/,this._newline=/^[ \t]*(?:#[^\n\r]*)?(?:\r\n|\n|\r)[ \t]*/,this._comment=/#([^\n\r]*)/,this._whitespace=/^[ \t]+/,this._endOfFile=/^(?:#[^\n\r]*)?$/,e=e||{},this._isImpliedBy=e.isImpliedBy,this._lineMode=!!e.lineMode){this._n3Mode=!1;for(let t in this)!(t in fse)&&this[t]instanceof RegExp&&(this[t]=hse)}else this._n3Mode=e.n3!==!1;this.comments=!!e.comments,this._literalClosingPos=0}_tokenizeToEnd(e,t){let r=this._input,i=r.length;for(;;){let a,l;for(;a=this._newline.exec(r);)this.comments&&(l=this._comment.exec(a[0]))&&o("comment",l[1],"",this._line,a[0].length),r=r.substr(a[0].length,r.length),i=r.length,this._line++;if(!a&&(a=this._whitespace.exec(r))&&(r=r.substr(a[0].length,r.length)),this._endOfFile.test(r))return t&&(this.comments&&(l=this._comment.exec(r))&&o("comment",l[1],"",this._line,r.length),r=null,o("eof","","",this._line,0)),this._input=r;let c=this._line,u=r[0],d="",h="",f="",p=null,w=0,y=!1;switch(u){case"^":if(r.length<3)break;if(r[1]==="^"){if(this._previousMarker="^^",r=r.substr(2),r[0]!=="<"){y=!0;break}}else{this._n3Mode&&(w=1,d="^");break}case"<":if(p=this._unescapedIri.exec(r))d="IRI",h=p[1];else if(p=this._iri.exec(r)){if(h=this._unescape(p[1]),h===null||dse.test(h))return s(this);d="IRI"}else r.length>1&&r[1]==="<"?(d="<<",w=2):this._n3Mode&&r.length>1&&r[1]==="="&&(w=2,this._isImpliedBy?(d="abbreviation",h="<"):(d="inverse",h=">"));break;case">":r.length>1&&r[1]===">"&&(d=">>",w=2);break;case"_":((p=this._blank.exec(r))||t&&(p=this._blank.exec(`${r} `)))&&(d="blank",f="_",h=p[1]);break;case'"':if(p=this._simpleQuotedString.exec(r))h=p[1];else if({value:h,matchLength:w}=this._parseLiteral(r),h===null)return s(this);(p!==null||w!==0)&&(d="literal",this._literalClosingPos=0);break;case"'":if(!this._lineMode){if(p=this._simpleApostropheString.exec(r))h=p[1];else if({value:h,matchLength:w}=this._parseLiteral(r),h===null)return s(this);(p!==null||w!==0)&&(d="literal",this._literalClosingPos=0)}break;case"?":this._n3Mode&&(p=this._variable.exec(r))&&(d="var",h=p[0]);break;case"@":this._previousMarker==="literal"&&(p=this._langcode.exec(r))?(d="langcode",h=p[1]):(p=this._keyword.exec(r))&&(d=p[0]);break;case".":if(r.length===1?t:r[1]<"0"||r[1]>"9"){d=".",w=1;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"+":case"-":(p=this._number.exec(r)||t&&(p=this._number.exec(`${r} `)))&&(d="literal",h=p[0],f=typeof p[1]=="string"?tx.double:typeof p[2]=="string"?tx.decimal:tx.integer);break;case"B":case"b":case"p":case"P":case"G":case"g":(p=this._sparqlKeyword.exec(r))?d=p[0].toUpperCase():y=!0;break;case"f":case"t":(p=this._boolean.exec(r))?(d="literal",h=p[0],f=tx.boolean):y=!0;break;case"a":(p=this._shortPredicates.exec(r))?(d="abbreviation",h="a"):y=!0;break;case"=":this._n3Mode&&r.length>1&&(d="abbreviation",r[1]!==">"?(w=1,h="="):(w=2,h=">"));break;case"!":if(!this._n3Mode)break;case",":case";":case"[":case"]":case"(":case")":case"}":this._lineMode||(w=1,d=u);break;case"{":!this._lineMode&&r.length>=2&&(r[1]==="|"?(d="{|",w=2):(d=u,w=1));break;case"|":r.length>=2&&r[1]==="}"&&(d="|}",w=2);break;default:y=!0}if(y&&((this._previousMarker==="@prefix"||this._previousMarker==="PREFIX")&&(p=this._prefix.exec(r))?(d="prefix",h=p[1]||""):((p=this._prefixed.exec(r))||t&&(p=this._prefixed.exec(`${r} `)))&&(d="prefixed",f=p[1]||"",h=this._unescape(p[2]))),this._previousMarker==="^^")switch(d){case"prefixed":d="type";break;case"IRI":d="typeIRI";break;default:d=""}if(!d)return t||!/^'''|^"""/.test(r)&&/\n|\r/.test(r)?s(this):this._input=r;let v=w||p[0].length,B=o(d,h,f,c,v);this.previousToken=B,this._previousMarker=d,r=r.substr(v,r.length)}function o(a,l,c,u,d){let h=r?i-r.length:i,f=h+d,p={type:a,value:l,prefix:c,line:u,start:h,end:f};return e(null,p),p}function s(a){e(a._syntaxError(/^\S*/.exec(r)[0]))}}_unescape(e){let t=!1,r=e.replace(use,(i,o,s,a)=>{if(typeof o=="string")return String.fromCharCode(Number.parseInt(o,16));if(typeof s=="string"){let l=Number.parseInt(s,16);return l<=65535?String.fromCharCode(Number.parseInt(s,16)):String.fromCharCode(55296+((l-=65536)>>10),56320+(l&1023))}return a in N9?N9[a]:(t=!0,"")});return t?null:r}_parseLiteral(e){if(e.length>=3){let t=e.match(/^(?:"""|"|'''|'|)/)[0],r=t.length,i=Math.max(this._literalClosingPos,r);for(;(i=e.indexOf(t,i))>0;){let o=0;for(;e[i-o-1]==="\\";)o++;if(o%2===0){let s=e.substring(r,i),a=s.split(/\r\n|\r|\n/).length-1,l=i+r;if(r===1&&a!==0||r===3&&this._lineMode)break;return this._line+=a,{value:this._unescape(s),matchLength:l}}i++}this._literalClosingPos=e.length-r+1}return{value:"",matchLength:0}}_syntaxError(e){this._input=null;let t=new Error(`Unexpected "${e}" on line ${this._line}.`);return t.context={token:void 0,line:this._line,previousToken:this.previousToken},t}_readStartingBom(e){return e.startsWith("\uFEFF")?e.substr(1):e}tokenize(e,t){if(this._line=1,typeof e=="string")if(this._input=this._readStartingBom(e),typeof t=="function")queueMicrotask(()=>this._tokenizeToEnd(t,!0));else{let r=[],i;if(this._tokenizeToEnd((o,s)=>o?i=o:r.push(s),!0),i)throw i;return r}else this._pendingBuffer=null,typeof e.setEncoding=="function"&&e.setEncoding("utf8"),e.on("data",r=>{this._input!==null&&r.length!==0&&(this._pendingBuffer&&(r=U9.Buffer.concat([this._pendingBuffer,r]),this._pendingBuffer=null),r[r.length-1]&128?this._pendingBuffer=r:(typeof this._input>"u"?this._input=this._readStartingBom(typeof r=="string"?r:r.toString()):this._input+=r,this._tokenizeToEnd(t,!1)))}),e.on("end",()=>{typeof this._input=="string"&&this._tokenizeToEnd(t,!0)}),e.on("error",t)}};var{rdf:pse,xsd:rm}=Io,Fw,mse=0;var gse={namedNode:K9,blankNode:J9,variable:Q9,literal:q9,defaultGraph:yse,quad:oD,triple:oD,fromTerm:Rw,fromQuad:V9},H9=gse,kl=class n{constructor(e){this.id=e}get value(){return this.id}equals(e){return e instanceof n?this.id===e.id:!!e&&this.termType===e.termType&&this.value===e.value}hashCode(){return 0}toJSON(){return{termType:this.termType,value:this.value}}},nx=class extends kl{get termType(){return"NamedNode"}},Mw=class n extends kl{get termType(){return"Literal"}get value(){return this.id.substring(1,this.id.lastIndexOf('"'))}get language(){let e=this.id,t=e.lastIndexOf('"')+1;return t<e.length&&e[t++]==="@"?e.substr(t).toLowerCase():""}get datatype(){return new nx(this.datatypeString)}get datatypeString(){let e=this.id,t=e.lastIndexOf('"')+1,r=t<e.length?e[t]:"";return r==="^"?e.substr(t+2):r!=="@"?rm.string:pse.langString}equals(e){return e instanceof n?this.id===e.id:!!e&&!!e.datatype&&this.termType===e.termType&&this.value===e.value&&this.language===e.language&&this.datatype.value===e.datatype.value}toJSON(){return{termType:this.termType,value:this.value,language:this.language,datatype:{termType:"NamedNode",value:this.datatypeString}}}},nD=class extends kl{constructor(e){super(`_:${e}`)}get termType(){return"BlankNode"}get value(){return this.id.substr(2)}},rD=class extends kl{constructor(e){super(`?${e}`)}get termType(){return"Variable"}get value(){return this.id.substr(1)}},iD=class extends kl{constructor(){return super(""),Fw||this}get termType(){return"DefaultGraph"}equals(e){return this===e||!!e&&this.termType===e.termType}};Fw=new iD;var rx=class extends kl{constructor(e,t,r,i){super(""),this._subject=e,this._predicate=t,this._object=r,this._graph=i||Fw}get termType(){return"Quad"}get subject(){return this._subject}get predicate(){return this._predicate}get object(){return this._object}get graph(){return this._graph}toJSON(){return{termType:this.termType,subject:this._subject.toJSON(),predicate:this._predicate.toJSON(),object:this._object.toJSON(),graph:this._graph.toJSON()}}equals(e){return!!e&&this._subject.equals(e.subject)&&this._predicate.equals(e.predicate)&&this._object.equals(e.object)&&this._graph.equals(e.graph)}};function K9(n){return new nx(n)}function J9(n){return new nD(n||`n3-${mse++}`)}function q9(n,e){if(typeof e=="string")return new Mw(`"${n}"@${e.toLowerCase()}`);let t=e?e.value:"";return t===""&&(typeof n=="boolean"?t=rm.boolean:typeof n=="number"&&(Number.isFinite(n)?t=Number.isInteger(n)?rm.integer:rm.double:(t=rm.double,Number.isNaN(n)||(n=n>0?"INF":"-INF")))),t===""||t===rm.string?new Mw(`"${n}"`):new Mw(`"${n}"^^${t}`)}function Q9(n){return new rD(n)}function yse(){return Fw}function oD(n,e,t,r){return new rx(n,e,t,r)}function Rw(n){if(n instanceof kl)return n;switch(n.termType){case"NamedNode":return K9(n.value);case"BlankNode":return J9(n.value);case"Variable":return Q9(n.value);case"DefaultGraph":return Fw;case"Literal":return q9(n.value,n.language||n.datatype);case"Quad":return V9(n);default:throw new Error(`Unexpected termType: ${n.termType}`)}}function V9(n){if(n instanceof rx)return n;if(n.termType!=="Quad")throw new Error(`Unexpected termType: ${n.termType}`);return oD(Rw(n.subject),Rw(n.predicate),Rw(n.object),Rw(n.graph))}var Y9=0,Th=class{constructor(e){this._contextStack=[],this._graph=null,e=e||{},this._setBase(e.baseIRI),e.factory&&z9(this,e.factory);let t=typeof e.format=="string"?e.format.match(/\w*$/)[0].toLowerCase():"",r=/turtle/.test(t),i=/trig/.test(t),o=/triple/.test(t),s=/quad/.test(t),a=this._n3Mode=/n3/.test(t),l=o||s;(this._supportsNamedGraphs=!(r||a))||(this._readPredicateOrNamedGraph=this._readPredicate),this._supportsQuads=!(r||i||o||a),this._isImpliedBy=e.isImpliedBy,this._supportsRDFStar=t===""||/star|\*$/.test(t),l&&(this._resolveRelativeIRI=c=>null),this._blankNodePrefix=typeof e.blankNodePrefix!="string"?"":e.blankNodePrefix.replace(/^(?!_:)/,"_:"),this._lexer=e.lexer||new Pw({lineMode:l,n3:a,isImpliedBy:this._isImpliedBy}),this._explicitQuantifiers=!!e.explicitQuantifiers}static _resetBlankNodePrefix(){Y9=0}_setBase(e){if(!e)this._base="",this._basePath="";else{let t=e.indexOf("#");t>=0&&(e=e.substr(0,t)),this._base=e,this._basePath=e.indexOf("/")<0?e:e.replace(/[^\/?]*(?:\?.*)?$/,""),e=e.match(/^(?:([a-z][a-z0-9+.-]*:))?(?:\/\/[^\/]*)?/i),this._baseRoot=e[0],this._baseScheme=e[1]}}_saveContext(e,t,r,i,o){let s=this._n3Mode;this._contextStack.push({type:e,subject:r,predicate:i,object:o,graph:t,inverse:s?this._inversePredicate:!1,blankPrefix:s?this._prefixes._:"",quantified:s?this._quantified:null}),s&&(this._inversePredicate=!1,this._prefixes._=this._graph?`${this._graph.value}.`:".",this._quantified=Object.create(this._quantified))}_restoreContext(e,t){let r=this._contextStack.pop();if(!r||r.type!==e)return this._error(`Unexpected ${t.type}`,t);this._subject=r.subject,this._predicate=r.predicate,this._object=r.object,this._graph=r.graph,this._n3Mode&&(this._inversePredicate=r.inverse,this._prefixes._=r.blankPrefix,this._quantified=r.quantified)}_readInTopContext(e){switch(e.type){case"eof":return this._graph!==null?this._error("Unclosed graph",e):(delete this._prefixes._,this._callback(null,null,this._prefixes));case"PREFIX":this._sparqlStyle=!0;case"@prefix":return this._readPrefix;case"BASE":this._sparqlStyle=!0;case"@base":return this._readBaseIRI;case"{":if(this._supportsNamedGraphs)return this._graph="",this._subject=null,this._readSubject;case"GRAPH":if(this._supportsNamedGraphs)return this._readNamedGraphLabel;default:return this._readSubject(e)}}_readEntity(e,t){let r;switch(e.type){case"IRI":case"typeIRI":let i=this._resolveIRI(e.value);if(i===null)return this._error("Invalid IRI",e);r=this._factory.namedNode(i);break;case"type":case"prefixed":let o=this._prefixes[e.prefix];if(o===void 0)return this._error(`Undefined prefix "${e.prefix}:"`,e);r=this._factory.namedNode(o+e.value);break;case"blank":r=this._factory.blankNode(this._prefixes[e.prefix]+e.value);break;case"var":r=this._factory.variable(e.value.substr(1));break;default:return this._error(`Expected entity but got ${e.type}`,e)}return!t&&this._n3Mode&&r.id in this._quantified&&(r=this._quantified[r.id]),r}_readSubject(e){switch(this._predicate=null,e.type){case"[":return this._saveContext("blank",this._graph,this._subject=this._factory.blankNode(),null,null),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this.RDF_NIL,null,null),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._graph=this._factory.blankNode(),null,null),this._readSubject):this._error("Unexpected graph",e);case"}":return this._readPunctuation(e);case"@forSome":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORSOME,this._quantifier="blankNode",this._readQuantifierList):this._error('Unexpected "@forSome"',e);case"@forAll":return this._n3Mode?(this._subject=null,this._predicate=this.N3_FORALL,this._quantifier="variable",this._readQuantifierList):this._error('Unexpected "@forAll"',e);case"literal":if(!this._n3Mode)return this._error("Unexpected literal",e);if(e.prefix.length===0)return this._literalValue=e.value,this._completeSubjectLiteral;this._subject=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,null,null,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._subject=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._readPredicateOrNamedGraph)}return this._readPredicateOrNamedGraph}_readPredicate(e){let t=e.type;switch(t){case"inverse":this._inversePredicate=!0;case"abbreviation":this._predicate=this.ABBREVIATIONS[e.value];break;case".":case"]":case"}":return this._predicate===null?this._error(`Unexpected ${t}`,e):(this._subject=null,t==="]"?this._readBlankNodeTail(e):this._readPunctuation(e));case";":return this._predicate!==null?this._readPredicate:this._error("Expected predicate but got ;",e);case"[":if(this._n3Mode)return this._saveContext("blank",this._graph,this._subject,this._subject=this._factory.blankNode(),null),this._readBlankNodeHead;case"blank":if(!this._n3Mode)return this._error("Disallowed blank node as predicate",e);default:if((this._predicate=this._readEntity(e))===void 0)return}return this._readObject}_readObject(e){switch(e.type){case"literal":if(e.prefix.length===0)return this._literalValue=e.value,this._readDataTypeOrLang;this._object=this._factory.literal(e.value,this._factory.namedNode(e.prefix));break;case"[":return this._saveContext("blank",this._graph,this._subject,this._predicate,this._subject=this._factory.blankNode()),this._readBlankNodeHead;case"(":return this._saveContext("list",this._graph,this._subject,this._predicate,this.RDF_NIL),this._subject=null,this._readListItem;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);case"<<":return this._supportsRDFStar?(this._saveContext("<<",this._graph,this._subject,this._predicate,null),this._graph=null,this._readSubject):this._error("Unexpected RDF-star syntax",e);default:if((this._object=this._readEntity(e))===void 0)return;if(this._n3Mode)return this._getPathReader(this._getContextEndReader())}return this._getContextEndReader()}_readPredicateOrNamedGraph(e){return e.type==="{"?this._readGraph(e):this._readPredicate(e)}_readGraph(e){return e.type!=="{"?this._error(`Expected graph but got ${e.type}`,e):(this._graph=this._subject,this._subject=null,this._readSubject)}_readBlankNodeHead(e){return e.type==="]"?(this._subject=null,this._readBlankNodeTail(e)):(this._predicate=null,this._readPredicate(e))}_readBlankNodeTail(e){if(e.type!=="]")return this._readBlankNodePunctuation(e);this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph);let t=this._predicate===null;return this._restoreContext("blank",e),this._object!==null?this._getContextEndReader():this._predicate!==null?this._readObject:t?this._readPredicateOrNamedGraph:this._readPredicateAfterBlank}_readPredicateAfterBlank(e){switch(e.type){case".":case"}":return this._subject=null,this._readPunctuation(e);default:return this._readPredicate(e)}}_readListItem(e){let t=null,r=null,i=this._readListItem,o=this._subject,s=this._contextStack,a=s[s.length-1];switch(e.type){case"[":this._saveContext("blank",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this._subject=t=this._factory.blankNode()),i=this._readBlankNodeHead;break;case"(":this._saveContext("list",this._graph,r=this._factory.blankNode(),this.RDF_FIRST,this.RDF_NIL),this._subject=null;break;case")":if(this._restoreContext("list",e),s.length!==0&&s[s.length-1].type==="list"&&this._emit(this._subject,this._predicate,this._object,this._graph),this._predicate===null){if(i=this._readPredicate,this._subject===this.RDF_NIL)return i}else if(i=this._getContextEndReader(),this._object===this.RDF_NIL)return i;r=this.RDF_NIL;break;case"literal":e.prefix.length===0?(this._literalValue=e.value,i=this._readListItemDataTypeOrLang):(t=this._factory.literal(e.value,this._factory.namedNode(e.prefix)),i=this._getContextEndReader());break;case"{":return this._n3Mode?(this._saveContext("formula",this._graph,this._subject,this._predicate,this._graph=this._factory.blankNode()),this._readSubject):this._error("Unexpected graph",e);default:if((t=this._readEntity(e))===void 0)return}if(r===null&&(this._subject=r=this._factory.blankNode()),o===null?a.predicate===null?a.subject=r:a.object=r:this._emit(o,this.RDF_REST,r,this._graph),t!==null){if(this._n3Mode&&(e.type==="IRI"||e.type==="prefixed"))return this._saveContext("item",this._graph,r,this.RDF_FIRST,t),this._subject=t,this._predicate=null,this._getPathReader(this._readListItem);this._emit(r,this.RDF_FIRST,t,this._graph)}return i}_readDataTypeOrLang(e){return this._completeObjectLiteral(e,!1)}_readListItemDataTypeOrLang(e){return this._completeObjectLiteral(e,!0)}_completeLiteral(e){let t=this._factory.literal(this._literalValue);switch(e.type){case"type":case"typeIRI":let r=this._readEntity(e);if(r===void 0)return;t=this._factory.literal(this._literalValue,r),e=null;break;case"langcode":t=this._factory.literal(this._literalValue,e.value),e=null;break}return{token:e,literal:t}}_completeSubjectLiteral(e){return this._subject=this._completeLiteral(e).literal,this._readPredicateOrNamedGraph}_completeObjectLiteral(e,t){let r=this._completeLiteral(e);if(r)return this._object=r.literal,t&&this._emit(this._subject,this.RDF_FIRST,this._object,this._graph),r.token===null?this._getContextEndReader():(this._readCallback=this._getContextEndReader(),this._readCallback(r.token))}_readFormulaTail(e){return e.type!=="}"?this._readPunctuation(e):(this._subject!==null&&this._emit(this._subject,this._predicate,this._object,this._graph),this._restoreContext("formula",e),this._object===null?this._readPredicate:this._getContextEndReader())}_readPunctuation(e){let t,r=this._graph,i=this._subject,o=this._inversePredicate;switch(e.type){case"}":if(this._graph===null)return this._error("Unexpected graph closing",e);if(this._n3Mode)return this._readFormulaTail(e);this._graph=null;case".":this._subject=null,t=this._contextStack.length?this._readSubject:this._readInTopContext,o&&(this._inversePredicate=!1);break;case";":t=this._readPredicate;break;case",":t=this._readObject;break;case"{|":if(!this._supportsRDFStar)return this._error("Unexpected RDF-star syntax",e);let s=this._predicate,a=this._object;this._subject=this._factory.quad(i,s,a,this.DEFAULTGRAPH),t=this._readPredicate;break;case"|}":if(this._subject.termType!=="Quad")return this._error("Unexpected asserted triple closing",e);this._subject=null,t=this._readPunctuation;break;default:if(this._supportsQuads&&this._graph===null&&(r=this._readEntity(e))!==void 0){t=this._readQuadPunctuation;break}return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}if(i!==null){let s=this._predicate,a=this._object;o?this._emit(a,s,i,r):this._emit(i,s,a,r)}return t}_readBlankNodePunctuation(e){let t;switch(e.type){case";":t=this._readPredicate;break;case",":t=this._readObject;break;default:return this._error(`Expected punctuation to follow "${this._object.id}"`,e)}return this._emit(this._subject,this._predicate,this._object,this._graph),t}_readQuadPunctuation(e){return e.type!=="."?this._error("Expected dot to follow quad",e):this._readInTopContext}_readPrefix(e){return e.type!=="prefix"?this._error("Expected prefix to follow @prefix",e):(this._prefix=e.value,this._readPrefixIRI)}_readPrefixIRI(e){if(e.type!=="IRI")return this._error(`Expected IRI to follow prefix "${this._prefix}:"`,e);let t=this._readEntity(e);return this._prefixes[this._prefix]=t.value,this._prefixCallback(this._prefix,t),this._readDeclarationPunctuation}_readBaseIRI(e){let t=e.type==="IRI"&&this._resolveIRI(e.value);return t?(this._setBase(t),this._readDeclarationPunctuation):this._error("Expected valid IRI to follow base declaration",e)}_readNamedGraphLabel(e){switch(e.type){case"IRI":case"blank":case"prefixed":return this._readSubject(e),this._readGraph;case"[":return this._readNamedGraphBlankLabel;default:return this._error("Invalid graph label",e)}}_readNamedGraphBlankLabel(e){return e.type!=="]"?this._error("Invalid graph label",e):(this._subject=this._factory.blankNode(),this._readGraph)}_readDeclarationPunctuation(e){return this._sparqlStyle?(this._sparqlStyle=!1,this._readInTopContext(e)):e.type!=="."?this._error("Expected declaration to end with a dot",e):this._readInTopContext}_readQuantifierList(e){let t;switch(e.type){case"IRI":case"prefixed":if((t=this._readEntity(e,!0))!==void 0)break;default:return this._error(`Unexpected ${e.type}`,e)}return this._explicitQuantifiers?(this._subject===null?this._emit(this._graph||this.DEFAULTGRAPH,this._predicate,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH):this._emit(this._subject,this.RDF_REST,this._subject=this._factory.blankNode(),this.QUANTIFIERS_GRAPH),this._emit(this._subject,this.RDF_FIRST,t,this.QUANTIFIERS_GRAPH)):this._quantified[t.id]=this._factory[this._quantifier](this._factory.blankNode().value),this._readQuantifierPunctuation}_readQuantifierPunctuation(e){return e.type===","?this._readQuantifierList:(this._explicitQuantifiers&&(this._emit(this._subject,this.RDF_REST,this.RDF_NIL,this.QUANTIFIERS_GRAPH),this._subject=null),this._readCallback=this._getContextEndReader(),this._readCallback(e))}_getPathReader(e){return this._afterPath=e,this._readPath}_readPath(e){switch(e.type){case"!":return this._readForwardPath;case"^":return this._readBackwardPath;default:let t=this._contextStack,r=t.length&&t[t.length-1];if(r&&r.type==="item"){let i=this._subject;this._restoreContext("item",e),this._emit(this._subject,this.RDF_FIRST,i,this._graph)}return this._afterPath(e)}}_readForwardPath(e){let t,r,i=this._factory.blankNode();if((r=this._readEntity(e))!==void 0)return this._predicate===null?(t=this._subject,this._subject=i):(t=this._object,this._object=i),this._emit(t,r,i,this._graph),this._readPath}_readBackwardPath(e){let t=this._factory.blankNode(),r,i;if((r=this._readEntity(e))!==void 0)return this._predicate===null?(i=this._subject,this._subject=t):(i=this._object,this._object=t),this._emit(t,r,i,this._graph),this._readPath}_readRDFStarTailOrGraph(e){return e.type!==">>"?this._supportsQuads&&this._graph===null&&(this._graph=this._readEntity(e))!==void 0?this._readRDFStarTail:this._error(`Expected >> to follow "${this._object.id}"`,e):this._readRDFStarTail(e)}_readRDFStarTail(e){if(e.type!==">>")return this._error(`Expected >> but got ${e.type}`,e);let t=this._factory.quad(this._subject,this._predicate,this._object,this._graph||this.DEFAULTGRAPH);return this._restoreContext("<<",e),this._subject===null?(this._subject=t,this._readPredicate):(this._object=t,this._getContextEndReader())}_getContextEndReader(){let e=this._contextStack;if(!e.length)return this._readPunctuation;switch(e[e.length-1].type){case"blank":return this._readBlankNodeTail;case"list":return this._readListItem;case"formula":return this._readFormulaTail;case"<<":return this._readRDFStarTailOrGraph}}_emit(e,t,r,i){this._callback(null,this._factory.quad(e,t,r,i||this.DEFAULTGRAPH))}_error(e,t){let r=new Error(`${e} on line ${t.line}.`);r.context={token:t,line:t.line,previousToken:this._lexer.previousToken},this._callback(r),this._callback=ix}_resolveIRI(e){return/^[a-z][a-z0-9+.-]*:/i.test(e)?e:this._resolveRelativeIRI(e)}_resolveRelativeIRI(e){if(!e.length)return this._base;switch(e[0]){case"#":return this._base+e;case"?":return this._base.replace(/(?:\?.*)?$/,e);case"/":return(e[1]==="/"?this._baseScheme:this._baseRoot)+this._removeDotSegments(e);default:return/^[^/:]*:/.test(e)?null:this._removeDotSegments(this._basePath+e)}}_removeDotSegments(e){if(!/(^|\/)\.\.?($|[/#?])/.test(e))return e;let t=e.length,r="",i=-1,o=-1,s=0,a="/";for(;i<t;){switch(a){case":":if(o<0&&e[++i]==="/"&&e[++i]==="/")for(;(o=i+1)<t&&e[o]!=="/";)i=o;break;case"?":case"#":i=t;break;case"/":if(e[i+1]===".")switch(a=e[++i+1],a){case"/":r+=e.substring(s,i-1),s=i+1;break;case void 0:case"?":case"#":return r+e.substring(s,i)+e.substr(i+1);case".":if(a=e[++i+1],a===void 0||a==="/"||a==="?"||a==="#"){if(r+=e.substring(s,i-2),(s=r.lastIndexOf("/"))>=o&&(r=r.substr(0,s)),a!=="/")return`${r}/${e.substr(i+1)}`;s=i+1}}}a=e[++i]}return r+e.substring(s)}parse(e,t,r){let i,o,s;if(t&&(t.onQuad||t.onPrefix||t.onComment)?(i=t.onQuad,o=t.onPrefix,s=t.onComment):(i=t,o=r),this._readCallback=this._readInTopContext,this._sparqlStyle=!1,this._prefixes=Object.create(null),this._prefixes._=this._blankNodePrefix?this._blankNodePrefix.substr(2):`b${Y9++}_`,this._prefixCallback=o||ix,this._inversePredicate=!1,this._quantified=Object.create(null),!i){let l=[],c;if(this._callback=(u,d)=>{u?c=u:d&&l.push(d)},this._lexer.tokenize(e).every(u=>this._readCallback=this._readCallback(u)),c)throw c;return l}let a=(l,c)=>{l!==null?(this._callback(l),this._callback=ix):this._readCallback&&(this._readCallback=this._readCallback(c))};s&&(this._lexer.comments=!0,a=(l,c)=>{l!==null?(this._callback(l),this._callback=ix):this._readCallback&&(c.type==="comment"?s(c.value):this._readCallback=this._readCallback(c))}),this._callback=i,this._lexer.tokenize(e,a)}};function ix(){}function z9(n,e){n._factory=e,n.DEFAULTGRAPH=e.defaultGraph(),n.RDF_FIRST=e.namedNode(Io.rdf.first),n.RDF_REST=e.namedNode(Io.rdf.rest),n.RDF_NIL=e.namedNode(Io.rdf.nil),n.N3_FORALL=e.namedNode(Io.r.forAll),n.N3_FORSOME=e.namedNode(Io.r.forSome),n.ABBREVIATIONS={a:e.namedNode(Io.rdf.type),"=":e.namedNode(Io.owl.sameAs),">":e.namedNode(Io.log.implies),"<":e.namedNode(Io.log.isImpliedBy)},n.QUANTIFIERS_GRAPH=e.namedNode("urn:n3:quantifiers")}z9(Th.prototype,H9);var tH=$n(vd(),1),nH=$n(yo(),1),rH=$n(gw(),1),Nl=$n(go(),1),iH=$n(uc(),1);var ui=$n(vd(),1);var wse=Object.defineProperty,bse=(n,e,t)=>e in n?wse(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Eo=(n,e,t)=>bse(n,typeof e!="symbol"?e+"":e,t),zt=Object.freeze({ERRORS:{CONTEXT_NOT_DEFINED:new Error("error: context not defined on the object"),PARSED_CONTEXT_IS_NULL:new Error("error: parsed context is null"),TERM_IS_NOT_DEFINED:new Error("error: term is not defined"),NO_ID_ATTR:new Error("error: no @id attribute is defined"),CTX_TYP_IS_EMPTY:new Error("error: ctx type is empty"),FIELD_PATH_IS_EMPTY:new Error("error: filed path is empty"),UNEXPECTED_ARR_ELEMENT:new Error("error: unexpected array elements"),INVALID_REFERENCE_TYPE:new Error("error: invalid reference type"),MULTIPLE_PARENTS_FOUND:new Error("error: multiple parents found"),PARENT_NOT_FOUND:new Error("error: parent not found"),GRAPH_NOT_FOUND:new Error("error: graph not found"),QUAD_NOT_FOUND:new Error("error: quad not found"),MT_VALUE_INCORRECT_TYPE:new Error("error: incorrect type")},DEFAULT_GRAPH_NODE_NAME:"@default",DEFAULT_GRAPH_TERM_TYPE:"DefaultGraph",QUADS_FORMAT:"application/n-quads",DIGITS_ONLY_REGEX:/^\d+$/,Q:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617")}),Z9=class{constructor(n=an){this._hasher=n}async hash(n){return this._hasher.hash(n)}async hashBytes(n){return this._hasher.hashBytes(n)}prime(){return zt.Q}},Ul=new Z9,sD=n=>n.toExponential(15).replace(/(\d)0*e\+?/,"$1E");function X9(n){if(!n.graph.value)return zt.DEFAULT_GRAPH_NODE_NAME;if(n.graph.termType!=="BlankNode")throw new Error("graph node is not of BlankNode type");return n.graph.value}var j9=n=>n.sort((e,t)=>e<t?-1:e>t?1:0),Ise=new TextEncoder,Ese=n=>{switch(typeof n){case"boolean":case"string":case"bigint":case"number":return;case"object":if(n instanceof wa.Instant)return}throw new Error(`unexpected value type ${typeof n}, expected boolean | number | Temporal.Instant | string`)},ox=n=>{let e=n/2n;return{min:e-n+1n,max:e}};function xse(n,e){switch(n){case"http://www.w3.org/2001/XMLSchema#positiveInteger":return{min:1n,max:e-1n};case"http://www.w3.org/2001/XMLSchema#nonNegativeInteger":return{min:0n,max:e-1n};case"http://www.w3.org/2001/XMLSchema#integer":return ox(e);case"http://www.w3.org/2001/XMLSchema#negativeInteger":return{min:ox(e).min,max:-1n};case"http://www.w3.org/2001/XMLSchema#nonPositiveInteger":return{min:ox(e).min,max:0n};default:throw new Error(`unsupported XSD type: ${n}`)}}var _9=(n,e,t)=>{switch(n){case"http://www.w3.org/2001/XMLSchema#boolean":switch(e){case"false":case"0":return!1;case"true":case"1":return!0;default:throw new Error("incorrect boolean value")}case"http://www.w3.org/2001/XMLSchema#integer":case"http://www.w3.org/2001/XMLSchema#nonNegativeInteger":case"http://www.w3.org/2001/XMLSchema#nonPositiveInteger":case"http://www.w3.org/2001/XMLSchema#negativeInteger":case"http://www.w3.org/2001/XMLSchema#positiveInteger":{let r=BigInt(e),{min:i,max:o}=xse(n,t);if(r>o)throw new Error(`integer exceeds maximum value: ${r}`);if(r<i)throw new Error(`integer is below minimum value: ${r}`);return r}case"http://www.w3.org/2001/XMLSchema#dateTime":{if(isNaN(Date.parse(e)))throw new Error(`error: error parsing time string ${e}`);return/^\d{4}-\d{2}-\d{2}$/.test(e)?wa.Instant.from(new Date(e).toISOString()):wa.Instant.from(e)}case"http://www.w3.org/2001/XMLSchema#double":return sD(parseFloat(e));default:return e}},Ase=(n,e)=>{let t=e==="http://www.w3.org/2001/XMLSchema#double";switch(typeof n){case"string":return t?sD(parseFloat(n)):n;case"boolean":return`${n}`;case"number":return t?sD(n):`${n}`;default:throw new Error("unsupported type")}},vse=new TextEncoder,Zo=class $9{constructor(e,t=Ul){this.value=e,this.h=t}isString(){return typeof this.value=="string"}asString(){if(!this.isString())throw zt.ERRORS.MT_VALUE_INCORRECT_TYPE;return this.value.toString()}isTime(){return this.value instanceof wa.Instant}asTime(){if(!this.isTime())throw zt.ERRORS.MT_VALUE_INCORRECT_TYPE;return this.value}isNumber(){return typeof this.value=="number"}asNumber(){if(!this.isNumber())throw zt.ERRORS.MT_VALUE_INCORRECT_TYPE;return this.value}isBool(){return typeof this.value=="boolean"}asBool(){if(!this.isBool())throw zt.ERRORS.MT_VALUE_INCORRECT_TYPE;return this.value}mtEntry(){return $9.mkValueMtEntry(this.h,this.value)}isBigInt(){return typeof this.value=="bigint"}asBigInt(){if(!this.isBigInt())throw zt.ERRORS.MT_VALUE_INCORRECT_TYPE;return this.value}static async mkValueInt(e,t){return t>=0?BigInt(t):e.prime()+BigInt(t)}};Eo(Zo,"mkValueMtEntry",(n,e)=>{switch(typeof e){case"number":return Zo.mkValueInt(n,e);case"string":return Zo.mkValueString(n,e);case"boolean":return Zo.mkValueBool(n,e);case"bigint":return Zo.mkValueBigInt(n,e);default:{if(e instanceof wa.Instant)return Zo.mkValueTime(n,e);throw new Error(`error: unexpected type ${typeof e}`)}}});Eo(Zo,"mkValueUInt",(n,e)=>BigInt.asUintN(64,e));Eo(Zo,"mkValueBool",(n,e)=>e?n.hash([BigInt.asIntN(64,BigInt(1))]):n.hash([BigInt.asIntN(64,BigInt(0))]));Eo(Zo,"mkValueString",(n,e)=>n.hashBytes(vse.encode(e)));Eo(Zo,"mkValueTime",async(n,e)=>Zo.mkValueInt(n,e.epochNanoseconds));Eo(Zo,"mkValueBigInt",async(n,e)=>{let t=n.prime();if(e>=t)throw new Error(`value is too big: ${e}`);if(e<0n){let{min:r}=ox(t);if(e<r)throw new Error(`value is too small: ${e}`);return e+t}return e});var kw=Zo,ux=class{constructor(n,e){this.graphName=n,this.idx=e}toString(){return`${this.graphName}:${this.idx}`}},im=class sx{constructor(e,t){this.tp=e,this.val=t}toString(){return JSON.stringify(this)}static getRefFromQuad(e){return e.termType==="NamedNode"?new sx("NamedNode",e.value):e.termType==="BlankNode"?new sx("BlankNode",e.value):new sx("Undefined","")}},oH=class{async loadDocument(n,e=[]){let t=n.startsWith("http:"),r=n.startsWith("https:");if(!t&&!r)throw new Nl.default('URL could not be dereferenced; only "http" and "https" URLs are supported.',"jsonld.InvalidUrl",{code:"loading document failed",url:n});let i=null,{res:o,body:s}=await sH({url:n}),a={contextUrl:void 0,documentUrl:n,document:s};if(o.status>=400)throw new Nl.default(`URL "${n}" could not be dereferenced: ${o.statusText}`,"jsonld.InvalidUrl",{code:"loading document failed",url:n,httpStatusCode:o.status});let l=o.headers.get("link"),c=o.headers.get("location"),u=o.headers.get("content-type");if(l&&u!=="application/ld+json"&&u!=="application/json"){let d=nH.default.parseLinkHeader(l),h=d[rH.default.LINK_HEADER_CONTEXT];if(Array.isArray(h))throw new Nl.default("URL could not be dereferenced, it has more than one associated HTTP Link Header.","jsonld.InvalidUrl",{code:"multiple context link headers",url:n});h&&(a.contextUrl=h.target),i=d.alternate,i&&i.type=="application/ld+json"&&!(u||"").match(/^application\/(\w*\+)?json$/)&&(c=iH.default.prependBase(n,i.target))}if((i||o.status>=300&&o.status<400)&&c){if(e.length===-1)throw new Nl.default("URL could not be dereferenced; there were too many redirects.","jsonld.TooManyRedirects",{code:"loading document failed",url:n,httpStatusCode:o.status,redirects:e});if(e.indexOf(n)!==-1)throw new Nl.default("URL could not be dereferenced; infinite redirection was detected.","jsonld.InfiniteRedirectDetected",{code:"recursive context inclusion",url:n,httpStatusCode:o.status,redirects:e});e.push(n);let d=new URL(c,n).href;return this.loadDocument(d,e)}return e.push(n),a}},Cse="cat";function Sse(n,e){let t="/api/v0";for(;n.endsWith("/");)n=n.slice(0,-1);return n.endsWith(t)||(n+=t),n+"/"+e}function Dse(n){for(;n.endsWith("/");)n=n.slice(0,-1);return n}function Lse(n){for(;n.startsWith("/");)n=n.slice(1);return n}function Bse(n,e){return Dse(n)+"/ipfs/"+Lse(e)}async function Tse(n,e=void 0,t=void 0){let r=om+n;if(!e&&!t)throw new Nl.default("IPFS is not configured","jsonld.IPFSNotConfigured",{code:"loading document failed",url:r});return e?await Pse(n,e):await Rse(n,t)}async function Pse(n,e){let t=new URL(Sse(e,Cse));t.searchParams.append("arg",n);let{res:r,body:i}=await sH({url:t,method:"POST"});if(r.status!=200)throw new Error(`Error calling IPFS node: [${r.status}] ${r.statusText}
38
38
  ${i}`);return{contextUrl:void 0,document:i||null,documentUrl:om+n}}async function Rse(n,e=void 0){if(!e)throw new Nl.default("IPFS gateway is not configured","jsonld.IPFSNotConfigured",{code:"loading document failed",url:om+n});let r=await new oH().loadDocument(Bse(e,n),[]);return r.contextUrl=void 0,r.documentUrl=om+n,r}async function sH({url:n,method:e}){let t={};typeof e<"u"&&(t.method=e);try{n=new URL(n),n.username&&n.password&&(t.headers={...t.headers??{},authorization:`Basic ${btoa(n.username+":"+n.password)}`},n=Mse(n));let r=await fetch(n,t);if(r.status>=300&&r.status<400)return{res:r,body:null};let i=await r.text();return i&&i.length>0&&i.startsWith("{")?{res:r,body:JSON.parse(i)}:{res:r,body:i}}catch(r){if(r instanceof Error&&"response"in r)return{res:r.response,body:null};throw new Nl.default("URL could not be dereferenced, an error occurred.","jsonld.LoadDocumentError",{code:"loading document failed",url:n.toString(),cause:r})}}function Mse(n){let e=new URL(n);return e.username="",e.password="",e.href}var om="ipfs://",Fse=(n=void 0,e=void 0)=>async t=>{if(t.startsWith(om)){let i=t.slice(om.length);return await Tse(i,n,e)}return new oH().loadDocument(t,[])};function ax(n){return n?.hasher??Ul}function Wi(n){return n?.documentLoader??Fse(n?.ipfsNodeURL,n?.ipfsGatewayURL)}var aH=class cx{constructor(e=new Map){this.graphs=e}static async fromDocument(e,t=Wi()){let r=await tH.default.canonize(e,{format:zt.QUADS_FORMAT,documentLoader:t}),o=new Th({format:zt.QUADS_FORMAT}).parse(r),s=new cx;for(let a of o){let l=a.graph.termType===zt.DEFAULT_GRAPH_TERM_TYPE?zt.DEFAULT_GRAPH_NODE_NAME:a.graph.value,c=s.graphs.get(l)??[];c.push(a),s.graphs.set(l,c)}return s}static getQuad(e,t){let r=e.graphs.get(t.graphName);if(!r)throw zt.ERRORS.GRAPH_NOT_FOUND;if(t.idx>=r.length)throw zt.ERRORS.QUAD_NOT_FOUND;return r[t.idx]}static iterGraphsOrdered(e,t){let r=[];for(let i of e.graphs.keys())r.push(i);r.sort((i,o)=>i.localeCompare(o));for(let i of r){let o=e.graphs.get(i);o&&t(i,o)}}static findParent(e,t){let r=cx.findParentInsideGraph(e,t);return r||cx.findGraphParent(e,t)}static findParentInsideGraph(e,t){let r=X9(t),i,o=e.graphs.get(r);if(!o)return;let s=im.getRefFromQuad(t.subject);if(s.tp==="Undefined")return;let a=!1;for(let l=0;l<o.length;l++){let c=o[l];if(c.equals(t))continue;let u=im.getRefFromQuad(c.object);if(u.tp!=="Undefined"&&s?.tp===u?.tp&&s?.val===u?.val){if(a)throw zt.ERRORS.MULTIPLE_PARENTS_FOUND;a=!0,i=new ux(r,l)}}return i}static findGraphParent(e,t){if(!t.graph)return;let r=im.getRefFromQuad(t.graph);if(r.tp==="Undefined")return;if(r.tp!=="BlankNode")throw new Error("graph parent can only be a blank node");let i=!1,o;for(let[s,a]of e.graphs)for(let l=0;l<a.length;l++){let c=a[l];if(c.equals(t))continue;let u=im.getRefFromQuad(c.object);if(u.tp!=="Undefined"&&r.toString()==u.toString()){if(i)throw zt.ERRORS.MULTIPLE_PARENTS_FOUND;i=!0,o=new ux(s,l)}}if(i)return o;throw zt.ERRORS.PARENT_NOT_FOUND}};Eo(aH,"assertDatasetConsistency",n=>{for(let[e,t]of n.graphs)for(let r of t){if(!e)throw new Error("empty graph name");if(e===zt.DEFAULT_GRAPH_NODE_NAME&&r.graph.id)throw new Error("graph should be nil for @default graph");if(!r.graph.id&&e!==zt.DEFAULT_GRAPH_NODE_NAME)throw new Error("graph should not be nil for non-@default graph")}});var Gl=aH,kse=(n="",e=!0,t=40)=>({db:new bp(Ua(n)),writable:e,maxLevels:t}),Ose=async(n,e)=>{for(let t of e){let{k:r,v:i}=await t.getKeyValueMTEntry();await n.add(r,i)}},Ph=class Ol{constructor(e=[],t=Ul){this.parts=e,this.hasher=t}reverse(){return this.parts.reverse()}append(e){this.parts=[...this.parts,...e]}prepend(e){this.parts=[...e,...this.parts]}async mtEntry(){let e=this.hasher??Ul,t=new Array(this.parts.length).fill(BigInt(0));for(let r=0;r<this.parts.length;r+=1){let i=this.parts[r];if(typeof i=="string"){let o=Ise.encode(i);t[r]=await e.hashBytes(o)}else if(typeof i=="number")t[r]=BigInt(i);else throw new Error(`error: unexpected type ${typeof i}`)}return e.hash(t)}async pathFromContext(e,t,r){let i=JSON.parse(e);if(!i["@context"])throw zt.ERRORS.CONTEXT_NOT_DEFINED;let o={documentLoader:Wi(r)},s=await ui.default.processContext(null,null,o),a=await ui.default.processContext(s,i,o),l=t.split(".");for(let c in l){let u=l[c];if(zt.DIGITS_ONLY_REGEX.test(u))this.parts.push(parseInt(u));else{let d=a.mappings.get(u);if(typeof d!="object")throw zt.ERRORS.TERM_IS_NOT_DEFINED;let h=d["@id"];if(!h)throw zt.ERRORS.NO_ID_ATTR;d["@context"]&&(a=await ui.default.processContext(a,d,o)),this.parts.push(h)}}}async typeFromContext(e,t,r){let i=JSON.parse(e);if(!("@context"in i))throw zt.ERRORS.PARSED_CONTEXT_IS_NULL;let o={documentLoader:Wi(r)},s=await ui.default.processContext(null,null,o),a=await ui.default.processContext(s,i,o),l=t.split(".");for(let c in l){let u=l[c],d=W9(a,u);d.hasContext&&(a=await ui.default.processContext(a,d.typeDef,o)),this.parts.push(d["@id"])}return Ol.getTypeMapping(a,l[l.length-1])}static getTypeMapping(e,t){let r="",i=e.mappings.get("@type");i&&(r=i);let o=e.mappings.get(t);return o&&o["@type"]&&(r=o["@type"]),r}static async pathFromDocument(e,t,r,i,o){if(r.length===0)return[];let s=r[0],a=r.slice(1),l={documentLoader:Wi(o)};if(zt.DIGITS_ONLY_REGEX.test(s)){let f=parseInt(s),p=await Ol.pathFromDocument(e,t,a,!0,o);return[f,...p]}if(typeof t!="object")throw new Error(`error: expected type object got ${typeof t}`);if(Array.isArray(t)){if(!t.length)throw new Error("error: can't generate path on zero-sized array");if(!i)throw zt.ERRORS.UNEXPECTED_ARR_ELEMENT;return Ol.pathFromDocument(e,t[0],r,!1,o)}if("@context"in t)if(e)e=await ui.default.processContext(e,t,l);else{let f=await ui.default.processContext(null,null,l);e=await ui.default.processContext(f,t,l)}let c=j9(Object.keys(t)),u=e;for(let f in c){let p=c[f];if(p!=="@type"){let v=e?.mappings.get(p);if(typeof v!="object"||v["@id"]!=="@type")continue}let w=[],y=t[p];if(Array.isArray(y))y.forEach(v=>{if(typeof v!="string")throw new Error(`error: @type value must be an array of strings: ${typeof v}`);w.push(v),w=j9(w)});else if(typeof y=="string")w.push(y);else throw new Error(`error: unexpected @type field type: ${typeof y}`);for(let v of w){let B=u?.mappings.get(v);typeof B=="object"&&"@context"in B&&(e=await ui.default.processContext(e,B,l))}break}let d=W9(e,s);if(d.hasContext)if(e)e=await ui.default.processContext(e,d.typeDef,l);else{let f=await ui.default.processContext(null,null,l);e=await ui.default.processContext(f,d.typeDef,l)}let h=await Ol.pathFromDocument(e,t[s],a,!0,o);return[d["@id"],...h]}static async newPathFromCtx(e,t,r){let i=new Ol([],ax(r));return await i.pathFromContext(e,t,r),i}static async fromDocument(e,t,r,i){let o=JSON.parse(t),s=r.split(".");if(s.length===0)throw zt.ERRORS.FIELD_PATH_IS_EMPTY;let a=await Ol.pathFromDocument(e,o,s,!1,i);return new Ol(a,ax(i))}static async newTypeFromContext(e,t,r){return await new Ol([],ax(r)).typeFromContext(e,t,r)}static async getTypeIDFromContext(e,t,r){let i=JSON.parse(e),o={documentLoader:Wi(r)},s=await ui.default.processContext(null,null,o),l=(await ui.default.processContext(s,i,o)).mappings.get(t);if(!l)throw new Error(`looks like ${t} is not a type`);let c=l["@id"];if(!c)throw new Error(`@id attribute is not found for type ${t}`);if(typeof c!="string")throw new Error(`@id attribute is not a string for type ${t}`);return c}};Eo(Ph,"newPath",n=>{let e=new Ph;return e.append(n),e});Eo(Ph,"getContextPathKey",async(n,e,t,r)=>{if(e==="")throw zt.ERRORS.CTX_TYP_IS_EMPTY;if(t==="")throw zt.ERRORS.FIELD_PATH_IS_EMPTY;let i=await Ph.newPathFromCtx(n,`${e}.${t}`,r),o=await Ph.newPathFromCtx(n,e,r);return new Ph(i.parts.slice(o.parts.length))});var rr=Ph;function W9(n,e){let t=n?.mappings.get(e);if(typeof t!="object")throw zt.ERRORS.TERM_IS_NOT_DEFINED;let r=t["@id"];if(!r)throw zt.ERRORS.NO_ID_ATTR;if(typeof r!="string")throw new Error(`error: @id attr is not of type string: ${typeof r}`);return{"@id":r,hasContext:"@context"in t,typeDef:t}}var aD=class{constructor(e){Eo(this,"subject"),Eo(this,"predicate"),Eo(this,"graph"),this.graph=X9(e);let t=e.subject;switch(t.termType){case"NamedNode":this.subject={tp:"NamedNode",val:t.value};break;case"BlankNode":this.subject={tp:"BlankNode",val:t.value};break;default:throw new Error("invalid subject type")}if(e.predicate.termType!=="NamedNode")throw new Error("invalid predicate type");this.predicate=e.predicate.value}toString(){return JSON.stringify(this)}};Eo(aD,"countEntries",n=>{let e=new Map;for(let t of n){let r=new aD(t),i=e.get(r.toString())??0;e.set(r.toString(),++i)}return e});var dx=aD,Gse=class lx{constructor(e=new Map,t=new Map,r=Ul){this.parents=e,this.children=t,this.hasher=r}static getIriValue(e){if(e.predicate.termType==="NamedNode")return e.predicate.value;throw new Error("type is not IRI")}path(e,t,r){let i=new rr([],this.hasher);typeof r=="number"&&i.append([r]);let o=Gl.getQuad(t,e),s=lx.getIriValue(o);i.append([s]);let a=e;for(;;){let l=this.parents.get(a.toString());if(!l)break;let c=Gl.getQuad(t,l),u=new dx(c),d=this.children.get(u.toString());if(!d)throw new Error("parent mapping not found");let h=Gl.getQuad(t,a),f=im.getRefFromQuad(h.subject),p=d.get(f.toString());if(typeof p!="number")throw new Error("child not found in parents mapping");let w=lx.getIriValue(c);d.size===1?i.append([w]):i.append([p,w]),a=l}return i.reverse(),i}static async newRelationship(e,t){let r=new lx(new Map,new Map,t);return Gl.iterGraphsOrdered(e,(i,o)=>{for(let s=0;s<o.length;s++){let a=o[s],l=Gl.findParent(e,a);if(!l)continue;let c=new ux(i,s);r.parents.set(c.toString(),l);let u=Gl.getQuad(e,l),d=new dx(u),h=r.children.get(d.toString());h||(h=new Map,r.children.set(d.toString(),h));let f=im.getRefFromQuad(a.subject);if(typeof h.get(f.toString())!="number"){let w=h.size;h.set(f.toString(),w)}}}),r}},cD=class cH{constructor(e,t,r="",i=Ul){if(this.key=e,this.value=t,this.dataType=r,this.hasher=i,!e.parts.length)throw new Error("key length is zero");Ese(t)}getHasher(){return this.hasher}getKeyMtEntry(){return this.key.mtEntry()}getValueMtEntry(){return kw.mkValueMtEntry(this.getHasher(),this.value)}async getKeyValueMTEntry(){let e=await this.getKeyMtEntry(),t=await this.getValueMtEntry();return{k:e,v:t}}static async fromDataSet(e,t=Ul){if(Gl.assertDatasetConsistency(e),!e.graphs.get(zt.DEFAULT_GRAPH_NODE_NAME)?.length)throw new Error("@default graph not found in dataset");let i=await Gse.newRelationship(e,t),o=[],s=(a,l)=>{let c=dx.countEntries(l),u=new Map;for(let d=0;d<l.length;d++){let h="",f=l[d],p=new ux(a,d),w=new dx(f),y,v=f.object.termType,B=f.object.value;switch(v){case"Literal":h=f?.object?.datatype?.value,y=_9(h,B,t.prime());break;case"NamedNode":if(!v)throw new Error("object IRI is nil");y=B;break;case"BlankNode":{if(i.children.get(w.toString()))continue;throw new Error("BlankNode is not supported yet")}case"Variable":y=B;break;default:throw new Error("unexpected Quad's Object type")}let U=c.get(w.toString()),k;switch(U){case 0:throw new Error("[assertion] key not found in counts");case 1:break;default:{let I=w.toString();k=u.get(I)??0,u.set(I,k+1)}}let F=i.path(p,e,k),P=new cH(F,y,h,t);o.push(P)}};return Gl.iterGraphsOrdered(e,s),o}};Eo(cD,"newRDFEntry",(n,e)=>{let t=new cD(n,e);switch(typeof e){case"number":case"string":case"boolean":t.value=e;break;default:if(e instanceof wa.Instant)t.value=e;else throw new Error(`error: incorrect value type ${typeof e}`)}return t});var Nse=cD,yc=class lH{constructor(e=null,t=null,r=Ul,i=new Map,o=null,s=Wi()){if(this.srcDoc=e,this.mt=t,this.hasher=r,this.entries=i,this.compacted=o,this.documentLoader=s,!t){let{db:a,writable:l,maxLevels:c}=kse();this.mt=new os(a,l,c)}}async proof(e){let t=await e.mtEntry();if(!this.mt)throw new Error("Merkle tree is not initialized");let{proof:r}=await this.mt.generateProof(t);if(r.existence){if(!this.entries.has(t.toString()))throw new Error("error: [assertion] no entry found while existence is true");let i=this.entries.get(t.toString());if(!i)throw new Error("entry not found");let o=new kw(i.value,this.hasher);return{proof:r,value:o}}return{proof:r}}mkValue(e){return new kw(e,this.hasher)}async resolveDocPath(e,t){if(!this.srcDoc)throw new Error("Source document is not initialized");let r=await rr.fromDocument(null,this.srcDoc,e,t);return r.hasher=this.hasher,r}async entry(e){let t=await e.mtEntry(),r=this.entries.get(t.toString());if(!r)throw new Error("entry not found");return r}async jsonLDType(e){return(await this.entry(e)).dataType}async root(){if(!this.mt)throw new Error("Merkle tree is not initialized");return this.mt.root()}rawValue(e){let t=e.parts;if(!this.compacted)throw new Error("Compact document is not initialized");let r=this.compacted,i=[],o=()=>i.join(" / ");for(;t.length>0;){let s=t[0];if(typeof s=="string"){if(i.push(s),r=r[s]??(r["@graph"]??{})[s],!r)throw new Error("value not found")}else if(typeof s=="number")i.push(s.toString()),r=this.rvExtractArrayIdx(r,s);else throw new Error(`unexpected type of path ${o()}`);t=t.slice(1)}return typeof r["@value"]<"u"?r["@value"]:r}rvExtractArrayIdx(e,t){if(!Array.isArray(e))throw new Error("expected array");if(t<0||t>=e.length)throw new Error("index is out of range");return e[t]}static async merklizeJSONLD(e,t){let r=ax(t),i=Wi(t),o=new lH(e,null,r,new Map,null,i);if(!o)throw new Error("Merklizer is not initialized");if(!o.srcDoc)throw new Error("Source document is not initialized");let s=JSON.parse(o.srcDoc),a=await Gl.fromDocument(s,i),l=await Nse.fromDataSet(a,r);for(let c of l){let u=await c.getKeyMtEntry();o.entries.set(u.toString(),c)}if(!o.mt)throw new Error("Merkle tree is not initialized");return await Ose(o.mt,l),o.compacted=await eH.default.compact(s,{},{documentLoader:i,base:null,compactArrays:!0,compactToRelative:!0}),o}static async hashValue(e,t){return this.hashValueWithHasher(Ul,e,t)}static async hashValueWithHasher(e,t,r){let i=Ase(r,t),o=_9(t,i,e.prime());return await kw.mkValueMtEntry(e,o)}get options(){return{hasher:this.hasher,documentLoader:this.documentLoader}}};var Hl=(n,e)=>{if(!e.credentialSubject.id)return n;if(typeof e.credentialSubject.id!="string")throw new Error("credential subject `id` is not a string");return Ie.parse(e.credentialSubject.id)},fx=n=>{if(!n.type.includes("AuthBJJCredential"))throw new Error("can't sign with not AuthBJJCredential credential");let e=n.credentialSubject.x,t=n.credentialSubject.y,r=new Tc([BigInt(e),BigInt(t)]),i=qs("BJJ",r.hex());return{type:"BJJ",id:i}};var Ow=$n(vd(),1);var Use="credentialSubject",fH="@context",Hse="iden3_serialization",uH="iden3:v1:",Kse="https://www.w3.org/2018/credentials#credentialSubject",Jse="https://www.w3.org/2018/credentials#VerifiableCredential",dH="@type",Gw=async(n,e,t)=>{let r=JSON.parse(tt.decode(t));if(r=r[fH],r===void 0)throw new Error("document has no @context");let i=await Ow.default.processContext(await Ow.default.processContext(null,null,{}),r,{}),o=await Mh(i,e);if(!o)throw new Error("serialization attribute is not set");let s=Uw(o);switch(n){case s.indexAPath:return 2;case s.indexBPath:return 3;case s.valueAPath:return 6;case s.valueBPath:return 7;default:throw new Error(`field ${n} not specified in serialization info`)}},Rh=async(n,e,t)=>{if(t){t=Use+"."+t;try{let r=await e.resolveDocPath(t,e.options),o=await(await e.entry(r)).getValueMtEntry(),s=ht.intToBytes(o);n.set(s,0)}catch(r){throw r.toString().includes("entry not found")?new Error(`field not found in credential ${t}`):r}}},Nw=async(n,e,t)=>{let r=await Ow.default.processContext(await Ow.default.processContext(null,null,{}),n,e);return Mh(r,t)},Mh=async(n,e)=>{let t=n.mappings;if(!t)throw new Error("terms definitions is not of correct type");let r=t.get(e)??[...t.values()].find(s=>s["@id"]===e);if(!r)return"";let i=r[fH];if(!i)throw new Error("type @context is not of correct type");return i[Hse]??""},Uw=n=>{if(!n.startsWith(uH))throw new Error("serialization attribute does not have correct prefix");let e=n.slice(uH.length).split("&");if(e.length>4)throw new Error("serialization attribute has too many parts");let t={};for(let r of e){let i=r.split("=");if(i.length!==2)throw new Error("serialization attribute part does not have correct format");switch(i[0]){case"slotIndexA":t.indexAPath=i[1];break;case"slotIndexB":t.indexBPath=i[1];break;case"slotValueA":t.valueAPath=i[1];break;case"slotValueB":t.valueBPath=i[1];break;default:throw new Error("unknown serialization attribute slot")}}return t},Hw=n=>{let e=n.options;try{let t=new rr([Kse,dH],e.hasher);return n.rawValue(t)}catch{let r=new rr([dH],e.hasher),i=n.rawValue(r);if(!Array.isArray(i))throw new Error("top level @type expected to be an array");if(i.length!==2)throw new Error("top level @type expected to be of length 2");switch(Jse){case i[0]:return i[1];case i[1]:return i[0];default:throw new Error("@type(s) are expected to contain VerifiableCredential type")}}},Kw=async(n,e,t)=>{let r={indexA:new Uint8Array(32),indexB:new Uint8Array(32),valueA:new Uint8Array(32),valueB:new Uint8Array(32)},i=await Mh(n,t);if(!i)return{slots:r,nonMerklized:!1};let o=Uw(i);return Object.values(o).some(Boolean)?(await Rh(r.indexA,e,o.indexAPath),await Rh(r.indexB,e,o.indexBPath),await Rh(r.valueA,e,o.valueAPath),await Rh(r.valueB,e,o.valueBPath),{slots:r,nonMerklized:!0}):{slots:r,nonMerklized:!0}},Kl=n=>{let e=To(at(n));return new ro(e.slice(e.length-16,e.length))};var uD=$n(vd(),1),fr=class n{id="";"@context"=[];type=[];expirationDate;refreshService;displayMethod;issuanceDate;credentialSubject={};credentialStatus;issuer="";credentialSchema;proof;static fromCredentialRequest(e,t){if(!t.id)throw new Error("Credential id is required");if(!t.context)throw new Error("Credential context is required");let r=[Fe.JSONLD_SCHEMA.W3C_CREDENTIAL_2018,Fe.JSONLD_SCHEMA.IDEN3_CREDENTIAL,...t.context],i=[Fe.CREDENTIAL_TYPE.W3C_VERIFIABLE_CREDENTIAL,t.type],o=t.credentialSubject;o.type=t.type;let s=new n;return s.id=t.id,s["@context"]=r,s.type=i,s.credentialSubject=o,s.issuer=e.string(),s.credentialSchema={id:t.credentialSchema,type:Fe.JSON_SCHEMA_VALIDATOR},s.credentialStatus=n.buildCredentialStatus(t,e),t.expiration&&(s.expirationDate=new Date(t.expiration).toISOString()),t.refreshService&&(s.refreshService=t.refreshService),t.displayMethod&&(s.displayMethod=t.displayMethod),t.issuanceDate&&(s.issuanceDate=new Date(t.issuanceDate).toISOString()),s}static buildCredentialStatus(e,t){let r={id:e.revocationOpts.id,type:e.revocationOpts.type,revocationNonce:e.revocationOpts.nonce};switch(e.revocationOpts.type){case"SparseMerkleTreeProof":return{...r,id:`${r.id.replace(/\/$/,"")}/${r.revocationNonce}`};case"Iden3ReverseSparseMerkleTreeProof":return{...r,id:e.revocationOpts.issuerState?`${r.id.replace(/\/$/,"")}/node?state=${e.revocationOpts.issuerState}`:`${r.id.replace(/\/$/,"")}`};case"Iden3OnchainSparseMerkleTreeProof2023":{let i=Ie.idFromDID(t),o=Zm(Ie.blockchainFromId(i),Ie.networkIdFromId(i)),s=[["revocationNonce",e.revocationOpts.nonce?.toString()||""],["contractAddress",`${o}:${e.revocationOpts.id}`],["state",e.revocationOpts.issuerState||""]].filter(([,a])=>!!a).map(([a,l])=>`${a}=${l}`).join("&");return{...r,id:`${t.string()}/credentialStatus?${s}`}}default:return r}}toJSON(){return{...this,proof:Array.isArray(this.proof)?this.proof.map(this.proofToJSON):this.proofToJSON(this.proof)}}proofToJSON(e){if(!e)return e;if(!e.type)throw new Error("proof must have type property");switch(e.type){case"Iden3SparseMerkleTreeProof":case"BJJSignature2021":return e.toJSON();default:return e}}static proofFromJSON=e=>{if(!e)return e;if(!e.type)throw new Error("proof must have type property");switch(e.type){case"Iden3SparseMerkleTreeProof":return ha.fromJSON(e);case"BJJSignature2021":return sd.fromJSON(e);default:return e}};static fromJSON(e){let t=new n;return Object.assign(t,structuredClone(e)),t.proof=Array.isArray(t.proof)?t.proof.map(n.proofFromJSON):n.proofFromJSON(t.proof),t}async merklize(e){let t={...this};return delete t.proof,await yc.merklizeJSONLD(JSON.stringify(t),e)}getCoreClaimFromProof(e){if(Array.isArray(this.proof))for(let t of this.proof){let{claim:r,proofType:i}=dD(t);if(e===i)return r}else if(typeof this.proof=="object"){let{claim:t,proofType:r}=dD(this.proof);if(r==e)return t}}async toCoreClaim(e){e||(e={revNonce:0,version:0,subjectPosition:"index",merklizedRootPosition:"",updatable:!1,merklizeOpts:{}});let t=await this.merklize(e.merklizeOpts),r=Hw(t),i=this.credentialSubject.id,o=await uD.default.processContext(await uD.default.processContext(null,null,{}),this["@context"],t.options),{slots:s,nonMerklized:a}=await Kw(o,t,r);if(a&&e.merklizedRootPosition!=="")throw new Error("merklized root position is not supported for non-merklized claims");!a&&e.merklizedRootPosition===""&&(e.merklizedRootPosition="index");let l=Kl(Me.encode(r)),c=er.newClaim(l,Js.withIndexDataBytes(s.indexA,s.indexB),Js.withValueDataBytes(s.valueA,s.valueB),Js.withRevocationNonce(BigInt(e.revNonce)),Js.withVersion(e.version));if(e.updatable&&c.setFlagUpdatable(e.updatable),this.expirationDate&&c.setExpirationDate(new Date(this.expirationDate)),i){let u=Ie.parse(i.toString()),d=Ie.idFromDID(u);switch(e.subjectPosition){case"":case"index":c.setIndexId(d);break;case"value":c.setValueId(d);break;default:throw new Error("unknown subject position")}}switch(e.merklizedRootPosition){case"index":{let u=await this.merklize(e.merklizeOpts);c.setIndexMerklizedRoot((await u.root()).bigInt());break}case"value":{let u=await this.merklize(e.merklizeOpts);c.setValueMerklizedRoot((await u.root()).bigInt());break}case"":break;default:throw new Error("unknown merklized root position")}return c}getBJJSignature2021Proof(){let e=this.getProofByType("BJJSignature2021");if(e)return e}getIden3SparseMerkleTreeProof(){let e=this.getProofByType("Iden3SparseMerkleTreeProof");if(e)return e}async verifyProof(e,t,r){let i=this.getProofByType(e);if(!i)throw new Error("proof not found");let o=this.getCoreClaimFromProof(e);if(!o)throw new Error("can't get core claim");switch(await this.verifyCoreClaimMatch(o,r?.merklizeOptions),e){case"BJJSignature2021":{if(!r?.credStatusResolverRegistry)throw new Error("please provide credential status resolver registry");let s=i,a=Hl(s.issuerData.id,this);return this.verifyBJJSignatureProof(s,o,t,a,r.credStatusResolverRegistry)}case"Iden3SparseMerkleTreeProof":return this.verifyIden3SparseMerkleTreeProof(i,o,t);default:throw new Error("invalid proof type")}}async verifyCoreClaimMatch(e,t){let r="";switch(e.getMerklizedPosition()){case wn.None:r="";break;case wn.Index:r="index";break;case wn.Value:r="value";break}let o="";switch(e.getIdPosition()){case Ei.None:o="";break;case Ei.Index:o="index";break;case Ei.Value:o="value";break}let a={revNonce:Number(e.getRevocationNonce()),version:e.getVersion(),merklizedRootPosition:r,subjectPosition:o,updatable:e.getFlagUpdatable(),merklizeOpts:t},l=await this.toCoreClaim(a);if(e.hex()!=l.hex())throw new Error("proof generated for another credential")}async verifyBJJSignatureProof(e,t,r,i,o){let a=e.issuerData.authCoreClaim.rawSlotsAsInts(),l=new Tc([a[2],a[3]]),{hi:c,hv:u}=t.hiHv(),d=an.hash([c,u]);if(!l.verifyPoseidon(d,e.signature))throw new Error("signature is not valid");await II(e.issuerData.id,r,e.issuerData.state.value);let f=e.issuerData.credentialStatus.type,p=await o.get(f);if(!p)throw new Error(`please register credential status resolver for ${f} type`);let w=await p.resolve(e.issuerData.credentialStatus,{issuerDID:e.issuerData.id,userDID:i});if(!hH(w.issuer))throw new Error("signature proof: invalid tree state of the issuer while checking credential status of singing key");let v=BigInt(e.issuerData.credentialStatus.revocationNonce||0);if(v!==e.issuerData.authCoreClaim.getRevocationNonce())throw new Error("revocation nonce mismatch: revocation nonce from core representation of auth credential is not the same as in its credential");if(!await B5(me.fromHex(w.issuer.revocationTreeRoot),w.mtp,v,BigInt(0)))throw new Error(`proof validation failed. revNonce=${v}`);if(w.mtp.existence)throw new Error("signature proof: singing key of the issuer is revoked");return!0}async verifyIden3SparseMerkleTreeProof(e,t,r){await II(e.issuerData.id,r,e.issuerData.state.value);let{hi:i,hv:o}=t.hiHv();if(!(await q3(e.mtp,i,o)).equals(e.issuerData.state.claimsTreeRoot))throw new Error("verifyIden3SparseMerkleTreeProof: root from proof not equal to issuer data claims tree root");return!0}getProofByType(e){if(Array.isArray(this.proof)){for(let t of this.proof)if(t?.type===e)return t}else if(this.proof?.type==e)return this.proof}};function dD(n){if(n instanceof ha)return{claim:n.coreClaim,proofType:"Iden3SparseMerkleTreeProof"};if(n instanceof sd)return{claim:n.coreClaim,proofType:"BJJSignature2021"};if(typeof n=="object"){let e=n,t=e.type;if(!t)throw new Error("proof type is not specified");if(!e.coreClaim)throw new Error(`coreClaim field is not defined in proof type ${t}`);return{claim:e.coreClaim instanceof er?e.coreClaim:new er().fromHex(e.coreClaim),proofType:t}}throw new Error("proof format is not supported")}function hH(n){let e=n.claimsTreeRoot?me.fromHex(n.claimsTreeRoot):new me,t=n.revocationTreeRoot?me.fromHex(n.revocationTreeRoot):new me,r=n.rootOfRoots?me.fromHex(n.rootOfRoots):new me,i=an.hash([e.bigInt(),t.bigInt(),r.bigInt()]),o=n.state?me.fromHex(n.state):new me;return i===o.bigInt()}var qse=(n,e)=>{let t=e.split("."),r=n;for(let i=0;i<t.length;i++){let o=t[i];if(!o)throw new Error("path is empty");if(r=r[o],r===void 0)throw new Error("path not found")}return r.toString()},fD=async(n,e,t,r)=>{let i=new rr;return t&&(i=await rr.getContextPathKey(n,e,t,r)),i.prepend([Fe.CREDENTIAL_SUBJECT_PATH]),i},pH=(n,e)=>{let[t,...r]=n.split("."),i=e.credentialSubject[t];for(let o of r)i=i[o];return i},hD=(n,e,t,r)=>{let i=[Fe.JSONLD_SCHEMA.W3C_CREDENTIAL_2018],o=i[0]===n?i:[...i,n],s=Fe.CREDENTIAL_TYPE.W3C_VERIFIABLE_CREDENTIAL,a=[s];e!==s&&a.push(e);let l={"@context":i,type:Fe.CREDENTIAL_TYPE.W3C_VERIFIABLE_PRESENTATION,verifiableCredential:{"@context":o,type:a,credentialSubject:{type:e}}},c={};for(let u of r){let h=u.fieldName.split(".").reduceRight((f,p)=>c[p]?{[p]:{...c[p],...f}}:{[p]:f},pH(u.fieldName,t));c={...c,...h}}return l.verifiableCredential.credentialSubject={...l.verifiableCredential.credentialSubject,...c},l};var Qse=`{
39
39
  "type": "object",
@@ -410,7 +410,7 @@ ${i}`);return{contextUrl:void 0,document:i||null,documentUrl:om+n}}async functio
410
410
  `?i="":(i!==""&&(i+=" "),i+=u)},showSharedRWMemory:function(){c()}}}),s=e;return new nT(o,s);function l(){let u="",d=o.exports.getMessageChar();for(;d!=0;)u+=String.fromCharCode(d),d=o.exports.getMessageChar();return u}function c(){let u=o.exports.getFieldNumLen32(),d=new Uint32Array(u);for(let h=0;h<u;h++)d[u-1-h]=o.exports.readSharedRWMemory(h);i!==""&&(i+=" "),i+=rT(d).toString()}}var nT=class{instance;version;n32;prime;witnessSize;sanityCheck;constructor(e,t){this.instance=e,this.instance=e,this.version=this.instance.exports.getVersion(),this.n32=this.instance.exports.getFieldNumLen32(),this.instance.exports.getRawPrime();let r=new Uint32Array(this.n32);for(let i=0;i<this.n32;i++)r[this.n32-1-i]=this.instance.exports.readSharedRWMemory(i);this.prime=rT(r),this.witnessSize=this.instance.exports.getWitnessSize(),this.sanityCheck=t}circom_version(){return this.instance.exports.getVersion()}async _doCalculateWitness(e,t){this.instance.exports.init(this.sanityCheck||t?1:0);let r=Object.keys(e),i=0;if(r.forEach(o=>{let s=Jge(o),a=parseInt(s.slice(0,8),16),l=parseInt(s.slice(8,16),16),c=Kge(e[o]),u=this.instance.exports.getInputSignalSize(a,l);if(u<0)throw new Error(`Signal ${o} not found
411
411
  `);if(c.length<u)throw new Error(`Not enough values for input signal ${o}
412
412
  `);if(c.length>u)throw new Error(`Too many values for input signal ${o}
413
- `);for(let d=0;d<c.length;d++){let h=Hge(BigInt(c[d])%this.prime,this.n32);for(let f=0;f<this.n32;f++)this.instance.exports.writeSharedRWMemory(f,h[this.n32-1-f]);try{this.instance.exports.setInputSignal(a,l,d),i++}catch(f){throw new Error(f)}}}),i<this.instance.exports.getInputSize())throw new Error(`Not all inputs have been set. Only ${i} out of ${this.instance.exports.getInputSize()}`)}async calculateWitness(e,t){let r=[];await this._doCalculateWitness(e,t);for(let i=0;i<this.witnessSize;i++){this.instance.exports.getWitness(i);let o=new Uint32Array(this.n32);for(let s=0;s<this.n32;s++)o[this.n32-1-s]=this.instance.exports.readSharedRWMemory(s);r.push(rT(o))}return r}async calculateBinWitness(e,t){let r=new Uint32Array(this.witnessSize*this.n32),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t);for(let o=0;o<this.witnessSize;o++){this.instance.exports.getWitness(o);let s=o*this.n32;for(let a=0;a<this.n32;a++)r[s+a]=this.instance.exports.readSharedRWMemory(a)}return i}async calculateWTNSBin(e,t){let r=new Uint32Array(this.witnessSize*this.n32+this.n32+11),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t),i[0]=119,i[1]=116,i[2]=110,i[3]=115,r[1]=2,r[2]=2,r[3]=1;let o=this.n32*4,a=(8+o).toString(16);r[4]=parseInt(a.slice(0,8),16),r[5]=parseInt(a.slice(8,16),16),r[6]=o,this.instance.exports.getRawPrime();let l=7;for(let d=0;d<this.n32;d++)r[l+d]=this.instance.exports.readSharedRWMemory(d);l+=this.n32,r[l]=this.witnessSize,l++,r[l]=2,l++;let u=(o*this.witnessSize).toString(16);r[l]=parseInt(u.slice(0,8),16),r[l+1]=parseInt(u.slice(8,16),16),l+=2;for(let d=0;d<this.witnessSize;d++){this.instance.exports.getWitness(d);for(let h=0;h<this.n32;h++)r[l+h]=this.instance.exports.readSharedRWMemory(h);l+=this.n32}return i}};function Hge(n,e){let t=[],r=BigInt(4294967296);for(;n;)t.unshift(Number(n%r)),n=n/r;if(e){let i=e-t.length;for(;i>0;)t.unshift(0),i--}return t}function rT(n){let e=BigInt(0),t=BigInt(4294967296);for(let r=0;r<n.length;r++)e=e*t+BigInt(n[r]);return e}function Kge(n){let e=[];return t(e,n),e;function t(r,i){if(Array.isArray(i))for(let o=0;o<i.length;o++)t(r,i[o]);else r.push(i)}}function Jge(n){let e=BigInt(2)**BigInt(64),t=BigInt("0xCBF29CE484222325");for(let o=0;o<n.length;o++)t^=BigInt(n[o].charCodeAt()),t*=BigInt(1099511628211),t%=e;let r=t.toString(16),i=16-r.length;return r="0".repeat(i).concat(r),r}var Fm=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function KA(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function iT(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function to(n,...e){if(!KA(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function qge(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");iT(n.outputLen),iT(n.blockLen)}function FA(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function Qge(n,e){to(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function kA(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function zB(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Cc(n,e){return n<<32-e|n>>>e}var nY=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Vge=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function ob(n){if(to(n),nY)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Vge[n[t]];return e}var eu={_0:48,_9:57,A:65,F:70,a:97,f:102};function OV(n){if(n>=eu._0&&n<=eu._9)return n-eu._0;if(n>=eu.A&&n<=eu.F)return n-(eu.A-10);if(n>=eu.a&&n<=eu.f)return n-(eu.a-10)}function wT(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(nY)return Uint8Array.fromHex(n);let e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let i=0,o=0;i<t;i++,o+=2){let s=OV(n.charCodeAt(o)),a=OV(n.charCodeAt(o+1));if(s===void 0||a===void 0){let l=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+o)}r[i]=s*16+a}return r}function JA(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function bT(n){return typeof n=="string"&&(n=JA(n)),to(n),n}function mi(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];to(i),e+=i.length}let t=new Uint8Array(e);for(let r=0,i=0;r<n.length;r++){let o=n[r];t.set(o,i),i+=o.length}return t}var OA=class{};function Yge(n){let e=r=>n().update(bT(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function rY(n=32){if(Fm&&typeof Fm.getRandomValues=="function")return Fm.getRandomValues(new Uint8Array(n));if(Fm&&typeof Fm.randomBytes=="function")return Uint8Array.from(Fm.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function zge(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);let i=BigInt(32),o=BigInt(4294967295),s=Number(t>>i&o),a=Number(t&o),l=r?4:0,c=r?0:4;n.setUint32(e+l,s,r),n.setUint32(e+c,a,r)}function jge(n,e,t){return n&e^~n&t}function Wge(n,e,t){return n&e^n&t^e&t}var oT=class extends OA{constructor(e,t,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=zB(this.buffer)}update(e){FA(this),e=bT(e),to(e);let{view:t,buffer:r,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let l=zB(e);for(;i<=o-s;s+=i)this.process(l,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){FA(this),Qge(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,kA(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;zge(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=zB(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=l/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Kd=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Zge=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]),Jd=new Uint32Array(64),sT=class extends oT{constructor(e=32){super(64,e,8,!1),this.A=Kd[0]|0,this.B=Kd[1]|0,this.C=Kd[2]|0,this.D=Kd[3]|0,this.E=Kd[4]|0,this.F=Kd[5]|0,this.G=Kd[6]|0,this.H=Kd[7]|0}get(){let{A:e,B:t,C:r,D:i,E:o,F:s,G:a,H:l}=this;return[e,t,r,i,o,s,a,l]}set(e,t,r,i,o,s,a,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=l|0}process(e,t){for(let d=0;d<16;d++,t+=4)Jd[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=Jd[d-15],f=Jd[d-2],p=Cc(h,7)^Cc(h,18)^h>>>3,w=Cc(f,17)^Cc(f,19)^f>>>10;Jd[d]=w+Jd[d-7]+p+Jd[d-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:l,G:c,H:u}=this;for(let d=0;d<64;d++){let h=Cc(a,6)^Cc(a,11)^Cc(a,25),f=u+h+jge(a,l,c)+Zge[d]+Jd[d]|0,w=(Cc(r,2)^Cc(r,13)^Cc(r,22))+Wge(r,i,o)|0;u=c,c=l,l=a,a=s+f|0,s=o,o=i,i=r,r=f+w|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,l=l+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,i,o,s,a,l,c,u)}roundClean(){kA(Jd)}destroy(){this.set(0,0,0,0,0,0,0,0),kA(this.buffer)}},IT=Yge(()=>new sT);var ET=BigInt(0),GA=BigInt(1);function NA(n,e){if(typeof e!="boolean")throw new Error(n+" boolean expected, got "+e)}function LA(n){let e=n.toString(16);return e.length&1?"0"+e:e}function iY(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?ET:BigInt("0x"+n)}function cb(n){return iY(ob(n))}function oY(n){return to(n),iY(ob(Uint8Array.from(n).reverse()))}function xT(n,e){return wT(n.toString(16).padStart(e*2,"0"))}function sY(n,e){return xT(n,e).reverse()}function Lo(n,e,t){let r;if(typeof e=="string")try{r=wT(e)}catch(o){throw new Error(n+" must be hex string or Uint8Array, cause: "+o)}else if(KA(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");let i=r.length;if(typeof t=="number"&&i!==t)throw new Error(n+" of length "+t+" expected, got "+i);return r}var jB=n=>typeof n=="bigint"&&ET<=n;function aY(n,e,t){return jB(n)&&jB(e)&&jB(t)&&e<=n&&n<t}function Xge(n,e,t,r){if(!aY(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function tb(n){let e;for(e=0;n>ET;n>>=GA,e+=1);return e}function _ge(n,e){return n>>BigInt(e)&GA}var ip=n=>(GA<<BigInt(n))-GA;function $ge(n,e,t){if(typeof n!="number"||n<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 t!="function")throw new Error("hmacFn must be a function");let r=f=>new Uint8Array(f),i=f=>Uint8Array.of(f),o=r(n),s=r(n),a=0,l=()=>{o.fill(1),s.fill(0),a=0},c=(...f)=>t(s,o,...f),u=(f=r(0))=>{s=c(i(0),f),o=c(),f.length!==0&&(s=c(i(1),f),o=c())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<e;){o=c();let w=o.slice();p.push(w),f+=o.length}return mi(...p)};return(f,p)=>{l(),u(f);let w;for(;!(w=p(d()));)u();return l(),w}}function eye(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function qA(n,e,t={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(i,o,s){let a=n[i];if(s&&a===void 0)return;let l=typeof a;if(l!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}Object.entries(e).forEach(([i,o])=>r(i,o,!1)),Object.entries(t).forEach(([i,o])=>r(i,o,!0))}var Lr=()=>{throw new Error("not implemented")};function aT(n){let e=new WeakMap;return(t,...r)=>{let i=e.get(t);if(i!==void 0)return i;let o=n(t,...r);return e.set(t,o),o}}var es=BigInt(0),eo=BigInt(1),np=BigInt(2),tye=BigInt(3),cY=BigInt(4),lY=BigInt(5),uY=BigInt(8);function Ba(n,e){let t=n%e;return t>=es?t:e+t}function GV(n,e){if(n===es)throw new Error("invert: expected non-zero number");if(e<=es)throw new Error("invert: expected positive modulus, got "+e);let t=Ba(n,e),r=e,i=es,o=eo;for(;t!==es;){let a=r/t,l=r%t,c=i-o*a;r=t,t=l,i=o,o=c}if(r!==eo)throw new Error("invert: does not exist");return Ba(i,e)}function dY(n,e){let t=(n.ORDER+eo)/cY,r=n.pow(e,t);if(!n.eql(n.sqr(r),e))throw new Error("Cannot find square root");return r}function nye(n,e){let t=(n.ORDER-lY)/uY,r=n.mul(e,np),i=n.pow(r,t),o=n.mul(e,i),s=n.mul(n.mul(o,np),i),a=n.mul(o,n.sub(s,n.ONE));if(!n.eql(n.sqr(a),e))throw new Error("Cannot find square root");return a}function rye(n){if(n<BigInt(3))throw new Error("sqrt is not defined for small field");let e=n-eo,t=0;for(;e%np===es;)e/=np,t++;let r=np,i=lb(n);for(;UA(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return dY;let o=i.pow(r,e),s=(e+eo)/np;return function(l,c){if(l.is0(c))return c;if(UA(l,c)!==1)throw new Error("Cannot find square root");let u=t,d=l.mul(l.ONE,o),h=l.pow(c,e),f=l.pow(c,s);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let p=1,w=l.sqr(h);for(;!l.eql(w,l.ONE);)if(p++,w=l.sqr(w),p===u)throw new Error("Cannot find square root");let y=eo<<BigInt(u-p-1),v=l.pow(d,y);u=p,d=l.sqr(v),h=l.mul(h,d),f=l.mul(f,v)}return f}}function iye(n){return n%cY===tye?dY:n%uY===lY?nye:rye(n)}var oye=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function sye(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=oye.reduce((r,i)=>(r[i]="function",r),e);return qA(n,t),n}function MA(n,e,t){if(t<es)throw new Error("invalid exponent, negatives unsupported");if(t===es)return n.ONE;if(t===eo)return e;let r=n.ONE,i=e;for(;t>es;)t&eo&&(r=n.mul(r,i)),i=n.sqr(i),t>>=eo;return r}function nb(n,e,t=!1){let r=new Array(e.length).fill(t?n.ZERO:void 0),i=e.reduce((s,a,l)=>n.is0(a)?s:(r[l]=s,n.mul(s,a)),n.ONE),o=n.inv(i);return e.reduceRight((s,a,l)=>n.is0(a)?s:(r[l]=n.mul(s,r[l]),n.mul(s,a)),o),r}function UA(n,e){let t=(n.ORDER-eo)/np,r=n.pow(e,t),i=n.eql(r,n.ONE),o=n.eql(r,n.ZERO),s=n.eql(r,n.neg(n.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function aye(n,e){e!==void 0&&iT(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function lb(n,e,t=!1,r={}){if(n<=es)throw new Error("invalid field: expected ORDER > 0, got "+n);let i,o;if(typeof e=="object"&&e!=null){if(r.sqrt||t)throw new Error("cannot specify opts in two arguments");let u=e;u.BITS&&(i=u.BITS),u.sqrt&&(o=u.sqrt),typeof u.isLE=="boolean"&&(t=u.isLE)}else typeof e=="number"&&(i=e),r.sqrt&&(o=r.sqrt);let{nBitLength:s,nByteLength:a}=aye(n,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l,c=Object.freeze({ORDER:n,isLE:t,BITS:s,BYTES:a,MASK:ip(s),ZERO:es,ONE:eo,create:u=>Ba(u,n),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return es<=u&&u<n},is0:u=>u===es,isValidNot0:u=>!c.is0(u)&&c.isValid(u),isOdd:u=>(u&eo)===eo,neg:u=>Ba(-u,n),eql:(u,d)=>u===d,sqr:u=>Ba(u*u,n),add:(u,d)=>Ba(u+d,n),sub:(u,d)=>Ba(u-d,n),mul:(u,d)=>Ba(u*d,n),pow:(u,d)=>MA(c,u,d),div:(u,d)=>Ba(u*GV(d,n),n),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>GV(u,n),sqrt:o||(u=>(l||(l=iye(n)),l(c,u))),toBytes:u=>t?sY(u,a):xT(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return t?oY(u):cb(u)},invertBatch:u=>nb(c,u),cmov:(u,d,h)=>h?d:u});return Object.freeze(c)}function fY(n){if(typeof n!="bigint")throw new Error("field order must be bigint");let e=n.toString(2).length;return Math.ceil(e/8)}function AT(n){let e=fY(n);return e+Math.ceil(e/2)}function hY(n,e,t=!1){let r=n.length,i=fY(e),o=AT(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?oY(n):cb(n),a=Ba(s,e-eo)+eo;return t?sY(a,i):xT(a,i)}var Um=BigInt(0),rp=BigInt(1);function rb(n,e){let t=e.negate();return n?t:e}function cT(n,e,t){let r=s=>s.pz,i=nb(n.Fp,t.map(r));return t.map((s,a)=>s.toAffine(i[a])).map(n.fromAffine)}function pY(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function WB(n,e){pY(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=ip(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function NV(n,e,t){let{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=t,a=Number(n&i),l=n>>s;a>r&&(a-=o,l+=rp);let c=e*r,u=c+Math.abs(a)-1,d=a===0,h=a<0,f=e%2!==0;return{nextN:l,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:c}}function cye(n,e){if(!Array.isArray(n))throw new Error("array expected");n.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function lye(n,e){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}var ZB=new WeakMap,mY=new WeakMap;function XB(n){return mY.get(n)||1}function UV(n){if(n!==Um)throw new Error("invalid wNAF")}function uye(n,e){return{constTimeNegate:rb,hasPrecomputes(t){return XB(t)!==1},unsafeLadder(t,r,i=n.ZERO){let o=t;for(;r>Um;)r&rp&&(i=i.add(o)),o=o.double(),r>>=rp;return i},precomputeWindow(t,r){let{windows:i,windowSize:o}=WB(r,e),s=[],a=t,l=a;for(let c=0;c<i;c++){l=a,s.push(l);for(let u=1;u<o;u++)l=l.add(a),s.push(l);a=l.double()}return s},wNAF(t,r,i){let o=n.ZERO,s=n.BASE,a=WB(t,e);for(let l=0;l<a.windows;l++){let{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:p}=NV(i,l,a);i=c,d?s=s.add(rb(f,r[p])):o=o.add(rb(h,r[u]))}return UV(i),{p:o,f:s}},wNAFUnsafe(t,r,i,o=n.ZERO){let s=WB(t,e);for(let a=0;a<s.windows&&i!==Um;a++){let{nextN:l,offset:c,isZero:u,isNeg:d}=NV(i,a,s);if(i=l,!u){let h=r[c];o=o.add(d?h.negate():h)}}return UV(i),o},getPrecomputes(t,r,i){let o=ZB.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof i=="function"&&(o=i(o)),ZB.set(r,o))),o},wNAFCached(t,r,i){let o=XB(t);return this.wNAF(o,this.getPrecomputes(o,t,i),r)},wNAFCachedUnsafe(t,r,i,o){let s=XB(t);return s===1?this.unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,i),r,o)},setWindowSize(t,r){pY(r,e),mY.set(t,r),ZB.delete(t)}}}function dye(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Um||r>Um;)t&rp&&(o=o.add(i)),r&rp&&(s=s.add(i)),i=i.double(),t>>=rp,r>>=rp;return{p1:o,p2:s}}function fye(n,e,t,r){cye(t,n),lye(r,e);let i=t.length,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=n.ZERO,a=tb(BigInt(i)),l=1;a>12?l=a-3:a>4?l=a-2:a>0&&(l=2);let c=ip(l),u=new Array(Number(c)+1).fill(s),d=Math.floor((e.BITS-1)/l)*l,h=s;for(let f=d;f>=0;f-=l){u.fill(s);for(let w=0;w<o;w++){let y=r[w],v=Number(y>>BigInt(f)&c);u[v]=u[v].add(t[w])}let p=s;for(let w=u.length-1,y=s;w>0;w--)y=y.add(u[w]),p=p.add(y);if(h=h.add(p),f!==0)for(let w=0;w<l;w++)h=h.double()}return h}function HV(n,e){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return sye(e),e}else return lb(n)}function hye(n,e,t={}){if(!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let a of["p","n","h"]){let l=e[a];if(!(typeof l=="bigint"&&l>Um))throw new Error(`CURVE.${a} must be positive bigint`)}let r=HV(e.p,t.Fp),i=HV(e.n,t.Fn),s=["Gx","Gy","a","b"];for(let a of s)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:i}}var pye=cb;function qd(n,e){if(sb(n),sb(e),n<0||n>=1<<8*e)throw new Error("invalid I2OSP input: "+n);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=n&255,n>>>=8;return new Uint8Array(t)}function mye(n,e){let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function sb(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function gye(n,e,t,r){to(n),to(e),sb(t),e.length>255&&(e=r(mi(JA("H2C-OVERSIZE-DST-"),e)));let{outputLen:i,blockLen:o}=r,s=Math.ceil(t/i);if(t>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=mi(e,qd(e.length,1)),l=qd(0,o),c=qd(t,2),u=new Array(s),d=r(mi(l,n,c,qd(0,1),a));u[0]=r(mi(d,qd(1,1),a));for(let f=1;f<=s;f++){let p=[mye(d,u[f-1]),qd(f+1,1),a];u[f]=r(mi(...p))}return mi(...u).slice(0,t)}function yye(n,e,t,r,i){if(to(n),to(e),sb(t),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update(JA("H2C-OVERSIZE-DST-")).update(e).digest()}if(t>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:t}).update(n).update(qd(t,2)).update(e).update(qd(e.length,1)).digest()}function KV(n,e,t){qA(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:l}=t;if(!KA(l)&&typeof l!="string")throw new Error("DST must be string or uint8array");if(!eye(t.hash))throw new Error("expected valid hash");to(n),sb(e);let c=typeof l=="string"?JA(l):l,u=r.toString(2).length,d=Math.ceil((u+i)/8),h=e*o*d,f;if(a==="xmd")f=gye(n,c,h,s);else if(a==="xof")f=yye(n,c,h,i,s);else if(a==="_internal_pass")f=n;else throw new Error('expand must be "xmd" or "xof"');let p=new Array(e);for(let w=0;w<e;w++){let y=new Array(o);for(let v=0;v<o;v++){let B=d*(v+w*o),U=f.subarray(B,B+d);y[v]=Ba(pye(U),r)}p[w]=y}return p}function JV(n,e,t){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(o){return n.fromAffine(e(o))}function i(o){let s=o.clearCofactor();return s.equals(n.ZERO)?n.ZERO:(s.assertValidity(),s)}return{defaults:t,hashToCurve(o,s){let a=t.DST?t.DST:{},l=Object.assign({},t,a,s),c=KV(o,2,l),u=r(c[0]),d=r(c[1]);return i(u.add(d))},encodeToCurve(o,s){let a=t.encodeDST?t.encodeDST:{},l=Object.assign({},t,a,s),c=KV(o,1,l);return i(r(c[0]))},mapToCurve(o){if(!Array.isArray(o))throw new Error("expected array of bigints");for(let s of o)if(typeof s!="bigint")throw new Error("expected array of bigints");return i(r(o))}}}var HA=class extends OA{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,qge(e);let r=bT(t);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 i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),kA(o)}update(e){return FA(this),this.iHash.update(e),this}digestInto(e){FA(this),to(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:t,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},gY=(n,e,t)=>new HA(n,e).update(t).digest();gY.create=(n,e)=>new HA(n,e);function qV(n){n.lowS!==void 0&&NA("lowS",n.lowS),n.prehash!==void 0&&NA("prehash",n.prehash)}var lT=class extends Error{constructor(e=""){super(e)}},tu={Err:lT,_tlv:{encode:(n,e)=>{let{Err:t}=tu;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,i=LA(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?LA(i.length/2|128):"";return LA(n)+o+i+e},decode(n,e){let{Err:t}=tu,r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");let i=e[r++],o=!!(i&128),s=0;if(!o)s=i;else{let l=i&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let c=e.subarray(r,r+l);if(c.length!==l)throw new t("tlv.decode: length bytes not complete");if(c[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of c)s=s<<8|u;if(r+=l,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(n){let{Err:e}=tu;if(n<ib)throw new e("integer: negative integers are not allowed");let t=LA(n);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(n){let{Err:e}=tu;if(n[0]&128)throw new e("invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return cb(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=tu,i=Lo("signature",n),{v:o,l:s}=r.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,o),{v:c,l:u}=r.decode(2,l);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(c)}},hexFromSig(n){let{_tlv:e,_int:t}=tu,r=e.encode(2,t.encode(n.r)),i=e.encode(2,t.encode(n.s)),o=r+i;return e.encode(48,o)}},ib=BigInt(0),Gm=BigInt(1),wye=BigInt(2),BA=BigInt(3),bye=BigInt(4);function yY(n,e,t){function r(i){let o=n.sqr(i),s=n.mul(o,i);return n.add(n.add(s,n.mul(i,e)),t)}return r}function vT(n,e,t){let{BYTES:r}=n;function i(o){let s;if(typeof o=="bigint")s=o;else{let a=Lo("private key",o);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");let l=new Uint8Array(r);l.set(a,l.length-a.length),a=l}try{s=n.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof o}`)}}if(t&&(s=n.create(s)),!n.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}return i}function wY(n,e={}){let{Fp:t,Fn:r}=hye("weierstrass",n,e),{h:i,n:o}=n;qA(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:s}=e;if(s&&(!t.is0(n.a)||typeof s.beta!="bigint"||typeof s.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(D,V,K){let{x:q,y:G}=V.toAffine(),x=t.toBytes(q);if(NA("isCompressed",K),K){a();let S=!t.isOdd(G);return mi(bY(S),x)}else return mi(Uint8Array.of(4),x,t.toBytes(G))}function c(D){to(D);let V=t.BYTES,K=V+1,q=2*V+1,G=D.length,x=D[0],S=D.subarray(1);if(G===K&&(x===2||x===3)){let M=t.fromBytes(S);if(!t.isValid(M))throw new Error("bad point: is not on curve, wrong x");let b=h(M),A;try{A=t.sqrt(b)}catch(Q){let Y=Q instanceof Error?": "+Q.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}a();let R=t.isOdd(A);return(x&1)===1!==R&&(A=t.neg(A)),{x:M,y:A}}else if(G===q&&x===4){let M=t.fromBytes(S.subarray(V*0,V*1)),b=t.fromBytes(S.subarray(V*1,V*2));if(!f(M,b))throw new Error("bad point: is not on curve");return{x:M,y:b}}else throw new Error(`bad point: got length ${G}, expected compressed=${K} or uncompressed=${q}`)}let u=e.toBytes||l,d=e.fromBytes||c,h=yY(t,n.a,n.b);function f(D,V){let K=t.sqr(V),q=h(D);return t.eql(K,q)}if(!f(n.Gx,n.Gy))throw new Error("bad curve params: generator point");let p=t.mul(t.pow(n.a,BA),bye),w=t.mul(t.sqr(n.b),BigInt(27));if(t.is0(t.add(p,w)))throw new Error("bad curve params: a or b");function y(D,V,K=!1){if(!t.isValid(V)||K&&t.is0(V))throw new Error(`bad point coordinate ${D}`);return V}function v(D){if(!(D instanceof F))throw new Error("ProjectivePoint expected")}let B=aT((D,V)=>{let{px:K,py:q,pz:G}=D;if(t.eql(G,t.ONE))return{x:K,y:q};let x=D.is0();V==null&&(V=x?t.ONE:t.inv(G));let S=t.mul(K,V),M=t.mul(q,V),b=t.mul(G,V);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(b,t.ONE))throw new Error("invZ was invalid");return{x:S,y:M}}),U=aT(D=>{if(D.is0()){if(e.allowInfinityPoint&&!t.is0(D.py))return;throw new Error("bad point: ZERO")}let{x:V,y:K}=D.toAffine();if(!t.isValid(V)||!t.isValid(K))throw new Error("bad point: x or y not field elements");if(!f(V,K))throw new Error("bad point: equation left != right");if(!D.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(D,V,K,q,G){return K=new F(t.mul(K.px,D),K.py,K.pz),V=rb(q,V),K=rb(G,K),V.add(K)}class F{constructor(V,K,q){this.px=y("x",V),this.py=y("y",K,!0),this.pz=y("z",q),Object.freeze(this)}static fromAffine(V){let{x:K,y:q}=V||{};if(!V||!t.isValid(K)||!t.isValid(q))throw new Error("invalid affine point");if(V instanceof F)throw new Error("projective point not allowed");return t.is0(K)&&t.is0(q)?F.ZERO:new F(K,q,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(V){return cT(F,"pz",V)}static fromBytes(V){return to(V),F.fromHex(V)}static fromHex(V){let K=F.fromAffine(d(Lo("pointHex",V)));return K.assertValidity(),K}static fromPrivateKey(V){let K=vT(r,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return F.BASE.multiply(K(V))}static msm(V,K){return fye(F,r,V,K)}precompute(V=8,K=!0){return I.setWindowSize(this,V),K||this.multiply(BA),this}_setWindowSize(V){this.precompute(V)}assertValidity(){U(this)}hasEvenY(){let{y:V}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(V)}equals(V){v(V);let{px:K,py:q,pz:G}=this,{px:x,py:S,pz:M}=V,b=t.eql(t.mul(K,M),t.mul(x,G)),A=t.eql(t.mul(q,M),t.mul(S,G));return b&&A}negate(){return new F(this.px,t.neg(this.py),this.pz)}double(){let{a:V,b:K}=n,q=t.mul(K,BA),{px:G,py:x,pz:S}=this,M=t.ZERO,b=t.ZERO,A=t.ZERO,R=t.mul(G,G),J=t.mul(x,x),Q=t.mul(S,S),Y=t.mul(G,x);return Y=t.add(Y,Y),A=t.mul(G,S),A=t.add(A,A),M=t.mul(V,A),b=t.mul(q,Q),b=t.add(M,b),M=t.sub(J,b),b=t.add(J,b),b=t.mul(M,b),M=t.mul(Y,M),A=t.mul(q,A),Q=t.mul(V,Q),Y=t.sub(R,Q),Y=t.mul(V,Y),Y=t.add(Y,A),A=t.add(R,R),R=t.add(A,R),R=t.add(R,Q),R=t.mul(R,Y),b=t.add(b,R),Q=t.mul(x,S),Q=t.add(Q,Q),R=t.mul(Q,Y),M=t.sub(M,R),A=t.mul(Q,J),A=t.add(A,A),A=t.add(A,A),new F(M,b,A)}add(V){v(V);let{px:K,py:q,pz:G}=this,{px:x,py:S,pz:M}=V,b=t.ZERO,A=t.ZERO,R=t.ZERO,J=n.a,Q=t.mul(n.b,BA),Y=t.mul(K,x),Z=t.mul(q,S),X=t.mul(G,M),_=t.add(K,q),E=t.add(x,S);_=t.mul(_,E),E=t.add(Y,Z),_=t.sub(_,E),E=t.add(K,G);let m=t.add(x,M);return E=t.mul(E,m),m=t.add(Y,X),E=t.sub(E,m),m=t.add(q,G),b=t.add(S,M),m=t.mul(m,b),b=t.add(Z,X),m=t.sub(m,b),R=t.mul(J,E),b=t.mul(Q,X),R=t.add(b,R),b=t.sub(Z,R),R=t.add(Z,R),A=t.mul(b,R),Z=t.add(Y,Y),Z=t.add(Z,Y),X=t.mul(J,X),E=t.mul(Q,E),Z=t.add(Z,X),X=t.sub(Y,X),X=t.mul(J,X),E=t.add(E,X),Y=t.mul(Z,E),A=t.add(A,Y),Y=t.mul(m,E),b=t.mul(_,b),b=t.sub(b,Y),Y=t.mul(_,Z),R=t.mul(m,R),R=t.add(R,Y),new F(b,A,R)}subtract(V){return this.add(V.negate())}is0(){return this.equals(F.ZERO)}multiply(V){let{endo:K}=e;if(!r.isValidNot0(V))throw new Error("invalid scalar: out of range");let q,G,x=S=>I.wNAFCached(this,S,F.normalizeZ);if(K){let{k1neg:S,k1:M,k2neg:b,k2:A}=K.splitScalar(V),{p:R,f:J}=x(M),{p:Q,f:Y}=x(A);G=J.add(Y),q=k(K.beta,R,Q,S,b)}else{let{p:S,f:M}=x(V);q=S,G=M}return F.normalizeZ([q,G])[0]}multiplyUnsafe(V){let{endo:K}=e,q=this;if(!r.isValid(V))throw new Error("invalid scalar: out of range");if(V===ib||q.is0())return F.ZERO;if(V===Gm)return q;if(I.hasPrecomputes(this))return this.multiply(V);if(K){let{k1neg:G,k1:x,k2neg:S,k2:M}=K.splitScalar(V),{p1:b,p2:A}=dye(F,q,x,M);return k(K.beta,b,A,G,S)}else return I.wNAFCachedUnsafe(q,V)}multiplyAndAddUnsafe(V,K,q){let G=this.multiplyUnsafe(K).add(V.multiplyUnsafe(q));return G.is0()?void 0:G}toAffine(V){return B(this,V)}isTorsionFree(){let{isTorsionFree:V}=e;return i===Gm?!0:V?V(F,this):I.wNAFCachedUnsafe(this,o).is0()}clearCofactor(){let{clearCofactor:V}=e;return i===Gm?this:V?V(F,this):this.multiplyUnsafe(i)}toBytes(V=!0){return NA("isCompressed",V),this.assertValidity(),u(F,this,V)}toRawBytes(V=!0){return this.toBytes(V)}toHex(V=!0){return ob(this.toBytes(V))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}F.BASE=new F(n.Gx,n.Gy,t.ONE),F.ZERO=new F(t.ZERO,t.ONE,t.ZERO),F.Fp=t,F.Fn=r;let P=r.BITS,I=uye(F,e.endo?Math.ceil(P/2):P);return F}function QV(n){let{CURVE:e,curveOpts:t}=IY(n),r=wY(e,t);return xye(n,r)}function bY(n){return Uint8Array.of(n?2:3)}function Iye(n,e,t={}){qA(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=e.randomBytes||rY,i=e.hmac||((q,...G)=>gY(e.hash,q,mi(...G))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:l}=s;function c(q){let G=a>>Gm;return q>G}function u(q){return c(q)?s.neg(q):q}function d(q,G){if(!s.isValidNot0(G))throw new Error(`invalid signature ${q}: out of range 1..CURVE.n`)}class h{constructor(G,x,S){d("r",G),d("s",x),this.r=G,this.s=x,S!=null&&(this.recovery=S),Object.freeze(this)}static fromCompact(G){let x=s.BYTES,S=Lo("compactSignature",G,x*2);return new h(s.fromBytes(S.subarray(0,x)),s.fromBytes(S.subarray(x,x*2)))}static fromDER(G){let{r:x,s:S}=tu.toSig(Lo("DER",G));return new h(x,S)}assertValidity(){}addRecoveryBit(G){return new h(this.r,this.s,G)}recoverPublicKey(G){let x=o.ORDER,{r:S,s:M,recovery:b}=this;if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");if(a*wye<x&&b>1)throw new Error("recovery id is ambiguous for h>1 curve");let R=b===2||b===3?S+a:S;if(!o.isValid(R))throw new Error("recovery id 2 or 3 invalid");let J=o.toBytes(R),Q=n.fromHex(mi(bY((b&1)===0),J)),Y=s.inv(R),Z=U(Lo("msgHash",G)),X=s.create(-Z*Y),_=s.create(M*Y),E=n.BASE.multiplyUnsafe(X).add(Q.multiplyUnsafe(_));if(E.is0())throw new Error("point at infinify");return E.assertValidity(),E}hasHighS(){return c(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,s.neg(this.s),this.recovery):this}toBytes(G){if(G==="compact")return mi(s.toBytes(this.r),s.toBytes(this.s));if(G==="der")return wT(tu.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return ob(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ob(this.toBytes("compact"))}}let f=vT(s,t.allowedPrivateKeyLengths,t.wrapPrivateKey),p={isValidPrivateKey(q){try{return f(q),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let q=a;return hY(r(AT(q)),q)},precompute(q=8,G=n.BASE){return G.precompute(q,!1)}};function w(q,G=!0){return n.fromPrivateKey(q).toBytes(G)}function y(q){if(typeof q=="bigint")return!1;if(q instanceof n)return!0;let x=Lo("key",q).length,S=o.BYTES,M=S+1,b=2*S+1;if(!(t.allowedPrivateKeyLengths||s.BYTES===M))return x===M||x===b}function v(q,G,x=!0){if(y(q)===!0)throw new Error("first arg must be private key");if(y(G)===!1)throw new Error("second arg must be public key");return n.fromHex(G).multiply(f(q)).toBytes(x)}let B=e.bits2int||function(q){if(q.length>8192)throw new Error("input is too large");let G=cb(q),x=q.length*8-l;return x>0?G>>BigInt(x):G},U=e.bits2int_modN||function(q){return s.create(B(q))},k=ip(l);function F(q){return Xge("num < 2^"+l,q,ib,k),s.toBytes(q)}function P(q,G,x=I){if(["recovered","canonical"].some(_=>_ in x))throw new Error("sign() legacy options not supported");let{hash:S}=e,{lowS:M,prehash:b,extraEntropy:A}=x;M==null&&(M=!0),q=Lo("msgHash",q),qV(x),b&&(q=Lo("prehashed msgHash",S(q)));let R=U(q),J=f(G),Q=[F(J),F(R)];if(A!=null&&A!==!1){let _=A===!0?r(o.BYTES):A;Q.push(Lo("extraEntropy",_))}let Y=mi(...Q),Z=R;function X(_){let E=B(_);if(!s.isValidNot0(E))return;let m=s.inv(E),O=n.BASE.multiply(E).toAffine(),g=s.create(O.x);if(g===ib)return;let H=s.create(m*s.create(Z+g*J));if(H===ib)return;let N=(O.x===g?0:2)|Number(O.y&Gm),C=H;return M&&c(H)&&(C=u(H),N^=1),new h(g,C,N)}return{seed:Y,k2sig:X}}let I={lowS:e.lowS,prehash:!1},D={lowS:e.lowS,prehash:!1};function V(q,G,x=I){let{seed:S,k2sig:M}=P(q,G,x);return $ge(e.hash.outputLen,s.BYTES,i)(S,M)}n.BASE.precompute(8);function K(q,G,x,S=D){let M=q;G=Lo("msgHash",G),x=Lo("publicKey",x),qV(S);let{lowS:b,prehash:A,format:R}=S;if("strict"in S)throw new Error("options.strict was renamed to lowS");if(R!==void 0&&!["compact","der","js"].includes(R))throw new Error('format must be "compact", "der" or "js"');let J=typeof M=="string"||KA(M),Q=!J&&!R&&typeof M=="object"&&M!==null&&typeof M.r=="bigint"&&typeof M.s=="bigint";if(!J&&!Q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Y,Z;try{if(Q)if(R===void 0||R==="js")Y=new h(M.r,M.s);else throw new Error("invalid format");if(J){try{R!=="compact"&&(Y=h.fromDER(M))}catch(C){if(!(C instanceof tu.Err))throw C}!Y&&R!=="der"&&(Y=h.fromCompact(M))}Z=n.fromHex(x)}catch{return!1}if(!Y||b&&Y.hasHighS())return!1;A&&(G=e.hash(G));let{r:X,s:_}=Y,E=U(G),m=s.inv(_),O=s.create(E*m),g=s.create(X*m),H=n.BASE.multiplyUnsafe(O).add(Z.multiplyUnsafe(g));return H.is0()?!1:s.create(H.x)===X}return Object.freeze({getPublicKey:w,getSharedSecret:v,sign:V,verify:K,utils:p,Point:n,Signature:h})}function IY(n){let e={a:n.a,b:n.b,p:n.Fp.ORDER,n:n.n,h:n.h,Gx:n.Gx,Gy:n.Gy},t=n.Fp,r=lb(e.n,n.nBitLength),i={Fp:t,Fn:r,allowedPrivateKeyLengths:n.allowedPrivateKeyLengths,allowInfinityPoint:n.allowInfinityPoint,endo:n.endo,wrapPrivateKey:n.wrapPrivateKey,isTorsionFree:n.isTorsionFree,clearCofactor:n.clearCofactor,fromBytes:n.fromBytes,toBytes:n.toBytes};return{CURVE:e,curveOpts:i}}function Eye(n){let{CURVE:e,curveOpts:t}=IY(n),r={hash:n.hash,hmac:n.hmac,randomBytes:n.randomBytes,lowS:n.lowS,bits2int:n.bits2int,bits2int_modN:n.bits2int_modN};return{CURVE:e,curveOpts:t,ecdsaOpts:r}}function xye(n,e){let{Fp:t,Fn:r}=e;function i(a){return aY(a,Gm,r.ORDER)}let o=yY(t,n.a,n.b),s=vT(r,n.allowedPrivateKeyLengths,n.wrapPrivateKey);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s,weierstrassEquation:o,isWithinCurveOrder:i})}function Aye(n,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:n})}function vye(n){let{CURVE:e,curveOpts:t,ecdsaOpts:r}=Eye(n),i=wY(e,t),o=Iye(i,r,t);return Aye(n,o)}var Cye=BigInt(0),TA=BigInt(1),VV=BigInt(2),km=BigInt(3);function Sye(n){let e=[];for(;n>TA;n>>=TA)(n&TA)===Cye?e.unshift(0):(n&km)===km?(e.unshift(-1),n+=TA):e.unshift(1);return e}function Dye(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=QV(n.G1),a=Object.assign(s,JV(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),l=QV(n.G2),c=Object.assign(l,JV(l.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),u;u=(E,m,O,g,H,N)=>o.mul034(g,r.mul(O,N),r.mul(m,H),E);let d=r.div(r.ONE,r.mul(r.ONE,VV));function h(E,m,O,g){let H=r.sqr(O),N=r.sqr(g),C=r.mulByB(r.mul(N,km)),W=r.mul(C,km),$=r.sub(r.sub(r.sqr(r.add(O,g)),N),H),ee=r.sub(C,H),le=r.mul(r.sqr(m),km),Ce=r.neg($);return E.push([ee,le,Ce]),m=r.mul(r.mul(r.mul(r.sub(H,W),m),O),d),O=r.sub(r.sqr(r.mul(r.add(H,W),d)),r.mul(r.sqr(C),km)),g=r.mul(H,$),{Rx:m,Ry:O,Rz:g}}function f(E,m,O,g,H,N){let C=r.sub(O,r.mul(N,g)),W=r.sub(m,r.mul(H,g)),$=r.sub(r.mul(C,H),r.mul(W,N)),ee=r.neg(C),le=W;E.push([$,ee,le]);let Ce=r.sqr(W),Ae=r.mul(Ce,W),Re=r.mul(Ce,m),_e=r.add(r.sub(Ae,r.mul(Re,VV)),r.mul(r.sqr(C),g));return m=r.mul(W,_e),O=r.sub(r.mul(r.sub(Re,_e),C),r.mul(Ae,O)),g=r.mul(g,Ae),{Rx:m,Ry:O,Rz:g}}let p=Sye(n.params.ateLoopSize),w=aT(E=>{let m=E,{x:O,y:g}=m.toAffine(),H=O,N=g,C=r.neg(g),W=H,$=N,ee=r.ONE,le=[];for(let Ce of p){let Ae=[];({Rx:W,Ry:$,Rz:ee}=h(Ae,W,$,ee)),Ce&&({Rx:W,Ry:$,Rz:ee}=f(Ae,W,$,ee,H,Ce===-1?C:N)),le.push(Ae)}if(n.postPrecompute){let Ce=le[le.length-1];n.postPrecompute(W,$,ee,H,N,f.bind(null,Ce))}return le});function y(E,m=!1){let O=o.ONE;if(E.length){let g=E[0][0].length;for(let H=0;H<g;H++){O=o.sqr(O);for(let[N,C,W]of E)for(let[$,ee,le]of N[H])O=u($,ee,le,O,C,W)}}return m?o.finalExponentiate(O):O}function v(E,m=!0){let O=[];cT(a.Point,"pz",E.map(({g1:g})=>g)),cT(c.Point,"pz",E.map(({g2:g})=>g));for(let{g1:g,g2:H}of E){if(g.is0()||H.is0())throw new Error("pairing is not available for ZERO point");g.assertValidity(),H.assertValidity();let N=g.toAffine();O.push([w(H),N.x,N.y])}return y(O,m)}function B(E,m,O=!0){return v([{g1:E,g2:m}],O)}let U=n.randomBytes||rY,k={randomPrivateKey:()=>{let E=AT(t.ORDER);return hY(U(E),t.ORDER)},calcPairingPrecomputes:w};function F(E){if(!Array.isArray(E)||E.length===0)throw new Error("expected non-empty array")}function P(E){return E instanceof a.Point?E:a.Point.fromHex(E)}function I(E){return E instanceof c.Point?E:G.fromHex(E)}function D(E,m){function O(C){return C instanceof E.Point?C:E.Point.fromHex(C)}function g(C){return C instanceof m.Point?C:m.Point.fromHex(C)}function H(C){if(!(C instanceof m.Point))throw new Error(`expected valid message hashed to ${N?"G2":"G1"} curve`);return C}let N=m.Point.Fp.BYTES>E.Point.Fp.BYTES;return{getPublicKey(C){return E.Point.fromPrivateKey(C)},sign(C,W,$){if($!=null)throw new Error("sign() expects 2 arguments");return H(C).assertValidity(),C.multiply(E.normPrivateKeyToScalar(W))},verify(C,W,$,ee){if(ee!=null)throw new Error("verify() expects 3 arguments");C=g(C),$=O($);let le=$.negate(),Ce=E.Point.BASE,Ae=H(W),Re=C,Pe=v(N?[{g1:le,g2:Ae},{g1:Ce,g2:Re}]:[{g1:Ae,g2:le},{g1:Re,g2:Ce}]);return o.eql(Pe,o.ONE)},aggregatePublicKeys(C){F(C),C=C.map($=>O($));let W=C.reduce(($,ee)=>$.add(ee),E.Point.ZERO);return W.assertValidity(),W},aggregateSignatures(C){F(C),C=C.map($=>g($));let W=C.reduce(($,ee)=>$.add(ee),m.Point.ZERO);return W.assertValidity(),W},hash(C,W){to(C);let $=W?{DST:W}:void 0;return m.hashToCurve(C,$)},Signature:N?n.G2.Signature:n.G1.ShortSignature}}let V=D(a,c),K=D(c,a),{ShortSignature:q}=n.G1,{Signature:G}=n.G2;function x(E,m){return E instanceof a.Point?E:K.hash(Lo("point",E),m?.DST)}function S(E,m){return E instanceof c.Point?E:V.hash(Lo("point",E),m?.DST)}function M(E){return V.getPublicKey(E).toBytes(!0)}function b(E){return K.getPublicKey(E).toBytes(!0)}function A(E,m,O){let g=S(E,O),H=V.sign(g,m);return E instanceof c.Point?H:G.toBytes(H)}function R(E,m,O){let g=x(E,O),H=K.sign(g,m);return E instanceof a.Point?H:q.toBytes(H)}function J(E,m,O,g){let H=S(m,g);return V.verify(E,H,O)}function Q(E,m,O,g){let H=x(m,g);return K.verify(E,H,O)}function Y(E){let m=V.aggregatePublicKeys(E);return E[0]instanceof a.Point?m:m.toBytes(!0)}function Z(E){let m=V.aggregateSignatures(E);return E[0]instanceof c.Point?m:G.toBytes(m)}function X(E){let m=K.aggregateSignatures(E);return E[0]instanceof a.Point?m:q.toBytes(m)}function _(E,m,O,g){if(F(m),O.length!==m.length)throw new Error("amount of public keys and messages should be equal");let H=I(E),N=m.map(ee=>S(ee,g)),C=O.map(P),W=new Map;for(let ee=0;ee<C.length;ee++){let le=C[ee],Ce=N[ee],Ae=W.get(Ce);Ae===void 0&&(Ae=[],W.set(Ce,Ae)),Ae.push(le)}let $=[];try{for(let[ee,le]of W){let Ce=le.reduce((Ae,Re)=>Ae.add(Re));$.push({g1:Ce,g2:ee})}return $.push({g1:a.Point.BASE.negate(),g2:H}),o.eql(v($),o.ONE)}catch{return!1}}return a.Point.BASE.precompute(4),{longSignatures:V,shortSignatures:K,millerLoopBatch:y,pairing:B,pairingBatch:v,verifyBatch:_,curves:{G1:s.Point,G2:l.Point},fields:{Fr:t,Fp:e,Fp2:r,Fp6:i,Fp12:o},params:{ateLoopSize:n.params.ateLoopSize,twistType:n.params.twistType,r:n.params.r,G1b:n.G1.b,G2b:n.G2.b},utils:k,getPublicKey:M,getPublicKeyForShortSignatures:b,sign:A,signShortSignature:R,verify:J,verifyShortSignature:Q,aggregatePublicKeys:Y,aggregateSignatures:Z,aggregateShortSignatures:X,G1:a,G2:c,Signature:G,ShortSignature:q}}var YV=BigInt(0),Om=BigInt(1),nu=BigInt(2),zV=BigInt(3);function _B(n,e,t,r,i=1,o){let s=BigInt(o===void 0?r:o),a=t**BigInt(r),l=[];for(let c=0;c<i;c++){let u=BigInt(c+1),d=[];for(let h=0,f=Om;h<r;h++){let p=(u*f-u)/s%a;d.push(n.pow(e,p)),f*=t}l.push(d)}return l}function Lye(n,e,t){let r=e.pow(t,(n.ORDER-Om)/zV),i=e.pow(t,(n.ORDER-Om)/nu);function o(h,f){let p=e.mul(e.frobeniusMap(h,1),r),w=e.mul(e.frobeniusMap(f,1),i);return[p,w]}let s=e.pow(t,(n.ORDER**nu-Om)/zV),a=e.pow(t,(n.ORDER**nu-Om)/nu);if(!e.eql(a,e.neg(e.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function l(h,f){return[e.mul(h,s),e.neg(f)]}let c=h=>(f,p)=>{let w=p.toAffine(),y=h(w.x,w.y);return f.fromAffine({x:y[0],y:y[1]})},u=c(o),d=c(l);return{psi:o,psi2:l,G2psi:u,G2psi2:d,PSI_X:r,PSI_Y:i,PSI2_X:s,PSI2_Y:a}}function Bye(n){let{ORDER:e}=n,t=lb(e),r=t.create(n.NONRESIDUE||BigInt(-1)),i=t.div(t.ONE,nu),o=_B(t,r,t.ORDER,2)[0],s=({c0:x,c1:S},{c0:M,c1:b})=>({c0:t.add(x,M),c1:t.add(S,b)}),a=({c0:x,c1:S},{c0:M,c1:b})=>({c0:t.sub(x,M),c1:t.sub(S,b)}),l=({c0:x,c1:S},M)=>{if(typeof M=="bigint")return{c0:t.mul(x,M),c1:t.mul(S,M)};let{c0:b,c1:A}=M,R=t.mul(x,b),J=t.mul(S,A),Q=t.sub(R,J),Y=t.sub(t.mul(t.add(x,S),t.add(b,A)),t.add(R,J));return{c0:Q,c1:Y}},c=({c0:x,c1:S})=>{let M=t.add(x,S),b=t.sub(x,S),A=t.add(x,x);return{c0:t.mul(M,b),c1:t.mul(A,S)}},u=x=>{if(x.length!==2)throw new Error("invalid tuple");let S=x.map(M=>t.create(M));return{c0:S[0],c1:S[1]}};function d(x,S){return typeof x=="bigint"&&YV<=x&&x<S}let h=e*e,f=u(n.FP2_NONRESIDUE),p={ORDER:h,isLE:t.isLE,NONRESIDUE:f,BITS:tb(h),BYTES:Math.ceil(tb(h)/8),MASK:ip(tb(h)),ZERO:{c0:t.ZERO,c1:t.ZERO},ONE:{c0:t.ONE,c1:t.ZERO},create:x=>x,isValid:({c0:x,c1:S})=>d(x,h)&&d(S,h),is0:({c0:x,c1:S})=>t.is0(x)&&t.is0(S),isValidNot0:x=>!p.is0(x)&&p.isValid(x),eql:({c0:x,c1:S},{c0:M,c1:b})=>t.eql(x,M)&&t.eql(S,b),neg:({c0:x,c1:S})=>({c0:t.neg(x),c1:t.neg(S)}),pow:(x,S)=>MA(p,x,S),invertBatch:x=>nb(p,x),add:s,sub:a,mul:l,sqr:c,addN:s,subN:a,mulN:l,sqrN:c,div:(x,S)=>p.mul(x,typeof S=="bigint"?t.inv(t.create(S)):p.inv(S)),inv:({c0:x,c1:S})=>{let M=t.inv(t.create(x*x+S*S));return{c0:t.mul(M,t.create(x)),c1:t.mul(M,t.create(-S))}},sqrt:x=>{if(n.Fp2sqrt)return n.Fp2sqrt(x);let{c0:S,c1:M}=x;if(t.is0(M))return UA(t,S)===1?p.create({c0:t.sqrt(S),c1:t.ZERO}):p.create({c0:t.ZERO,c1:t.sqrt(t.div(S,r))});let b=t.sqrt(t.sub(t.sqr(S),t.mul(t.sqr(M),r))),A=t.mul(t.add(b,S),i);UA(t,A)===-1&&(A=t.sub(A,b));let J=t.sqrt(A),Q=p.create({c0:J,c1:t.div(t.mul(M,i),J)});if(!p.eql(p.sqr(Q),x))throw new Error("Cannot find square root");let Y=Q,Z=p.neg(Y),{re:X,im:_}=p.reim(Y),{re:E,im:m}=p.reim(Z);return _>m||_===m&&X>E?Y:Z},isOdd:x=>{let{re:S,im:M}=p.reim(x),b=S%nu,A=S===YV,R=M%nu;return BigInt(b||A&&R)==Om},fromBytes(x){if(x.length!==p.BYTES)throw new Error("fromBytes invalid length="+x.length);return{c0:t.fromBytes(x.subarray(0,t.BYTES)),c1:t.fromBytes(x.subarray(t.BYTES))}},toBytes:({c0:x,c1:S})=>mi(t.toBytes(x),t.toBytes(S)),cmov:({c0:x,c1:S},{c0:M,c1:b},A)=>({c0:t.cmov(x,M,A),c1:t.cmov(S,b,A)}),reim:({c0:x,c1:S})=>({re:x,im:S}),mulByNonresidue:({c0:x,c1:S})=>p.mul({c0:x,c1:S},f),mulByB:n.Fp2mulByB,fromBigTuple:u,frobeniusMap:({c0:x,c1:S},M)=>({c0:x,c1:t.mul(S,o[M%2])})},w=({c0:x,c1:S,c2:M},{c0:b,c1:A,c2:R})=>({c0:p.add(x,b),c1:p.add(S,A),c2:p.add(M,R)}),y=({c0:x,c1:S,c2:M},{c0:b,c1:A,c2:R})=>({c0:p.sub(x,b),c1:p.sub(S,A),c2:p.sub(M,R)}),v=({c0:x,c1:S,c2:M},b)=>{if(typeof b=="bigint")return{c0:p.mul(x,b),c1:p.mul(S,b),c2:p.mul(M,b)};let{c0:A,c1:R,c2:J}=b,Q=p.mul(x,A),Y=p.mul(S,R),Z=p.mul(M,J);return{c0:p.add(Q,p.mulByNonresidue(p.sub(p.mul(p.add(S,M),p.add(R,J)),p.add(Y,Z)))),c1:p.add(p.sub(p.mul(p.add(x,S),p.add(A,R)),p.add(Q,Y)),p.mulByNonresidue(Z)),c2:p.sub(p.add(Y,p.mul(p.add(x,M),p.add(A,J))),p.add(Q,Z))}},B=({c0:x,c1:S,c2:M})=>{let b=p.sqr(x),A=p.mul(p.mul(x,S),nu),R=p.mul(p.mul(S,M),nu),J=p.sqr(M);return{c0:p.add(p.mulByNonresidue(R),b),c1:p.add(p.mulByNonresidue(J),A),c2:p.sub(p.sub(p.add(p.add(A,p.sqr(p.add(p.sub(x,S),M))),R),b),J)}},[U,k]=_B(p,f,t.ORDER,6,2,3),F={ORDER:p.ORDER,isLE:p.isLE,BITS:3*p.BITS,BYTES:3*p.BYTES,MASK:ip(3*p.BITS),ZERO:{c0:p.ZERO,c1:p.ZERO,c2:p.ZERO},ONE:{c0:p.ONE,c1:p.ZERO,c2:p.ZERO},create:x=>x,isValid:({c0:x,c1:S,c2:M})=>p.isValid(x)&&p.isValid(S)&&p.isValid(M),is0:({c0:x,c1:S,c2:M})=>p.is0(x)&&p.is0(S)&&p.is0(M),isValidNot0:x=>!F.is0(x)&&F.isValid(x),neg:({c0:x,c1:S,c2:M})=>({c0:p.neg(x),c1:p.neg(S),c2:p.neg(M)}),eql:({c0:x,c1:S,c2:M},{c0:b,c1:A,c2:R})=>p.eql(x,b)&&p.eql(S,A)&&p.eql(M,R),sqrt:Lr,div:(x,S)=>F.mul(x,typeof S=="bigint"?t.inv(t.create(S)):F.inv(S)),pow:(x,S)=>MA(F,x,S),invertBatch:x=>nb(F,x),add:w,sub:y,mul:v,sqr:B,addN:w,subN:y,mulN:v,sqrN:B,inv:({c0:x,c1:S,c2:M})=>{let b=p.sub(p.sqr(x),p.mulByNonresidue(p.mul(M,S))),A=p.sub(p.mulByNonresidue(p.sqr(M)),p.mul(x,S)),R=p.sub(p.sqr(S),p.mul(x,M)),J=p.inv(p.add(p.mulByNonresidue(p.add(p.mul(M,A),p.mul(S,R))),p.mul(x,b)));return{c0:p.mul(J,b),c1:p.mul(J,A),c2:p.mul(J,R)}},fromBytes:x=>{if(x.length!==F.BYTES)throw new Error("fromBytes invalid length="+x.length);return{c0:p.fromBytes(x.subarray(0,p.BYTES)),c1:p.fromBytes(x.subarray(p.BYTES,2*p.BYTES)),c2:p.fromBytes(x.subarray(2*p.BYTES))}},toBytes:({c0:x,c1:S,c2:M})=>mi(p.toBytes(x),p.toBytes(S),p.toBytes(M)),cmov:({c0:x,c1:S,c2:M},{c0:b,c1:A,c2:R},J)=>({c0:p.cmov(x,b,J),c1:p.cmov(S,A,J),c2:p.cmov(M,R,J)}),fromBigSix:x=>{if(!Array.isArray(x)||x.length!==6)throw new Error("invalid Fp6 usage");return{c0:p.fromBigTuple(x.slice(0,2)),c1:p.fromBigTuple(x.slice(2,4)),c2:p.fromBigTuple(x.slice(4,6))}},frobeniusMap:({c0:x,c1:S,c2:M},b)=>({c0:p.frobeniusMap(x,b),c1:p.mul(p.frobeniusMap(S,b),U[b%6]),c2:p.mul(p.frobeniusMap(M,b),k[b%6])}),mulByFp2:({c0:x,c1:S,c2:M},b)=>({c0:p.mul(x,b),c1:p.mul(S,b),c2:p.mul(M,b)}),mulByNonresidue:({c0:x,c1:S,c2:M})=>({c0:p.mulByNonresidue(M),c1:x,c2:S}),mul1:({c0:x,c1:S,c2:M},b)=>({c0:p.mulByNonresidue(p.mul(M,b)),c1:p.mul(x,b),c2:p.mul(S,b)}),mul01({c0:x,c1:S,c2:M},b,A){let R=p.mul(x,b),J=p.mul(S,A);return{c0:p.add(p.mulByNonresidue(p.sub(p.mul(p.add(S,M),A),J)),R),c1:p.sub(p.sub(p.mul(p.add(b,A),p.add(x,S)),R),J),c2:p.add(p.sub(p.mul(p.add(x,M),b),R),J)}}},P=_B(p,f,t.ORDER,12,1,6)[0],I=({c0:x,c1:S},{c0:M,c1:b})=>({c0:F.add(x,M),c1:F.add(S,b)}),D=({c0:x,c1:S},{c0:M,c1:b})=>({c0:F.sub(x,M),c1:F.sub(S,b)}),V=({c0:x,c1:S},M)=>{if(typeof M=="bigint")return{c0:F.mul(x,M),c1:F.mul(S,M)};let{c0:b,c1:A}=M,R=F.mul(x,b),J=F.mul(S,A);return{c0:F.add(R,F.mulByNonresidue(J)),c1:F.sub(F.mul(F.add(x,S),F.add(b,A)),F.add(R,J))}},K=({c0:x,c1:S})=>{let M=F.mul(x,S);return{c0:F.sub(F.sub(F.mul(F.add(F.mulByNonresidue(S),x),F.add(x,S)),M),F.mulByNonresidue(M)),c1:F.add(M,M)}};function q(x,S){let M=p.sqr(x),b=p.sqr(S);return{first:p.add(p.mulByNonresidue(b),M),second:p.sub(p.sub(p.sqr(p.add(x,S)),M),b)}}let G={ORDER:p.ORDER,isLE:F.isLE,BITS:2*F.BITS,BYTES:2*F.BYTES,MASK:ip(2*F.BITS),ZERO:{c0:F.ZERO,c1:F.ZERO},ONE:{c0:F.ONE,c1:F.ZERO},create:x=>x,isValid:({c0:x,c1:S})=>F.isValid(x)&&F.isValid(S),is0:({c0:x,c1:S})=>F.is0(x)&&F.is0(S),isValidNot0:x=>!G.is0(x)&&G.isValid(x),neg:({c0:x,c1:S})=>({c0:F.neg(x),c1:F.neg(S)}),eql:({c0:x,c1:S},{c0:M,c1:b})=>F.eql(x,M)&&F.eql(S,b),sqrt:Lr,inv:({c0:x,c1:S})=>{let M=F.inv(F.sub(F.sqr(x),F.mulByNonresidue(F.sqr(S))));return{c0:F.mul(x,M),c1:F.neg(F.mul(S,M))}},div:(x,S)=>G.mul(x,typeof S=="bigint"?t.inv(t.create(S)):G.inv(S)),pow:(x,S)=>MA(G,x,S),invertBatch:x=>nb(G,x),add:I,sub:D,mul:V,sqr:K,addN:I,subN:D,mulN:V,sqrN:K,fromBytes:x=>{if(x.length!==G.BYTES)throw new Error("fromBytes invalid length="+x.length);return{c0:F.fromBytes(x.subarray(0,F.BYTES)),c1:F.fromBytes(x.subarray(F.BYTES))}},toBytes:({c0:x,c1:S})=>mi(F.toBytes(x),F.toBytes(S)),cmov:({c0:x,c1:S},{c0:M,c1:b},A)=>({c0:F.cmov(x,M,A),c1:F.cmov(S,b,A)}),fromBigTwelve:x=>({c0:F.fromBigSix(x.slice(0,6)),c1:F.fromBigSix(x.slice(6,12))}),frobeniusMap(x,S){let{c0:M,c1:b,c2:A}=F.frobeniusMap(x.c1,S),R=P[S%12];return{c0:F.frobeniusMap(x.c0,S),c1:F.create({c0:p.mul(M,R),c1:p.mul(b,R),c2:p.mul(A,R)})}},mulByFp2:({c0:x,c1:S},M)=>({c0:F.mulByFp2(x,M),c1:F.mulByFp2(S,M)}),conjugate:({c0:x,c1:S})=>({c0:x,c1:F.neg(S)}),mul014:({c0:x,c1:S},M,b,A)=>{let R=F.mul01(x,M,b),J=F.mul1(S,A);return{c0:F.add(F.mulByNonresidue(J),R),c1:F.sub(F.sub(F.mul01(F.add(S,x),M,p.add(b,A)),R),J)}},mul034:({c0:x,c1:S},M,b,A)=>{let R=F.create({c0:p.mul(x.c0,M),c1:p.mul(x.c1,M),c2:p.mul(x.c2,M)}),J=F.mul01(S,b,A),Q=F.mul01(F.add(x,S),p.add(M,b),A);return{c0:F.add(F.mulByNonresidue(J),R),c1:F.sub(Q,F.add(R,J))}},_cyclotomicSquare:n.Fp12cyclotomicSquare,_cyclotomicExp:n.Fp12cyclotomicExp,finalExponentiate:n.Fp12finalExponentiate};return{Fp:t,Fp2:p,Fp6:F,Fp12:G,Fp4Square:q}}var Tye=BigInt(0),uT=BigInt(1),Qd=BigInt(2),Pye=BigInt(3),EY=BigInt(6),QA=BigInt("4965661367192848881"),Rye=tb(QA),Mye=EY*QA**Qd,VA={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:uT,a:Tye,b:Pye,Gx:uT,Gy:BigInt(2)},jV=lb(VA.n),xY={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:ab,Fp2:sn,Fp6:dT,Fp4Square:$B,Fp12:en}=Bye({ORDER:VA.p,FP2_NONRESIDUE:[BigInt(9),uT],Fp2mulByB:n=>sn.mul(n,xY),Fp12cyclotomicSquare:({c0:n,c1:e})=>{let{c0:t,c1:r,c2:i}=n,{c0:o,c1:s,c2:a}=e,{first:l,second:c}=$B(t,s),{first:u,second:d}=$B(o,i),{first:h,second:f}=$B(r,a),p=sn.mulByNonresidue(f);return{c0:dT.create({c0:sn.add(sn.mul(sn.sub(l,t),Qd),l),c1:sn.add(sn.mul(sn.sub(u,r),Qd),u),c2:sn.add(sn.mul(sn.sub(h,i),Qd),h)}),c1:dT.create({c0:sn.add(sn.mul(sn.add(p,o),Qd),p),c1:sn.add(sn.mul(sn.add(c,s),Qd),c),c2:sn.add(sn.mul(sn.add(d,a),Qd),d)})}},Fp12cyclotomicExp(n,e){let t=en.ONE;for(let r=Rye-1;r>=0;r--)t=en._cyclotomicSquare(t),_ge(e,r)&&(t=en.mul(t,n));return t},Fp12finalExponentiate:n=>{let e=u=>en.conjugate(en._cyclotomicExp(u,QA)),t=en.mul(en.conjugate(n),en.inv(n)),r=en.mul(en.frobeniusMap(t,2),t),i=en._cyclotomicSquare(e(r)),o=en.mul(en._cyclotomicSquare(i),i),s=e(o),a=e(en._cyclotomicSquare(s)),l=en.mul(en.mul(en.conjugate(a),s),en.conjugate(o)),c=en.mul(l,i);return en.mul(en.frobeniusMap(en.mul(en.conjugate(r),c),3),en.mul(en.frobeniusMap(l,2),en.mul(en.frobeniusMap(c,1),en.mul(en.mul(l,s),r))))}}),{G2psi:Fye,psi:WV}=Lye(ab,sn,sn.NONRESIDUE),eT=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:ab.ORDER,m:2,k:128,expand:"xmd",hash:IT}),kye=(n,e,t,r,i,o)=>{let s=WV(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=WV(s[0],s[1]);o(n,e,t,a[0],sn.neg(a[1]))},Oye={p:sn.ORDER,n:VA.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:sn.ZERO,b:xY,Gx:sn.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:sn.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},op=Dye({fields:{Fp:ab,Fp2:sn,Fp6:dT,Fp12:en,Fr:jV},G1:{...VA,Fp:ab,htfDefaults:{...eT,m:1,DST:"BN254G2_XMD:SHA-256_SVDW_RO_"},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:Lr,fromBytes:Lr,toBytes:Lr,ShortSignature:{fromBytes:Lr,fromHex:Lr,toBytes:Lr,toRawBytes:Lr,toHex:Lr}},G2:{...Oye,Fp:sn,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...eT},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(Mye).equals(Fye(n,e)),mapToCurve:Lr,fromBytes:Lr,toBytes:Lr,Signature:{fromBytes:Lr,fromHex:Lr,toBytes:Lr,toRawBytes:Lr,toHex:Lr}},params:{ateLoopSize:QA*EY+Qd,r:jV.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:eT,hash:IT,postPrecompute:kye});vye({a:BigInt(0),b:BigInt(3),Fp:ab,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:IT});var AY="groth16",Gye="auth",Nye="authV2",Uye=new TextDecoder,ZV=BigInt(0),XV=op.fields.Fp2,_V=op.fields.Fp12;async function vY(n,e,t){let r=await Uge(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:l}=await DA.prove(e,s);return{proof:a,pub_signals:l}}var[fT,Hye]=[op.G1.ProjectivePoint,op.G2.ProjectivePoint],PA=([n,e])=>fT.fromAffine({x:BigInt(n),y:BigInt(e)}),RA=([[n,e],[t,r]])=>Hye.fromAffine({x:XV.fromBigTuple([BigInt(n),BigInt(e)]),y:XV.fromBigTuple([BigInt(t),BigInt(r)])});async function CY(n,e,t,r){if(r(e.pub_signals).challenge!==Hb(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(Uye.decode(t));return CT(e,o)}function CT(n,e){if(!e.IC)throw new Error("verification file doesn't exist for circuit");let{proof:t,pub_signals:r}=n;if(r.length+1!==e.IC.length)throw new Error(`Invalid number of public signals, expected ${e.IC.length-1} but got ${r.length}`);let i=fT.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<ZV||BigInt(r[s])>=op.G1.CURVE.n)throw new Error(`Input value is not in the field ${op.G1.CURVE.n}`);if(BigInt(r[s])!==ZV){let[a,l]=e.IC[s+1].map(BigInt);i=i.add(fT.fromAffine({x:a,y:l}).multiply(BigInt(r[s])))}}i=i.add(PA(e.IC[0]));let o=op.pairingBatch([{g1:PA(t.pi_a).negate(),g2:RA(t.pi_b)},{g1:i,g2:RA(e.vk_gamma_2)},{g1:PA(t.pi_c),g2:RA(e.vk_delta_2)},{g1:PA(e.vk_alpha_1),g2:RA(e.vk_beta_2)}]);return _V.eql(o,_V.ONE)}var hT=class{methodAlg;constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}unmarshall(e){let t={};if(e.length!=3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return t.challenge=BigInt(e[0]),t.userState=BigInt(e[1]),t.userId=Je.fromBigInt(BigInt(e[2])),t}async verify(e,t,r){return CY(e,t,r,this.unmarshall)}prove(e,t,r){return vY(e,t,r)}},pT=new hT(new ru(AY,Gye)),mT=class n{methodAlg;static curveName="bn128";constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}async verify(e,t,r){return CY(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await vY(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await EA(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:Je.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:me.fromString(e[2])}}},gT=new mT(new ru(AY,Nye));yT(pT.methodAlg,()=>pT);yT(gT.methodAlg,()=>gT);var gi={registerProvingMethod:yT,getProvingMethod:tY,provingMethodGroth16AuthInstance:pT,provingMethodGroth16AuthV2Instance:gT};var Kye=(n,e)=>(Object.keys(e).forEach(t=>{if(!n[t]||typeof e[t]!=typeof n[t])return!1}),!0),Jye=n=>{let e=zq();return Object.keys(e).forEach(t=>{if(!n[t]||t!=="body"&&!(typeof e[t]==typeof n[t]))return!1}),!0};var SY=n=>{let e=tt.decode(n),t=JSON.parse(e);if(!Jye(t))throw new Error(Wq);return t};var DY=n=>{let e=jq(),t=tt.decode(n),r=JSON.parse(t);if(!Kye(r,e))throw new Error(Zq);return r};var ST=class{packers;constructor(){this.packers=new Map}getSupportedProfiles(){let e=[],t=this.getSupportedMediaTypes();for(let r of t){let i=this.packers.get(r);i&&e.push(...i.getSupportedProfiles())}return[...new Set(e)]}isProfileSupported(e,t){let r=this.packers.get(e);return r?r.isProfileSupported(t):!1}getSupportedMediaTypes(){return[...this.packers.keys()]}registerPackers(e){e.forEach(t=>{this.packers.set(t.mediaType(),t)})}async pack(e,t,r){let i=this.packers.get(e);if(!i)throw new Error(`packer for media type ${e} not found`);return await i.pack(t,r)}packMessage(e,t,r){let i=this.packers.get(e);if(!i)throw new Error(`packer for media type ${e} not found`);return i.packMessage(t,r)}async unpack(e){let r=tt.decode(e).trim(),i=this.getMediaType(r);return{unpackedMessage:await this.unpackWithSafeEnvelope(i,Me.encode(r)),unpackedMediaType:i}}async unpackWithType(e,t){let o=new TextDecoder("utf-8").decode(t).trim();return await this.unpackWithSafeEnvelope(e,Me.encode(o))}async unpackWithSafeEnvelope(e,t){let r=this.packers.get(e);if(!r)throw new Error(`packer for media type ${e} not found`);return await r.unpack(t)}getMediaType(e){let t;if(e[0]==="{")return JSON.parse(e).typ;{let i=e.split(".")[0];t=$m.parse(i,{loose:!0})}return DY(t).typ}};var yi={};sr(yi,{AcceptAuthCircuits:()=>YA,AcceptJwsAlgorithms:()=>Jm,AcceptJwzAlgorithms:()=>zA,DEFAULT_AUTH_VERIFY_DELAY:()=>LT,DEFAULT_PROOF_VERIFY_DELAY:()=>qye,MediaType:()=>Sc,PROTOCOL_MESSAGE_TYPE:()=>je,ProtocolVersion:()=>Km,SUPPORTED_PUBLIC_KEY_TYPES:()=>Hm,defaultAcceptProfile:()=>ub});var ir="https://iden3-communication.io/",DT="https://didcomm.org/",je=Object.freeze({AUTHORIZATION_REQUEST_MESSAGE_TYPE:`${ir}authorization/1.0/request`,AUTHORIZATION_RESPONSE_MESSAGE_TYPE:`${ir}authorization/1.0/response`,CREDENTIAL_ISSUANCE_REQUEST_MESSAGE_TYPE:`${ir}credentials/1.0/issuance-request`,CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:`${ir}credentials/1.0/fetch-request`,CREDENTIAL_OFFER_MESSAGE_TYPE:`${ir}credentials/1.0/offer`,CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:`${ir}credentials/1.0/issuance-response`,CREDENTIAL_REFRESH_MESSAGE_TYPE:`${ir}credentials/1.0/refresh`,DEVICE_REGISTRATION_REQUEST_MESSAGE_TYPE:`${ir}devices/1.0/registration`,MESSAGE_FETCH_REQUEST_MESSAGE_TYPE:`${ir}messages/1.0/fetch`,PROOF_GENERATION_REQUEST_MESSAGE_TYPE:`${ir}proofs/1.0/request`,PROOF_GENERATION_RESPONSE_MESSAGE_TYPE:`${ir}proofs/1.0/response`,REVOCATION_STATUS_REQUEST_MESSAGE_TYPE:`${ir}revocation/1.0/request-status`,REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE:`${ir}revocation/1.0/status`,CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE:`${ir}proofs/1.0/contract-invoke-request`,CONTRACT_INVOKE_RESPONSE_MESSAGE_TYPE:`${ir}proofs/1.0/contract-invoke-response`,CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE:`${ir}credentials/1.0/onchain-offer`,PROPOSAL_REQUEST_MESSAGE_TYPE:`${ir}credentials/0.1/proposal-request`,PROPOSAL_MESSAGE_TYPE:`${ir}credentials/0.1/proposal`,PAYMENT_REQUEST_MESSAGE_TYPE:`${ir}credentials/0.1/payment-request`,PAYMENT_MESSAGE_TYPE:`${ir}credentials/0.1/payment`,DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:`${DT}discover-features/2.0/queries`,DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE:`${DT}discover-features/2.0/disclose`,PROBLEM_REPORT_MESSAGE_TYPE:`${DT}report-problem/2.0/problem-report`}),Sc=(r=>(r.ZKPMessage="application/iden3-zkp-json",r.PlainMessage="application/iden3comm-plain-json",r.SignedMessage="application/iden3comm-signed-json",r))(Sc||{}),Hm={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","JsonWebKey2020"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","JsonWebKey2020"]},Km=(e=>(e.V1="iden3comm/v1",e))(Km||{}),YA=(t=>(t.AuthV2="authV2",t.AuthV3="authV3",t))(YA||{}),zA=(e=>(e.Groth16="groth16",e))(zA||{}),Jm=(t=>(t.ES256K="ES256K",t.ES256KR="ES256K-R",t))(Jm||{}),ub={protocolVersion:"iden3comm/v1",env:"application/iden3-zkp-json",circuits:["authV2"],alg:["groth16"]},qye=3600*1e3,LT=300*1e3;var Qye="authentication",jA=n=>{let e=n.verificationMethod||[],t=(n[Qye]||[]).map(r=>typeof r=="string"?e.find(i=>i.id===r):r).filter(r=>r);for(let r=0;r<e.length;r++){let i=e[r].id;t.findIndex(o=>o.id===i)===-1&&t.push(e[r])}return t},BT=n=>{let e=Object.keys(Hm).some(t=>Hm[t].includes(n.type));if(n.publicKeyBase58&&e)return{publicKeyBytes:M3(n.publicKeyBase58),kmsKeyType:"Secp256k1"};if(n.publicKeyBase64&&e)return{publicKeyBytes:jd(n.publicKeyBase64),kmsKeyType:"Secp256k1"};if(n.publicKeyHex&&e)return{publicKeyBytes:To(n.publicKeyHex),kmsKeyType:"Secp256k1"};if(n.publicKeyJwk&&n.publicKeyJwk.crv==="secp256k1"&&n.publicKeyJwk.x&&n.publicKeyJwk.y){let[t,r]=[jd(n.publicKeyJwk.x),jd(n.publicKeyJwk.y)].map(xi),i=t.includes("0x")?BigInt(t):BigInt(`0x${t}`),o=r.includes("0x")?BigInt(r):BigInt(`0x${r}`);return{publicKeyBytes:No.ProjectivePoint.fromAffine({x:i,y:o}).toRawBytes(!1),kmsKeyType:"Secp256k1"}}return{publicKeyBytes:null}};function Vye(n){return Object.values(Km).includes(n)}function Yye(n){return Object.values(Sc).includes(n)}function zye(n){return Object.values(YA).includes(n)}function jye(n){return Object.values(Jm).includes(n)}function Wye(n){return Object.values(zA).includes(n)}var Zye=n=>{let e=[];for(let t of n){let r=`${t.protocolVersion};env=${t.env}`;t.circuits?.length&&(r+=`;circuitId=${t.circuits.join(",")}`),t.alg?.length&&(r+=`;alg=${t.alg.join(",")}`),e.push(r)}return e},Ta=n=>{let e=n.split(";");if(e.length<2)throw new Error("Invalid accept profile");let t=e[0].trim();if(!Vye(t))throw new Error(`Protocol version '${t}' not supported`);if(e[1].split("=").length!==2)throw new Error("Invalid accept profile 'env' parameter");let i=e[1].split("=")[1].trim();if(!Yye(i))throw new Error(`Envelop '${i}' not supported`);let o=e.findIndex(c=>c.includes("circuitId="));if(i!=="application/iden3-zkp-json"&&o>0)throw new Error(`Circuits not supported for env '${i}'`);let s;o>0&&(s=e[o].split("=")[1].split(",").map(c=>c.trim()).map(c=>{if(!zye(c))throw new Error(`Circuit '${c}' not supported`);return c}));let a=e.findIndex(c=>c.includes("alg=")),l;if(a>0)if(i==="application/iden3-zkp-json")l=e[a].split("=")[1].split(",").map(c=>{if(c=c.trim(),!Wye(c))throw new Error(`Algorithm '${c}' not supported for '${i}'`);return c});else if(i==="application/iden3comm-signed-json")l=e[a].split("=")[1].split(",").map(c=>{if(c=c.trim(),!jye(c))throw new Error(`Algorithm '${c}' not supported for '${i}'`);return c});else throw new Error(`Algorithm not supported for '${i}'`);return{protocolVersion:t,env:i,circuits:s,alg:l}};var{getProvingMethod:Xye}=gi,TT=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},PT=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},RT=class{constructor(e,t,r={acceptedStateTransitionDelay:LT}){this.provingParamsMap=e;this.verificationParamsMap=t;this._opts=r}supportedProtocolVersions=["iden3comm/v1"];supportedAlgorithms=["groth16"];supportedCircuitIds=["authV2"];packMessage(e,t){return this.pack(Me.encode(JSON.stringify(e)),t)}async pack(e,t){let r=await Xye(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(tQ);let o=new Nm(r,tt.decode(e),(a,l)=>i?.dataPreparer?.prepare(a,t.senderDID,l));o.setHeader(Gs.Type,"application/iden3-zkp-json");let s=await o.prove(i.provingKey,i.wasm);return Me.encode(s)}async unpack(e){let t=await Nm.parse(tt.decode(e)),r=new ru(t.alg,t.circuitId),i=this.verificationParamsMap.get(r.toString());if(!i?.key)throw new Error(_q);if(!await t.verify(i?.key))throw new Error($q);if(!await i?.verificationFn?.verify(t.circuitId,t.zkProof.pub_signals,this._opts))throw new Error(eQ);let a=SY(Me.encode(t.getPayload()));return _ye(t,a),a}mediaType(){return"application/iden3-zkp-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")};circuitIds=${this.supportedCircuitIds.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=Ta(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;let s=this.supportedCircuitIds,a=!i?.length||i.some(u=>s.includes(u)),l=this.supportedAlgorithms;return(!o?.length||o.some(u=>l.includes(u)))&&a}},_ye=async(n,e)=>{switch(n.circuitId){case"authV2":{if(!e.from)throw new Error(rA);let t=new La().pubSignalsUnmarshal(Me.encode(JSON.stringify(n.zkProof.pub_signals))),r=Ie.parseFromId(t.userID),i=await n.getMessageHash();if(ht.bytesToInt(i.reverse())!==t.challenge)throw new Error(rA);if(e.from!==r.string())throw new Error(rA)}break;default:throw new Error(Xq)}};var MT=class{supportedProtocolVersions=["iden3comm/v1"];packMessage(e){return e.typ="application/iden3comm-plain-json",Promise.resolve(Me.encode(JSON.stringify(e)))}async pack(e){let t=JSON.parse(tt.decode(e));return t.typ="application/iden3comm-plain-json",Promise.resolve(Me.encode(JSON.stringify(t)))}async unpack(e){return JSON.parse(tt.decode(e))}mediaType(){return"application/iden3comm-plain-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=Ta(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);if(o)throw new Error(`Algorithms are not supported for ${r} media type`);return!0}};var FT=class{constructor(e,t){this._kms=e;this._documentResolver=t}supportedAlgorithms=["ES256K","ES256K-R"];supportedProtocolVersions=["iden3comm/v1"];packMessage(e,t){return this.packInternal(e,t)}async pack(e,t){let r=JSON.parse(tt.decode(e));return this.packInternal(r,t)}async unpack(e){let t=tt.decode(e),[r,i]=t.split("."),o=JSON.parse(Vb(r)),s=JSON.parse(Vb(i)),a=lG(o.kid)?.did;if(a&&a!==s.from)throw new Error(`Sender does not match DID in message with kid ${o?.kid}`);let l=await this.resolveDidDoc(s.from),c=jA(l);if(!c?.length)throw new Error(`No verification methods defined in the DID document of ${l.id}`);if(o.kid){let d=c.find(h=>h.id===o.kid);if(!d)throw new Error(`verification method with specified kid ${o.kid} is not found in the DID Document`);c=[d]}if(!LG(t,c))throw new Error("JWS verification failed");return s}mediaType(){return"application/iden3comm-signed-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=Ta(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);return!o?.length||o.some(a=>this.supportedAlgorithms.includes(a))}async resolveDidDoc(e){let t;try{let r=await this._documentResolver.resolve(e);if(!r?.didDocument?.id)throw new Error(`did document for ${e} is not found in resolution result`);t=r.didDocument}catch(r){throw new Error(`did document for ${e} is not resolved: ${r.message}`)}return t}async packInternal(e,t){if(!t.alg)throw new Error("Missing algorithm");let r=e.from??"";if(!r)throw new Error("Missing sender DID");if(!Hm[t.alg]?.length)throw new Error(`No supported verification methods for algorithm ${t.alg}`);let o=t.didDocument??await this.resolveDidDoc(r),s=jA(o);if(!s.length)throw new Error(`No verification methods defined in the DID document of ${o.id}`);let a=t.kid?s.find(v=>v.id===t.kid):s[0];if(!a)throw new Error(`No key found with id ${t.kid} in DID document of ${o.id}`);let{publicKeyBytes:l,kmsKeyType:c}=BT(a);if(!l&&!c&&(a.blockchainAccountId||a.ethereumAddress)&&!t.signer)throw new Error(`No signer provided for ${a.blockchainAccountId||a.ethereumAddress}`);let u=a.id,d={alg:t.alg,kid:u,typ:"application/iden3comm-signed-json"},h=Qb(JSON.stringify(d)),f=Qb(JSON.stringify(e)),p=`${h}.${f}`,w=Me.encode(p),y;if(t.signer){let v=await t.signer(a,w);y=qb(v)}else{if(!l)throw new Error("No public key found");if(!c)throw new Error("No KMS key type found");let v=await this._kms.sign({type:c,id:qs(c,xi(l))},w,{alg:t.alg});y=qb(v)}return Me.encode(`${p}.${y}`)}};var LY=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(LY||{});var kT=(t=>(t.AUTHV2="authV2",t.ETH_IDENTITY="ethIdentity",t))(kT||{});var BY=(e=>(e.FeatureType="feature-type",e))(BY||{}),TY=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(TY||{});var $ye=n=>n.reduce((e,t)=>{let r=t.query.groupId;if(!r)return e;let i=e.get(r);if(!i){let s=Ma(12),l=new DataView(s.buffer).getUint32(0);return e.set(r,{query:t.query,linkNonce:l}),e}let o=F3(i.query.credentialSubject,t.query.credentialSubject);return e.set(r,{...i,query:{skipClaimRevocationCheck:i.query.skipClaimRevocationCheck||t.query.skipClaimRevocationCheck,...i.query,credentialSubject:o}}),e},new Map),qm=async(n,e,t,r,i)=>{let o=e??[],s=$ye(o),a=new Map,l=[];for(let c of o){let u;try{if(!i.supportedCircuits.includes(c.circuitId)){if(c.optional)continue;throw new Error(`Circuit ${c.circuitId} is not allowed`)}let h=c.query,f=h.groupId,p=s.get(f);if(f){if(!p)throw new Error(`Invalid group id ${h.groupId}`);let y=p.query;if(!a.has(f)){let v=await r.findCredentialByProofQuery(n,p.query);if(!v.cred){if(c.optional)continue;throw new Error(Fe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(y)}`)}a.set(f,v)}}let w=a.get(f);u=await r.generateProof(c,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h.skipClaimRevocationCheck,credential:w?.cred,credentialRevocationStatus:w?.revStatus,linkNonce:p?.linkNonce?BigInt(p.linkNonce):void 0})}catch(d){let h=[Fe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,Fe.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,Fe.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(Fe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY))&&c.optional)continue;throw d}l.push(u)}return l},OT=async(n,e,t)=>{switch(t.acceptProfile||(t.acceptProfile=ub),t.acceptProfile.env){case"application/iden3-zkp-json":if(!t.acceptProfile.circuits)throw new Error("Circuit not specified in accept profile");for(let r of t.acceptProfile.circuits){if(!t.supportedCircuits.includes(r))throw new Error(`Circuit ${r} is not supported`);if(!t.senderAddress)throw new Error("Sender address is not provided");let i=PY(t.senderAddress,t.zkpResponses),o=await e.generateAuthProof(r,n,{challenge:i});return{authProof:{authMethod:"authV2",zkp:o}}}throw new Error("Auth method is not supported");case"application/iden3comm-signed-json":if(!t.acceptProfile.alg||t.acceptProfile.alg.length===0)throw new Error("Algorithm not specified");if(t.acceptProfile.alg[0]==="ES256K-R")return{authProof:{authMethod:"ethIdentity",userDid:n}};throw new Error(`Algorithm ${t.acceptProfile.alg[0]} not supported`);default:throw new Error("Accept env not supported")}},db=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=Zh(n.proof),o=tA(t,i.a,i.b,i.c);return{requestId:e,zkProofEncoded:o,metadata:r}},PY=(n,e)=>{let t=e.map(r=>{let i=db(r);return{requestId:i.requestId,proof:i.zkProofEncoded,metadata:i.metadata}});return BigInt(nn.keccak256(new nn.AbiCoder().encode(["address","(uint256 requestId,bytes proof,bytes metadata)[]"],[n,t])))&BigInt("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")},ewe=n=>new nn.AbiCoder().encode(["tuple(string key,bytes value)[]"],[n]),Qn=n=>{if(n?.expires_time&&n.expires_time<Bt(new Date))throw new Error("Message expired")};var Xr=class{nextMessageHandler;setNext(e){return this.nextMessageHandler=e,e}async handle(e,t){return t.allowExpiredMessages||Qn(e),this.nextMessageHandler?this.nextMessageHandler.handle(e,t):Promise.reject("Message handler not provided or message not supported")}},GT=class{constructor(e){this._params=e;this.registerHandlers(e.messageHandlers)}messageHandler;registerHandlers(e){if(!e.length)return;let[t,...r]=e,i=t;for(let o of r){let s=i;for(;s.nextMessageHandler;)s=s.nextMessageHandler;s.setNext(o)}this.messageHandler?this.messageHandler.setNext(t):this.messageHandler=t}async handleMessage(e,t){let{unpackedMediaType:r,unpackedMessage:i}=await this._params.packageManager.unpack(e);if(!this.messageHandler)return Promise.reject(new Error("Message handler not provided"));let o=await this.messageHandler.handle(i,t);if(!o)return null;let s={},a=t?.senderDid;return r==="application/iden3-zkp-json"&&a?(s={senderDID:a,provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};function twe(n,e,t,r){return RY(n,"",e,t,r)}function RY(n,e,t,r,i){let o=Et();return{id:o,thid:o,from:t,typ:"application/iden3comm-plain-json",type:je.AUTHORIZATION_REQUEST_MESSAGE_TYPE,body:{accept:i?.accept,reason:n,message:e,callbackUrl:r,scope:i?.scope??[]},created_time:Bt(new Date),expires_time:i?.expires_time?Bt(i.expires_time):void 0}}var NT=class extends Xr{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=["credentialAtomicQueryV3-beta.1","credentialAtomicQuerySigV2","credentialAtomicQueryMTPV2","linkedMultiQuery10-beta.1"];handle(t,r){switch(t.type){case je.AUTHORIZATION_REQUEST_MESSAGE_TYPE:return this.handleAuthRequest(t,r);case je.AUTHORIZATION_RESPONSE_MESSAGE_TYPE:return this.handleAuthResponse(t,r);default:return super.handle(t,r)}}async parseAuthorizationRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i.body.scope=i.body.scope||[],i}async handleAuthRequest(t,r){if(t.type!==je.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for authorization request");let i=t.to?Ie.parse(t.to):r.senderDid,o=Et();if(!t.from)throw new Error("auth request should contain from field");let s=je.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,a=this.getSupportedMediaTypeByProfile(r,s,t.body.accept),l=Ie.parse(t.from),c=await qm(i,t?.body.scope,l,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits});return{id:o,typ:a,type:s,thid:t.thid??o,body:{message:t?.body?.message,scope:c},from:i.string(),to:t.from}}async handleAuthorizationRequest(t,r,i){let o=await this.parseAuthorizationRequest(r);if(i?.allowExpiredMessages||Qn(o),i||(i={mediaType:"application/iden3-zkp-json"}),i.mediaType==="application/iden3comm-signed-json"&&!i.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let s=await this.handleAuthRequest(o,{senderDid:t,mediaType:i.mediaType}),a=Me.encode(JSON.stringify(s)),l=i.mediaType==="application/iden3comm-signed-json"?i.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg},c=tt.decode(await this._packerMgr.pack(i.mediaType,a,{senderDID:t,...l}));return{authRequest:o,authResponse:s,token:c}}async handleAuthResponse(t,r){let i=r.request;if(t.type!==je.AUTHORIZATION_RESPONSE_MESSAGE_TYPE)throw new Error("Invalid message type for authorization response");if((i.body.message??"")!==(t.body.message??""))throw new Error("message for signing from request is not presented in response");if(i.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${i.from}, given ${t.to}`);this.verifyAuthRequest(i);let o=i.body.scope||[],s=t.body.scope||[];if(!t.from)throw new Error("proof response doesn't contain from field");let a=new Map;for(let l of o){let c=l.query.groupId,u=s.find(w=>w.id.toString()===l.id.toString());if(!u)throw new Error(`proof is not given for requestId ${l.id}`);let d=u.circuitId;if(d!==l.circuitId)throw new Error(`proof is not given for requested circuit expected: ${l.circuitId}, given ${d}`);let h=l.params??{};h.verifierDid=Ie.parse(i.from);let f=[r.acceptedProofGenerationDelay,r.acceptedStateTransitionDelay].some(w=>w!==void 0)?{acceptedProofGenerationDelay:r.acceptedProofGenerationDelay,acceptedStateTransitionDelay:r.acceptedStateTransitionDelay}:void 0,{linkID:p}=await this._proofService.verifyZKPResponse(u,{query:l.query,sender:t.from,params:h,opts:f});p&&c&&a.set(c,[...a.get(c)??[],{linkID:p,requestId:u.id}])}for(let[l,c]of a.entries())if(c.some(u=>u.linkID!==c[0].linkID))throw new Error(`Link id validation failed for group ${l}, request linkID to requestIds info: ${JSON.stringify(c)}`);return t}async handleAuthorizationResponse(t,r,i){i?.allowExpiredMessages||Qn(t);let o=await this.handleAuthResponse(t,{request:r,acceptedStateTransitionDelay:i?.acceptedStateTransitionDelay,acceptedProofGenerationDelay:i?.acceptedProofGenerationDelay});return{request:r,response:o}}verifyAuthRequest(t){let r={},i=t.body.scope||[];for(let o of i){let s=o.query.groupId;if(s){let a=r[s]??[];for(let l of a){if(l.query.type!==o.query.type)throw new Error("all requests in the group should have the same type");if(l.query.context!==o.query.context)throw new Error("all requests in the group should have the same context");let c=o.query.allowedIssuers,u=l.query.allowedIssuers;if(!(c.includes("*")||c.every(d=>u.includes(d))))throw new Error("all requests in the group should have the same issuer")}r[s]=[...r[s]??[],o]}}}getSupportedMediaTypeByProfile(t,r,i){let o;if(!i?.length)return t.mediaType||"application/iden3-zkp-json";let s=[];for(let a of i){let{env:l}=Ta(a);this._packerMgr.isProfileSupported(l,a)&&s.push(l)}if(!s.length)throw new Error("no packer with profile which meets `accept` header requirements");return o=s.includes("application/iden3-zkp-json")?"application/iden3-zkp-json":s[0],t.mediaType&&s.includes(t.mediaType)&&(o=t.mediaType),o}};var MY=[{inputs:[],name:"MAX_SMT_DEPTH",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"key",type:"uint256"}],name:"getNode",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatus",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatusByIdAndState",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256[][]",name:"nodes",type:"uint256[][]"}],name:"saveNodes",outputs:[],stateMutability:"nonpayable",type:"function"}];var fb=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new Tt(e.url);let i=new $t(t,MY,this._provider);this._signer&&(this._signer=this._signer.connect(this._provider),i=i.connect(this._signer)),this._contract=i,this._transactionService=new _o(this._provider)}_contract;_provider;_transactionService;async getRevocationStatusByIdAndState(e,t,r){let i=await this._contract.getRevocationStatusByIdAndState(e,t,r),o=n.convertIssuerInfo(i.issuer),s=n.convertSmtProofToProof(i.mtp);return{issuer:o,mtp:s}}async getRevocationStatus(e,t){let r=await this._contract.getRevocationStatus(e,t),i=n.convertIssuerInfo(r.issuer),o=n.convertSmtProofToProof(r.mtp);return{issuer:i,mtp:o}}async saveNodes(e){if(!this._signer)throw new Error("No signer provided");let t=await this._provider.getFeeData(),r=this._config.maxFeePerGas?BigInt(this._config.maxFeePerGas):t.maxFeePerGas,i=this._config.maxPriorityFeePerGas?BigInt(this._config.maxPriorityFeePerGas):t.maxPriorityFeePerGas,o=await this._contract.saveNodes.estimateGas(e),s=await this._contract.saveNodes.populateTransaction(e),a={to:s.to,data:s.data,gasLimit:o,maxFeePerGas:r,maxPriorityFeePerGas:i},{txnReceipt:l}=await this._transactionService.sendTransactionRequest(this._signer,a);return l}static convertIssuerInfo(e){let[t,r,i,o]=e.map(s=>me.fromBigInt(s).hex());return{state:t,claimsTreeRoot:r,revocationTreeRoot:i,rootOfRoots:o}}static convertSmtProofToProof(e){let t,r=e.siblings?.map(i=>i.toString());return e.auxExistence&&(t={key:e.auxIndex.toString(),value:e.auxValue.toString()}),yt.fromJSON({existence:e.existence,node_aux:t,siblings:r})}};function rwe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function iwe(n){return(rwe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function Qm(n,e){return iwe(n).includes(e)}function hb(n){return Qm(n,Fe.ERRORS.IDENTITY_DOES_NOT_EXIST)||Qm(n,Fe.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function UT(n){return Qm(n,Fe.ERRORS.STATE_DOES_NOT_EXIST)||Qm(n,Fe.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function HT(n){return Qm(n,Fe.ERRORS.ROOT_DOES_NOT_EXIST)||Qm(n,Fe.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var KT=class{constructor(e,t){this._configs=e;this._stateStorage=new pb(e,t?.stateStorageOptions)}_stateStorage;async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");return this.getRevocationOnChain(e,t.issuerDID)}async getRevocationOnChain(e,t){let{contractAddress:r,chainId:i,revocationNonce:o,stateHex:s}=this.extractCredentialStatusInfo(e);if(o!==e.revocationNonce)throw new Error("revocationNonce does not match");let a=Ie.idFromDID(t),l;try{let h=await this._stateStorage.getLatestStateById(a.bigInt());if(!h.state)throw new Error("state contract returned empty state");l=h.state}catch(h){if(!hb(h))throw h;if(!s)throw new Error("latest state not found and state parameter is not present in credentialStatus.id");let f=me.fromHex(s).bigInt();if(!Za(t,f))throw new Error(`latest state not found and state parameter ${s} is not genesis state`);l=f}let c=Ie.idFromDID(t);return await this._getOnChainRevocationStorageForIssuer(i,r).getRevocationStatusByIdAndState(c.bigInt(),l,o)}extractCredentialStatusInfo(e){if(!e.id)throw new Error("credentialStatus id is empty");if(e.id.split("/").length!==2)throw new Error("invalid credentialStatus id");let r=new URL(e.id),i=r.searchParams.get("state")||"",o=r.searchParams.get("contractAddress");if(!o)throw new Error("contractAddress not found in credentialStatus.id field");let s=o.split(":");if(s.length!=2)throw new Error("invalid contract address encoding. should be chainId:contractAddress");let a=parseInt(s[0],10),l=s[1],c=r.searchParams.get("revocationNonce")||e.revocationNonce;if(c==null)throw new Error("revocationNonce not found in credentialStatus id field");let u=typeof c=="number"?c:parseInt(c,10);return{contractAddress:l,chainId:a,revocationNonce:u,stateHex:i}}networkByChainId(e){let t=this._configs.find(r=>r.chainId===e);if(!t)throw new Error(`chainId "${e}" not supported`);return t}_getOnChainRevocationStorageForIssuer(e,t){let r=this.networkByChainId(e);return new fb(r,t)}};var sp=class{async resolve(e){let r=await(await fetch(e.id)).json();return WA(r)}},WA=({issuer:n,mtp:e})=>({mtp:yt.fromJSON(e),issuer:n});var ap=class n{constructor(e=Le,t=[]){this.hash=e;this.children=t}nodeType(){return this.children.length===2?1:this.children.length===3&&this.children[2].hex()===me.fromBigInt(BigInt(1)).hex()?2:this.children.length===3?3:0}toJSON(){return{hash:this.hash.hex(),children:this.children.map(e=>e.hex())}}static fromHex(e){return new n(me.fromHex(e.hash),e.children.map(t=>me.fromHex(t)))}};var JT=class{constructor(e){this._state=e}async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");try{return await this.getStatus(e,t.issuerDID,t.issuerData,t.issuerGenesisState)}catch(r){if(e?.statusIssuer?.type==="SparseMerkleTreeProof")try{return await new sp().resolve(e.statusIssuer)}catch(i){throw new Error(`can't fetch revocation status from backup endpoint: ${i?.message}`)}throw new Error(`can't fetch revocation status: ${r?.message}`)}}async getStatus(e,t,r,i){let o=Ie.idFromDID(t),s;try{let u=await this._state.getLatestStateById(o.bigInt());if(!u.state)throw new Error("state contract returned empty state");s=u.state}catch(u){if(!hb(u))throw u;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=me.fromHex(d).bigInt(),f=Hf(t);if(!f&&!Za(t,h))throw new Error(`latest state not found and state parameter ${d} is not genesis state`);if(f)throw new Error("State must be published for Ethereum based identity");s=h}let a=e.id.split("/node")[0],l=me.fromBigInt(BigInt(e.revocationNonce??0)),c=me.fromBigInt(s);return await this.getRevocationStatusFromRHS(l,c,a)}getRevocationStatusFromIssuerData(e,t,r){if(r&&Za(e,r.value.bigInt()))return{mtp:new yt,issuer:{state:r.value.hex(),revocationTreeRoot:r.revocationTreeRoot.hex(),rootOfRoots:r.rootOfRoots.hex(),claimsTreeRoot:r.claimsTreeRoot.hex()}};if(t&&Za(e,t.state.value))return{mtp:new yt,issuer:{state:t.state.value,revocationTreeRoot:t.state.revocationTreeRoot,rootOfRoots:t.state.rootOfRoots,claimsTreeRoot:t.state.claimsTreeRoot}};throw new Error("issuer data / genesis state param is empty")}async getRevocationStatusFromRHS(e,t,r){if(!r)throw new Error("HTTP reverse hash service URL is not specified");let o=(await(await fetch(`${r}/node/${t.hex()}`)).json())?.node;if(o.children.length!==3)throw new Error("state should has tree children");let s=t.hex(),[a,l,c]=o.children,u=me.fromHex(l);return{mtp:await this.rhsGenerateProof(u,e,`${r}/node`),issuer:{state:s,claimsTreeRoot:a,revocationTreeRoot:l,rootOfRoots:c}}}async rhsGenerateProof(e,t,r){let i=!1,o=[],s,a=()=>new yt({siblings:o,existence:i,nodeAux:s}),l=e;for(let c=0;c<t.bytes.length*8;c++){if(l.bytes.every(f=>f===0))return a();let d=(await(await fetch(`${r}/${l.hex()}`)).json())?.node,h=ap.fromHex(d);switch(h.nodeType()){case 2:return t.bytes.every((f,p)=>f===h.children[0].bytes[p])?(i=!0,a()):(s={key:h.children[0],value:h.children[1]},a());case 1:sg(t.bytes,c)?(l=h.children[1],o.push(h.children[0])):(l=h.children[0],o.push(h.children[1]));break;default:throw new Error(`found unexpected node type in tree ${h.hash.hex()}`)}}throw new Error("tree depth is too high")}extractState(e){return new URL(e).searchParams.get("state")}};function owe(n,e){let t=Ie.parse(n),r=Ie.idFromDID(t),{method:i,blockchain:o,networkId:s}=Ie.decodePartsFromId(r),a=ht.hexToBytes(e),l=ht.bytesToInt(a),c=Oa(i,o,s);return FY(Ie.idFromDID(t).bigInt(),l,c)}function FY(n,e,t){let r=Je.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var mb=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var gb=class{async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");if(!t?.userDID)throw new Error("UserDID is not set in options");if(typeof e.revocationNonce!="number")throw new Error("Revocation nonce is not set in credential status");let r=t.userDID.string(),i=t.issuerDID.string(),o=swe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return WA(a.body)}};function swe(n,e,t){return{id:Et(),typ:"application/iden3comm-plain-json",type:je.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE,body:{revocation_nonce:t},thid:Et(),from:n,to:e}}var yb=class{_publishers=new Map;register(e,...t){let r=this._publishers.get(e)??[];r.push(...t),this._publishers.set(e,r)}get(e){return this._publishers.get(e)}},qT=class{constructor(e){this._storage=e}async publish(e){if(!["Iden3OnchainSparseMerkleTreeProof2023"].includes(e.credentialStatusType))throw new Error(`On-chain publishing is not supported for credential status type ${e.credentialStatusType}`);let t=e.nodes.map(o=>o.children.map(s=>s.bigInt())),r=this._storage.saveNodes(t),i=e.onChain?.publishMode??"sync";switch(e.onChain?.txCallback&&(i="callback"),i){case"sync":await r;break;case"callback":{if(!e.onChain?.txCallback)throw new Error('txCallback is required for publishMode "callback"');let o=e.onChain?.txCallback;r.then(s=>o(s));break}case"async":{let o=_g.getInstance();r.then(s=>o.publish(qC.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},cp=class{async publish(e){if(!["Iden3ReverseSparseMerkleTreeProof"].includes(e.credentialStatusType))throw new Error(`On-chain publishing is not supported for credential status type ${e.credentialStatusType}`);let t=e.nodes.map(i=>i.toJSON()),r=await fetch(e.rhsUrl+"/node",{method:"post",body:JSON.stringify(t)});if(r.status!==200)throw new Error(`Failed to publish credential status. Status: ${r.status}`)}};var QT=class{constructor(e){this.didResolverUrl=e}async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");let r=`${this.didResolverUrl}/1.0/credential-status/${encodeURIComponent(t.issuerDID.string())}`;return await(await fetch(r,{method:"POST",body:JSON.stringify(e)})).json()}};var VT=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new mb,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new sp),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new gb))}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:Fe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Fe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(Fe.ERRORS.NO_AUTH_CRED_FOUND);for(let r=0;r<t.length;r++){let i=t[r];if(!(await this.getRevocationStatusFromCredential(i)).mtp.existence)return i}throw new Error("all auth bjj credentials are revoked")}async getAllAuthBJJCredentials(e){return this._storage.credential.findCredentialsByQuery({context:Fe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Fe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]})}async getRevocationStatusFromCredential(e){let t=e.getIden3SparseMerkleTreeProof(),r=e.getBJJSignature2021Proof(),i=t?t.issuerData.state:r?.issuerData.state,o=Ie.parse(e.issuer),s=Hl(o,e),a={issuerGenesisState:i,issuerDID:o,userDID:s};return this.getRevocationStatus(e.credentialStatus,a)}async getRevocationStatus(e,t){let r=this._credentialStatusResolverRegistry?.get(e.type);if(!r)throw new Error(`credential status resolver does not exist for ${e.type} type`);return r.resolve(e,t)}createCredential=(e,t,r)=>{if(!r.$metadata.uris.jsonLdContext)throw new Error("jsonLdContext is missing is the schema");let i={...t};return i.context=i.context??[],i.displayMethod?.type==="Iden3BasicDisplayMethodV1"&&!i.context.includes(Fe.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(Fe.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD),i.context.push(r.$metadata.uris.jsonLdContext),i.expiration=i.expiration?i.expiration*1e3:void 0,i.id=i.id?i.id:`urn:${Et()}`,i.issuanceDate=i.issuanceDate?i.issuanceDate*1e3:Date.now(),fr.fromCredentialRequest(e,i)};async findById(e){return this._storage.credential.findCredentialById(e)}async findByContextType(e,t){return this._storage.credential.findCredentialsByQuery({context:e,type:t})}async save(e){return this._storage.credential.saveCredential(e)}async saveAll(e){return this._storage.credential.saveAllCredentials(e)}async remove(e){return this._storage.credential.removeCredential(e)}async list(){return this._storage.credential.listCredentials()}async findByQuery(e){return this._storage.credential.findCredentialsByQuery(e)}async filterByCredentialSubject(e,t){return e.filter(r=>r.credentialSubject.id===t.string())}async findNonRevokedCredential(e){for(let t of e){let r=await this.getRevocationStatusFromCredential(t);if(!r.mtp.existence)return{cred:t,revStatus:r}}throw new Error(Fe.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function ZA(n,e,t,r){let i=await XA(r,e,n);await new cp().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function XA(n,e,t){let r=new YT;return n&&await cwe(r,e,n),await awe(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new ap(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function awe(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function cwe(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var YT=class{constructor(e=[],t=new Map){this.nodes=e;this.seen=t}async addKey(e,t){let{value:r,siblings:i}=await e.get(t),o=me.fromBigInt(t),s=me.fromBigInt(r),a=new Na(o,s),l=await lwe(i,a);for(let c of l)this.seen.get(c.hash.hex())||(this.nodes.push(c),this.seen.set(c.hash.hex(),!0))}addProofNode(e){let t=e.hash.hex();this.seen.get(t)||(this.nodes.push(e),this.seen.set(t,!0))}};async function lwe(n,e){if(e.type!==is)throw new Error("node is not a leaf");let t=await e.getKey(),r=n.length,i=new Array(r+1);for(let a=0;a<i.length;a++)i[a]=new ap;i[r].hash=t;let o=me.fromBigInt(BigInt(1));i[r].children=[e.entry[0],e.entry[1],o];let s=e.entry[0];for(let a=r-1;a>=0;a--){let l=sg(s.bytes,a);i[a].children=new Array(2),l?(i[a].children[0]=n[a],i[a].children[1]=t):(i[a].children[0]=t,i[a].children[1]=n[a]),i[a].hash=Wd([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var zT=class n extends Xr{constructor(t,r){super();this._packerMgr=t;this.opts=r}async handle(t,r){switch(t.type){case je.CREDENTIAL_OFFER_MESSAGE_TYPE:{let i=await this.handleOfferMessage(t,r);if(Array.isArray(i)){let o=this.opts?.credentialWallet;if(!o)throw new Error("Credential wallet is not provided");return await o.saveAll(i),null}return i}case je.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:return this.handleFetchRequest(t);case je.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:return this.handleIssuanceResponseMsg(t);case je.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE:{let i=await this.handleOnchainOfferMessage(t);if(Array.isArray(i)){let o=this.opts?.credentialWallet;if(!o)throw new Error("Credential wallet is not provided");return await o.saveAll(i),null}return i}default:return super.handle(t,r)}}async handleOnchainOfferMessage(t){if(!this.opts?.onchainIssuer)throw new Error("onchain issuer is not provided");let r=[];for(let i of t.body.credentials){let o=Ie.parse(t.from),s=Ie.parse(t.to),a=await this.opts.onchainIssuer.getCredential(o,s,BigInt(i.id));r.push(a)}return r}async handleOfferMessage(t,r){r.mediaType||(r.mediaType="application/iden3-zkp-json");let i=[];for(let o of t.body.credentials){let s=Et(),a={id:s,typ:r.mediaType,type:je.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE,thid:t.thid??s,body:{id:o.id},from:t.to,to:t.from},l=Me.encode(JSON.stringify(a)),c=r.mediaType==="application/iden3comm-signed-json"?r.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg},u=Ie.parse(t.to),d=tt.decode(await this._packerMgr.pack(r.mediaType,l,{senderDID:u,...c}));try{if(!t?.body?.url)throw new Error("could not fetch W3C credential, body url is missing");let f=await(await fetch(t.body.url,{method:"post",headers:{"Content-Type":"application/x-www-form-urlencoded",...r.headers},body:d})).arrayBuffer();if(!f.byteLength)throw new Error(`could not fetch , ${o?.id}, response is empty`);let{unpackedMessage:p}=await this._packerMgr.unpack(new Uint8Array(f));if(p.type!==je.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE)return p;i.push(fr.fromJSON(p.body.credential))}catch(h){throw new Error(`could not fetch protocol message for credential offer id: , ${o?.id}, error: ${h.message??h}`)}}return i}async handleCredentialOffer(t,r){if(r?.mediaType==="application/iden3comm-signed-json"&&!r.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let i=await n.unpackMessage(this._packerMgr,t,je.CREDENTIAL_OFFER_MESSAGE_TYPE);r?.allowExpiredMessages||Qn(i);let o=await this.handleOfferMessage(i,{mediaType:r?.mediaType,headers:r?.headers,packerOptions:r?.packerOptions});if(Array.isArray(o))return o;throw new Error("invalid protocol message response")}async handleOnchainOffer(t){let r=await n.unpackMessage(this._packerMgr,t,je.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE);return this.handleOnchainOfferMessage(r)}async handleFetchRequest(t){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");let r=Ie.parse(t.to),i=Ie.parse(t.from),o=t.body?.id;if(!o)throw new Error("invalid credential id in fetch request body");if(!this.opts?.credentialWallet)throw new Error("please, provide credential wallet in options");let s=await this.opts.credentialWallet.findById(o);if(!s)throw new Error("credential not found");if(Hl(r,s).string()!==i.string())throw new Error("credential subject is not a sender DID");return{id:Et(),type:je.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE,typ:t.typ??"application/iden3comm-plain-json",thid:t.thid??Et(),body:{credential:s},from:t.to,to:t.from}}async handleCredentialFetchRequest(t,r){let i=await n.unpackMessage(this._packerMgr,t,je.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);r?.allowExpiredMessages||Qn(i);let o=await this.handleFetchRequest(i);return this._packerMgr.pack("application/iden3comm-plain-json",Me.encode(JSON.stringify(o)),{})}async handleIssuanceResponseMsg(t){if(!this.opts?.credentialWallet)throw new Error("please provide credential wallet in options");if(!t.body?.credential)throw new Error("credential is missing in issuance response message");return await this.opts.credentialWallet.save(fr.fromJSON(t.body.credential)),null}async handleIssuanceResponseMessage(t,r){let i=await n.unpackMessage(this._packerMgr,t,je.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);return r?.allowExpiredMessages||Qn(i),await this.handleIssuanceResponseMsg(i),Uint8Array.from([])}static async unpackMessage(t,r,i){let{unpackedMessage:o}=await t.unpack(r),s=o;if(o.type!==i)throw new Error("Invalid message type");return s}};var jT=class extends Xr{constructor(t,r,i){super();this._packerMgr=t;this._proofService=r;this._zkpVerifier=i}_supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","authV2","credentialAtomicQueryV3-beta.1","linkedMultiQuery10-beta.1"];async handle(t,r){switch(t.type){case je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE:{let i=t,o=await this.handleContractInvoke(i,r);return this.createContractInvokeResponse(i,o)}default:return super.handle(t,r)}}async handleContractInvoke(t,r){if(t.type!==je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for contract invoke request");let{senderDid:i,ethSigner:o,challenge:s}=r;if(!r.ethSigner)throw new Error("Can't sign transaction. Provide Signer in options.");let{chain_id:a}=t.body.transaction_data;if(!Object.keys(ts).find(f=>ts[f]===a))throw new Error(`Invalid chain id ${a}`);let c=t.from?Ie.parse(t.from):void 0,{scope:u=[]}=t.body,d=await qm(i,u,c,this._proofService,{ethSigner:o,challenge:s??ht.bytesToInt(To(await o.getAddress())),supportedCircuits:this._supportedCircuits});switch(t.body.transaction_data.method_id.replace("0x","")){case"ade09fcd":{let f=await this._zkpVerifier.submitZKPResponseV2(o,t.body.transaction_data,d),p=new Map;for(let[w,y]of f)p.set(w,{responses:y});return t.body.transaction_data.txHash=f.keys().next().value,p}case"b68967e2":{let f=await this._zkpVerifier.submitZKPResponse(o,t.body.transaction_data,d),p=new Map;for(let[w,y]of f)p.set(w,{responses:[y]});return t.body.transaction_data.txHash=f.keys().next().value,p}case"06c86a91":{if(!t.to)throw new Error("failed message. empty 'to' field");let f=this.getFirstSupportedProfile(je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE,t.body.accept),p=Ie.parse(t.to),{authProof:w}=await OT(p,this._proofService,{supportedCircuits:this._supportedCircuits,acceptProfile:f,senderAddress:await o.getAddress(),zkpResponses:d}),y=await this._zkpVerifier.submitResponse(o,t.body.transaction_data,d,w);return t.body.transaction_data.txHash=y.keys().next().value,y}default:throw new Error("Not supported method id. Only 'b68967e2, ade09fcd and 06c86a91 are supported.'")}}getFirstSupportedProfile(t,r){if(r?.length)for(let i of r){let o=Ta(i),s=Number(t.split("/").at(-2));if(!(o.protocolVersion!=="iden3comm/v1"||o.protocolVersion==="iden3comm/v1"&&(s<1||s>=2))&&this._packerMgr.isProfileSupported(o.env,i))return o}return ub}async parseContractInvokeRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i.body.scope=i.body.scope||[],i}async createContractInvokeResponse(t,r){let i={id:t.id,thid:t.thid,type:je.CONTRACT_INVOKE_RESPONSE_MESSAGE_TYPE,from:t.to,to:t.from,body:{transaction_data:t.body.transaction_data,scope:[]},created_time:Bt(new Date)};for(let[o,s]of r){for(let a of s.responses)i.body.scope.push({txHash:o,...a});i.body={...i.body,crossChainProof:s.crossChainProof,authProof:s.authProof}}return i}async handleContractInvokeRequest(t,r,i){let o=await this.parseContractInvokeRequest(r);if(i.allowExpiredMessages||Qn(o),o.body.transaction_data.method_id!=="b68967e2")throw new Error("please use handle method to work with other method ids");if(o.type!==je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for contract invoke request");let{ethSigner:s,challenge:a}=i;if(!s)throw new Error("Can't sign transaction. Provide Signer in options.");let{chain_id:l}=o.body.transaction_data;if(!Object.keys(ts).find(h=>ts[h]===l))throw new Error(`Invalid chain id ${l}`);let u=o.from?Ie.parse(o.from):void 0,d=await qm(t,o?.body?.scope,u,this._proofService,{ethSigner:s,challenge:a,supportedCircuits:this._supportedCircuits});return this._zkpVerifier.submitZKPResponse(s,o.body.transaction_data,d)}};var WT=class{constructor(e){this._options=e}async refreshCredential(e,t){if(!e.refreshService)throw new Error("refreshService not specified for W3CCredential");if(e.refreshService.type!=="Iden3RefreshService2023")throw new Error(`refresh service type ${e.refreshService.type} is not supported`);let r=e.credentialSubject.id;if(!r)throw new Error("self credentials do not support refresh");let o={senderDID:Ie.parse(r),provingMethodAlg:new ru(gi.provingMethodGroth16AuthV2Instance.methodAlg.alg,"authV2")},s={id:Et(),typ:"application/iden3-zkp-json",type:je.CREDENTIAL_REFRESH_MESSAGE_TYPE,thid:Et(),body:{id:e.id,reason:t?.reason??"credential is expired"},from:r,to:e.issuer},a=Me.encode(JSON.stringify(s)),l=await this._options.packageManager.pack("application/iden3-zkp-json",a,o),c=await fetch(e.refreshService.id,{method:"post",headers:{"Content-Type":"application/json"},body:l});if(c.status!==200)throw new Error(`could not refresh W3C credential, return status ${c.status}`);let u=await c.json();if(!u.body?.credential)throw new Error("no credential in CredentialIssuanceMessage response");return fr.fromJSON(u.body.credential)}};var ZT=class extends Xr{constructor(t,r){super();this._packerMgr=t;this._identityWallet=r}handle(t,r){if(!r.senderDid)throw new Error("DID is required");if(!r.mediaType)throw new Error("mediaType is required");switch(t.type){case je.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE:return this.handleRevocationStatusRequestMessage(t,r);default:return super.handle(t,r)}}async handleRevocationStatusRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body?.revocation_nonce)throw new Error("failed request. empty 'revocation_nonce' field");let i=Ie.parse(t.to),o=await this._identityWallet.generateNonRevocationMtpWithNonce(i,BigInt(t.body.revocation_nonce),r.treeState),s=o.treeState,a={issuer:{state:s?.state.string(),claimsTreeRoot:s.claimsRoot.string(),revocationTreeRoot:s.revocationRoot.string(),rootOfRoots:s.rootOfRoots.string()},mtp:o.proof},l=Et();return{id:l,typ:"application/iden3comm-plain-json",type:je.REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE,thid:t.thid??l,body:a,from:r.senderDid.string(),to:t.from}}async parseRevocationStatusRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handleRevocationStatusRequest(t,r,i){if(i||(i={mediaType:"application/iden3comm-plain-json"}),i.mediaType==="application/iden3comm-signed-json"&&!i.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let o=await this.parseRevocationStatusRequest(r);i.allowExpiredMessages||Qn(o);let s=await this.handleRevocationStatusRequestMessage(o,{senderDid:t,mediaType:i.mediaType,packerOptions:i.packerOptions,treeState:i.treeState}),a=i.mediaType==="application/iden3comm-signed-json"?i.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg};if(!o.to)throw new Error("failed request. empty 'to' field");let l=Ie.parse(o.to);return this._packerMgr.pack(i.mediaType,Me.encode(JSON.stringify(s)),{senderDID:l,...a})}};function uwe(n,e,t){let r=Et();return{id:r,thid:r,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:je.PROPOSAL_REQUEST_MESSAGE_TYPE,body:t,created_time:Bt(new Date),expires_time:t?.expires_time?Bt(t.expires_time):void 0}}function dwe(n,e,t,r){let i=Et();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:je.PROPOSAL_MESSAGE_TYPE,body:{proposals:t||[]},created_time:Bt(new Date),expires_time:r?.expires_time?Bt(r.expires_time):void 0}}var XT=class extends Xr{constructor(t,r,i){super();this._packerMgr=t;this._identityWallet=r;this._params=i}async handle(t,r){switch(t.type){case je.PROPOSAL_REQUEST_MESSAGE_TYPE:return await this.handleProposalRequestMessage(t,r);default:return super.handle(t,r)}}async parseProposalRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.PROPOSAL_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handleProposalRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body?.credentials?.length)throw new Error("failed request. no 'credentials' in body");let i,o;for(let s=0;s<t.body.credentials.length;s++){let a=t.body.credentials[s],l=[];try{l=await this._identityWallet.credentialWallet.findByQuery({credentialSubject:{id:{$eq:t.from}},type:a.type,context:a.context,allowedIssuers:[t.to]})}catch(u){if(u.message!=="no credential satisfied query")throw u}if(l.length){let u=Et();i||(i={id:u,typ:this._params.packerParams.mediaType,type:je.CREDENTIAL_OFFER_MESSAGE_TYPE,thid:t.thid??u,body:{url:this._params.agentUrl,credentials:[]},from:t.to,to:t.from}),i.body.credentials.push(...l.map(d=>({id:d.id,description:""})));continue}let c=await this._params.proposalResolverFn(a.context,a.type);if(!c)throw new Error(`can't resolve Proposal for type: ${a.type}, context: ${a.context}`);if(!o){let u=Et();o={id:u,typ:this._params.packerParams.mediaType,type:je.PROPOSAL_MESSAGE_TYPE,thid:t.thid??u,body:{proposals:[]},from:t.to,to:t.from}}o.body?.proposals.push(c)}return o??i}async handleProposalRequest(t,r){if(this._params.packerParams.mediaType==="application/iden3comm-signed-json"&&!this._params.packerParams.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let i=await this.parseProposalRequest(t);if(!i.from)throw new Error("failed request. empty 'from' field");r?.allowExpiredMessages||Qn(i);let o=Ie.parse(i.from),s=await this.handleProposalRequestMessage(i),a=Me.encode(JSON.stringify(s)),l=this._params.packerParams.mediaType==="application/iden3comm-signed-json"?this._params.packerParams.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg};return this._packerMgr.pack(this._params.packerParams.mediaType,a,{senderDID:o,...l})}async handleProposal(t,r){if(r?.allowExpiredMessages||Qn(t),r?.proposalRequest&&r.proposalRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.proposalRequest.from}, given ${t.to}`);return{proposal:t}}};function kY(n,e,t,r,i){let o=Et();return{id:o,thid:o,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:je.PAYMENT_REQUEST_MESSAGE_TYPE,body:{agent:t,payments:r},created_time:Bt(new Date),expires_time:i?.expires_time?Bt(i.expires_time):void 0}}async function _T(n,e){let t=n.type==="Iden3PaymentRailsRequestV1"?{recipient:n.recipient,amount:n.amount,expirationDate:Bt(new Date(n.expirationDate)),nonce:n.nonce,metadata:"0x"}:{tokenAddress:n.tokenAddress,recipient:n.recipient,amount:n.amount,expirationDate:Bt(new Date(n.expirationDate)),nonce:n.nonce,metadata:"0x"},r=Array.isArray(n.proof)?n.proof[0]:n.proof,o=await(await fetch(r.eip712.types)).json();delete o.EIP712Domain;let s=nn.verifyTypedData(r.eip712.domain,o,t,r.proofValue),{didDocument:a}=await e.resolve(r.verificationMethod);if(a?.verificationMethod){for(let l of a.verificationMethod)if(l.blockchainAccountId?.split(":").slice(-1)[0].toLowerCase()===s.toLowerCase())return s}else throw new Error("failed request. issuer DIDDocument does not contain any verificationMethods");throw new Error("failed request. no matching verificationMethod")}function OY(n,e,t,r){let i=Et();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:je.PAYMENT_MESSAGE_TYPE,body:{payments:t},created_time:Bt(new Date),expires_time:r?.expires_time?Bt(r.expires_time):void 0}}var $T=class extends Xr{constructor(t,r){super();this._packerMgr=t;this._params=r}async handle(t,r){switch(t.type){case je.PAYMENT_REQUEST_MESSAGE_TYPE:return await this.handlePaymentRequestMessage(t,r);case je.PAYMENT_MESSAGE_TYPE:return await this.handlePayment(t,r),null;default:return super.handle(t,r)}}async parsePaymentRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.PAYMENT_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handlePaymentRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body.payments?.length)throw new Error("failed request. no 'payments' in body");if(!r.paymentHandler)throw new Error("please provide payment handler in context");let i=Ie.parse(t.to),o=Ie.parse(t.from),s=[];for(let h=0;h<t.body.payments.length;h++){let{data:f}=t.body.payments[h],p=Array.isArray(f)?f.find(w=>w.type==="Iden3PaymentRequestCryptoV1"?w.id===r.nonce:w.nonce===r.nonce):f;if(!p)throw new Error(`failed request. no payment in request for nonce ${r.nonce}`);switch(p.type){case"Iden3PaymentRequestCryptoV1":s.push(await this.handleIden3PaymentRequestCryptoV1(p,r.paymentHandler));break;case"Iden3PaymentRailsRequestV1":s.push(await this.handleIden3PaymentRailsRequestV1(p,r.paymentHandler));break;case"Iden3PaymentRailsERC20RequestV1":s.push(await this.handleIden3PaymentRailsERC20RequestV1(p,r.paymentHandler,r.erc20TokenApproveHandler));break}}let a=OY(i,o,s),l=await this.packMessage(a,i),u=await(await fetch(t.body.agent,{method:"POST",body:l,headers:{"Content-Type":this._params.packerParams.mediaType==="application/iden3comm-plain-json"?"application/json":"application/octet-stream"}})).arrayBuffer();if(!u.byteLength)return null;let{unpackedMessage:d}=await this._packerMgr.unpack(new Uint8Array(u));return d}async handlePaymentRequest(t,r){if(this._params.packerParams.mediaType==="application/iden3comm-signed-json"&&!this._params.packerParams.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let i=await this.parsePaymentRequest(t);if(!i.from)throw new Error("failed request. empty 'from' field");if(!i.to)throw new Error("failed request. empty 'to' field");r?.allowExpiredMessages||Qn(i);let o=await this.handlePaymentRequestMessage(i,r);if(!o)return null;let s=Ie.parse(i.to);return this.packMessage(o,s)}async handlePayment(t,r){if(r?.allowExpiredMessages||Qn(t),r.paymentRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.paymentRequest.from}, given ${t.to}`);if(!t.body.payments.length)throw new Error("failed request. empty 'payments' field in body");if(!r.paymentValidationHandler)throw new Error("please provide payment validation handler in options");for(let i=0;i<t.body.payments.length;i++){let o=t.body.payments[i],s=o.type==="Iden3PaymentCryptoV1"?o.id:o.nonce,l=r.paymentRequest.body.payments.map(c=>Array.isArray(c.data)?c.data:[c.data]).flat().find(c=>c.type==="Iden3PaymentRequestCryptoV1"?c.id===s:c.nonce===s);if(!l)throw new Error(`can't find payment request for payment ${o.type==="Iden3PaymentCryptoV1"?"id":"nonce"} ${s}`);await r.paymentValidationHandler(o.paymentData.txId,l)}}async createPaymentRailsV1(t,r,i,o,s){let a=[];for(let l=0;l<s.length;l++){let{credentials:c,description:u}=s[l],d=[];for(let h=0;h<s[l].options.length;h++){let{nonce:f,amount:p,chainId:w,optionId:y,expirationDate:v}=s[l].options[h],B=this._params.multiChainPaymentConfig?.find(b=>b.chainId===w);if(!B)throw new Error(`failed request. no config for chain ${w}`);let{recipient:U,paymentRails:k,options:F}=B,P=F.find(b=>b.id===y);if(!P)throw new Error(`failed request. no option for id ${y}`);if(P.type==="Iden3PaymentRailsERC20RequestV1"&&!P.contractAddress)throw new Error(`failed request. no token address for option id ${y}`);let I=v??new Date(new Date().setHours(new Date().getHours()+1)),D=`https://schema.iden3.io/core/json/${P.type}.json`,K=await(await fetch(D)).json();delete K.EIP712Domain;let q=P.type==="Iden3PaymentRailsRequestV1"?{recipient:U,amount:p,expirationDate:Bt(I),nonce:f,metadata:"0x"}:{tokenAddress:P.contractAddress,recipient:U,amount:p,expirationDate:Bt(I),nonce:f,metadata:"0x"},G={name:"MCPayment",version:"1.0.0",chainId:w,verifyingContract:k},x=await o.signTypedData(G,K,q),S=[{type:"EthereumEip712Signature2021",proofPurpose:"assertionMethod",proofValue:x,verificationMethod:`did:pkh:eip155:${w}:${await o.getAddress()}`,created:new Date().toISOString(),eip712:{types:D,primaryType:"Iden3PaymentRailsRequestV1",domain:G}}],M={type:"Iden3PaymentRailsRequestV1","@context":[`https://schema.iden3.io/core/jsonld/payment.jsonld#${P.type}`,"https://w3id.org/security/suites/eip712sig-2021/v1"],recipient:U,amount:p.toString(),expirationDate:I.toISOString(),nonce:f.toString(),metadata:"0x",proof:S};d.push(P.type==="Iden3PaymentRailsRequestV1"?M:{...M,type:P.type,tokenAddress:P.contractAddress||"",features:P.features||[]})}a.push({data:d,credentials:c,description:u})}return kY(t,r,i,a)}async packMessage(t,r){let i=Me.encode(JSON.stringify(t)),o=this._params.packerParams.mediaType==="application/iden3comm-signed-json"?this._params.packerParams.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg};return await this._packerMgr.pack(this._params.packerParams.mediaType,i,{senderDID:r,...o})}async handleIden3PaymentRequestCryptoV1(t,r){if(t.expiration&&new Date(t.expiration)<new Date)throw new Error("failed request. expired request");let i=await r(t);return{id:t.id,"@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentCryptoV1",type:"Iden3PaymentCryptoV1",paymentData:{txId:i}}}async handleIden3PaymentRailsRequestV1(t,r){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");let i=await _T(t,this._params.documentResolver);if(this._params.allowedSigners&&!this._params.allowedSigners.includes(i))throw new Error("failed request. signer is not in the allowed signers list");let o=await r(t),s=Array.isArray(t.proof)?t.proof[0]:t.proof;return{nonce:t.nonce,type:"Iden3PaymentRailsV1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsV1",paymentData:{txId:o,chainId:s.eip712.domain.chainId}}}async handleIden3PaymentRailsERC20RequestV1(t,r,i){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");let o=await _T(t,this._params.documentResolver);if(this._params.allowedSigners&&!this._params.allowedSigners.includes(o))throw new Error("failed request. signer is not in the allowed signers list");if(!t.features?.includes("EIP-2612")&&!i)throw new Error("please provide erc20TokenApproveHandler in context for ERC-20 payment type");i&&await i(t);let s=await r(t),a=Array.isArray(t.proof)?t.proof[0]:t.proof;return{nonce:t.nonce,type:"Iden3PaymentRailsERC20V1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsERC20V1",paymentData:{txId:s,chainId:a.eip712.domain.chainId,tokenAddress:t.tokenAddress}}}};function fwe(n,e){let t=Et();return{id:t,thid:t,typ:"application/iden3comm-plain-json",type:je.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE,body:{queries:n},from:e?.from,to:e?.to,created_time:Bt(new Date),expires_time:e?.expires_time}}function GY(n,e){let t=Et();return{id:t,typ:"application/iden3comm-plain-json",thid:t,type:je.DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE,body:{disclosures:n},from:e?.from,to:e?.to,created_time:Bt(new Date),expires_time:e?.expires_time}}var eP=class extends Xr{constructor(t){super();this._options=t;let r=["id","typ","type","thid","body","from","to","created_time","expires_time"];t.headers||(t.headers=r)}async handle(t,r){switch(t.type){case je.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:return await this.handleDiscoveryQuery(t,r);default:return super.handle(t,r)}}async handleDiscoveryQuery(t,r){r?.allowExpiredMessages||Qn(t);let i=[];for(let o of t.body.queries)i.push(...this.handleQuery(o));return Promise.resolve(GY(i,{to:t.from,from:t.to,expires_time:r?.disclosureExpiresDate?Bt(r.disclosureExpiresDate):void 0}))}handleQuery(t){let r=[];switch(t["feature-type"]){case"accept":r=this.handleAcceptQuery();break;case"protocol":r=this.handleProtocolQuery();break;case"goal-code":r=this.handleGoalCodeQuery();break;case"header":r=this.handleHeaderQuery();break}return this.handleMatch(r,t.match)}handleAcceptQuery(){return this._options.packageManager.getSupportedProfiles().map(r=>({"feature-type":"accept",id:r}))}handleProtocolQuery(){return this._options.protocols?.map(t=>({"feature-type":"protocol",id:t}))??[]}handleGoalCodeQuery(){return this._options.goalCodes?.map(t=>({"feature-type":"goal-code",id:t}))??[]}handleHeaderQuery(){return this._options.headers?.map(t=>({"feature-type":"header",id:t}))??[]}handleMatch(t,r){if(!r||r==="*")return t;let i=this.wildcardToRegExp(r);return t.filter(o=>i.test(o.id))}wildcardToRegExp(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`)}};function hwe(n,e,t){return{id:Et(),pthid:n,typ:"application/iden3comm-plain-json",type:je.PROBLEM_REPORT_MESSAGE_TYPE,ack:t?.ack,body:{code:e,comment:t?.comment,args:t?.args,escalate_to:t?.escalate_to},from:t?.from,to:t?.to}}var iu={url:"http://localhost:8545",defaultGasLimit:6e5,minGasPrice:"0",maxGasPrice:"100000000000",confirmationBlockCount:5,confirmationTimeout:6e5,contractAddress:"",receiptTimeout:6e5,rpcResponseTimeout:5e3,waitReceiptCycleTime:3e4,waitBlockCycleTime:3e3},pb=class{constructor(e,t){this.ethConfig=e;let r=Array.isArray(e)?e[0]:e;this.provider=new Tt(r.url),this.stateContract=new $t(r.contractAddress,eB,this.provider),this._transactionService=new _o(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??yi.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??v0},this._stateCacheOptions={notReplacedTtl:t?.stateCacheOptions?.notReplacedTtl??yi.DEFAULT_PROOF_VERIFY_DELAY/2,replacedTtl:t?.stateCacheOptions?.replacedTtl??yi.DEFAULT_PROOF_VERIFY_DELAY,maxSize:t?.stateCacheOptions?.maxSize??v0},this._rootCacheOptions={replacedTtl:t?.rootCacheOptions?.replacedTtl??yi.DEFAULT_AUTH_VERIFY_DELAY,notReplacedTtl:t?.rootCacheOptions?.notReplacedTtl??yi.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.rootCacheOptions?.maxSize??v0},this._gistProofCacheOptions={ttl:yi.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??v0},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??Dm({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??Dm({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??Dm({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??Dm({maxSize:this._gistProofCacheOptions.maxSize,ttl:this._gistProofCacheOptions.ttl}),this._disableCache=t?.disableCache??!1}stateContract;provider;_transactionService;_latestStateResolveCache;_stateResolveCache;_rootResolveCache;_gistProofResolveCache;_latestStateCacheOptions;_stateCacheOptions;_rootCacheOptions;_gistProofCacheOptions;_disableCache=!1;async getLatestStateById(e){let t=this.getLatestStateCacheKey(e);if(!this._disableCache){let s=await this._latestStateResolveCache?.get(t);if(s)return s}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=await r.getStateInfoById(e),o={id:BigInt(i[0]),state:BigInt(i[1]),replacedByState:BigInt(i[2]),createdAtTimestamp:BigInt(i[3]),replacedAtTimestamp:BigInt(i[4]),createdAtBlock:BigInt(i[5]),replacedAtBlock:BigInt(i[6])};return!this._disableCache&&await this._latestStateResolveCache?.set(t,o,this._latestStateCacheOptions.ttl),o}async getStateInfoByIdAndState(e,t){let r=this.getStateCacheKey(e,t);if(!this._disableCache){let l=await this._stateResolveCache?.get(r);if(l)return l}let{stateContract:i}=this.getStateContractAndProviderForId(e),o=await i.getStateInfoByIdAndState(e,t),s={id:BigInt(o[0]),state:BigInt(o[1]),replacedByState:BigInt(o[2]),createdAtTimestamp:BigInt(o[3]),replacedAtTimestamp:BigInt(o[4]),createdAtBlock:BigInt(o[5]),replacedAtBlock:BigInt(o[6])},a=s.replacedAtTimestamp===0n?this._stateCacheOptions.notReplacedTtl:this._stateCacheOptions.replacedTtl;return!this._disableCache&&await this._stateResolveCache?.set(r,s,a),s}async publishState(e,t){let r=new G2;r.pubSignalsUnmarshal(Me.encode(JSON.stringify(e.pub_signals)));let{userId:i,oldUserState:o,newUserState:s,isOldStateGenesis:a}=r,{stateContract:l,provider:c}=this.getStateContractAndProviderForId(i.bigInt()),u=l.connect(t),d=Zh(e.proof),h=[i.bigInt().toString(),o.bigInt().toString(),s.bigInt().toString(),a,d.a,d.b,d.c],f=await c.getFeeData(),p=iu.maxFeePerGas?BigInt(iu.maxFeePerGas):f.maxFeePerGas,w=iu.maxPriorityFeePerGas?BigInt(iu.maxPriorityFeePerGas):f.maxPriorityFeePerGas,y=await u.transitState.estimateGas(...h),v=await u.transitState.populateTransaction(...h),B={to:v.to,data:v.data,gasLimit:y,maxFeePerGas:p,maxPriorityFeePerGas:w},{txnHash:U}=await this._transactionService.sendTransactionRequest(t,B);return U}async publishStateGeneric(e,t){let{userId:r,oldUserState:i,newUserState:o,isOldStateGenesis:s,methodId:a,methodParams:l}=t,{stateContract:c,provider:u}=this.getStateContractAndProviderForId(r.bigInt()),d=c.connect(e),h=await u.getFeeData(),f=iu.maxFeePerGas?BigInt(iu.maxFeePerGas):h.maxFeePerGas,p=iu.maxPriorityFeePerGas?BigInt(iu.maxPriorityFeePerGas):h.maxPriorityFeePerGas,w=[r.bigInt().toString(),i.bigInt().toString(),o.bigInt().toString(),s,a,l],y=await d.transitStateGeneric.estimateGas(...w),v=await d.transitStateGeneric.populateTransaction(...w),B={to:v.to,data:v.data,gasLimit:y,maxFeePerGas:f,maxPriorityFeePerGas:p},{txnHash:U}=await this._transactionService.sendTransactionRequest(e,B);return U}async getGISTProof(e){let t=this.getGistProofCacheKey(e);if(!this._disableCache){let s=await this._gistProofResolveCache?.get(t);if(s)return s}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=await r.getGISTProof(e),o={root:BigInt(i.root.toString()),existence:i.existence,siblings:i.siblings?.map(s=>BigInt(s.toString())),index:BigInt(i.index.toString()),value:BigInt(i.value.toString()),auxExistence:i.auxExistence,auxIndex:BigInt(i.auxIndex.toString()),auxValue:BigInt(i.auxValue.toString())};return!this._disableCache&&await this._gistProofResolveCache?.set(t,o,this._gistProofCacheOptions.ttl),o}async getGISTRootInfo(e,t){let r=this.getRootCacheKey(e);if(!this._disableCache){let l=await this._rootResolveCache?.get(r);if(l)return l}let{stateContract:i}=this.getStateContractAndProviderForId(t),o=await i.getGISTRootInfo(e),s={root:BigInt(o.root.toString()),replacedByRoot:BigInt(o.replacedByRoot.toString()),createdAtTimestamp:BigInt(o.createdAtTimestamp.toString()),replacedAtTimestamp:BigInt(o.replacedAtTimestamp.toString()),createdAtBlock:BigInt(o.createdAtBlock.toString()),replacedAtBlock:BigInt(o.replacedAtBlock.toString())},a=s.replacedAtTimestamp==0n?this._rootCacheOptions.notReplacedTtl:this._rootCacheOptions.replacedTtl;return!this._disableCache&&await this._rootResolveCache?.set(r,s,a),s}getRpcProvider(){return this.provider}enableCache(){this._disableCache=!1}disableCache(){this._disableCache=!0}getStateContractAndProviderForId(e){let t=Je.fromBigInt(e),r=Zm(Ie.blockchainFromId(t),Ie.networkIdFromId(t)),i=this.networkByChainId(r),o=new Tt(i.url);return{stateContract:new $t(i.contractAddress,eB,o),provider:o}}networkByChainId(e){let r=(Array.isArray(this.ethConfig)?this.ethConfig:[this.ethConfig]).find(i=>i.chainId===e);if(!r)throw new Error(`chainId "${e}" not supported`);return r}getGistProofCacheKey(e){return`gist-${e.toString()}`}getLatestStateCacheKey(e){return`latest-${e.toString()}`}getStateCacheKey(e,t){return`${e.toString()}-${t.toString()}`}getRootCacheKey(e){return e.toString()}};var tP=[{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[{internalType:"string",name:"message",type:"string"},{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256",name:"linkID",type:"uint256"},{internalType:"uint64",name:"requestIdToCompare",type:"uint64"},{internalType:"uint256",name:"linkIdToCompare",type:"uint256"}],name:"LinkedProofError",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint64",name:"requestId",type:"uint64"},{indexed:!0,internalType:"address",name:"requestOwner",type:"address"},{indexed:!1,internalType:"string",name:"metadata",type:"string"},{indexed:!1,internalType:"address",name:"validator",type:"address"},{indexed:!1,internalType:"bytes",name:"data",type:"bytes"}],name:"ZKPRequestSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint64",name:"requestId",type:"uint64"},{indexed:!0,internalType:"address",name:"caller",type:"address"}],name:"ZKPResponseSubmitted",type:"event"},{inputs:[],name:"REQUESTS_RETURN_LIMIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"acceptOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"addValidatorToWhitelist",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"disableZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"enableZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getProofStatus",outputs:[{components:[{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"uint256",name:"blockTimestamp",type:"uint256"}],internalType:"struct IZKPVerifier.ProofStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"string",name:"key",type:"string"}],name:"getProofStorageField",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getRequestOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getZKPRequest",outputs:[{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest",name:"zkpRequest",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"startIndex",type:"uint256"},{internalType:"uint256",name:"length",type:"uint256"}],name:"getZKPRequests",outputs:[{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getZKPRequestsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IStateCrossChain",name:"stateCrossChain",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"}],name:"isProofVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"isWhitelistedValidator",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"isZKPRequestEnabled",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pendingOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"removeValidatorFromWhitelist",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"requestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"address",name:"requestOwner",type:"address"}],name:"setRequestOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest",name:"request",type:"tuple"}],name:"setZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256[]",name:"inputs",type:"uint256[]"},{internalType:"uint256[2]",name:"a",type:"uint256[2]"},{internalType:"uint256[2][2]",name:"b",type:"uint256[2][2]"},{internalType:"uint256[2]",name:"c",type:"uint256[2]"}],name:"submitZKPResponse",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"bytes",name:"zkProof",type:"bytes"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ZKPResponse[]",name:"responses",type:"tuple[]"},{internalType:"bytes",name:"crossChainProof",type:"bytes"}],name:"submitZKPResponseV2",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64[]",name:"requestIds",type:"uint64[]"}],name:"verifyLinkedProofs",outputs:[],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256[]",name:"inputs",type:"uint256[]"},{internalType:"uint256[2]",name:"a",type:"uint256[2]"},{internalType:"uint256[2][2]",name:"b",type:"uint256[2][2]"},{internalType:"uint256[2]",name:"c",type:"uint256[2]"},{internalType:"address",name:"sender",type:"address"}],name:"verifyZKPResponse",outputs:[{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"inputValue",type:"uint256"}],internalType:"struct ICircuitValidator.KeyToInputValue[]",name:"",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"}];var nP=[{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"address",name:"userAddress",type:"address"}],name:"areMultiRequestProofsVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"groupID",type:"uint256"}],name:"getGroupedRequests",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.RequestInfo[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getGroupsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"}],name:"getMultiRequest",outputs:[{components:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"uint256[]",name:"requestIds",type:"uint256[]"},{internalType:"uint256[]",name:"groupIds",type:"uint256[]"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.MultiRequest",name:"multiRequest",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"address",name:"userAddress",type:"address"}],name:"getMultiRequestProofsStatus",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct IVerifier.RequestProofStatus[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"}],name:"getRequest",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.RequestInfo",name:"request",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"requestId",type:"uint256"}],name:"getRequestProofStatus",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct IVerifier.RequestProofStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRequestsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"address",name:"sender",type:"address"},{internalType:"string",name:"responseFieldName",type:"string"}],name:"getResponseFieldValue",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"address",name:"sender",type:"address"}],name:"getResponseFields",outputs:[{components:[{internalType:"string",name:"name",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct IRequestValidator.ResponseField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"groupId",type:"uint256"}],name:"groupIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"requestId",type:"uint256"}],name:"isRequestProofVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"}],name:"multiRequestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"}],name:"requestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"string",name:"authMethod",type:"string"},{internalType:"contract IAuthValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"}],internalType:"struct IVerifier.AuthMethod",name:"authMethod",type:"tuple"}],name:"setAuthMethod",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"uint256[]",name:"requestIds",type:"uint256[]"},{internalType:"uint256[]",name:"groupIds",type:"uint256[]"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.MultiRequest",name:"multiRequest",type:"tuple"}],name:"setMultiRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.Request[]",name:"requests",type:"tuple[]"}],name:"setRequests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"string",name:"authMethod",type:"string"},{internalType:"bytes",name:"proof",type:"bytes"}],internalType:"struct IVerifier.AuthResponse",name:"authResponse",type:"tuple"},{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bytes",name:"proof",type:"bytes"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.Response[]",name:"responses",type:"tuple[]"},{internalType:"bytes",name:"crossChainProofs",type:"bytes"}],name:"submitResponse",outputs:[],stateMutability:"nonpayable",type:"function"}];var rP=10000000n,NY=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(NY||{}),UY=function(n){return[{authMethod:n.authProof.raw.authMethod,proof:n.authProof.encoded},n.proofs.map(e=>({requestId:e.requestId,proof:e.encoded,metadata:e.metadata})),n.crossChainProof.encoded]},iP=class n{constructor(e,t){this._configs=e;this._opts=t}static _supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1"];static _supportedCircuitsPubSignalsMap={credentialAtomicQueryMTPV2OnChain:S2,credentialAtomicQuerySigV2OnChain:F2,"credentialAtomicQueryV3OnChain-beta.1":R2,authV2:La};static async prepareTxArgsSubmitV1(e,t){if(e.method_id.replace("0x","")!=="b68967e2")throw new Error("prepareTxArgsSubmitV1 function doesn't implement requested method id. Only '0xb68967e2' is supported.");let r=t.id,i=t.pub_signals,o=Zh(t.proof);return[r,i,o.a,o.b,o.c]}async prepareTxArgsSubmitV1(e,t){return n.prepareTxArgsSubmitV1(e,t)}async submitZKPResponse(e,t,r){let i=this._configs.find(d=>d.chainId==t.chain_id);if(!i)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="b68967e2")throw new Error("submitZKPResponse function doesn't implement requested method id. Only '0xb68967e2' is supported.");let o=new Tt(i.url,i.chainId);e=e.connect(o);let s=new Map,a=await o.getFeeData(),l=i.maxFeePerGas?BigInt(i.maxFeePerGas):a.maxFeePerGas,c=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,u=new $t(t.contract_address,tP);for(let d of r){let h=await this.prepareTxArgsSubmitV1(t,d),f=await u.submitZKPResponse.populateTransaction(...h),p={to:t.contract_address,data:f.data,maxFeePerGas:l,maxPriorityFeePerGas:c},w;try{w=await e.estimateGas(p)}catch{w=rP}p.gasLimit=w;let y=new _o(o),{txnHash:v}=await y.sendTransactionRequest(e,p);s.set(v,d)}return s}async submitZKPResponseV2(e,t,r){let i=this._configs.find(y=>y.chainId==t.chain_id);if(!i)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="ade09fcd")throw new Error("submitZKPResponseV2 function doesn't implement requested method id. Only '0xade09fcd' is supported.");if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");let o=new Tt(i.url,i.chainId);e=e.connect(o);let s=await this.prepareTxArgsSubmitV2(t,r),a=await o.getFeeData(),l=i.maxFeePerGas?BigInt(i.maxFeePerGas):a.maxFeePerGas,c=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,d=await new $t(t.contract_address,tP).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:l,maxPriorityFeePerGas:c},f;try{f=await e.estimateGas(h)}catch{f=rP}h.gasLimit=f;let p=new _o(o),{txnHash:w}=await p.sendTransactionRequest(e,h);return new Map().set(w,r)}async submitResponse(e,t,r,i){let o=this._configs.find(v=>v.chainId==t.chain_id);if(!o)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="06c86a91")throw new Error("submitResponse function doesn't implement requested method id. Only '0x06c86a91' is supported.");if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");let s=new Tt(o.url,o.chainId);e=e.connect(s);let a=await this.prepareTxArgsSubmit(t,r,i),l=await s.getFeeData(),c=o.maxFeePerGas?BigInt(o.maxFeePerGas):l.maxFeePerGas,u=o.maxPriorityFeePerGas?BigInt(o.maxPriorityFeePerGas):l.maxPriorityFeePerGas,h=await new $t(t.contract_address,nP).submitResponse.populateTransaction(...a.txDataArgs),f={to:t.contract_address,data:h.data,maxFeePerGas:c,maxPriorityFeePerGas:u},p;try{p=await e.estimateGas(f)}catch{p=rP}f.gasLimit=p;let w=new _o(s),{txnHash:y}=await w.sendTransactionRequest(e,f);return new Map().set(y,{authProof:a.result.authProof.raw,crossChainProof:a.result.crossChainProof.raw,responses:a.result.proofs.map(v=>v.proof)})}static async prepareTxArgsSubmit(e,t,r,i){if(t.method_id.replace("0x","")!=="06c86a91")throw new Error("submit cross chain doesn't implement requested method id. Only '0x06c86a91' is supported.");let o=[],s=[],a=[],l="0x",c="";switch(i.authMethod){case"authV2":{let f=Zh(i.zkp.proof);c=tA(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{c=HY(i.userDid);break}default:throw new Error("auth proof must use method AuthV2 or ethIdentity")}for(let f of r){this.checkSupportedCircuit(f.circuitId);let{requestId:p,zkProofEncoded:w,metadata:y}=db(f);a.push({proof:f,requestId:p,encoded:w,metadata:y})}let u=r.map(f=>({circuitId:f.circuitId,pub_signals:f.pub_signals}));i.authMethod=="authV2"&&u.push({circuitId:i.zkp.circuitId,pub_signals:i.zkp.pub_signals});for(let f of u){let{gistUpdateResolutions:p,stateUpdateResolutions:w}=this.getUpdateResolutions(e,t.chain_id,f.circuitId,f.pub_signals);p.length>0&&o.push(...await Promise.all(p)),w.length>0&&s.push(...await Promise.all(w))}let d=o.length||s.length?this.packCrossChainProofs(o,s):l,h={authProof:{raw:i,encoded:c},proofs:a,crossChainProof:{raw:{globalStateProofs:o||[],identityStateProofs:s||[]},encoded:d}};return{result:h,txDataArgs:UY(h)}}async prepareTxArgsSubmit(e,t,r){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmit(this._opts.didResolverUrl,e,t,r)}static checkSupportedCircuit(e){if(!this._supportedCircuits.includes(e))throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`)}static getCrossChainResolvers(e,t,r,i){return[...new Set(e.map(o=>JSON.stringify({id:o.id.string(),[r]:r==="gist"?o.root?.string():o.state?.string()})))].reduce((o,s)=>{let a=JSON.parse(s),l=Je.fromString(a.id),c=Xm(Ie.parseFromId(l));if(t===c)return o;let u=this.resolveDidDocumentEip712MessageAndSignature(Ie.parseFromId(Je.fromString(a.id)),i,{[r]:me.fromString(a[r])});return[...o,u]},[])}static async prepareTxArgsSubmitV2(e,t,r){if(t.method_id.replace("0x","")!=="ade09fcd")throw new Error("submit cross chain doesn't implement requested method id. Only '0xade09fcd' is supported.");let i=[],o=[],s=[],a="0x";for(let c of r){this.checkSupportedCircuit(c.circuitId);let{requestId:u,zkProofEncoded:d,metadata:h}=db(c);s.push({requestId:u,zkProof:d,data:h});let{gistUpdateResolutions:f,stateUpdateResolutions:p}=this.getUpdateResolutions(e,t.chain_id,c.circuitId,c.pub_signals);f.length>0&&i.push(...await Promise.all(f)),p.length>0&&o.push(...await Promise.all(p))}let l=i.length||o.length?this.packCrossChainProofs(i,o):a;return[s,l]}async prepareTxArgsSubmitV2(e,t){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmitV2(this._opts.didResolverUrl,e,t)}static getUpdateResolutions(e,t,r,i){let o=this.getOnChainGistRootStatePubSignals(r,i),s=this.getCrossChainResolvers(o.gists,t,"gist",e),a=this.getCrossChainResolvers(o.states,t,"state",e);return{gistUpdateResolutions:s,stateUpdateResolutions:a}}static packCrossChainProofs(e,t){let r=[];for(let i of e)r.push({proofType:"globalStateProof",proof:this.packGlobalStateMsg(i)});for(let i of t)r.push({proofType:"stateProof",proof:this.packIdentityStateMsg(i)});return new nn.AbiCoder().encode(["tuple(string proofType,bytes proof)[]"],[r])}static packGlobalStateMsg(e){return new nn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,bytes2 idType,uint256 root,uint256 replacedAtTimestamp) globalStateMsg,bytes signature,)"],[e])}static packIdentityStateMsg(e){return new nn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,uint256 id,uint256 state,uint256 replacedAtTimestamp) idStateMsg,bytes signature,)"],[e])}static getOnChainGistRootStatePubSignals(e,t){let r=this._supportedCircuitsPubSignalsMap[e];if(!r)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=new r,o=Me.encode(JSON.stringify(t));return i.pubSignalsUnmarshal(o),i.getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await Kf(e,t,{...r,signature:"EthereumEip712Signature2021"});if(!i.didResolutionMetadata.proof?.length)throw new Error("No proof found in resolved DID document");let o=i.didResolutionMetadata.proof[0].eip712.message,s=i.didResolutionMetadata.proof[0].proofValue;return r?.gist&&!r.state?{globalStateMsg:{timestamp:o.timestamp,idType:o.idType,root:o.root,replacedAtTimestamp:o.replacedAtTimestamp},signature:s}:{idStateMsg:{timestamp:o.timestamp,id:o.id,state:o.state,replacedAtTimestamp:o.replacedAtTimestamp},signature:s}}},HY=n=>`0x${xi(ht.intToBytes(Ie.idFromDID(n).bigInt()))}`;var oP=[{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"},{internalType:"uint256",name:"_credentialId",type:"uint256"}],name:"getCredential",outputs:[{components:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"string[]",name:"context",type:"string[]"},{internalType:"string",name:"_type",type:"string"},{internalType:"uint64",name:"issuanceDate",type:"uint64"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.CredentialSchema",name:"credentialSchema",type:"tuple"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.DisplayMethod",name:"displayMethod",type:"tuple"}],internalType:"struct INonMerklizedIssuer.CredentialData",name:"",type:"tuple"},{internalType:"uint256[8]",name:"",type:"uint256[8]"},{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct INonMerklizedIssuer.SubjectField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCredentialAdapterVersion",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"}],name:"getUserCredentialIds",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"}];var sP=[{inputs:[],name:"CREDENTIAL_ADAPTER_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"}],name:"getClaimProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getClaimProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"}],name:"getClaimProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getClaimsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"},{internalType:"uint256",name:"_credentialId",type:"uint256"}],name:"getCredential",outputs:[{components:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"string[]",name:"context",type:"string[]"},{internalType:"string",name:"_type",type:"string"},{internalType:"uint64",name:"issuanceDate",type:"uint64"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.CredentialSchema",name:"credentialSchema",type:"tuple"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.DisplayMethod",name:"displayMethod",type:"tuple"}],internalType:"struct INonMerklizedIssuer.CredentialData",name:"",type:"tuple"},{internalType:"uint256[8]",name:"",type:"uint256[8]"},{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct INonMerklizedIssuer.SubjectField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCredentialAdapterVersion",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getIsOldStateGenesis",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedClaimsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedRevocationsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedRootsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedState",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"}],name:"getRevocationProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getRevocationProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"}],name:"getRevocationProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatus",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatusByIdAndState",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRevocationsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"rootsTreeRoot",type:"uint256"}],name:"getRootProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getRootProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"rootsTreeRoot",type:"uint256"}],name:"getRootProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"state",type:"uint256"}],name:"getRootsByState",outputs:[{components:[{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.Roots",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRootsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getSmtDepth",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"}],name:"getUserCredentialIds",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_stateContractAddr",type:"address"},{internalType:"bytes2",name:"idType",type:"bytes2"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],Vm=class{static abi=sP;static createInterface(){return new ca(sP)}static connect(e,t){return new $t(e,sP,t)}};var wb=class{_contract;_contractAddress;_chainId;_issuerDid;_merklizationOptions;constructor(e,t,r){if(!e.chainId)throw new Error("Chain ID is required");this._chainId=e.chainId,this._contractAddress=nn.getAddress(nn.hexlify(Je.ethAddressFromId(Ie.idFromDID(t)))),this._contract=Vm.connect(this._contractAddress,new nn.JsonRpcProvider(e.url)),this._issuerDid=t,this._merklizationOptions=r?.merklizationOptions}async isInterfaceSupported(){let e=[{name:"Interface detection ERC-165",value:"0x01ffc9a7"},{name:"Interface non-merklized issuer",value:"0x58874949"},{name:"Interface get credential",value:"0x5d1ca631"}],r=(await Promise.all(e.map(async i=>await this._contract.supportsInterface(i.value)?null:i.name))).filter(i=>i!==null);if(r.length>0)throw new Error(`Unsupported interfaces: ${r.join(", ")}`)}async getCredential(e,t){let[r,i,o]=await this._contract.getCredential(e.bigInt(),t);return{credentialData:r,coreClaimBigInts:i,credentialSubjectFields:o}}async getUserCredentialsIds(e){return this._contract.getUserCredentialIds(e.bigInt())}async convertOnChainInfoToW3CCredential(e,t,r){let i=new er().unMarshalJson(JSON.stringify(t.map(c=>c.toString()))),o=await this.convertCredentialSubject(i,e.context,e._type,r),s={id:this.credentialId(e.id),credentialSchema:e.credentialSchema.id,type:e._type,credentialSubject:o,expiration:i.getExpirationDate()?.getTime(),displayMethod:this.convertDisplayMethod(e.displayMethod),context:e.context,revocationOpts:{id:this._contractAddress,nonce:Number(i.getRevocationNonce()),type:"Iden3OnchainSparseMerkleTreeProof2023"},issuanceDate:ns(Number(e.issuanceDate)).getTime()},a=await this.existenceProof(i),l=fr.fromCredentialRequest(this._issuerDid,s);return l.proof=[a],l}credentialId(e){return`urn:iden3:onchain:${this._chainId}:${this._contractAddress}:${e}`}async convertCredentialSubject(e,t,r,i){let o=JSON.stringify({"@context":t}),s={};for(let c of i){let u=await rr.newTypeFromContext(o,`${r}.${c.key}`,this._merklizationOptions);switch(u){case"http://www.w3.org/2001/XMLSchema#boolean":{switch(c.rawValue.toString()){case"18586133768512220936620570745912940619677854269274689475585506675881198879027":s[c.key]=!0;break;case"19014214495641488759237505126948346942972912379615652741039992445865937985820":s[c.key]=!1;break}break}case("http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#positiveInteger"):{s[c.key]=c.value.toString();break}case"http://www.w3.org/2001/XMLSchema#integer":{s[c.key]=Number(c.value);break}case"http://www.w3.org/2001/XMLSchema#string":{this.validateSourceValue(u,c.value,c.rawValue),s[c.key]=c.rawValue;break}case"http://www.w3.org/2001/XMLSchema#dateTime":{let d=BigInt(c.rawValue),h=ns(Number(d)).toISOString();this.validateSourceValue(u,c.value,h),s[c.key]=h;break}case"http://www.w3.org/2001/XMLSchema#double":{let d=Number(c.rawValue);this.validateSourceValue(u,c.value,d),s[c.key]=d;break}default:throw new Error(`Unsupported data type ${u}`)}}s.type=r;let a=e.getId(),l=Ie.parseFromId(a);return s.id=l.string(),s}async existenceProof(e){let[t,r]=await this._contract.getClaimProofWithStateInfo(e.hIndex());if(!t.existence)throw new Error("Claim does not exist");let i=me.fromBigInt(r.state),o=me.fromBigInt(r.claimsRoot),s=me.fromBigInt(r.revocationsRoot),a=me.fromBigInt(r.rootsRoot),l=new yt({siblings:t.siblings.map(c=>me.fromBigInt(c)),existence:t.existence,nodeAux:t.auxExistence?{key:me.fromBigInt(t.auxIndex),value:me.fromBigInt(t.auxValue)}:void 0});return new ha({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:l,coreClaim:e})}async validateSourceValue(e,t,r){if(await yc.hashValue(e,r)!==t)throw new Error(`Invalid source value for ${e} type`)}convertDisplayMethod(e){if(!(!e.id||!e._type))switch(e._type){case"Iden3BasicDisplayMethodV1":return{id:e.id,type:"Iden3BasicDisplayMethodV1"};default:throw new Error(`Unsupported display method type ${e._type}`)}}};var aP=class{_ethConnectionConfig;_onchainIssuerOptions;constructor(e,t){this._ethConnectionConfig=e,this._onchainIssuerOptions=t}async getCredential(e,t,r){let{contract:i,connection:o}=this.getContractConnection(e),s=await i.getCredentialAdapterVersion();switch(s){case"0.0.1":{let a=new wb(o,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});await a.isInterfaceSupported();let{credentialData:l,coreClaimBigInts:c,credentialSubjectFields:u}=await a.getCredential(Ie.idFromDID(t),r);return await a.convertOnChainInfoToW3CCredential(l,c,u)}default:throw new Error(`Unsupported adapter version ${s}`)}}async getUserCredentialIds(e,t){let{contract:r,connection:i}=this.getContractConnection(e),o=await r.getCredentialAdapterVersion();switch(o){case"0.0.1":{let s=new wb(i,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});return await s.isInterfaceSupported(),await s.getUserCredentialsIds(Ie.idFromDID(t))}default:throw new Error(`Unsupported adapter version ${o}`)}}getContractConnection(e){let t=Ie.idFromDID(e),r=Xm(e),i=nn.getAddress(nn.hexlify(Je.ethAddressFromId(t))),o=this._ethConnectionConfig.find(a=>a.chainId===r);if(!o)throw new Error(`No connection found for chain ID ${r}`);if(!o.url)throw new Error(`No URL found for chain ID ${r}`);return{contract:new $t(i,oP,new nn.JsonRpcProvider(o.url)),connection:o}}};var cP=class{constructor(e){this.resolverUrl=e}async getLatestStateById(e){return this.getStateInfo(e)}async getStateInfoByIdAndState(e,t){return this.getStateInfo(e,t)}async getGISTProof(e){let{didDocument:t}=await Kf(Ie.parseFromId(Je.fromBigInt(e)),this.resolverUrl),{global:r}=this.getIden3StateInfo2023(t);if(!r)throw new Error("GIST root not found");let{proof:i}=r;if(!i)throw new Error("GIST proof not found");return{root:r.root,existence:i.existence,siblings:i.siblings?.map(o=>BigInt(o)),index:BigInt(0),value:BigInt(0),auxExistence:!!i.node_aux,auxIndex:i.node_aux?BigInt(i.node_aux.key):BigInt(0),auxValue:i.node_aux?BigInt(i.node_aux.value):BigInt(0)}}async getGISTRootInfo(e,t){let{didDocument:r}=await Kf(Ie.parseFromId(Je.fromBigInt(t)),this.resolverUrl,{gist:me.fromBigInt(e)}),{global:i}=this.getIden3StateInfo2023(r);if(!i)throw new Error("GIST root not found");return i}getRpcProvider(){return new Tt}publishState(){throw new Error("publishState method not implemented.")}publishStateGeneric(){throw new Error("publishStateGeneric method not implemented.")}async getStateInfo(e,t){let r=t?{state:me.fromBigInt(t)}:void 0,{didDocument:i}=await Kf(Ie.parseFromId(Je.fromBigInt(e)),this.resolverUrl,r),{info:o}=this.getIden3StateInfo2023(i);return{...o}}getIden3StateInfo2023(e){let t=e.verificationMethod?.find(r=>r.type==="Iden3StateInfo2023");if(!t)throw new Error("Iden3StateInfo2023 verification method not found");return t}};var KY=[{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"allowance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientAllowance",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC20InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC20InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC20InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"}],name:"ERC20InvalidSpender",type:"error"},{inputs:[{internalType:"uint256",name:"deadline",type:"uint256"}],name:"ERC2612ExpiredSignature",type:"error"},{inputs:[{internalType:"address",name:"signer",type:"address"},{internalType:"address",name:"owner",type:"address"}],name:"ERC2612InvalidSigner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"currentNonce",type:"uint256"}],name:"InvalidAccountNonce",type:"error"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[],name:"DOMAIN_SEPARATOR",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"nonces",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"permit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];var JY=[{inputs:[{internalType:"uint256",name:"initialSupply",type:"uint256"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"allowance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientAllowance",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC20InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC20InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC20InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"}],name:"ERC20InvalidSpender",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];async function xwe(n,e,t,r,i){let o=new $t(e,KY,n),s=await o.nonces(await n.getAddress()),a=await o.eip712Domain(),l={name:a[1],version:a[2],chainId:a[3],verifyingContract:e},c={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:await n.getAddress(),spender:t,value:r,nonce:s,deadline:i};return n.signTypedData(l,c,u)}async function Awe(n,e){return new $t(n,JY,e).decimals()}var jY=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(jY||{}),WY=(o=>(o[o.BigInt=0]="BigInt",o[o.Boolean=1]="Boolean",o[o.Double=2]="Double",o[o.DateTime=3]="DateTime",o[o.String=4]="String",o))(WY||{}),lP=[!0,1,"true"],uP=[!1,0,"false"],qY=(n,e)=>Array.isArray(n)&&Array.isArray(e)?n.length===e.length&&n.every((t,r)=>t===e[r]):!Array.isArray(n)&&Array.isArray(e)?e.includes(n):Array.isArray(n)&&!Array.isArray(e)?n.includes(e):(n=n,e=e,lP.includes(n)&&lP.includes(e)||uP.includes(n)&&uP.includes(e)?!0:n===e),QY=(n,e)=>XY(n,e,(r,i)=>{switch(_Y(r.toString())){case 0:case 1:return BigInt(r)>BigInt(i);case 3:return Date.parse(r.toString())>Date.parse(i.toString());case 2:case 4:default:return r>i}}),VY=(n,e)=>XY(n,e,(r,i)=>{switch(_Y(r.toString())){case 0:case 1:return BigInt(r)>=BigInt(i);case 3:return Date.parse(r.toString())>=Date.parse(i.toString());case 2:case 4:default:return r>=i}}),vwe=(n,e)=>!!(lP.includes(e)&&typeof n<"u"||uP.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),YY=(n,e)=>Array.isArray(n)&&Array.isArray(e)?n.every(t=>e.includes(t)):!Array.isArray(n)&&Array.isArray(e)?e.includes(n):Array.isArray(n)&&!Array.isArray(e)?n.includes(e):!1,zY=(n,e)=>{if(!Array.isArray(e)||e.length!==2)throw new Error("$between/$nonbetween operator value should be 2 elements array");let[t,r]=e.map(BigInt),i=o=>o>=t&&o<=r;return Array.isArray(n)?n.map(BigInt).every(i):i(BigInt(n))},Dc={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>vwe(n,e),$eq:(n,e)=>qY(n,e),$in:(n,e)=>YY(n,e),$nin:(n,e)=>!YY(n,e),$gt:(n,e)=>QY(n,e),$lt:(n,e)=>!VY(n,e),$ne:(n,e)=>!qY(n,e),$gte:(n,e)=>VY(n,e),$lte:(n,e)=>!QY(n,e),$between:(n,e)=>zY(n,e),$nonbetween:(n,e)=>!zY(n,e)},ZY=(n,e,t=null)=>{let r=e.split("."),i=n;for(let o of r){if(i==null)return t;i=i[o]}return i},Pa=class{constructor(e,t,r,i=!1){this.path=e;this.operatorFunc=t;this.value=r;this.isReverseParams=i}execute(e){if(!this.operatorFunc)throw new Error("not defined comparator");let t=ZY(e,this.path);return t==null&&this.operatorFunc!==Dc.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},dP=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new Pa("id",Dc.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new Pa("issuer",Dc.$in,r));case"type":return e.concat(new Pa("type",Dc.$in,r,!0));case"context":return e.concat(new Pa("@context",Dc.$in,r,!0));case"credentialSubjectId":return e.concat(new Pa("credentialSubject.id",Dc.$eq,r));case"schema":return e.concat(new Pa("credentialSchema.id",Dc.$eq,r));case"credentialSubject":{let i=Object.keys(r).reduce((o,s)=>{let a=r[s];if(typeof a=="object"&&Object.keys(a).length===0)return o.concat([new Pa(`credentialSubject.${s}`,Dc.$noop,null)]);let l=Object.keys(a).map(c=>{let u=a[c],d=`credentialSubject.${s}`;return new Pa(d,Dc[c],u)});return o.concat(l)},[]);return e.concat(i)}case"proofType":case"groupId":case"skipClaimRevocationCheck":return e;default:throw new Error(`${t} : not defined query key`)}},[]),XY=(n,e,t)=>Array.isArray(n)&&Array.isArray(e)?n.every((r,i)=>t(r,e[i])):!Array.isArray(n)&&Array.isArray(e)?e.every(r=>t(n,r)):Array.isArray(n)&&!Array.isArray(e)?n.every(r=>t(r,e)):t(n,e),Cwe=/^[+-]?\d+$/,Swe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,Dwe=/^([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))$/,Lwe=/^(true)|(false)$/,Bwe=/^\d{4}-\d{2}-\d{2}$/,_Y=n=>Cwe.test(n)?0:Swe.test(n)?2:Dwe.test(n)||Bwe.test(n)?3:Lwe.test(n)?1:4;var fP=class{constructor(e){this._localStorageKey=e;localStorage.getItem(this._localStorageKey)||localStorage.setItem(e,JSON.stringify([]))}async save(e,t,r="id"){if(localStorage){let i=localStorage.getItem(this._localStorageKey),o=[];i&&(o=JSON.parse(i));let s=o.findIndex(a=>a[r]===e);s===-1?o.push(t):o[s]=t,localStorage.setItem(this._localStorageKey,JSON.stringify(o))}}async get(e,t="id"){let r=localStorage.getItem(this._localStorageKey),i=[];return r&&(i=JSON.parse(r)),i.find(o=>o[t]===e)}async load(){let e=localStorage.getItem(this._localStorageKey);return e&&JSON.parse(e)}async delete(e,t="id"){let r=localStorage.getItem(this._localStorageKey),i=[];r&&(i=JSON.parse(r));let o=i.filter(s=>s[t]!==e);if(i.length===o.length)throw new Error(`item not found to delete: ${e}`);localStorage.setItem(this._localStorageKey,JSON.stringify(o))}};var hP=class n{constructor(e){this._mtDepth=e}static storageKeyMeta="merkle-tree-meta";async createIdentityMerkleTrees(e){e||(e=`${Et()}`);let t=localStorage.getItem(n.storageKeyMeta);if(t){let i=JSON.parse(t);if(i.find(l=>l.treeId===`${e}+${l.type}`))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let s=i.filter(l=>l.identifier===e);if(s.length>0)return s;let a=U2(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify([...i,...a])),[...i,...a]}let r=U2(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify(r)),r}async getIdentityMerkleTreesInfo(e){let t=localStorage.getItem(n.storageKeyMeta);if(t)return JSON.parse(t).filter(i=>i.identifier===e);throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=this.getMeta(e,t);return new os(new ig(Ua(r.treeId)),!0,this._mtDepth)}getMeta(e,t){let r=localStorage.getItem(n.storageKeyMeta),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let s=JSON.parse(r).filter(a=>a.identifier===e&&a.type===t)[0];if(!s)throw i;return s}async addToMerkleTree(e,t,r,i){let o=this.getMeta(e,t);await new os(new ig(Ua(o.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=localStorage.getItem(n.storageKeyMeta);if(!r)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=JSON.parse(r),o=i.filter(a=>a.identifier===e).map(a=>({...a,identifier:t}));if(o.length===0)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=[...i.filter(a=>a.identifier!==e),...o];localStorage.setItem(n.storageKeyMeta,JSON.stringify(s))}};var pP=class{constructor(e){this._storageKey=e;this._store=gu(`${e}-db`,e)}_store;async save(e,t,r="id"){return yu(e,t,this._store)}async get(e,t="id"){return Ga(e,this._store)}async load(){return m5(this._store)}async delete(e,t="id"){return Jb(e,this._store)}};var mP=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=gu(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=gu(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Et()}`),await Ga(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=U2(e);return await yu(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await Ga(e,this._merkleTreeMetaStore);if(t)return t;throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=await Ga(e,this._merkleTreeMetaStore),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let o=r.find(s=>s.identifier===e&&s.type===t);if(!o)throw i;return new os(new og(Ua(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await Ga(e,this._merkleTreeMetaStore);if(!o)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=o.find(l=>l.identifier===e&&l.type===t);if(!s)throw new Error(`Merkle tree not found for identifier ${e} and type ${t}`);await new os(new og(Ua(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await Ga(e,this._merkleTreeMetaStore);if(!r||!r?.length)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=r.map(o=>({...o,identifier:t}));await Jb(e,this._merkleTreeMetaStore),await yu(t,i,this._merkleTreeMetaStore),await yu(e,t,this._bindingStore)}};var gP=class{constructor(e){this._dataSource=e}static storageKey="circuits";async loadCircuitData(e){let t=await this._dataSource.get(e.toString(),"circuitId");if(!t)throw new Error(`item not found: ${e}`);return t}async saveCircuitData(e,t){await this._dataSource.save(e.toString(),t,"circuitId")}};var yP=class{constructor(e){this._dataSource=e}static storageKey="credentials";async listCredentials(){return(await this._dataSource.load()).filter(t=>t!==void 0).map(t=>t&&fr.fromJSON(t))}async saveCredential(e){return this._dataSource.save(e.id,e.toJSON())}async saveAllCredentials(e){for(let t of e)await this.saveCredential(t)}async removeCredential(e){return this._dataSource.delete(e)}async findCredentialById(e){let t=await this._dataSource.get(e);return t&&fr.fromJSON(t)}async findCredentialsByQuery(e){let t=dP(e);return(await this._dataSource.load()).filter(o=>t.every(s=>s.execute(o))).filter(o=>o!==void 0).map(o=>fr.fromJSON(o))}};var wP=class{constructor(e,t){this._identityDataSource=e;this._profileDataSource=t}static identitiesStorageKey="identities";static profilesStorageKey="profiles";async saveProfile(e){let r=(await this._profileDataSource.load()).filter(o=>o.genesisIdentifier===e.genesisIdentifier),i=r.length?[...r,e]:[e];for(let o=0;o<i.length;o++){let s=i[o];await this._profileDataSource.save(s.id,s)}}async getProfileByVerifier(e){return this._profileDataSource.get(e,"verifier")}async getProfilesByVerifier(e,t){return(await this._profileDataSource.load()).filter(r=>r.verifier===e&&(!t||t.every(i=>r.tags?.includes(i))))}async getProfileById(e){return this._profileDataSource.get(e)}async getProfilesByGenesisIdentifier(e){return(await this._profileDataSource.load()).filter(t=>t.genesisIdentifier===e)}async getAllIdentities(){return this._identityDataSource.load()}async saveIdentity(e){return this._identityDataSource.save(e.did,e,"did")}async getIdentity(e){return this._identityDataSource.get(e,"did")}};var bP=class{constructor(e){this.opts=e;this._verificationKeyPath=this.opts.verificationFileName??this._verificationKeyPath,this._provingKeyPath=this.opts.provingFileName??this._provingKeyPath,this._wasmFilePath=this.opts.wasmFileName??this._wasmFilePath}_verificationKeyPath="verification_key.json";_provingKeyPath="circuit_final.zkey";_wasmFilePath="circuit.wasm";_fs=null;_browserNotSupportedError=new Error("File system operations are not supported in browser environment");async getFs(){return this._fs?this._fs:(this._fs={existsSync:()=>{throw this._browserNotSupportedError},readFileSync:()=>{throw this._browserNotSupportedError},writeFileSync:()=>{throw this._browserNotSupportedError},mkdirSync:()=>{throw this._browserNotSupportedError}},this._fs)}async loadCircuitData(e){let t=await this.loadCircuitFile(e,this._verificationKeyPath),r=await this.loadCircuitFile(e,this._provingKeyPath),i=await this.loadCircuitFile(e,this._wasmFilePath);return{circuitId:e,wasm:i,provingKey:r,verificationKey:t}}async loadCircuitFile(e,t){let r=`${this.opts.dirname}/${e}/${t}`,i=await this.getFs();if(i.existsSync(r)){let o=i.readFileSync(r);return new Uint8Array(o)}return null}async writeCircuitFile(e,t,r,i){let o=`${this.opts.dirname}/${e}`,s=`${o}/${t}`,a=await this.getFs();a.mkdirSync(o,{recursive:!0}),a.writeFileSync(s,r,i)}async saveCircuitData(e,t){t.verificationKey&&await this.writeCircuitFile(e,this._verificationKeyPath,t.verificationKey,"utf-8"),t.provingKey&&await this.writeCircuitFile(e,this._provingKeyPath,t.provingKey),t.wasm&&await this.writeCircuitFile(e,this._wasmFilePath,t.wasm)}};var Lc=n=>{if(!n){let e=an.hash(new Array(3).fill(0n));return{proof:new yt,treeState:{state:me.fromBigInt(e),claimsRoot:Le,revocationRoot:Le,rootOfRoots:Le}}}return{proof:n.mtp,treeState:Z6(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},lp=n=>{let e=!1,t;n.existence?e=!0:n.auxExistence&&(t={key:me.fromBigInt(n.auxIndex),value:me.fromBigInt(n.auxValue)});let r=n.siblings.map(s=>me.fromBigInt(s)),i=new yt({siblings:r,nodeAux:t,existence:e});return{root:me.fromBigInt(n.root),proof:i}},_A=n=>{if(!n)return[{operator:Jt.$noop,fieldName:""}];let e=[],t=Object.entries(n);if(!t.length)throw new Error("query must have at least 1 predicate");for(let[r,i]of t){let o=Object.entries(i);if(o.length===0){e.push({operator:Jt.$sd,fieldName:r});continue}for(let[a,l]of o){if(!Jt[a])throw new Error("operator is not supported by lib");let c=Jt[a];e.push({operator:c,fieldName:r,operatorValue:l})}}return e},$A=async(n,e,t,r)=>{let i={...n,slotIndex:0,merklizedSchema:!1,datatype:"",claimPathKey:BigInt(0),values:[],path:new rr};if(!n.fieldName&&n.operator!==0)throw new Error("query must have a field name if operator is not $noop");if(n.fieldName&&(i.datatype=await rr.newTypeFromContext(e,`${t}.${n.fieldName}`,r)),await Nw(JSON.parse(e),r,t)||(i.merklizedSchema=!0),!i.merklizedSchema)i.slotIndex=await Gw(n.fieldName,t,Me.encode(e));else try{let s=await fD(e,t,n.fieldName,r);i.claimPathKey=await s.mtEntry(),i.path=s}catch(s){throw new Error(`field does not exist in the schema ${s.message}`)}if(n.operatorValue!==void 0){if(!_6(i.datatype,n.operator))throw new Error(`operator ${n.operator} is not supported for datatype ${i.datatype}`);if((n.operator===0||n.operator===16)&&n.operatorValue)throw new Error(`operator value should be undefined for ${n.operator} operator`);let s;switch(n.operator){case 0:case 16:s=[];break;case 11:s=Twe(n.operatorValue);break;default:s=await e3(n.operatorValue,i.datatype)}i.values=s}return i},bb=async(n,e,t,r)=>{let i=_A(t);return Promise.all(i.map(o=>$A(o,e,n,r)))},e3=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await yc.hashValue(e,n[r]);else t[0]=await yc.hashValue(e,n);return t},Twe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")};async function xP(n,e){e=e||{};let t;try{t=await WebAssembly.compile(n)}catch(u){throw new Error(u)}let r="",i="",o=await WebAssembly.instantiate(t,{runtime:{exceptionHandler:function(u){let d;throw u==1?d=`Signal not found.
413
+ `);for(let d=0;d<c.length;d++){let h=Hge(BigInt(c[d])%this.prime,this.n32);for(let f=0;f<this.n32;f++)this.instance.exports.writeSharedRWMemory(f,h[this.n32-1-f]);try{this.instance.exports.setInputSignal(a,l,d),i++}catch(f){throw new Error(f)}}}),i<this.instance.exports.getInputSize())throw new Error(`Not all inputs have been set. Only ${i} out of ${this.instance.exports.getInputSize()}`)}async calculateWitness(e,t){let r=[];await this._doCalculateWitness(e,t);for(let i=0;i<this.witnessSize;i++){this.instance.exports.getWitness(i);let o=new Uint32Array(this.n32);for(let s=0;s<this.n32;s++)o[this.n32-1-s]=this.instance.exports.readSharedRWMemory(s);r.push(rT(o))}return r}async calculateBinWitness(e,t){let r=new Uint32Array(this.witnessSize*this.n32),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t);for(let o=0;o<this.witnessSize;o++){this.instance.exports.getWitness(o);let s=o*this.n32;for(let a=0;a<this.n32;a++)r[s+a]=this.instance.exports.readSharedRWMemory(a)}return i}async calculateWTNSBin(e,t){let r=new Uint32Array(this.witnessSize*this.n32+this.n32+11),i=new Uint8Array(r.buffer);await this._doCalculateWitness(e,t),i[0]=119,i[1]=116,i[2]=110,i[3]=115,r[1]=2,r[2]=2,r[3]=1;let o=this.n32*4,a=(8+o).toString(16);r[4]=parseInt(a.slice(0,8),16),r[5]=parseInt(a.slice(8,16),16),r[6]=o,this.instance.exports.getRawPrime();let l=7;for(let d=0;d<this.n32;d++)r[l+d]=this.instance.exports.readSharedRWMemory(d);l+=this.n32,r[l]=this.witnessSize,l++,r[l]=2,l++;let u=(o*this.witnessSize).toString(16);r[l]=parseInt(u.slice(0,8),16),r[l+1]=parseInt(u.slice(8,16),16),l+=2;for(let d=0;d<this.witnessSize;d++){this.instance.exports.getWitness(d);for(let h=0;h<this.n32;h++)r[l+h]=this.instance.exports.readSharedRWMemory(h);l+=this.n32}return i}};function Hge(n,e){let t=[],r=BigInt(4294967296);for(;n;)t.unshift(Number(n%r)),n=n/r;if(e){let i=e-t.length;for(;i>0;)t.unshift(0),i--}return t}function rT(n){let e=BigInt(0),t=BigInt(4294967296);for(let r=0;r<n.length;r++)e=e*t+BigInt(n[r]);return e}function Kge(n){let e=[];return t(e,n),e;function t(r,i){if(Array.isArray(i))for(let o=0;o<i.length;o++)t(r,i[o]);else r.push(i)}}function Jge(n){let e=BigInt(2)**BigInt(64),t=BigInt("0xCBF29CE484222325");for(let o=0;o<n.length;o++)t^=BigInt(n[o].charCodeAt()),t*=BigInt(1099511628211),t%=e;let r=t.toString(16),i=16-r.length;return r="0".repeat(i).concat(r),r}var Fm=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function KA(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"}function iT(n){if(!Number.isSafeInteger(n)||n<0)throw new Error("positive integer expected, got "+n)}function to(n,...e){if(!KA(n))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(n.length))throw new Error("Uint8Array expected of length "+e+", got length="+n.length)}function qge(n){if(typeof n!="function"||typeof n.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");iT(n.outputLen),iT(n.blockLen)}function FA(n,e=!0){if(n.destroyed)throw new Error("Hash instance has been destroyed");if(e&&n.finished)throw new Error("Hash#digest() has already been called")}function Qge(n,e){to(n);let t=e.outputLen;if(n.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function kA(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function zB(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Cc(n,e){return n<<32-e|n>>>e}var nY=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Vge=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function ob(n){if(to(n),nY)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Vge[n[t]];return e}var eu={_0:48,_9:57,A:65,F:70,a:97,f:102};function OV(n){if(n>=eu._0&&n<=eu._9)return n-eu._0;if(n>=eu.A&&n<=eu.F)return n-(eu.A-10);if(n>=eu.a&&n<=eu.f)return n-(eu.a-10)}function wT(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);if(nY)return Uint8Array.fromHex(n);let e=n.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(t);for(let i=0,o=0;i<t;i++,o+=2){let s=OV(n.charCodeAt(o)),a=OV(n.charCodeAt(o+1));if(s===void 0||a===void 0){let l=n[o]+n[o+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+o)}r[i]=s*16+a}return r}function JA(n){if(typeof n!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(n))}function bT(n){return typeof n=="string"&&(n=JA(n)),to(n),n}function mi(...n){let e=0;for(let r=0;r<n.length;r++){let i=n[r];to(i),e+=i.length}let t=new Uint8Array(e);for(let r=0,i=0;r<n.length;r++){let o=n[r];t.set(o,i),i+=o.length}return t}var OA=class{};function Yge(n){let e=r=>n().update(bT(r)).digest(),t=n();return e.outputLen=t.outputLen,e.blockLen=t.blockLen,e.create=()=>n(),e}function rY(n=32){if(Fm&&typeof Fm.getRandomValues=="function")return Fm.getRandomValues(new Uint8Array(n));if(Fm&&typeof Fm.randomBytes=="function")return Uint8Array.from(Fm.randomBytes(n));throw new Error("crypto.getRandomValues must be defined")}function zge(n,e,t,r){if(typeof n.setBigUint64=="function")return n.setBigUint64(e,t,r);let i=BigInt(32),o=BigInt(4294967295),s=Number(t>>i&o),a=Number(t&o),l=r?4:0,c=r?0:4;n.setUint32(e+l,s,r),n.setUint32(e+c,a,r)}function jge(n,e,t){return n&e^~n&t}function Wge(n,e,t){return n&e^n&t^e&t}var oT=class extends OA{constructor(e,t,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=zB(this.buffer)}update(e){FA(this),e=bT(e),to(e);let{view:t,buffer:r,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let a=Math.min(i-this.pos,o-s);if(a===i){let l=zB(e);for(;i<=o-s;s+=i)this.process(l,s);continue}r.set(e.subarray(s,s+a),this.pos),this.pos+=a,s+=a,this.pos===i&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){FA(this),Qge(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:i,isLE:o}=this,{pos:s}=this;t[s++]=128,kA(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(r,0),s=0);for(let d=s;d<i;d++)t[d]=0;zge(r,i-8,BigInt(this.length*8),o),this.process(r,0);let a=zB(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let c=l/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)a.setUint32(4*d,u[d],o)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:t,buffer:r,length:i,finished:o,destroyed:s,pos:a}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=a,i%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Kd=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Zge=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]),Jd=new Uint32Array(64),sT=class extends oT{constructor(e=32){super(64,e,8,!1),this.A=Kd[0]|0,this.B=Kd[1]|0,this.C=Kd[2]|0,this.D=Kd[3]|0,this.E=Kd[4]|0,this.F=Kd[5]|0,this.G=Kd[6]|0,this.H=Kd[7]|0}get(){let{A:e,B:t,C:r,D:i,E:o,F:s,G:a,H:l}=this;return[e,t,r,i,o,s,a,l]}set(e,t,r,i,o,s,a,l){this.A=e|0,this.B=t|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=a|0,this.H=l|0}process(e,t){for(let d=0;d<16;d++,t+=4)Jd[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let h=Jd[d-15],f=Jd[d-2],p=Cc(h,7)^Cc(h,18)^h>>>3,w=Cc(f,17)^Cc(f,19)^f>>>10;Jd[d]=w+Jd[d-7]+p+Jd[d-16]|0}let{A:r,B:i,C:o,D:s,E:a,F:l,G:c,H:u}=this;for(let d=0;d<64;d++){let h=Cc(a,6)^Cc(a,11)^Cc(a,25),f=u+h+jge(a,l,c)+Zge[d]+Jd[d]|0,w=(Cc(r,2)^Cc(r,13)^Cc(r,22))+Wge(r,i,o)|0;u=c,c=l,l=a,a=s+f|0,s=o,o=i,i=r,r=f+w|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,a=a+this.E|0,l=l+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,i,o,s,a,l,c,u)}roundClean(){kA(Jd)}destroy(){this.set(0,0,0,0,0,0,0,0),kA(this.buffer)}},IT=Yge(()=>new sT);var ET=BigInt(0),GA=BigInt(1);function NA(n,e){if(typeof e!="boolean")throw new Error(n+" boolean expected, got "+e)}function LA(n){let e=n.toString(16);return e.length&1?"0"+e:e}function iY(n){if(typeof n!="string")throw new Error("hex string expected, got "+typeof n);return n===""?ET:BigInt("0x"+n)}function cb(n){return iY(ob(n))}function oY(n){return to(n),iY(ob(Uint8Array.from(n).reverse()))}function xT(n,e){return wT(n.toString(16).padStart(e*2,"0"))}function sY(n,e){return xT(n,e).reverse()}function Lo(n,e,t){let r;if(typeof e=="string")try{r=wT(e)}catch(o){throw new Error(n+" must be hex string or Uint8Array, cause: "+o)}else if(KA(e))r=Uint8Array.from(e);else throw new Error(n+" must be hex string or Uint8Array");let i=r.length;if(typeof t=="number"&&i!==t)throw new Error(n+" of length "+t+" expected, got "+i);return r}var jB=n=>typeof n=="bigint"&&ET<=n;function aY(n,e,t){return jB(n)&&jB(e)&&jB(t)&&e<=n&&n<t}function Xge(n,e,t,r){if(!aY(e,t,r))throw new Error("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function tb(n){let e;for(e=0;n>ET;n>>=GA,e+=1);return e}function _ge(n,e){return n>>BigInt(e)&GA}var ip=n=>(GA<<BigInt(n))-GA;function $ge(n,e,t){if(typeof n!="number"||n<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 t!="function")throw new Error("hmacFn must be a function");let r=f=>new Uint8Array(f),i=f=>Uint8Array.of(f),o=r(n),s=r(n),a=0,l=()=>{o.fill(1),s.fill(0),a=0},c=(...f)=>t(s,o,...f),u=(f=r(0))=>{s=c(i(0),f),o=c(),f.length!==0&&(s=c(i(1),f),o=c())},d=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,p=[];for(;f<e;){o=c();let w=o.slice();p.push(w),f+=o.length}return mi(...p)};return(f,p)=>{l(),u(f);let w;for(;!(w=p(d()));)u();return l(),w}}function eye(n){return typeof n=="function"&&Number.isSafeInteger(n.outputLen)}function qA(n,e,t={}){if(!n||typeof n!="object")throw new Error("expected valid options object");function r(i,o,s){let a=n[i];if(s&&a===void 0)return;let l=typeof a;if(l!==o||a===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}Object.entries(e).forEach(([i,o])=>r(i,o,!1)),Object.entries(t).forEach(([i,o])=>r(i,o,!0))}var Lr=()=>{throw new Error("not implemented")};function aT(n){let e=new WeakMap;return(t,...r)=>{let i=e.get(t);if(i!==void 0)return i;let o=n(t,...r);return e.set(t,o),o}}var es=BigInt(0),eo=BigInt(1),np=BigInt(2),tye=BigInt(3),cY=BigInt(4),lY=BigInt(5),uY=BigInt(8);function Ba(n,e){let t=n%e;return t>=es?t:e+t}function GV(n,e){if(n===es)throw new Error("invert: expected non-zero number");if(e<=es)throw new Error("invert: expected positive modulus, got "+e);let t=Ba(n,e),r=e,i=es,o=eo;for(;t!==es;){let a=r/t,l=r%t,c=i-o*a;r=t,t=l,i=o,o=c}if(r!==eo)throw new Error("invert: does not exist");return Ba(i,e)}function dY(n,e){let t=(n.ORDER+eo)/cY,r=n.pow(e,t);if(!n.eql(n.sqr(r),e))throw new Error("Cannot find square root");return r}function nye(n,e){let t=(n.ORDER-lY)/uY,r=n.mul(e,np),i=n.pow(r,t),o=n.mul(e,i),s=n.mul(n.mul(o,np),i),a=n.mul(o,n.sub(s,n.ONE));if(!n.eql(n.sqr(a),e))throw new Error("Cannot find square root");return a}function rye(n){if(n<BigInt(3))throw new Error("sqrt is not defined for small field");let e=n-eo,t=0;for(;e%np===es;)e/=np,t++;let r=np,i=lb(n);for(;UA(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return dY;let o=i.pow(r,e),s=(e+eo)/np;return function(l,c){if(l.is0(c))return c;if(UA(l,c)!==1)throw new Error("Cannot find square root");let u=t,d=l.mul(l.ONE,o),h=l.pow(c,e),f=l.pow(c,s);for(;!l.eql(h,l.ONE);){if(l.is0(h))return l.ZERO;let p=1,w=l.sqr(h);for(;!l.eql(w,l.ONE);)if(p++,w=l.sqr(w),p===u)throw new Error("Cannot find square root");let y=eo<<BigInt(u-p-1),v=l.pow(d,y);u=p,d=l.sqr(v),h=l.mul(h,d),f=l.mul(f,v)}return f}}function iye(n){return n%cY===tye?dY:n%uY===lY?nye:rye(n)}var oye=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function sye(n){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=oye.reduce((r,i)=>(r[i]="function",r),e);return qA(n,t),n}function MA(n,e,t){if(t<es)throw new Error("invalid exponent, negatives unsupported");if(t===es)return n.ONE;if(t===eo)return e;let r=n.ONE,i=e;for(;t>es;)t&eo&&(r=n.mul(r,i)),i=n.sqr(i),t>>=eo;return r}function nb(n,e,t=!1){let r=new Array(e.length).fill(t?n.ZERO:void 0),i=e.reduce((s,a,l)=>n.is0(a)?s:(r[l]=s,n.mul(s,a)),n.ONE),o=n.inv(i);return e.reduceRight((s,a,l)=>n.is0(a)?s:(r[l]=n.mul(s,r[l]),n.mul(s,a)),o),r}function UA(n,e){let t=(n.ORDER-eo)/np,r=n.pow(e,t),i=n.eql(r,n.ONE),o=n.eql(r,n.ZERO),s=n.eql(r,n.neg(n.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function aye(n,e){e!==void 0&&iT(e);let t=e!==void 0?e:n.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}function lb(n,e,t=!1,r={}){if(n<=es)throw new Error("invalid field: expected ORDER > 0, got "+n);let i,o;if(typeof e=="object"&&e!=null){if(r.sqrt||t)throw new Error("cannot specify opts in two arguments");let u=e;u.BITS&&(i=u.BITS),u.sqrt&&(o=u.sqrt),typeof u.isLE=="boolean"&&(t=u.isLE)}else typeof e=="number"&&(i=e),r.sqrt&&(o=r.sqrt);let{nBitLength:s,nByteLength:a}=aye(n,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l,c=Object.freeze({ORDER:n,isLE:t,BITS:s,BYTES:a,MASK:ip(s),ZERO:es,ONE:eo,create:u=>Ba(u,n),isValid:u=>{if(typeof u!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof u);return es<=u&&u<n},is0:u=>u===es,isValidNot0:u=>!c.is0(u)&&c.isValid(u),isOdd:u=>(u&eo)===eo,neg:u=>Ba(-u,n),eql:(u,d)=>u===d,sqr:u=>Ba(u*u,n),add:(u,d)=>Ba(u+d,n),sub:(u,d)=>Ba(u-d,n),mul:(u,d)=>Ba(u*d,n),pow:(u,d)=>MA(c,u,d),div:(u,d)=>Ba(u*GV(d,n),n),sqrN:u=>u*u,addN:(u,d)=>u+d,subN:(u,d)=>u-d,mulN:(u,d)=>u*d,inv:u=>GV(u,n),sqrt:o||(u=>(l||(l=iye(n)),l(c,u))),toBytes:u=>t?sY(u,a):xT(u,a),fromBytes:u=>{if(u.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+u.length);return t?oY(u):cb(u)},invertBatch:u=>nb(c,u),cmov:(u,d,h)=>h?d:u});return Object.freeze(c)}function fY(n){if(typeof n!="bigint")throw new Error("field order must be bigint");let e=n.toString(2).length;return Math.ceil(e/8)}function AT(n){let e=fY(n);return e+Math.ceil(e/2)}function hY(n,e,t=!1){let r=n.length,i=fY(e),o=AT(e);if(r<16||r<o||r>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+r);let s=t?oY(n):cb(n),a=Ba(s,e-eo)+eo;return t?sY(a,i):xT(a,i)}var Um=BigInt(0),rp=BigInt(1);function rb(n,e){let t=e.negate();return n?t:e}function cT(n,e,t){let r=s=>s.pz,i=nb(n.Fp,t.map(r));return t.map((s,a)=>s.toAffine(i[a])).map(n.fromAffine)}function pY(n,e){if(!Number.isSafeInteger(n)||n<=0||n>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+n)}function WB(n,e){pY(n,e);let t=Math.ceil(e/n)+1,r=2**(n-1),i=2**n,o=ip(n),s=BigInt(n);return{windows:t,windowSize:r,mask:o,maxNumber:i,shiftBy:s}}function NV(n,e,t){let{windowSize:r,mask:i,maxNumber:o,shiftBy:s}=t,a=Number(n&i),l=n>>s;a>r&&(a-=o,l+=rp);let c=e*r,u=c+Math.abs(a)-1,d=a===0,h=a<0,f=e%2!==0;return{nextN:l,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:c}}function cye(n,e){if(!Array.isArray(n))throw new Error("array expected");n.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function lye(n,e){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((t,r)=>{if(!e.isValid(t))throw new Error("invalid scalar at index "+r)})}var ZB=new WeakMap,mY=new WeakMap;function XB(n){return mY.get(n)||1}function UV(n){if(n!==Um)throw new Error("invalid wNAF")}function uye(n,e){return{constTimeNegate:rb,hasPrecomputes(t){return XB(t)!==1},unsafeLadder(t,r,i=n.ZERO){let o=t;for(;r>Um;)r&rp&&(i=i.add(o)),o=o.double(),r>>=rp;return i},precomputeWindow(t,r){let{windows:i,windowSize:o}=WB(r,e),s=[],a=t,l=a;for(let c=0;c<i;c++){l=a,s.push(l);for(let u=1;u<o;u++)l=l.add(a),s.push(l);a=l.double()}return s},wNAF(t,r,i){let o=n.ZERO,s=n.BASE,a=WB(t,e);for(let l=0;l<a.windows;l++){let{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:f,offsetF:p}=NV(i,l,a);i=c,d?s=s.add(rb(f,r[p])):o=o.add(rb(h,r[u]))}return UV(i),{p:o,f:s}},wNAFUnsafe(t,r,i,o=n.ZERO){let s=WB(t,e);for(let a=0;a<s.windows&&i!==Um;a++){let{nextN:l,offset:c,isZero:u,isNeg:d}=NV(i,a,s);if(i=l,!u){let h=r[c];o=o.add(d?h.negate():h)}}return UV(i),o},getPrecomputes(t,r,i){let o=ZB.get(r);return o||(o=this.precomputeWindow(r,t),t!==1&&(typeof i=="function"&&(o=i(o)),ZB.set(r,o))),o},wNAFCached(t,r,i){let o=XB(t);return this.wNAF(o,this.getPrecomputes(o,t,i),r)},wNAFCachedUnsafe(t,r,i,o){let s=XB(t);return s===1?this.unsafeLadder(t,r,o):this.wNAFUnsafe(s,this.getPrecomputes(s,t,i),r,o)},setWindowSize(t,r){pY(r,e),mY.set(t,r),ZB.delete(t)}}}function dye(n,e,t,r){let i=e,o=n.ZERO,s=n.ZERO;for(;t>Um||r>Um;)t&rp&&(o=o.add(i)),r&rp&&(s=s.add(i)),i=i.double(),t>>=rp,r>>=rp;return{p1:o,p2:s}}function fye(n,e,t,r){cye(t,n),lye(r,e);let i=t.length,o=r.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=n.ZERO,a=tb(BigInt(i)),l=1;a>12?l=a-3:a>4?l=a-2:a>0&&(l=2);let c=ip(l),u=new Array(Number(c)+1).fill(s),d=Math.floor((e.BITS-1)/l)*l,h=s;for(let f=d;f>=0;f-=l){u.fill(s);for(let w=0;w<o;w++){let y=r[w],v=Number(y>>BigInt(f)&c);u[v]=u[v].add(t[w])}let p=s;for(let w=u.length-1,y=s;w>0;w--)y=y.add(u[w]),p=p.add(y);if(h=h.add(p),f!==0)for(let w=0;w<l;w++)h=h.double()}return h}function HV(n,e){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return sye(e),e}else return lb(n)}function hye(n,e,t={}){if(!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);for(let a of["p","n","h"]){let l=e[a];if(!(typeof l=="bigint"&&l>Um))throw new Error(`CURVE.${a} must be positive bigint`)}let r=HV(e.p,t.Fp),i=HV(e.n,t.Fn),s=["Gx","Gy","a","b"];for(let a of s)if(!r.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:i}}var pye=cb;function qd(n,e){if(sb(n),sb(e),n<0||n>=1<<8*e)throw new Error("invalid I2OSP input: "+n);let t=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)t[r]=n&255,n>>>=8;return new Uint8Array(t)}function mye(n,e){let t=new Uint8Array(n.length);for(let r=0;r<n.length;r++)t[r]=n[r]^e[r];return t}function sb(n){if(!Number.isSafeInteger(n))throw new Error("number expected")}function gye(n,e,t,r){to(n),to(e),sb(t),e.length>255&&(e=r(mi(JA("H2C-OVERSIZE-DST-"),e)));let{outputLen:i,blockLen:o}=r,s=Math.ceil(t/i);if(t>65535||s>255)throw new Error("expand_message_xmd: invalid lenInBytes");let a=mi(e,qd(e.length,1)),l=qd(0,o),c=qd(t,2),u=new Array(s),d=r(mi(l,n,c,qd(0,1),a));u[0]=r(mi(d,qd(1,1),a));for(let f=1;f<=s;f++){let p=[mye(d,u[f-1]),qd(f+1,1),a];u[f]=r(mi(...p))}return mi(...u).slice(0,t)}function yye(n,e,t,r,i){if(to(n),to(e),sb(t),e.length>255){let o=Math.ceil(2*r/8);e=i.create({dkLen:o}).update(JA("H2C-OVERSIZE-DST-")).update(e).digest()}if(t>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:t}).update(n).update(qd(t,2)).update(e).update(qd(e.length,1)).digest()}function KV(n,e,t){qA(t,{p:"bigint",m:"number",k:"number",hash:"function"});let{p:r,k:i,m:o,hash:s,expand:a,DST:l}=t;if(!KA(l)&&typeof l!="string")throw new Error("DST must be string or uint8array");if(!eye(t.hash))throw new Error("expected valid hash");to(n),sb(e);let c=typeof l=="string"?JA(l):l,u=r.toString(2).length,d=Math.ceil((u+i)/8),h=e*o*d,f;if(a==="xmd")f=gye(n,c,h,s);else if(a==="xof")f=yye(n,c,h,i,s);else if(a==="_internal_pass")f=n;else throw new Error('expand must be "xmd" or "xof"');let p=new Array(e);for(let w=0;w<e;w++){let y=new Array(o);for(let v=0;v<o;v++){let B=d*(v+w*o),U=f.subarray(B,B+d);y[v]=Ba(pye(U),r)}p[w]=y}return p}function JV(n,e,t){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(o){return n.fromAffine(e(o))}function i(o){let s=o.clearCofactor();return s.equals(n.ZERO)?n.ZERO:(s.assertValidity(),s)}return{defaults:t,hashToCurve(o,s){let a=t.DST?t.DST:{},l=Object.assign({},t,a,s),c=KV(o,2,l),u=r(c[0]),d=r(c[1]);return i(u.add(d))},encodeToCurve(o,s){let a=t.encodeDST?t.encodeDST:{},l=Object.assign({},t,a,s),c=KV(o,1,l);return i(r(c[0]))},mapToCurve(o){if(!Array.isArray(o))throw new Error("expected array of bigints");for(let s of o)if(typeof s!="bigint")throw new Error("expected array of bigints");return i(r(o))}}}var HA=class extends OA{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,qge(e);let r=bT(t);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 i=this.blockLen,o=new Uint8Array(i);o.set(r.length>i?e.create().update(r).digest():r);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),kA(o)}update(e){return FA(this),this.iHash.update(e),this}digestInto(e){FA(this),to(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:t,iHash:r,finished:i,destroyed:o,blockLen:s,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},gY=(n,e,t)=>new HA(n,e).update(t).digest();gY.create=(n,e)=>new HA(n,e);function qV(n){n.lowS!==void 0&&NA("lowS",n.lowS),n.prehash!==void 0&&NA("prehash",n.prehash)}var lT=class extends Error{constructor(e=""){super(e)}},tu={Err:lT,_tlv:{encode:(n,e)=>{let{Err:t}=tu;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");let r=e.length/2,i=LA(r);if(i.length/2&128)throw new t("tlv.encode: long form length too big");let o=r>127?LA(i.length/2|128):"";return LA(n)+o+i+e},decode(n,e){let{Err:t}=tu,r=0;if(n<0||n>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==n)throw new t("tlv.decode: wrong tlv");let i=e[r++],o=!!(i&128),s=0;if(!o)s=i;else{let l=i&127;if(!l)throw new t("tlv.decode(long): indefinite length not supported");if(l>4)throw new t("tlv.decode(long): byte length is too big");let c=e.subarray(r,r+l);if(c.length!==l)throw new t("tlv.decode: length bytes not complete");if(c[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(let u of c)s=s<<8|u;if(r+=l,s<128)throw new t("tlv.decode(long): not minimal encoding")}let a=e.subarray(r,r+s);if(a.length!==s)throw new t("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+s)}}},_int:{encode(n){let{Err:e}=tu;if(n<ib)throw new e("integer: negative integers are not allowed");let t=LA(n);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(n){let{Err:e}=tu;if(n[0]&128)throw new e("invalid signature integer: negative");if(n[0]===0&&!(n[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return cb(n)}},toSig(n){let{Err:e,_int:t,_tlv:r}=tu,i=Lo("signature",n),{v:o,l:s}=r.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:a,l}=r.decode(2,o),{v:c,l:u}=r.decode(2,l);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(a),s:t.decode(c)}},hexFromSig(n){let{_tlv:e,_int:t}=tu,r=e.encode(2,t.encode(n.r)),i=e.encode(2,t.encode(n.s)),o=r+i;return e.encode(48,o)}},ib=BigInt(0),Gm=BigInt(1),wye=BigInt(2),BA=BigInt(3),bye=BigInt(4);function yY(n,e,t){function r(i){let o=n.sqr(i),s=n.mul(o,i);return n.add(n.add(s,n.mul(i,e)),t)}return r}function vT(n,e,t){let{BYTES:r}=n;function i(o){let s;if(typeof o=="bigint")s=o;else{let a=Lo("private key",o);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");let l=new Uint8Array(r);l.set(a,l.length-a.length),a=l}try{s=n.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof o}`)}}if(t&&(s=n.create(s)),!n.isValidNot0(s))throw new Error("invalid private key: out of range [1..N-1]");return s}return i}function wY(n,e={}){let{Fp:t,Fn:r}=hye("weierstrass",n,e),{h:i,n:o}=n;qA(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:s}=e;if(s&&(!t.is0(n.a)||typeof s.beta!="bigint"||typeof s.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(D,V,K){let{x:q,y:G}=V.toAffine(),x=t.toBytes(q);if(NA("isCompressed",K),K){a();let S=!t.isOdd(G);return mi(bY(S),x)}else return mi(Uint8Array.of(4),x,t.toBytes(G))}function c(D){to(D);let V=t.BYTES,K=V+1,q=2*V+1,G=D.length,x=D[0],S=D.subarray(1);if(G===K&&(x===2||x===3)){let M=t.fromBytes(S);if(!t.isValid(M))throw new Error("bad point: is not on curve, wrong x");let b=h(M),A;try{A=t.sqrt(b)}catch(Q){let Y=Q instanceof Error?": "+Q.message:"";throw new Error("bad point: is not on curve, sqrt error"+Y)}a();let R=t.isOdd(A);return(x&1)===1!==R&&(A=t.neg(A)),{x:M,y:A}}else if(G===q&&x===4){let M=t.fromBytes(S.subarray(V*0,V*1)),b=t.fromBytes(S.subarray(V*1,V*2));if(!f(M,b))throw new Error("bad point: is not on curve");return{x:M,y:b}}else throw new Error(`bad point: got length ${G}, expected compressed=${K} or uncompressed=${q}`)}let u=e.toBytes||l,d=e.fromBytes||c,h=yY(t,n.a,n.b);function f(D,V){let K=t.sqr(V),q=h(D);return t.eql(K,q)}if(!f(n.Gx,n.Gy))throw new Error("bad curve params: generator point");let p=t.mul(t.pow(n.a,BA),bye),w=t.mul(t.sqr(n.b),BigInt(27));if(t.is0(t.add(p,w)))throw new Error("bad curve params: a or b");function y(D,V,K=!1){if(!t.isValid(V)||K&&t.is0(V))throw new Error(`bad point coordinate ${D}`);return V}function v(D){if(!(D instanceof F))throw new Error("ProjectivePoint expected")}let B=aT((D,V)=>{let{px:K,py:q,pz:G}=D;if(t.eql(G,t.ONE))return{x:K,y:q};let x=D.is0();V==null&&(V=x?t.ONE:t.inv(G));let S=t.mul(K,V),M=t.mul(q,V),b=t.mul(G,V);if(x)return{x:t.ZERO,y:t.ZERO};if(!t.eql(b,t.ONE))throw new Error("invZ was invalid");return{x:S,y:M}}),U=aT(D=>{if(D.is0()){if(e.allowInfinityPoint&&!t.is0(D.py))return;throw new Error("bad point: ZERO")}let{x:V,y:K}=D.toAffine();if(!t.isValid(V)||!t.isValid(K))throw new Error("bad point: x or y not field elements");if(!f(V,K))throw new Error("bad point: equation left != right");if(!D.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(D,V,K,q,G){return K=new F(t.mul(K.px,D),K.py,K.pz),V=rb(q,V),K=rb(G,K),V.add(K)}class F{constructor(V,K,q){this.px=y("x",V),this.py=y("y",K,!0),this.pz=y("z",q),Object.freeze(this)}static fromAffine(V){let{x:K,y:q}=V||{};if(!V||!t.isValid(K)||!t.isValid(q))throw new Error("invalid affine point");if(V instanceof F)throw new Error("projective point not allowed");return t.is0(K)&&t.is0(q)?F.ZERO:new F(K,q,t.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(V){return cT(F,"pz",V)}static fromBytes(V){return to(V),F.fromHex(V)}static fromHex(V){let K=F.fromAffine(d(Lo("pointHex",V)));return K.assertValidity(),K}static fromPrivateKey(V){let K=vT(r,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return F.BASE.multiply(K(V))}static msm(V,K){return fye(F,r,V,K)}precompute(V=8,K=!0){return I.setWindowSize(this,V),K||this.multiply(BA),this}_setWindowSize(V){this.precompute(V)}assertValidity(){U(this)}hasEvenY(){let{y:V}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(V)}equals(V){v(V);let{px:K,py:q,pz:G}=this,{px:x,py:S,pz:M}=V,b=t.eql(t.mul(K,M),t.mul(x,G)),A=t.eql(t.mul(q,M),t.mul(S,G));return b&&A}negate(){return new F(this.px,t.neg(this.py),this.pz)}double(){let{a:V,b:K}=n,q=t.mul(K,BA),{px:G,py:x,pz:S}=this,M=t.ZERO,b=t.ZERO,A=t.ZERO,R=t.mul(G,G),J=t.mul(x,x),Q=t.mul(S,S),Y=t.mul(G,x);return Y=t.add(Y,Y),A=t.mul(G,S),A=t.add(A,A),M=t.mul(V,A),b=t.mul(q,Q),b=t.add(M,b),M=t.sub(J,b),b=t.add(J,b),b=t.mul(M,b),M=t.mul(Y,M),A=t.mul(q,A),Q=t.mul(V,Q),Y=t.sub(R,Q),Y=t.mul(V,Y),Y=t.add(Y,A),A=t.add(R,R),R=t.add(A,R),R=t.add(R,Q),R=t.mul(R,Y),b=t.add(b,R),Q=t.mul(x,S),Q=t.add(Q,Q),R=t.mul(Q,Y),M=t.sub(M,R),A=t.mul(Q,J),A=t.add(A,A),A=t.add(A,A),new F(M,b,A)}add(V){v(V);let{px:K,py:q,pz:G}=this,{px:x,py:S,pz:M}=V,b=t.ZERO,A=t.ZERO,R=t.ZERO,J=n.a,Q=t.mul(n.b,BA),Y=t.mul(K,x),Z=t.mul(q,S),X=t.mul(G,M),_=t.add(K,q),E=t.add(x,S);_=t.mul(_,E),E=t.add(Y,Z),_=t.sub(_,E),E=t.add(K,G);let m=t.add(x,M);return E=t.mul(E,m),m=t.add(Y,X),E=t.sub(E,m),m=t.add(q,G),b=t.add(S,M),m=t.mul(m,b),b=t.add(Z,X),m=t.sub(m,b),R=t.mul(J,E),b=t.mul(Q,X),R=t.add(b,R),b=t.sub(Z,R),R=t.add(Z,R),A=t.mul(b,R),Z=t.add(Y,Y),Z=t.add(Z,Y),X=t.mul(J,X),E=t.mul(Q,E),Z=t.add(Z,X),X=t.sub(Y,X),X=t.mul(J,X),E=t.add(E,X),Y=t.mul(Z,E),A=t.add(A,Y),Y=t.mul(m,E),b=t.mul(_,b),b=t.sub(b,Y),Y=t.mul(_,Z),R=t.mul(m,R),R=t.add(R,Y),new F(b,A,R)}subtract(V){return this.add(V.negate())}is0(){return this.equals(F.ZERO)}multiply(V){let{endo:K}=e;if(!r.isValidNot0(V))throw new Error("invalid scalar: out of range");let q,G,x=S=>I.wNAFCached(this,S,F.normalizeZ);if(K){let{k1neg:S,k1:M,k2neg:b,k2:A}=K.splitScalar(V),{p:R,f:J}=x(M),{p:Q,f:Y}=x(A);G=J.add(Y),q=k(K.beta,R,Q,S,b)}else{let{p:S,f:M}=x(V);q=S,G=M}return F.normalizeZ([q,G])[0]}multiplyUnsafe(V){let{endo:K}=e,q=this;if(!r.isValid(V))throw new Error("invalid scalar: out of range");if(V===ib||q.is0())return F.ZERO;if(V===Gm)return q;if(I.hasPrecomputes(this))return this.multiply(V);if(K){let{k1neg:G,k1:x,k2neg:S,k2:M}=K.splitScalar(V),{p1:b,p2:A}=dye(F,q,x,M);return k(K.beta,b,A,G,S)}else return I.wNAFCachedUnsafe(q,V)}multiplyAndAddUnsafe(V,K,q){let G=this.multiplyUnsafe(K).add(V.multiplyUnsafe(q));return G.is0()?void 0:G}toAffine(V){return B(this,V)}isTorsionFree(){let{isTorsionFree:V}=e;return i===Gm?!0:V?V(F,this):I.wNAFCachedUnsafe(this,o).is0()}clearCofactor(){let{clearCofactor:V}=e;return i===Gm?this:V?V(F,this):this.multiplyUnsafe(i)}toBytes(V=!0){return NA("isCompressed",V),this.assertValidity(),u(F,this,V)}toRawBytes(V=!0){return this.toBytes(V)}toHex(V=!0){return ob(this.toBytes(V))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}F.BASE=new F(n.Gx,n.Gy,t.ONE),F.ZERO=new F(t.ZERO,t.ONE,t.ZERO),F.Fp=t,F.Fn=r;let P=r.BITS,I=uye(F,e.endo?Math.ceil(P/2):P);return F}function QV(n){let{CURVE:e,curveOpts:t}=IY(n),r=wY(e,t);return xye(n,r)}function bY(n){return Uint8Array.of(n?2:3)}function Iye(n,e,t={}){qA(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let r=e.randomBytes||rY,i=e.hmac||((q,...G)=>gY(e.hash,q,mi(...G))),{Fp:o,Fn:s}=n,{ORDER:a,BITS:l}=s;function c(q){let G=a>>Gm;return q>G}function u(q){return c(q)?s.neg(q):q}function d(q,G){if(!s.isValidNot0(G))throw new Error(`invalid signature ${q}: out of range 1..CURVE.n`)}class h{constructor(G,x,S){d("r",G),d("s",x),this.r=G,this.s=x,S!=null&&(this.recovery=S),Object.freeze(this)}static fromCompact(G){let x=s.BYTES,S=Lo("compactSignature",G,x*2);return new h(s.fromBytes(S.subarray(0,x)),s.fromBytes(S.subarray(x,x*2)))}static fromDER(G){let{r:x,s:S}=tu.toSig(Lo("DER",G));return new h(x,S)}assertValidity(){}addRecoveryBit(G){return new h(this.r,this.s,G)}recoverPublicKey(G){let x=o.ORDER,{r:S,s:M,recovery:b}=this;if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");if(a*wye<x&&b>1)throw new Error("recovery id is ambiguous for h>1 curve");let R=b===2||b===3?S+a:S;if(!o.isValid(R))throw new Error("recovery id 2 or 3 invalid");let J=o.toBytes(R),Q=n.fromHex(mi(bY((b&1)===0),J)),Y=s.inv(R),Z=U(Lo("msgHash",G)),X=s.create(-Z*Y),_=s.create(M*Y),E=n.BASE.multiplyUnsafe(X).add(Q.multiplyUnsafe(_));if(E.is0())throw new Error("point at infinify");return E.assertValidity(),E}hasHighS(){return c(this.s)}normalizeS(){return this.hasHighS()?new h(this.r,s.neg(this.s),this.recovery):this}toBytes(G){if(G==="compact")return mi(s.toBytes(this.r),s.toBytes(this.s));if(G==="der")return wT(tu.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return ob(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ob(this.toBytes("compact"))}}let f=vT(s,t.allowedPrivateKeyLengths,t.wrapPrivateKey),p={isValidPrivateKey(q){try{return f(q),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{let q=a;return hY(r(AT(q)),q)},precompute(q=8,G=n.BASE){return G.precompute(q,!1)}};function w(q,G=!0){return n.fromPrivateKey(q).toBytes(G)}function y(q){if(typeof q=="bigint")return!1;if(q instanceof n)return!0;let x=Lo("key",q).length,S=o.BYTES,M=S+1,b=2*S+1;if(!(t.allowedPrivateKeyLengths||s.BYTES===M))return x===M||x===b}function v(q,G,x=!0){if(y(q)===!0)throw new Error("first arg must be private key");if(y(G)===!1)throw new Error("second arg must be public key");return n.fromHex(G).multiply(f(q)).toBytes(x)}let B=e.bits2int||function(q){if(q.length>8192)throw new Error("input is too large");let G=cb(q),x=q.length*8-l;return x>0?G>>BigInt(x):G},U=e.bits2int_modN||function(q){return s.create(B(q))},k=ip(l);function F(q){return Xge("num < 2^"+l,q,ib,k),s.toBytes(q)}function P(q,G,x=I){if(["recovered","canonical"].some(_=>_ in x))throw new Error("sign() legacy options not supported");let{hash:S}=e,{lowS:M,prehash:b,extraEntropy:A}=x;M==null&&(M=!0),q=Lo("msgHash",q),qV(x),b&&(q=Lo("prehashed msgHash",S(q)));let R=U(q),J=f(G),Q=[F(J),F(R)];if(A!=null&&A!==!1){let _=A===!0?r(o.BYTES):A;Q.push(Lo("extraEntropy",_))}let Y=mi(...Q),Z=R;function X(_){let E=B(_);if(!s.isValidNot0(E))return;let m=s.inv(E),O=n.BASE.multiply(E).toAffine(),g=s.create(O.x);if(g===ib)return;let H=s.create(m*s.create(Z+g*J));if(H===ib)return;let N=(O.x===g?0:2)|Number(O.y&Gm),C=H;return M&&c(H)&&(C=u(H),N^=1),new h(g,C,N)}return{seed:Y,k2sig:X}}let I={lowS:e.lowS,prehash:!1},D={lowS:e.lowS,prehash:!1};function V(q,G,x=I){let{seed:S,k2sig:M}=P(q,G,x);return $ge(e.hash.outputLen,s.BYTES,i)(S,M)}n.BASE.precompute(8);function K(q,G,x,S=D){let M=q;G=Lo("msgHash",G),x=Lo("publicKey",x),qV(S);let{lowS:b,prehash:A,format:R}=S;if("strict"in S)throw new Error("options.strict was renamed to lowS");if(R!==void 0&&!["compact","der","js"].includes(R))throw new Error('format must be "compact", "der" or "js"');let J=typeof M=="string"||KA(M),Q=!J&&!R&&typeof M=="object"&&M!==null&&typeof M.r=="bigint"&&typeof M.s=="bigint";if(!J&&!Q)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let Y,Z;try{if(Q)if(R===void 0||R==="js")Y=new h(M.r,M.s);else throw new Error("invalid format");if(J){try{R!=="compact"&&(Y=h.fromDER(M))}catch(C){if(!(C instanceof tu.Err))throw C}!Y&&R!=="der"&&(Y=h.fromCompact(M))}Z=n.fromHex(x)}catch{return!1}if(!Y||b&&Y.hasHighS())return!1;A&&(G=e.hash(G));let{r:X,s:_}=Y,E=U(G),m=s.inv(_),O=s.create(E*m),g=s.create(X*m),H=n.BASE.multiplyUnsafe(O).add(Z.multiplyUnsafe(g));return H.is0()?!1:s.create(H.x)===X}return Object.freeze({getPublicKey:w,getSharedSecret:v,sign:V,verify:K,utils:p,Point:n,Signature:h})}function IY(n){let e={a:n.a,b:n.b,p:n.Fp.ORDER,n:n.n,h:n.h,Gx:n.Gx,Gy:n.Gy},t=n.Fp,r=lb(e.n,n.nBitLength),i={Fp:t,Fn:r,allowedPrivateKeyLengths:n.allowedPrivateKeyLengths,allowInfinityPoint:n.allowInfinityPoint,endo:n.endo,wrapPrivateKey:n.wrapPrivateKey,isTorsionFree:n.isTorsionFree,clearCofactor:n.clearCofactor,fromBytes:n.fromBytes,toBytes:n.toBytes};return{CURVE:e,curveOpts:i}}function Eye(n){let{CURVE:e,curveOpts:t}=IY(n),r={hash:n.hash,hmac:n.hmac,randomBytes:n.randomBytes,lowS:n.lowS,bits2int:n.bits2int,bits2int_modN:n.bits2int_modN};return{CURVE:e,curveOpts:t,ecdsaOpts:r}}function xye(n,e){let{Fp:t,Fn:r}=e;function i(a){return aY(a,Gm,r.ORDER)}let o=yY(t,n.a,n.b),s=vT(r,n.allowedPrivateKeyLengths,n.wrapPrivateKey);return Object.assign({},{CURVE:n,Point:e,ProjectivePoint:e,normPrivateKeyToScalar:s,weierstrassEquation:o,isWithinCurveOrder:i})}function Aye(n,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:n})}function vye(n){let{CURVE:e,curveOpts:t,ecdsaOpts:r}=Eye(n),i=wY(e,t),o=Iye(i,r,t);return Aye(n,o)}var Cye=BigInt(0),TA=BigInt(1),VV=BigInt(2),km=BigInt(3);function Sye(n){let e=[];for(;n>TA;n>>=TA)(n&TA)===Cye?e.unshift(0):(n&km)===km?(e.unshift(-1),n+=TA):e.unshift(1);return e}function Dye(n){let{Fp:e,Fr:t,Fp2:r,Fp6:i,Fp12:o}=n.fields,s=QV(n.G1),a=Object.assign(s,JV(s.Point,n.G1.mapToCurve,{...n.htfDefaults,...n.G1.htfDefaults})),l=QV(n.G2),c=Object.assign(l,JV(l.Point,n.G2.mapToCurve,{...n.htfDefaults,...n.G2.htfDefaults})),u;u=(E,m,O,g,H,N)=>o.mul034(g,r.mul(O,N),r.mul(m,H),E);let d=r.div(r.ONE,r.mul(r.ONE,VV));function h(E,m,O,g){let H=r.sqr(O),N=r.sqr(g),C=r.mulByB(r.mul(N,km)),W=r.mul(C,km),$=r.sub(r.sub(r.sqr(r.add(O,g)),N),H),ee=r.sub(C,H),le=r.mul(r.sqr(m),km),Ce=r.neg($);return E.push([ee,le,Ce]),m=r.mul(r.mul(r.mul(r.sub(H,W),m),O),d),O=r.sub(r.sqr(r.mul(r.add(H,W),d)),r.mul(r.sqr(C),km)),g=r.mul(H,$),{Rx:m,Ry:O,Rz:g}}function f(E,m,O,g,H,N){let C=r.sub(O,r.mul(N,g)),W=r.sub(m,r.mul(H,g)),$=r.sub(r.mul(C,H),r.mul(W,N)),ee=r.neg(C),le=W;E.push([$,ee,le]);let Ce=r.sqr(W),Ae=r.mul(Ce,W),Re=r.mul(Ce,m),_e=r.add(r.sub(Ae,r.mul(Re,VV)),r.mul(r.sqr(C),g));return m=r.mul(W,_e),O=r.sub(r.mul(r.sub(Re,_e),C),r.mul(Ae,O)),g=r.mul(g,Ae),{Rx:m,Ry:O,Rz:g}}let p=Sye(n.params.ateLoopSize),w=aT(E=>{let m=E,{x:O,y:g}=m.toAffine(),H=O,N=g,C=r.neg(g),W=H,$=N,ee=r.ONE,le=[];for(let Ce of p){let Ae=[];({Rx:W,Ry:$,Rz:ee}=h(Ae,W,$,ee)),Ce&&({Rx:W,Ry:$,Rz:ee}=f(Ae,W,$,ee,H,Ce===-1?C:N)),le.push(Ae)}if(n.postPrecompute){let Ce=le[le.length-1];n.postPrecompute(W,$,ee,H,N,f.bind(null,Ce))}return le});function y(E,m=!1){let O=o.ONE;if(E.length){let g=E[0][0].length;for(let H=0;H<g;H++){O=o.sqr(O);for(let[N,C,W]of E)for(let[$,ee,le]of N[H])O=u($,ee,le,O,C,W)}}return m?o.finalExponentiate(O):O}function v(E,m=!0){let O=[];cT(a.Point,"pz",E.map(({g1:g})=>g)),cT(c.Point,"pz",E.map(({g2:g})=>g));for(let{g1:g,g2:H}of E){if(g.is0()||H.is0())throw new Error("pairing is not available for ZERO point");g.assertValidity(),H.assertValidity();let N=g.toAffine();O.push([w(H),N.x,N.y])}return y(O,m)}function B(E,m,O=!0){return v([{g1:E,g2:m}],O)}let U=n.randomBytes||rY,k={randomPrivateKey:()=>{let E=AT(t.ORDER);return hY(U(E),t.ORDER)},calcPairingPrecomputes:w};function F(E){if(!Array.isArray(E)||E.length===0)throw new Error("expected non-empty array")}function P(E){return E instanceof a.Point?E:a.Point.fromHex(E)}function I(E){return E instanceof c.Point?E:G.fromHex(E)}function D(E,m){function O(C){return C instanceof E.Point?C:E.Point.fromHex(C)}function g(C){return C instanceof m.Point?C:m.Point.fromHex(C)}function H(C){if(!(C instanceof m.Point))throw new Error(`expected valid message hashed to ${N?"G2":"G1"} curve`);return C}let N=m.Point.Fp.BYTES>E.Point.Fp.BYTES;return{getPublicKey(C){return E.Point.fromPrivateKey(C)},sign(C,W,$){if($!=null)throw new Error("sign() expects 2 arguments");return H(C).assertValidity(),C.multiply(E.normPrivateKeyToScalar(W))},verify(C,W,$,ee){if(ee!=null)throw new Error("verify() expects 3 arguments");C=g(C),$=O($);let le=$.negate(),Ce=E.Point.BASE,Ae=H(W),Re=C,Pe=v(N?[{g1:le,g2:Ae},{g1:Ce,g2:Re}]:[{g1:Ae,g2:le},{g1:Re,g2:Ce}]);return o.eql(Pe,o.ONE)},aggregatePublicKeys(C){F(C),C=C.map($=>O($));let W=C.reduce(($,ee)=>$.add(ee),E.Point.ZERO);return W.assertValidity(),W},aggregateSignatures(C){F(C),C=C.map($=>g($));let W=C.reduce(($,ee)=>$.add(ee),m.Point.ZERO);return W.assertValidity(),W},hash(C,W){to(C);let $=W?{DST:W}:void 0;return m.hashToCurve(C,$)},Signature:N?n.G2.Signature:n.G1.ShortSignature}}let V=D(a,c),K=D(c,a),{ShortSignature:q}=n.G1,{Signature:G}=n.G2;function x(E,m){return E instanceof a.Point?E:K.hash(Lo("point",E),m?.DST)}function S(E,m){return E instanceof c.Point?E:V.hash(Lo("point",E),m?.DST)}function M(E){return V.getPublicKey(E).toBytes(!0)}function b(E){return K.getPublicKey(E).toBytes(!0)}function A(E,m,O){let g=S(E,O),H=V.sign(g,m);return E instanceof c.Point?H:G.toBytes(H)}function R(E,m,O){let g=x(E,O),H=K.sign(g,m);return E instanceof a.Point?H:q.toBytes(H)}function J(E,m,O,g){let H=S(m,g);return V.verify(E,H,O)}function Q(E,m,O,g){let H=x(m,g);return K.verify(E,H,O)}function Y(E){let m=V.aggregatePublicKeys(E);return E[0]instanceof a.Point?m:m.toBytes(!0)}function Z(E){let m=V.aggregateSignatures(E);return E[0]instanceof c.Point?m:G.toBytes(m)}function X(E){let m=K.aggregateSignatures(E);return E[0]instanceof a.Point?m:q.toBytes(m)}function _(E,m,O,g){if(F(m),O.length!==m.length)throw new Error("amount of public keys and messages should be equal");let H=I(E),N=m.map(ee=>S(ee,g)),C=O.map(P),W=new Map;for(let ee=0;ee<C.length;ee++){let le=C[ee],Ce=N[ee],Ae=W.get(Ce);Ae===void 0&&(Ae=[],W.set(Ce,Ae)),Ae.push(le)}let $=[];try{for(let[ee,le]of W){let Ce=le.reduce((Ae,Re)=>Ae.add(Re));$.push({g1:Ce,g2:ee})}return $.push({g1:a.Point.BASE.negate(),g2:H}),o.eql(v($),o.ONE)}catch{return!1}}return a.Point.BASE.precompute(4),{longSignatures:V,shortSignatures:K,millerLoopBatch:y,pairing:B,pairingBatch:v,verifyBatch:_,curves:{G1:s.Point,G2:l.Point},fields:{Fr:t,Fp:e,Fp2:r,Fp6:i,Fp12:o},params:{ateLoopSize:n.params.ateLoopSize,twistType:n.params.twistType,r:n.params.r,G1b:n.G1.b,G2b:n.G2.b},utils:k,getPublicKey:M,getPublicKeyForShortSignatures:b,sign:A,signShortSignature:R,verify:J,verifyShortSignature:Q,aggregatePublicKeys:Y,aggregateSignatures:Z,aggregateShortSignatures:X,G1:a,G2:c,Signature:G,ShortSignature:q}}var YV=BigInt(0),Om=BigInt(1),nu=BigInt(2),zV=BigInt(3);function _B(n,e,t,r,i=1,o){let s=BigInt(o===void 0?r:o),a=t**BigInt(r),l=[];for(let c=0;c<i;c++){let u=BigInt(c+1),d=[];for(let h=0,f=Om;h<r;h++){let p=(u*f-u)/s%a;d.push(n.pow(e,p)),f*=t}l.push(d)}return l}function Lye(n,e,t){let r=e.pow(t,(n.ORDER-Om)/zV),i=e.pow(t,(n.ORDER-Om)/nu);function o(h,f){let p=e.mul(e.frobeniusMap(h,1),r),w=e.mul(e.frobeniusMap(f,1),i);return[p,w]}let s=e.pow(t,(n.ORDER**nu-Om)/zV),a=e.pow(t,(n.ORDER**nu-Om)/nu);if(!e.eql(a,e.neg(e.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function l(h,f){return[e.mul(h,s),e.neg(f)]}let c=h=>(f,p)=>{let w=p.toAffine(),y=h(w.x,w.y);return f.fromAffine({x:y[0],y:y[1]})},u=c(o),d=c(l);return{psi:o,psi2:l,G2psi:u,G2psi2:d,PSI_X:r,PSI_Y:i,PSI2_X:s,PSI2_Y:a}}function Bye(n){let{ORDER:e}=n,t=lb(e),r=t.create(n.NONRESIDUE||BigInt(-1)),i=t.div(t.ONE,nu),o=_B(t,r,t.ORDER,2)[0],s=({c0:x,c1:S},{c0:M,c1:b})=>({c0:t.add(x,M),c1:t.add(S,b)}),a=({c0:x,c1:S},{c0:M,c1:b})=>({c0:t.sub(x,M),c1:t.sub(S,b)}),l=({c0:x,c1:S},M)=>{if(typeof M=="bigint")return{c0:t.mul(x,M),c1:t.mul(S,M)};let{c0:b,c1:A}=M,R=t.mul(x,b),J=t.mul(S,A),Q=t.sub(R,J),Y=t.sub(t.mul(t.add(x,S),t.add(b,A)),t.add(R,J));return{c0:Q,c1:Y}},c=({c0:x,c1:S})=>{let M=t.add(x,S),b=t.sub(x,S),A=t.add(x,x);return{c0:t.mul(M,b),c1:t.mul(A,S)}},u=x=>{if(x.length!==2)throw new Error("invalid tuple");let S=x.map(M=>t.create(M));return{c0:S[0],c1:S[1]}};function d(x,S){return typeof x=="bigint"&&YV<=x&&x<S}let h=e*e,f=u(n.FP2_NONRESIDUE),p={ORDER:h,isLE:t.isLE,NONRESIDUE:f,BITS:tb(h),BYTES:Math.ceil(tb(h)/8),MASK:ip(tb(h)),ZERO:{c0:t.ZERO,c1:t.ZERO},ONE:{c0:t.ONE,c1:t.ZERO},create:x=>x,isValid:({c0:x,c1:S})=>d(x,h)&&d(S,h),is0:({c0:x,c1:S})=>t.is0(x)&&t.is0(S),isValidNot0:x=>!p.is0(x)&&p.isValid(x),eql:({c0:x,c1:S},{c0:M,c1:b})=>t.eql(x,M)&&t.eql(S,b),neg:({c0:x,c1:S})=>({c0:t.neg(x),c1:t.neg(S)}),pow:(x,S)=>MA(p,x,S),invertBatch:x=>nb(p,x),add:s,sub:a,mul:l,sqr:c,addN:s,subN:a,mulN:l,sqrN:c,div:(x,S)=>p.mul(x,typeof S=="bigint"?t.inv(t.create(S)):p.inv(S)),inv:({c0:x,c1:S})=>{let M=t.inv(t.create(x*x+S*S));return{c0:t.mul(M,t.create(x)),c1:t.mul(M,t.create(-S))}},sqrt:x=>{if(n.Fp2sqrt)return n.Fp2sqrt(x);let{c0:S,c1:M}=x;if(t.is0(M))return UA(t,S)===1?p.create({c0:t.sqrt(S),c1:t.ZERO}):p.create({c0:t.ZERO,c1:t.sqrt(t.div(S,r))});let b=t.sqrt(t.sub(t.sqr(S),t.mul(t.sqr(M),r))),A=t.mul(t.add(b,S),i);UA(t,A)===-1&&(A=t.sub(A,b));let J=t.sqrt(A),Q=p.create({c0:J,c1:t.div(t.mul(M,i),J)});if(!p.eql(p.sqr(Q),x))throw new Error("Cannot find square root");let Y=Q,Z=p.neg(Y),{re:X,im:_}=p.reim(Y),{re:E,im:m}=p.reim(Z);return _>m||_===m&&X>E?Y:Z},isOdd:x=>{let{re:S,im:M}=p.reim(x),b=S%nu,A=S===YV,R=M%nu;return BigInt(b||A&&R)==Om},fromBytes(x){if(x.length!==p.BYTES)throw new Error("fromBytes invalid length="+x.length);return{c0:t.fromBytes(x.subarray(0,t.BYTES)),c1:t.fromBytes(x.subarray(t.BYTES))}},toBytes:({c0:x,c1:S})=>mi(t.toBytes(x),t.toBytes(S)),cmov:({c0:x,c1:S},{c0:M,c1:b},A)=>({c0:t.cmov(x,M,A),c1:t.cmov(S,b,A)}),reim:({c0:x,c1:S})=>({re:x,im:S}),mulByNonresidue:({c0:x,c1:S})=>p.mul({c0:x,c1:S},f),mulByB:n.Fp2mulByB,fromBigTuple:u,frobeniusMap:({c0:x,c1:S},M)=>({c0:x,c1:t.mul(S,o[M%2])})},w=({c0:x,c1:S,c2:M},{c0:b,c1:A,c2:R})=>({c0:p.add(x,b),c1:p.add(S,A),c2:p.add(M,R)}),y=({c0:x,c1:S,c2:M},{c0:b,c1:A,c2:R})=>({c0:p.sub(x,b),c1:p.sub(S,A),c2:p.sub(M,R)}),v=({c0:x,c1:S,c2:M},b)=>{if(typeof b=="bigint")return{c0:p.mul(x,b),c1:p.mul(S,b),c2:p.mul(M,b)};let{c0:A,c1:R,c2:J}=b,Q=p.mul(x,A),Y=p.mul(S,R),Z=p.mul(M,J);return{c0:p.add(Q,p.mulByNonresidue(p.sub(p.mul(p.add(S,M),p.add(R,J)),p.add(Y,Z)))),c1:p.add(p.sub(p.mul(p.add(x,S),p.add(A,R)),p.add(Q,Y)),p.mulByNonresidue(Z)),c2:p.sub(p.add(Y,p.mul(p.add(x,M),p.add(A,J))),p.add(Q,Z))}},B=({c0:x,c1:S,c2:M})=>{let b=p.sqr(x),A=p.mul(p.mul(x,S),nu),R=p.mul(p.mul(S,M),nu),J=p.sqr(M);return{c0:p.add(p.mulByNonresidue(R),b),c1:p.add(p.mulByNonresidue(J),A),c2:p.sub(p.sub(p.add(p.add(A,p.sqr(p.add(p.sub(x,S),M))),R),b),J)}},[U,k]=_B(p,f,t.ORDER,6,2,3),F={ORDER:p.ORDER,isLE:p.isLE,BITS:3*p.BITS,BYTES:3*p.BYTES,MASK:ip(3*p.BITS),ZERO:{c0:p.ZERO,c1:p.ZERO,c2:p.ZERO},ONE:{c0:p.ONE,c1:p.ZERO,c2:p.ZERO},create:x=>x,isValid:({c0:x,c1:S,c2:M})=>p.isValid(x)&&p.isValid(S)&&p.isValid(M),is0:({c0:x,c1:S,c2:M})=>p.is0(x)&&p.is0(S)&&p.is0(M),isValidNot0:x=>!F.is0(x)&&F.isValid(x),neg:({c0:x,c1:S,c2:M})=>({c0:p.neg(x),c1:p.neg(S),c2:p.neg(M)}),eql:({c0:x,c1:S,c2:M},{c0:b,c1:A,c2:R})=>p.eql(x,b)&&p.eql(S,A)&&p.eql(M,R),sqrt:Lr,div:(x,S)=>F.mul(x,typeof S=="bigint"?t.inv(t.create(S)):F.inv(S)),pow:(x,S)=>MA(F,x,S),invertBatch:x=>nb(F,x),add:w,sub:y,mul:v,sqr:B,addN:w,subN:y,mulN:v,sqrN:B,inv:({c0:x,c1:S,c2:M})=>{let b=p.sub(p.sqr(x),p.mulByNonresidue(p.mul(M,S))),A=p.sub(p.mulByNonresidue(p.sqr(M)),p.mul(x,S)),R=p.sub(p.sqr(S),p.mul(x,M)),J=p.inv(p.add(p.mulByNonresidue(p.add(p.mul(M,A),p.mul(S,R))),p.mul(x,b)));return{c0:p.mul(J,b),c1:p.mul(J,A),c2:p.mul(J,R)}},fromBytes:x=>{if(x.length!==F.BYTES)throw new Error("fromBytes invalid length="+x.length);return{c0:p.fromBytes(x.subarray(0,p.BYTES)),c1:p.fromBytes(x.subarray(p.BYTES,2*p.BYTES)),c2:p.fromBytes(x.subarray(2*p.BYTES))}},toBytes:({c0:x,c1:S,c2:M})=>mi(p.toBytes(x),p.toBytes(S),p.toBytes(M)),cmov:({c0:x,c1:S,c2:M},{c0:b,c1:A,c2:R},J)=>({c0:p.cmov(x,b,J),c1:p.cmov(S,A,J),c2:p.cmov(M,R,J)}),fromBigSix:x=>{if(!Array.isArray(x)||x.length!==6)throw new Error("invalid Fp6 usage");return{c0:p.fromBigTuple(x.slice(0,2)),c1:p.fromBigTuple(x.slice(2,4)),c2:p.fromBigTuple(x.slice(4,6))}},frobeniusMap:({c0:x,c1:S,c2:M},b)=>({c0:p.frobeniusMap(x,b),c1:p.mul(p.frobeniusMap(S,b),U[b%6]),c2:p.mul(p.frobeniusMap(M,b),k[b%6])}),mulByFp2:({c0:x,c1:S,c2:M},b)=>({c0:p.mul(x,b),c1:p.mul(S,b),c2:p.mul(M,b)}),mulByNonresidue:({c0:x,c1:S,c2:M})=>({c0:p.mulByNonresidue(M),c1:x,c2:S}),mul1:({c0:x,c1:S,c2:M},b)=>({c0:p.mulByNonresidue(p.mul(M,b)),c1:p.mul(x,b),c2:p.mul(S,b)}),mul01({c0:x,c1:S,c2:M},b,A){let R=p.mul(x,b),J=p.mul(S,A);return{c0:p.add(p.mulByNonresidue(p.sub(p.mul(p.add(S,M),A),J)),R),c1:p.sub(p.sub(p.mul(p.add(b,A),p.add(x,S)),R),J),c2:p.add(p.sub(p.mul(p.add(x,M),b),R),J)}}},P=_B(p,f,t.ORDER,12,1,6)[0],I=({c0:x,c1:S},{c0:M,c1:b})=>({c0:F.add(x,M),c1:F.add(S,b)}),D=({c0:x,c1:S},{c0:M,c1:b})=>({c0:F.sub(x,M),c1:F.sub(S,b)}),V=({c0:x,c1:S},M)=>{if(typeof M=="bigint")return{c0:F.mul(x,M),c1:F.mul(S,M)};let{c0:b,c1:A}=M,R=F.mul(x,b),J=F.mul(S,A);return{c0:F.add(R,F.mulByNonresidue(J)),c1:F.sub(F.mul(F.add(x,S),F.add(b,A)),F.add(R,J))}},K=({c0:x,c1:S})=>{let M=F.mul(x,S);return{c0:F.sub(F.sub(F.mul(F.add(F.mulByNonresidue(S),x),F.add(x,S)),M),F.mulByNonresidue(M)),c1:F.add(M,M)}};function q(x,S){let M=p.sqr(x),b=p.sqr(S);return{first:p.add(p.mulByNonresidue(b),M),second:p.sub(p.sub(p.sqr(p.add(x,S)),M),b)}}let G={ORDER:p.ORDER,isLE:F.isLE,BITS:2*F.BITS,BYTES:2*F.BYTES,MASK:ip(2*F.BITS),ZERO:{c0:F.ZERO,c1:F.ZERO},ONE:{c0:F.ONE,c1:F.ZERO},create:x=>x,isValid:({c0:x,c1:S})=>F.isValid(x)&&F.isValid(S),is0:({c0:x,c1:S})=>F.is0(x)&&F.is0(S),isValidNot0:x=>!G.is0(x)&&G.isValid(x),neg:({c0:x,c1:S})=>({c0:F.neg(x),c1:F.neg(S)}),eql:({c0:x,c1:S},{c0:M,c1:b})=>F.eql(x,M)&&F.eql(S,b),sqrt:Lr,inv:({c0:x,c1:S})=>{let M=F.inv(F.sub(F.sqr(x),F.mulByNonresidue(F.sqr(S))));return{c0:F.mul(x,M),c1:F.neg(F.mul(S,M))}},div:(x,S)=>G.mul(x,typeof S=="bigint"?t.inv(t.create(S)):G.inv(S)),pow:(x,S)=>MA(G,x,S),invertBatch:x=>nb(G,x),add:I,sub:D,mul:V,sqr:K,addN:I,subN:D,mulN:V,sqrN:K,fromBytes:x=>{if(x.length!==G.BYTES)throw new Error("fromBytes invalid length="+x.length);return{c0:F.fromBytes(x.subarray(0,F.BYTES)),c1:F.fromBytes(x.subarray(F.BYTES))}},toBytes:({c0:x,c1:S})=>mi(F.toBytes(x),F.toBytes(S)),cmov:({c0:x,c1:S},{c0:M,c1:b},A)=>({c0:F.cmov(x,M,A),c1:F.cmov(S,b,A)}),fromBigTwelve:x=>({c0:F.fromBigSix(x.slice(0,6)),c1:F.fromBigSix(x.slice(6,12))}),frobeniusMap(x,S){let{c0:M,c1:b,c2:A}=F.frobeniusMap(x.c1,S),R=P[S%12];return{c0:F.frobeniusMap(x.c0,S),c1:F.create({c0:p.mul(M,R),c1:p.mul(b,R),c2:p.mul(A,R)})}},mulByFp2:({c0:x,c1:S},M)=>({c0:F.mulByFp2(x,M),c1:F.mulByFp2(S,M)}),conjugate:({c0:x,c1:S})=>({c0:x,c1:F.neg(S)}),mul014:({c0:x,c1:S},M,b,A)=>{let R=F.mul01(x,M,b),J=F.mul1(S,A);return{c0:F.add(F.mulByNonresidue(J),R),c1:F.sub(F.sub(F.mul01(F.add(S,x),M,p.add(b,A)),R),J)}},mul034:({c0:x,c1:S},M,b,A)=>{let R=F.create({c0:p.mul(x.c0,M),c1:p.mul(x.c1,M),c2:p.mul(x.c2,M)}),J=F.mul01(S,b,A),Q=F.mul01(F.add(x,S),p.add(M,b),A);return{c0:F.add(F.mulByNonresidue(J),R),c1:F.sub(Q,F.add(R,J))}},_cyclotomicSquare:n.Fp12cyclotomicSquare,_cyclotomicExp:n.Fp12cyclotomicExp,finalExponentiate:n.Fp12finalExponentiate};return{Fp:t,Fp2:p,Fp6:F,Fp12:G,Fp4Square:q}}var Tye=BigInt(0),uT=BigInt(1),Qd=BigInt(2),Pye=BigInt(3),EY=BigInt(6),QA=BigInt("4965661367192848881"),Rye=tb(QA),Mye=EY*QA**Qd,VA={p:BigInt("0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"),n:BigInt("0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001"),h:uT,a:Tye,b:Pye,Gx:uT,Gy:BigInt(2)},jV=lb(VA.n),xY={c0:BigInt("19485874751759354771024239261021720505790618469301721065564631296452457478373"),c1:BigInt("266929791119991161246907387137283842545076965332900288569378510910307636690")},{Fp:ab,Fp2:sn,Fp6:dT,Fp4Square:$B,Fp12:en}=Bye({ORDER:VA.p,FP2_NONRESIDUE:[BigInt(9),uT],Fp2mulByB:n=>sn.mul(n,xY),Fp12cyclotomicSquare:({c0:n,c1:e})=>{let{c0:t,c1:r,c2:i}=n,{c0:o,c1:s,c2:a}=e,{first:l,second:c}=$B(t,s),{first:u,second:d}=$B(o,i),{first:h,second:f}=$B(r,a),p=sn.mulByNonresidue(f);return{c0:dT.create({c0:sn.add(sn.mul(sn.sub(l,t),Qd),l),c1:sn.add(sn.mul(sn.sub(u,r),Qd),u),c2:sn.add(sn.mul(sn.sub(h,i),Qd),h)}),c1:dT.create({c0:sn.add(sn.mul(sn.add(p,o),Qd),p),c1:sn.add(sn.mul(sn.add(c,s),Qd),c),c2:sn.add(sn.mul(sn.add(d,a),Qd),d)})}},Fp12cyclotomicExp(n,e){let t=en.ONE;for(let r=Rye-1;r>=0;r--)t=en._cyclotomicSquare(t),_ge(e,r)&&(t=en.mul(t,n));return t},Fp12finalExponentiate:n=>{let e=u=>en.conjugate(en._cyclotomicExp(u,QA)),t=en.mul(en.conjugate(n),en.inv(n)),r=en.mul(en.frobeniusMap(t,2),t),i=en._cyclotomicSquare(e(r)),o=en.mul(en._cyclotomicSquare(i),i),s=e(o),a=e(en._cyclotomicSquare(s)),l=en.mul(en.mul(en.conjugate(a),s),en.conjugate(o)),c=en.mul(l,i);return en.mul(en.frobeniusMap(en.mul(en.conjugate(r),c),3),en.mul(en.frobeniusMap(l,2),en.mul(en.frobeniusMap(c,1),en.mul(en.mul(l,s),r))))}}),{G2psi:Fye,psi:WV}=Lye(ab,sn,sn.NONRESIDUE),eT=Object.freeze({DST:"BN254G2_XMD:SHA-256_SVDW_RO_",encodeDST:"BN254G2_XMD:SHA-256_SVDW_RO_",p:ab.ORDER,m:2,k:128,expand:"xmd",hash:IT}),kye=(n,e,t,r,i,o)=>{let s=WV(r,i);({Rx:n,Ry:e,Rz:t}=o(n,e,t,s[0],s[1]));let a=WV(s[0],s[1]);o(n,e,t,a[0],sn.neg(a[1]))},Oye={p:sn.ORDER,n:VA.n,h:BigInt("0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d"),a:sn.ZERO,b:xY,Gx:sn.fromBigTuple([BigInt("10857046999023057135944570762232829481370756359578518086990519993285655852781"),BigInt("11559732032986387107991004021392285783925812861821192530917403151452391805634")]),Gy:sn.fromBigTuple([BigInt("8495653923123431417604973247489272438418190587263600148770280649306958101930"),BigInt("4082367875863433681332203403145435568316851327593401208105741076214120093531")])},op=Dye({fields:{Fp:ab,Fp2:sn,Fp6:dT,Fp12:en,Fr:jV},G1:{...VA,Fp:ab,htfDefaults:{...eT,m:1,DST:"BN254G2_XMD:SHA-256_SVDW_RO_"},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:Lr,fromBytes:Lr,toBytes:Lr,ShortSignature:{fromBytes:Lr,fromHex:Lr,toBytes:Lr,toRawBytes:Lr,toHex:Lr}},G2:{...Oye,Fp:sn,hEff:BigInt("21888242871839275222246405745257275088844257914179612981679871602714643921549"),htfDefaults:{...eT},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(n,e)=>e.multiplyUnsafe(Mye).equals(Fye(n,e)),mapToCurve:Lr,fromBytes:Lr,toBytes:Lr,Signature:{fromBytes:Lr,fromHex:Lr,toBytes:Lr,toRawBytes:Lr,toHex:Lr}},params:{ateLoopSize:QA*EY+Qd,r:jV.ORDER,xNegative:!1,twistType:"divisive"},htfDefaults:eT,hash:IT,postPrecompute:kye});vye({a:BigInt(0),b:BigInt(3),Fp:ab,n:BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"),Gx:BigInt(1),Gy:BigInt(2),h:BigInt(1),hash:IT});var AY="groth16",Gye="auth",Nye="authV2",Uye=new TextDecoder,ZV=BigInt(0),XV=op.fields.Fp2,_V=op.fields.Fp12;async function vY(n,e,t){let r=await Uge(t),i=new TextDecoder().decode(n),o=JSON.parse(i),s=await r.calculateWTNSBin(o,0),{proof:a,publicSignals:l}=await DA.prove(e,s);return{proof:a,pub_signals:l}}var[fT,Hye]=[op.G1.ProjectivePoint,op.G2.ProjectivePoint],PA=([n,e])=>fT.fromAffine({x:BigInt(n),y:BigInt(e)}),RA=([[n,e],[t,r]])=>Hye.fromAffine({x:XV.fromBigTuple([BigInt(n),BigInt(e)]),y:XV.fromBigTuple([BigInt(t),BigInt(r)])});async function CY(n,e,t,r){if(r(e.pub_signals).challenge!==Hb(n))throw new Error("challenge is not equal to message hash");let o=JSON.parse(Uye.decode(t));return CT(e,o)}function CT(n,e){if(!e.IC)throw new Error("verification file doesn't exist for circuit");let{proof:t,pub_signals:r}=n;if(r.length+1!==e.IC.length)throw new Error(`Invalid number of public signals, expected ${e.IC.length-1} but got ${r.length}`);let i=fT.ZERO;for(let s=0;s<r.length;s++){if(BigInt(r[s])<ZV||BigInt(r[s])>=op.G1.CURVE.n)throw new Error(`Input value is not in the field ${op.G1.CURVE.n}`);if(BigInt(r[s])!==ZV){let[a,l]=e.IC[s+1].map(BigInt);i=i.add(fT.fromAffine({x:a,y:l}).multiply(BigInt(r[s])))}}i=i.add(PA(e.IC[0]));let o=op.pairingBatch([{g1:PA(t.pi_a).negate(),g2:RA(t.pi_b)},{g1:i,g2:RA(e.vk_gamma_2)},{g1:PA(t.pi_c),g2:RA(e.vk_delta_2)},{g1:PA(e.vk_alpha_1),g2:RA(e.vk_beta_2)}]);return _V.eql(o,_V.ONE)}var hT=class{methodAlg;constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}unmarshall(e){let t={};if(e.length!=3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return t.challenge=BigInt(e[0]),t.userState=BigInt(e[1]),t.userId=Je.fromBigInt(BigInt(e[2])),t}async verify(e,t,r){return CY(e,t,r,this.unmarshall)}prove(e,t,r){return vY(e,t,r)}},pT=new hT(new ru(AY,Gye)),mT=class n{methodAlg;static curveName="bn128";constructor(e){this.methodAlg=e}get alg(){return this.methodAlg.alg}get circuitId(){return this.methodAlg.circuitId}async verify(e,t,r){return CY(e,t,r,this.unmarshall)}async prove(e,t,r){let i=await vY(e,t,r);return await this.terminateCurve(),i}async terminateCurve(){(await EA(n.curveName)).terminate()}unmarshall(e){if(e.length!==3)throw new Error(`invalid number of Output values expected 3 got ${e.length}`);return{userID:Je.fromBigInt(BigInt(e[0])),challenge:BigInt(e[1]),GISTRoot:me.fromString(e[2])}}},gT=new mT(new ru(AY,Nye));yT(pT.methodAlg,()=>pT);yT(gT.methodAlg,()=>gT);var gi={registerProvingMethod:yT,getProvingMethod:tY,provingMethodGroth16AuthInstance:pT,provingMethodGroth16AuthV2Instance:gT};var Kye=(n,e)=>(Object.keys(e).forEach(t=>{if(!n[t]||typeof e[t]!=typeof n[t])return!1}),!0),Jye=n=>{let e=zq();return Object.keys(e).forEach(t=>{if(!n[t]||t!=="body"&&!(typeof e[t]==typeof n[t]))return!1}),!0};var SY=n=>{let e=tt.decode(n),t=JSON.parse(e);if(!Jye(t))throw new Error(Wq);return t};var DY=n=>{let e=jq(),t=tt.decode(n),r=JSON.parse(t);if(!Kye(r,e))throw new Error(Zq);return r};var ST=class{packers;constructor(){this.packers=new Map}getSupportedProfiles(){let e=[],t=this.getSupportedMediaTypes();for(let r of t){let i=this.packers.get(r);i&&e.push(...i.getSupportedProfiles())}return[...new Set(e)]}isProfileSupported(e,t){let r=this.packers.get(e);return r?r.isProfileSupported(t):!1}getSupportedMediaTypes(){return[...this.packers.keys()]}registerPackers(e){e.forEach(t=>{this.packers.set(t.mediaType(),t)})}async pack(e,t,r){let i=this.packers.get(e);if(!i)throw new Error(`packer for media type ${e} not found`);return await i.pack(t,r)}packMessage(e,t,r){let i=this.packers.get(e);if(!i)throw new Error(`packer for media type ${e} not found`);return i.packMessage(t,r)}async unpack(e){let r=tt.decode(e).trim(),i=this.getMediaType(r);return{unpackedMessage:await this.unpackWithSafeEnvelope(i,Me.encode(r)),unpackedMediaType:i}}async unpackWithType(e,t){let o=new TextDecoder("utf-8").decode(t).trim();return await this.unpackWithSafeEnvelope(e,Me.encode(o))}async unpackWithSafeEnvelope(e,t){let r=this.packers.get(e);if(!r)throw new Error(`packer for media type ${e} not found`);return await r.unpack(t)}getMediaType(e){let t;if(e[0]==="{")return JSON.parse(e).typ;{let i=e.split(".")[0];t=$m.parse(i,{loose:!0})}return DY(t).typ}};var yi={};sr(yi,{AcceptAuthCircuits:()=>YA,AcceptJwsAlgorithms:()=>Jm,AcceptJwzAlgorithms:()=>zA,DEFAULT_AUTH_VERIFY_DELAY:()=>LT,DEFAULT_PROOF_VERIFY_DELAY:()=>qye,MediaType:()=>Sc,PROTOCOL_MESSAGE_TYPE:()=>je,ProtocolVersion:()=>Km,SUPPORTED_PUBLIC_KEY_TYPES:()=>Hm,defaultAcceptProfile:()=>ub});var ir="https://iden3-communication.io/",DT="https://didcomm.org/",je=Object.freeze({AUTHORIZATION_REQUEST_MESSAGE_TYPE:`${ir}authorization/1.0/request`,AUTHORIZATION_RESPONSE_MESSAGE_TYPE:`${ir}authorization/1.0/response`,CREDENTIAL_ISSUANCE_REQUEST_MESSAGE_TYPE:`${ir}credentials/1.0/issuance-request`,CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:`${ir}credentials/1.0/fetch-request`,CREDENTIAL_OFFER_MESSAGE_TYPE:`${ir}credentials/1.0/offer`,CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:`${ir}credentials/1.0/issuance-response`,CREDENTIAL_REFRESH_MESSAGE_TYPE:`${ir}credentials/1.0/refresh`,DEVICE_REGISTRATION_REQUEST_MESSAGE_TYPE:`${ir}devices/1.0/registration`,MESSAGE_FETCH_REQUEST_MESSAGE_TYPE:`${ir}messages/1.0/fetch`,PROOF_GENERATION_REQUEST_MESSAGE_TYPE:`${ir}proofs/1.0/request`,PROOF_GENERATION_RESPONSE_MESSAGE_TYPE:`${ir}proofs/1.0/response`,REVOCATION_STATUS_REQUEST_MESSAGE_TYPE:`${ir}revocation/1.0/request-status`,REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE:`${ir}revocation/1.0/status`,CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE:`${ir}proofs/1.0/contract-invoke-request`,CONTRACT_INVOKE_RESPONSE_MESSAGE_TYPE:`${ir}proofs/1.0/contract-invoke-response`,CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE:`${ir}credentials/1.0/onchain-offer`,PROPOSAL_REQUEST_MESSAGE_TYPE:`${ir}credentials/0.1/proposal-request`,PROPOSAL_MESSAGE_TYPE:`${ir}credentials/0.1/proposal`,PAYMENT_REQUEST_MESSAGE_TYPE:`${ir}credentials/0.1/payment-request`,PAYMENT_MESSAGE_TYPE:`${ir}credentials/0.1/payment`,DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:`${DT}discover-features/2.0/queries`,DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE:`${DT}discover-features/2.0/disclose`,PROBLEM_REPORT_MESSAGE_TYPE:`${DT}report-problem/2.0/problem-report`}),Sc=(r=>(r.ZKPMessage="application/iden3-zkp-json",r.PlainMessage="application/iden3comm-plain-json",r.SignedMessage="application/iden3comm-signed-json",r))(Sc||{}),Hm={ES256K:["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","JsonWebKey2020"],"ES256K-R":["EcdsaSecp256k1VerificationKey2019","EcdsaSecp256k1RecoveryMethod2020","JsonWebKey2020"]},Km=(e=>(e.V1="iden3comm/v1",e))(Km||{}),YA=(t=>(t.AuthV2="authV2",t.AuthV3="authV3",t))(YA||{}),zA=(e=>(e.Groth16="groth16",e))(zA||{}),Jm=(t=>(t.ES256K="ES256K",t.ES256KR="ES256K-R",t))(Jm||{}),ub={protocolVersion:"iden3comm/v1",env:"application/iden3-zkp-json",circuits:["authV2"],alg:["groth16"]},qye=3600*1e3,LT=300*1e3;var Qye="authentication",jA=n=>{let e=n.verificationMethod||[],t=(n[Qye]||[]).map(r=>typeof r=="string"?e.find(i=>i.id===r):r).filter(r=>r);for(let r=0;r<e.length;r++){let i=e[r].id;t.findIndex(o=>o.id===i)===-1&&t.push(e[r])}return t},BT=n=>{let e=Object.keys(Hm).some(t=>Hm[t].includes(n.type));if(n.publicKeyBase58&&e)return{publicKeyBytes:M3(n.publicKeyBase58),kmsKeyType:"Secp256k1"};if(n.publicKeyBase64&&e)return{publicKeyBytes:jd(n.publicKeyBase64),kmsKeyType:"Secp256k1"};if(n.publicKeyHex&&e)return{publicKeyBytes:To(n.publicKeyHex),kmsKeyType:"Secp256k1"};if(n.publicKeyJwk&&n.publicKeyJwk.crv==="secp256k1"&&n.publicKeyJwk.x&&n.publicKeyJwk.y){let[t,r]=[jd(n.publicKeyJwk.x),jd(n.publicKeyJwk.y)].map(xi),i=t.includes("0x")?BigInt(t):BigInt(`0x${t}`),o=r.includes("0x")?BigInt(r):BigInt(`0x${r}`);return{publicKeyBytes:No.ProjectivePoint.fromAffine({x:i,y:o}).toRawBytes(!1),kmsKeyType:"Secp256k1"}}return{publicKeyBytes:null}};function Vye(n){return Object.values(Km).includes(n)}function Yye(n){return Object.values(Sc).includes(n)}function zye(n){return Object.values(YA).includes(n)}function jye(n){return Object.values(Jm).includes(n)}function Wye(n){return Object.values(zA).includes(n)}var Zye=n=>{let e=[];for(let t of n){let r=`${t.protocolVersion};env=${t.env}`;t.circuits?.length&&(r+=`;circuitId=${t.circuits.join(",")}`),t.alg?.length&&(r+=`;alg=${t.alg.join(",")}`),e.push(r)}return e},Ta=n=>{let e=n.split(";");if(e.length<2)throw new Error("Invalid accept profile");let t=e[0].trim();if(!Vye(t))throw new Error(`Protocol version '${t}' not supported`);if(e[1].split("=").length!==2)throw new Error("Invalid accept profile 'env' parameter");let i=e[1].split("=")[1].trim();if(!Yye(i))throw new Error(`Envelop '${i}' not supported`);let o=e.findIndex(c=>c.includes("circuitId="));if(i!=="application/iden3-zkp-json"&&o>0)throw new Error(`Circuits not supported for env '${i}'`);let s;o>0&&(s=e[o].split("=")[1].split(",").map(c=>c.trim()).map(c=>{if(!zye(c))throw new Error(`Circuit '${c}' not supported`);return c}));let a=e.findIndex(c=>c.includes("alg=")),l;if(a>0)if(i==="application/iden3-zkp-json")l=e[a].split("=")[1].split(",").map(c=>{if(c=c.trim(),!Wye(c))throw new Error(`Algorithm '${c}' not supported for '${i}'`);return c});else if(i==="application/iden3comm-signed-json")l=e[a].split("=")[1].split(",").map(c=>{if(c=c.trim(),!jye(c))throw new Error(`Algorithm '${c}' not supported for '${i}'`);return c});else throw new Error(`Algorithm not supported for '${i}'`);return{protocolVersion:t,env:i,circuits:s,alg:l}};var{getProvingMethod:Xye}=gi,TT=class{constructor(e){this.dataPrepareFunc=e}prepare(e,t,r){return this.dataPrepareFunc(e,t,r)}},PT=class{constructor(e){this.stateVerificationFunc=e}verify(e,t,r){return this.stateVerificationFunc(e,t,r)}},RT=class{constructor(e,t,r={acceptedStateTransitionDelay:LT}){this.provingParamsMap=e;this.verificationParamsMap=t;this._opts=r}supportedProtocolVersions=["iden3comm/v1"];supportedAlgorithms=["groth16"];supportedCircuitIds=["authV2"];packMessage(e,t){return this.pack(Me.encode(JSON.stringify(e)),t)}async pack(e,t){let r=await Xye(t.provingMethodAlg),i=this.provingParamsMap.get(t.provingMethodAlg.toString());if(!i)throw new Error(tQ);let o=new Nm(r,tt.decode(e),(a,l)=>i?.dataPreparer?.prepare(a,t.senderDID,l));o.setHeader(Gs.Type,"application/iden3-zkp-json");let s=await o.prove(i.provingKey,i.wasm);return Me.encode(s)}async unpack(e){let t=await Nm.parse(tt.decode(e)),r=new ru(t.alg,t.circuitId),i=this.verificationParamsMap.get(r.toString());if(!i?.key)throw new Error(_q);if(!await t.verify(i?.key))throw new Error($q);if(!await i?.verificationFn?.verify(t.circuitId,t.zkProof.pub_signals,this._opts))throw new Error(eQ);let a=SY(Me.encode(t.getPayload()));return _ye(t,a),a}mediaType(){return"application/iden3-zkp-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")};circuitIds=${this.supportedCircuitIds.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=Ta(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;let s=this.supportedCircuitIds,a=!i?.length||i.some(u=>s.includes(u)),l=this.supportedAlgorithms;return(!o?.length||o.some(u=>l.includes(u)))&&a}},_ye=async(n,e)=>{switch(n.circuitId){case"authV2":{if(!e.from)throw new Error(rA);let t=new La().pubSignalsUnmarshal(Me.encode(JSON.stringify(n.zkProof.pub_signals))),r=Ie.parseFromId(t.userID),i=await n.getMessageHash();if(ht.bytesToInt(i.reverse())!==t.challenge)throw new Error(rA);if(e.from!==r.string())throw new Error(rA)}break;default:throw new Error(Xq)}};var MT=class{supportedProtocolVersions=["iden3comm/v1"];packMessage(e){return e.typ="application/iden3comm-plain-json",Promise.resolve(Me.encode(JSON.stringify(e)))}async pack(e){let t=JSON.parse(tt.decode(e));return t.typ="application/iden3comm-plain-json",Promise.resolve(Me.encode(JSON.stringify(t)))}async unpack(e){return JSON.parse(tt.decode(e))}mediaType(){return"application/iden3comm-plain-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=Ta(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);if(o)throw new Error(`Algorithms are not supported for ${r} media type`);return!0}};var FT=class{constructor(e,t){this._kms=e;this._documentResolver=t}supportedAlgorithms=["ES256K","ES256K-R"];supportedProtocolVersions=["iden3comm/v1"];packMessage(e,t){return this.packInternal(e,t)}async pack(e,t){let r=JSON.parse(tt.decode(e));return this.packInternal(r,t)}async unpack(e){let t=tt.decode(e),[r,i]=t.split("."),o=JSON.parse(Vb(r)),s=JSON.parse(Vb(i)),a=lG(o.kid)?.did;if(a&&a!==s.from)throw new Error(`Sender does not match DID in message with kid ${o?.kid}`);let l=await this.resolveDidDoc(s.from),c=jA(l);if(!c?.length)throw new Error(`No verification methods defined in the DID document of ${l.id}`);if(o.kid){let d=c.find(h=>h.id===o.kid);if(!d)throw new Error(`verification method with specified kid ${o.kid} is not found in the DID Document`);c=[d]}if(!LG(t,c))throw new Error("JWS verification failed");return s}mediaType(){return"application/iden3comm-signed-json"}getSupportedProfiles(){return this.supportedProtocolVersions.map(e=>`${e};env=${this.mediaType()};alg=${this.supportedAlgorithms.join(",")}`)}isProfileSupported(e){let{protocolVersion:t,env:r,circuits:i,alg:o}=Ta(e);if(!this.supportedProtocolVersions.includes(t)||r!==this.mediaType())return!1;if(i)throw new Error(`Circuits are not supported for ${r} media type`);return!o?.length||o.some(a=>this.supportedAlgorithms.includes(a))}async resolveDidDoc(e){let t;try{let r=await this._documentResolver.resolve(e);if(!r?.didDocument?.id)throw new Error(`did document for ${e} is not found in resolution result`);t=r.didDocument}catch(r){throw new Error(`did document for ${e} is not resolved: ${r.message}`)}return t}async packInternal(e,t){if(!t.alg)throw new Error("Missing algorithm");let r=e.from??"";if(!r)throw new Error("Missing sender DID");if(!Hm[t.alg]?.length)throw new Error(`No supported verification methods for algorithm ${t.alg}`);let o=t.didDocument??await this.resolveDidDoc(r),s=jA(o);if(!s.length)throw new Error(`No verification methods defined in the DID document of ${o.id}`);let a=t.kid?s.find(v=>v.id===t.kid):s[0];if(!a)throw new Error(`No key found with id ${t.kid} in DID document of ${o.id}`);let{publicKeyBytes:l,kmsKeyType:c}=BT(a);if(!l&&!c&&(a.blockchainAccountId||a.ethereumAddress)&&!t.signer)throw new Error(`No signer provided for ${a.blockchainAccountId||a.ethereumAddress}`);let u=a.id,d={alg:t.alg,kid:u,typ:"application/iden3comm-signed-json"},h=Qb(JSON.stringify(d)),f=Qb(JSON.stringify(e)),p=`${h}.${f}`,w=Me.encode(p),y;if(t.signer){let v=await t.signer(a,w);y=qb(v)}else{if(!l)throw new Error("No public key found");if(!c)throw new Error("No KMS key type found");let v=await this._kms.sign({type:c,id:qs(c,xi(l))},w,{alg:t.alg});y=qb(v)}return Me.encode(`${p}.${y}`)}};var LY=(r=>(r.Pending="pending",r.Completed="completed",r.Rejected="rejected",r))(LY||{});var kT=(t=>(t.AUTHV2="authV2",t.ETH_IDENTITY="ethIdentity",t))(kT||{});var BY=(e=>(e.FeatureType="feature-type",e))(BY||{}),TY=(i=>(i.Accept="accept",i.Protocol="protocol",i.GoalCode="goal-code",i.Header="header",i))(TY||{});var $ye=n=>n.reduce((e,t)=>{let r=t.query.groupId;if(!r)return e;let i=e.get(r);if(!i){let s=Ma(12),l=new DataView(s.buffer).getUint32(0);return e.set(r,{query:t.query,linkNonce:l}),e}let o=F3(i.query.credentialSubject,t.query.credentialSubject);return e.set(r,{...i,query:{skipClaimRevocationCheck:i.query.skipClaimRevocationCheck||t.query.skipClaimRevocationCheck,...i.query,credentialSubject:o}}),e},new Map),qm=async(n,e,t,r,i)=>{let o=e??[],s=$ye(o),a=new Map,l=[];for(let c of o){let u;try{if(!i.supportedCircuits.includes(c.circuitId)){if(c.optional)continue;throw new Error(`Circuit ${c.circuitId} is not allowed`)}let h=c.query,f=h.groupId,p=s.get(f);if(f){if(!p)throw new Error(`Invalid group id ${h.groupId}`);let y=p.query;if(!a.has(f)){let v=await r.findCredentialByProofQuery(n,p.query);if(!v.cred){if(c.optional)continue;throw new Error(Fe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY+`${JSON.stringify(y)}`)}a.set(f,v)}}let w=a.get(f);u=await r.generateProof(c,n,{verifierDid:t,challenge:i.challenge,skipRevocation:!!h.skipClaimRevocationCheck,credential:w?.cred,credentialRevocationStatus:w?.revStatus,linkNonce:p?.linkNonce?BigInt(p.linkNonce):void 0})}catch(d){let h=[Fe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_IDENTITY_OR_PROFILE,Fe.ERRORS.ID_WALLET_NO_CREDENTIAL_SATISFIED_QUERY,Fe.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED];if(d instanceof Error&&(h.includes(d.message)||d.message.includes(Fe.ERRORS.PROOF_SERVICE_NO_CREDENTIAL_FOR_QUERY))&&c.optional)continue;throw d}l.push(u)}return l},OT=async(n,e,t)=>{switch(t.acceptProfile||(t.acceptProfile=ub),t.acceptProfile.env){case"application/iden3-zkp-json":if(!t.acceptProfile.circuits)throw new Error("Circuit not specified in accept profile");for(let r of t.acceptProfile.circuits){if(!t.supportedCircuits.includes(r))throw new Error(`Circuit ${r} is not supported`);if(!t.senderAddress)throw new Error("Sender address is not provided");let i=PY(t.senderAddress,t.zkpResponses),o=await e.generateAuthProof(r,n,{challenge:i});return{authProof:{authMethod:"authV2",zkp:o}}}throw new Error("Auth method is not supported");case"application/iden3comm-signed-json":if(!t.acceptProfile.alg||t.acceptProfile.alg.length===0)throw new Error("Algorithm not specified");if(t.acceptProfile.alg[0]==="ES256K-R")return{authProof:{authMethod:"ethIdentity",userDid:n}};throw new Error(`Algorithm ${t.acceptProfile.alg[0]} not supported`);default:throw new Error("Accept env not supported")}},db=n=>{let e=n.id,t=n.pub_signals,r="0x";if(t.length===0)return{requestId:e,zkProofEncoded:r,metadata:r};let i=Zh(n.proof),o=tA(t,i.a,i.b,i.c);return{requestId:e,zkProofEncoded:o,metadata:r}},PY=(n,e)=>{let t=e.map(r=>{let i=db(r);return{requestId:i.requestId,proof:i.zkProofEncoded,metadata:i.metadata}});return BigInt(nn.keccak256(new nn.AbiCoder().encode(["address","(uint256 requestId,bytes proof,bytes metadata)[]"],[n,t])))&BigInt("0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")},ewe=n=>new nn.AbiCoder().encode(["tuple(string key,bytes value)[]"],[n]),Qn=n=>{if(n?.expires_time&&n.expires_time<Bt(new Date))throw new Error("Message expired")};var Xr=class{nextMessageHandler;setNext(e){return this.nextMessageHandler=e,e}async handle(e,t){return t.allowExpiredMessages||Qn(e),this.nextMessageHandler?this.nextMessageHandler.handle(e,t):Promise.reject("Message handler not provided or message not supported")}},GT=class{constructor(e){this._params=e;this.registerHandlers(e.messageHandlers)}messageHandler;registerHandlers(e){if(!e.length)return;let[t,...r]=e,i=t;for(let o of r){let s=i;for(;s.nextMessageHandler;)s=s.nextMessageHandler;s.setNext(o)}this.messageHandler?this.messageHandler.setNext(t):this.messageHandler=t}async handleMessage(e,t){let{unpackedMediaType:r,unpackedMessage:i}=await this._params.packageManager.unpack(e);if(!this.messageHandler)return Promise.reject(new Error("Message handler not provided"));let o=await this.messageHandler.handle(i,t);if(!o)return null;let s={},a=t?.senderDid;return r==="application/iden3-zkp-json"&&a?(s={senderDID:a,provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg},this._params.packageManager.packMessage(r,o,s)):this._params.packageManager.packMessage("application/iden3comm-plain-json",o,s)}};function twe(n,e,t,r){return RY(n,"",e,t,r)}function RY(n,e,t,r,i){let o=Et();return{id:o,thid:o,from:t,typ:"application/iden3comm-plain-json",type:je.AUTHORIZATION_REQUEST_MESSAGE_TYPE,body:{accept:i?.accept,reason:n,message:e,callbackUrl:r,scope:i?.scope??[]},created_time:Bt(new Date),expires_time:i?.expires_time?Bt(i.expires_time):void 0,attachments:i?.attachments}}var NT=class extends Xr{constructor(t,r){super();this._packerMgr=t;this._proofService=r}_supportedCircuits=["credentialAtomicQueryV3-beta.1","credentialAtomicQuerySigV2","credentialAtomicQueryMTPV2","linkedMultiQuery10-beta.1"];handle(t,r){switch(t.type){case je.AUTHORIZATION_REQUEST_MESSAGE_TYPE:return this.handleAuthRequest(t,r);case je.AUTHORIZATION_RESPONSE_MESSAGE_TYPE:return this.handleAuthResponse(t,r);default:return super.handle(t,r)}}async parseAuthorizationRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i.body.scope=i.body.scope||[],i}async handleAuthRequest(t,r){if(t.type!==je.AUTHORIZATION_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for authorization request");let i=t.to?Ie.parse(t.to):r.senderDid,o=Et();if(!t.from)throw new Error("auth request should contain from field");let s=je.AUTHORIZATION_RESPONSE_MESSAGE_TYPE,a=this.getSupportedMediaTypeByProfile(r,s,t.body.accept),l=Ie.parse(t.from),c=await qm(i,t?.body.scope,l,this._proofService,{mediaType:a,supportedCircuits:this._supportedCircuits});return{id:o,typ:a,type:s,thid:t.thid??o,body:{message:t?.body?.message,scope:c},from:i.string(),to:t.from}}async handleAuthorizationRequest(t,r,i){let o=await this.parseAuthorizationRequest(r);if(i?.allowExpiredMessages||Qn(o),i||(i={mediaType:"application/iden3-zkp-json"}),i.mediaType==="application/iden3comm-signed-json"&&!i.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let s=await this.handleAuthRequest(o,{senderDid:t,mediaType:i.mediaType}),a=Me.encode(JSON.stringify(s)),l=i.mediaType==="application/iden3comm-signed-json"?i.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg},c=tt.decode(await this._packerMgr.pack(i.mediaType,a,{senderDID:t,...l}));return{authRequest:o,authResponse:s,token:c}}async handleAuthResponse(t,r){let i=r.request;if(t.type!==je.AUTHORIZATION_RESPONSE_MESSAGE_TYPE)throw new Error("Invalid message type for authorization response");if((i.body.message??"")!==(t.body.message??""))throw new Error("message for signing from request is not presented in response");if(i.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${i.from}, given ${t.to}`);this.verifyAuthRequest(i);let o=i.body.scope||[],s=t.body.scope||[];if(!t.from)throw new Error("proof response doesn't contain from field");let a=new Map;for(let l of o){let c=l.query.groupId,u=s.find(w=>w.id.toString()===l.id.toString());if(!u)throw new Error(`proof is not given for requestId ${l.id}`);let d=u.circuitId;if(d!==l.circuitId)throw new Error(`proof is not given for requested circuit expected: ${l.circuitId}, given ${d}`);let h=l.params??{};h.verifierDid=Ie.parse(i.from);let f=[r.acceptedProofGenerationDelay,r.acceptedStateTransitionDelay].some(w=>w!==void 0)?{acceptedProofGenerationDelay:r.acceptedProofGenerationDelay,acceptedStateTransitionDelay:r.acceptedStateTransitionDelay}:void 0,{linkID:p}=await this._proofService.verifyZKPResponse(u,{query:l.query,sender:t.from,params:h,opts:f});p&&c&&a.set(c,[...a.get(c)??[],{linkID:p,requestId:u.id}])}for(let[l,c]of a.entries())if(c.some(u=>u.linkID!==c[0].linkID))throw new Error(`Link id validation failed for group ${l}, request linkID to requestIds info: ${JSON.stringify(c)}`);return t}async handleAuthorizationResponse(t,r,i){i?.allowExpiredMessages||Qn(t);let o=await this.handleAuthResponse(t,{request:r,acceptedStateTransitionDelay:i?.acceptedStateTransitionDelay,acceptedProofGenerationDelay:i?.acceptedProofGenerationDelay});return{request:r,response:o}}verifyAuthRequest(t){let r={},i=t.body.scope||[];for(let o of i){let s=o.query.groupId;if(s){let a=r[s]??[];for(let l of a){if(l.query.type!==o.query.type)throw new Error("all requests in the group should have the same type");if(l.query.context!==o.query.context)throw new Error("all requests in the group should have the same context");let c=o.query.allowedIssuers,u=l.query.allowedIssuers;if(!(c.includes("*")||c.every(d=>u.includes(d))))throw new Error("all requests in the group should have the same issuer")}r[s]=[...r[s]??[],o]}}}getSupportedMediaTypeByProfile(t,r,i){let o;if(!i?.length)return t.mediaType||"application/iden3-zkp-json";let s=[];for(let a of i){let{env:l}=Ta(a);this._packerMgr.isProfileSupported(l,a)&&s.push(l)}if(!s.length)throw new Error("no packer with profile which meets `accept` header requirements");return o=s.includes("application/iden3-zkp-json")?"application/iden3-zkp-json":s[0],t.mediaType&&s.includes(t.mediaType)&&(o=t.mediaType),o}};var MY=[{inputs:[],name:"MAX_SMT_DEPTH",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"key",type:"uint256"}],name:"getNode",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatus",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatusByIdAndState",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256[][]",name:"nodes",type:"uint256[][]"}],name:"saveNodes",outputs:[],stateMutability:"nonpayable",type:"function"}];var fb=class n{constructor(e,t,r){this._config=e;this._signer=r;this._provider=new Tt(e.url);let i=new $t(t,MY,this._provider);this._signer&&(this._signer=this._signer.connect(this._provider),i=i.connect(this._signer)),this._contract=i,this._transactionService=new _o(this._provider)}_contract;_provider;_transactionService;async getRevocationStatusByIdAndState(e,t,r){let i=await this._contract.getRevocationStatusByIdAndState(e,t,r),o=n.convertIssuerInfo(i.issuer),s=n.convertSmtProofToProof(i.mtp);return{issuer:o,mtp:s}}async getRevocationStatus(e,t){let r=await this._contract.getRevocationStatus(e,t),i=n.convertIssuerInfo(r.issuer),o=n.convertSmtProofToProof(r.mtp);return{issuer:i,mtp:o}}async saveNodes(e){if(!this._signer)throw new Error("No signer provided");let t=await this._provider.getFeeData(),r=this._config.maxFeePerGas?BigInt(this._config.maxFeePerGas):t.maxFeePerGas,i=this._config.maxPriorityFeePerGas?BigInt(this._config.maxPriorityFeePerGas):t.maxPriorityFeePerGas,o=await this._contract.saveNodes.estimateGas(e),s=await this._contract.saveNodes.populateTransaction(e),a={to:s.to,data:s.data,gasLimit:o,maxFeePerGas:r,maxPriorityFeePerGas:i},{txnReceipt:l}=await this._transactionService.sendTransactionRequest(this._signer,a);return l}static convertIssuerInfo(e){let[t,r,i,o]=e.map(s=>me.fromBigInt(s).hex());return{state:t,claimsTreeRoot:r,revocationTreeRoot:i,rootOfRoots:o}}static convertSmtProofToProof(e){let t,r=e.siblings?.map(i=>i.toString());return e.auxExistence&&(t={key:e.auxIndex.toString(),value:e.auxValue.toString()}),yt.fromJSON({existence:e.existence,node_aux:t,siblings:r})}};function rwe(n){return typeof n=="object"&&n!==null&&"errorArgs"in n&&Array.isArray(n.errorArgs)}function iwe(n){return(rwe(n)?n.errorArgs[0]:void 0)||(n instanceof Error?n.message:"")}function Qm(n,e){return iwe(n).includes(e)}function hb(n){return Qm(n,Fe.ERRORS.IDENTITY_DOES_NOT_EXIST)||Qm(n,Fe.ERRORS.IDENTITY_DOES_NOT_EXIST_CUSTOM_ERROR)}function UT(n){return Qm(n,Fe.ERRORS.STATE_DOES_NOT_EXIST)||Qm(n,Fe.ERRORS.STATE_DOES_NOT_EXIST_CUSTOM_ERROR)}function HT(n){return Qm(n,Fe.ERRORS.ROOT_DOES_NOT_EXIST)||Qm(n,Fe.ERRORS.ROOT_DOES_NOT_EXIST_CUSTOM_ERROR)}var KT=class{constructor(e,t){this._configs=e;this._stateStorage=new pb(e,t?.stateStorageOptions)}_stateStorage;async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");return this.getRevocationOnChain(e,t.issuerDID)}async getRevocationOnChain(e,t){let{contractAddress:r,chainId:i,revocationNonce:o,stateHex:s}=this.extractCredentialStatusInfo(e);if(o!==e.revocationNonce)throw new Error("revocationNonce does not match");let a=Ie.idFromDID(t),l;try{let h=await this._stateStorage.getLatestStateById(a.bigInt());if(!h.state)throw new Error("state contract returned empty state");l=h.state}catch(h){if(!hb(h))throw h;if(!s)throw new Error("latest state not found and state parameter is not present in credentialStatus.id");let f=me.fromHex(s).bigInt();if(!Za(t,f))throw new Error(`latest state not found and state parameter ${s} is not genesis state`);l=f}let c=Ie.idFromDID(t);return await this._getOnChainRevocationStorageForIssuer(i,r).getRevocationStatusByIdAndState(c.bigInt(),l,o)}extractCredentialStatusInfo(e){if(!e.id)throw new Error("credentialStatus id is empty");if(e.id.split("/").length!==2)throw new Error("invalid credentialStatus id");let r=new URL(e.id),i=r.searchParams.get("state")||"",o=r.searchParams.get("contractAddress");if(!o)throw new Error("contractAddress not found in credentialStatus.id field");let s=o.split(":");if(s.length!=2)throw new Error("invalid contract address encoding. should be chainId:contractAddress");let a=parseInt(s[0],10),l=s[1],c=r.searchParams.get("revocationNonce")||e.revocationNonce;if(c==null)throw new Error("revocationNonce not found in credentialStatus id field");let u=typeof c=="number"?c:parseInt(c,10);return{contractAddress:l,chainId:a,revocationNonce:u,stateHex:i}}networkByChainId(e){let t=this._configs.find(r=>r.chainId===e);if(!t)throw new Error(`chainId "${e}" not supported`);return t}_getOnChainRevocationStorageForIssuer(e,t){let r=this.networkByChainId(e);return new fb(r,t)}};var sp=class{async resolve(e){let r=await(await fetch(e.id)).json();return WA(r)}},WA=({issuer:n,mtp:e})=>({mtp:yt.fromJSON(e),issuer:n});var ap=class n{constructor(e=Le,t=[]){this.hash=e;this.children=t}nodeType(){return this.children.length===2?1:this.children.length===3&&this.children[2].hex()===me.fromBigInt(BigInt(1)).hex()?2:this.children.length===3?3:0}toJSON(){return{hash:this.hash.hex(),children:this.children.map(e=>e.hex())}}static fromHex(e){return new n(me.fromHex(e.hash),e.children.map(t=>me.fromHex(t)))}};var JT=class{constructor(e){this._state=e}async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");try{return await this.getStatus(e,t.issuerDID,t.issuerData,t.issuerGenesisState)}catch(r){if(e?.statusIssuer?.type==="SparseMerkleTreeProof")try{return await new sp().resolve(e.statusIssuer)}catch(i){throw new Error(`can't fetch revocation status from backup endpoint: ${i?.message}`)}throw new Error(`can't fetch revocation status: ${r?.message}`)}}async getStatus(e,t,r,i){let o=Ie.idFromDID(t),s;try{let u=await this._state.getLatestStateById(o.bigInt());if(!u.state)throw new Error("state contract returned empty state");s=u.state}catch(u){if(!hb(u))throw u;let d=this.extractState(e.id);if(!d)return this.getRevocationStatusFromIssuerData(t,r,i);let h=me.fromHex(d).bigInt(),f=Hf(t);if(!f&&!Za(t,h))throw new Error(`latest state not found and state parameter ${d} is not genesis state`);if(f)throw new Error("State must be published for Ethereum based identity");s=h}let a=e.id.split("/node")[0],l=me.fromBigInt(BigInt(e.revocationNonce??0)),c=me.fromBigInt(s);return await this.getRevocationStatusFromRHS(l,c,a)}getRevocationStatusFromIssuerData(e,t,r){if(r&&Za(e,r.value.bigInt()))return{mtp:new yt,issuer:{state:r.value.hex(),revocationTreeRoot:r.revocationTreeRoot.hex(),rootOfRoots:r.rootOfRoots.hex(),claimsTreeRoot:r.claimsTreeRoot.hex()}};if(t&&Za(e,t.state.value))return{mtp:new yt,issuer:{state:t.state.value,revocationTreeRoot:t.state.revocationTreeRoot,rootOfRoots:t.state.rootOfRoots,claimsTreeRoot:t.state.claimsTreeRoot}};throw new Error("issuer data / genesis state param is empty")}async getRevocationStatusFromRHS(e,t,r){if(!r)throw new Error("HTTP reverse hash service URL is not specified");let o=(await(await fetch(`${r}/node/${t.hex()}`)).json())?.node;if(o.children.length!==3)throw new Error("state should has tree children");let s=t.hex(),[a,l,c]=o.children,u=me.fromHex(l);return{mtp:await this.rhsGenerateProof(u,e,`${r}/node`),issuer:{state:s,claimsTreeRoot:a,revocationTreeRoot:l,rootOfRoots:c}}}async rhsGenerateProof(e,t,r){let i=!1,o=[],s,a=()=>new yt({siblings:o,existence:i,nodeAux:s}),l=e;for(let c=0;c<t.bytes.length*8;c++){if(l.bytes.every(f=>f===0))return a();let d=(await(await fetch(`${r}/${l.hex()}`)).json())?.node,h=ap.fromHex(d);switch(h.nodeType()){case 2:return t.bytes.every((f,p)=>f===h.children[0].bytes[p])?(i=!0,a()):(s={key:h.children[0],value:h.children[1]},a());case 1:sg(t.bytes,c)?(l=h.children[1],o.push(h.children[0])):(l=h.children[0],o.push(h.children[1]));break;default:throw new Error(`found unexpected node type in tree ${h.hash.hex()}`)}}throw new Error("tree depth is too high")}extractState(e){return new URL(e).searchParams.get("state")}};function owe(n,e){let t=Ie.parse(n),r=Ie.idFromDID(t),{method:i,blockchain:o,networkId:s}=Ie.decodePartsFromId(r),a=ht.hexToBytes(e),l=ht.bytesToInt(a),c=Oa(i,o,s);return FY(Ie.idFromDID(t).bigInt(),l,c)}function FY(n,e,t){let r=Je.idGenesisFromIdenState(t,e);return n.toString()===r.bigInt().toString()}var mb=class{resolvers=new Map;register(e,t){this.resolvers.set(e,t)}get(e){return this.resolvers.get(e)}};var gb=class{async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");if(!t?.userDID)throw new Error("UserDID is not set in options");if(typeof e.revocationNonce!="number")throw new Error("Revocation nonce is not set in credential status");let r=t.userDID.string(),i=t.issuerDID.string(),o=swe(r,i,e.revocationNonce),a=await(await fetch(e.id,{method:"POST",body:JSON.stringify(o),headers:{"Content-Type":"application/json"}})).json();return WA(a.body)}};function swe(n,e,t){return{id:Et(),typ:"application/iden3comm-plain-json",type:je.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE,body:{revocation_nonce:t},thid:Et(),from:n,to:e}}var yb=class{_publishers=new Map;register(e,...t){let r=this._publishers.get(e)??[];r.push(...t),this._publishers.set(e,r)}get(e){return this._publishers.get(e)}},qT=class{constructor(e){this._storage=e}async publish(e){if(!["Iden3OnchainSparseMerkleTreeProof2023"].includes(e.credentialStatusType))throw new Error(`On-chain publishing is not supported for credential status type ${e.credentialStatusType}`);let t=e.nodes.map(o=>o.children.map(s=>s.bigInt())),r=this._storage.saveNodes(t),i=e.onChain?.publishMode??"sync";switch(e.onChain?.txCallback&&(i="callback"),i){case"sync":await r;break;case"callback":{if(!e.onChain?.txCallback)throw new Error('txCallback is required for publishMode "callback"');let o=e.onChain?.txCallback;r.then(s=>o(s));break}case"async":{let o=_g.getInstance();r.then(s=>o.publish(qC.TX_RECEIPT_ACCEPTED,s));break}default:throw new Error(`Invalid publishMode: ${i}`)}}},cp=class{async publish(e){if(!["Iden3ReverseSparseMerkleTreeProof"].includes(e.credentialStatusType))throw new Error(`On-chain publishing is not supported for credential status type ${e.credentialStatusType}`);let t=e.nodes.map(i=>i.toJSON()),r=await fetch(e.rhsUrl+"/node",{method:"post",body:JSON.stringify(t)});if(r.status!==200)throw new Error(`Failed to publish credential status. Status: ${r.status}`)}};var QT=class{constructor(e){this.didResolverUrl=e}async resolve(e,t){if(!t?.issuerDID)throw new Error("IssuerDID is not set in options");let r=`${this.didResolverUrl}/1.0/credential-status/${encodeURIComponent(t.issuerDID.string())}`;return await(await fetch(r,{method:"POST",body:JSON.stringify(e)})).json()}};var VT=class{constructor(e,t){this._storage=e;this._credentialStatusResolverRegistry=t;this._credentialStatusResolverRegistry||(this._credentialStatusResolverRegistry=new mb,this._credentialStatusResolverRegistry.register("SparseMerkleTreeProof",new sp),this._credentialStatusResolverRegistry.register("Iden3commRevocationStatusV1.0",new gb))}async getAuthBJJCredential(e){let t=await this._storage.credential.findCredentialsByQuery({context:Fe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Fe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]});if(!t.length)throw new Error(Fe.ERRORS.NO_AUTH_CRED_FOUND);for(let r=0;r<t.length;r++){let i=t[r];if(!(await this.getRevocationStatusFromCredential(i)).mtp.existence)return i}throw new Error("all auth bjj credentials are revoked")}async getAllAuthBJJCredentials(e){return this._storage.credential.findCredentialsByQuery({context:Fe.AUTH.AUTH_BJJ_CREDENTIAL_SCHEMA_JSONLD_URL,type:Fe.AUTH.AUTH_BJJ_CREDENTIAL_TYPE,allowedIssuers:[e.string()]})}async getRevocationStatusFromCredential(e){let t=e.getIden3SparseMerkleTreeProof(),r=e.getBJJSignature2021Proof(),i=t?t.issuerData.state:r?.issuerData.state,o=Ie.parse(e.issuer),s=Hl(o,e),a={issuerGenesisState:i,issuerDID:o,userDID:s};return this.getRevocationStatus(e.credentialStatus,a)}async getRevocationStatus(e,t){let r=this._credentialStatusResolverRegistry?.get(e.type);if(!r)throw new Error(`credential status resolver does not exist for ${e.type} type`);return r.resolve(e,t)}createCredential=(e,t,r)=>{if(!r.$metadata.uris.jsonLdContext)throw new Error("jsonLdContext is missing is the schema");let i={...t};return i.context=i.context??[],i.displayMethod?.type==="Iden3BasicDisplayMethodV1"&&!i.context.includes(Fe.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD)&&i.context.push(Fe.JSONLD_SCHEMA.IDEN3_DISPLAY_METHOD),i.context.push(r.$metadata.uris.jsonLdContext),i.expiration=i.expiration?i.expiration*1e3:void 0,i.id=i.id?i.id:`urn:${Et()}`,i.issuanceDate=i.issuanceDate?i.issuanceDate*1e3:Date.now(),fr.fromCredentialRequest(e,i)};async findById(e){return this._storage.credential.findCredentialById(e)}async findByContextType(e,t){return this._storage.credential.findCredentialsByQuery({context:e,type:t})}async save(e){return this._storage.credential.saveCredential(e)}async saveAll(e){return this._storage.credential.saveAllCredentials(e)}async remove(e){return this._storage.credential.removeCredential(e)}async list(){return this._storage.credential.listCredentials()}async findByQuery(e){return this._storage.credential.findCredentialsByQuery(e)}async filterByCredentialSubject(e,t){return e.filter(r=>r.credentialSubject.id===t.string())}async findNonRevokedCredential(e){for(let t of e){let r=await this.getRevocationStatusFromCredential(t);if(!r.mtp.existence)return{cred:t,revStatus:r}}throw new Error(Fe.ERRORS.CREDENTIAL_WALLET_ALL_CREDENTIALS_ARE_REVOKED)}};async function ZA(n,e,t,r){let i=await XA(r,e,n);await new cp().publish({nodes:i,credentialStatusType:"Iden3ReverseSparseMerkleTreeProof",rhsUrl:t})}async function XA(n,e,t){let r=new YT;return n&&await cwe(r,e,n),await awe(r,e),t.bytes.every(i=>i===0)||r.addProofNode(new ap(t,[await e.claimsTree.root(),await e.revocationTree.root(),await e.rootsTree.root()])),r.nodes}async function awe(n,e){let t=e.rootsTree,r=e.claimsTree;return n.addKey(t,(await r.root()).bigInt())}async function cwe(n,e,t){let r=e.revocationTree;for(let i of t)await n.addKey(r,BigInt(i))}var YT=class{constructor(e=[],t=new Map){this.nodes=e;this.seen=t}async addKey(e,t){let{value:r,siblings:i}=await e.get(t),o=me.fromBigInt(t),s=me.fromBigInt(r),a=new Na(o,s),l=await lwe(i,a);for(let c of l)this.seen.get(c.hash.hex())||(this.nodes.push(c),this.seen.set(c.hash.hex(),!0))}addProofNode(e){let t=e.hash.hex();this.seen.get(t)||(this.nodes.push(e),this.seen.set(t,!0))}};async function lwe(n,e){if(e.type!==is)throw new Error("node is not a leaf");let t=await e.getKey(),r=n.length,i=new Array(r+1);for(let a=0;a<i.length;a++)i[a]=new ap;i[r].hash=t;let o=me.fromBigInt(BigInt(1));i[r].children=[e.entry[0],e.entry[1],o];let s=e.entry[0];for(let a=r-1;a>=0;a--){let l=sg(s.bytes,a);i[a].children=new Array(2),l?(i[a].children[0]=n[a],i[a].children[1]=t):(i[a].children[0]=t,i[a].children[1]=n[a]),i[a].hash=Wd([i[a].children[0].bigInt(),i[a].children[1].bigInt()]),t=i[a].hash}return i}var zT=class n extends Xr{constructor(t,r){super();this._packerMgr=t;this.opts=r}async handle(t,r){switch(t.type){case je.CREDENTIAL_OFFER_MESSAGE_TYPE:{let i=await this.handleOfferMessage(t,r);if(Array.isArray(i)){let o=this.opts?.credentialWallet;if(!o)throw new Error("Credential wallet is not provided");return await o.saveAll(i),null}return i}case je.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE:return this.handleFetchRequest(t);case je.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE:return this.handleIssuanceResponseMsg(t);case je.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE:{let i=await this.handleOnchainOfferMessage(t);if(Array.isArray(i)){let o=this.opts?.credentialWallet;if(!o)throw new Error("Credential wallet is not provided");return await o.saveAll(i),null}return i}default:return super.handle(t,r)}}async handleOnchainOfferMessage(t){if(!this.opts?.onchainIssuer)throw new Error("onchain issuer is not provided");let r=[];for(let i of t.body.credentials){let o=Ie.parse(t.from),s=Ie.parse(t.to),a=await this.opts.onchainIssuer.getCredential(o,s,BigInt(i.id));r.push(a)}return r}async handleOfferMessage(t,r){r.mediaType||(r.mediaType="application/iden3-zkp-json");let i=[];for(let o of t.body.credentials){let s=Et(),a={id:s,typ:r.mediaType,type:je.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE,thid:t.thid??s,body:{id:o.id},from:t.to,to:t.from},l=Me.encode(JSON.stringify(a)),c=r.mediaType==="application/iden3comm-signed-json"?r.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg},u=Ie.parse(t.to),d=tt.decode(await this._packerMgr.pack(r.mediaType,l,{senderDID:u,...c}));try{if(!t?.body?.url)throw new Error("could not fetch W3C credential, body url is missing");let f=await(await fetch(t.body.url,{method:"post",headers:{"Content-Type":"application/x-www-form-urlencoded",...r.headers},body:d})).arrayBuffer();if(!f.byteLength)throw new Error(`could not fetch , ${o?.id}, response is empty`);let{unpackedMessage:p}=await this._packerMgr.unpack(new Uint8Array(f));if(p.type!==je.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE)return p;i.push(fr.fromJSON(p.body.credential))}catch(h){throw new Error(`could not fetch protocol message for credential offer id: , ${o?.id}, error: ${h.message??h}`)}}return i}async handleCredentialOffer(t,r){if(r?.mediaType==="application/iden3comm-signed-json"&&!r.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let i=await n.unpackMessage(this._packerMgr,t,je.CREDENTIAL_OFFER_MESSAGE_TYPE);r?.allowExpiredMessages||Qn(i);let o=await this.handleOfferMessage(i,{mediaType:r?.mediaType,headers:r?.headers,packerOptions:r?.packerOptions});if(Array.isArray(o))return o;throw new Error("invalid protocol message response")}async handleOnchainOffer(t){let r=await n.unpackMessage(this._packerMgr,t,je.CREDENTIAL_ONCHAIN_OFFER_MESSAGE_TYPE);return this.handleOnchainOfferMessage(r)}async handleFetchRequest(t){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");let r=Ie.parse(t.to),i=Ie.parse(t.from),o=t.body?.id;if(!o)throw new Error("invalid credential id in fetch request body");if(!this.opts?.credentialWallet)throw new Error("please, provide credential wallet in options");let s=await this.opts.credentialWallet.findById(o);if(!s)throw new Error("credential not found");if(Hl(r,s).string()!==i.string())throw new Error("credential subject is not a sender DID");return{id:Et(),type:je.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE,typ:t.typ??"application/iden3comm-plain-json",thid:t.thid??Et(),body:{credential:s},from:t.to,to:t.from}}async handleCredentialFetchRequest(t,r){let i=await n.unpackMessage(this._packerMgr,t,je.CREDENTIAL_FETCH_REQUEST_MESSAGE_TYPE);r?.allowExpiredMessages||Qn(i);let o=await this.handleFetchRequest(i);return this._packerMgr.pack("application/iden3comm-plain-json",Me.encode(JSON.stringify(o)),{})}async handleIssuanceResponseMsg(t){if(!this.opts?.credentialWallet)throw new Error("please provide credential wallet in options");if(!t.body?.credential)throw new Error("credential is missing in issuance response message");return await this.opts.credentialWallet.save(fr.fromJSON(t.body.credential)),null}async handleIssuanceResponseMessage(t,r){let i=await n.unpackMessage(this._packerMgr,t,je.CREDENTIAL_ISSUANCE_RESPONSE_MESSAGE_TYPE);return r?.allowExpiredMessages||Qn(i),await this.handleIssuanceResponseMsg(i),Uint8Array.from([])}static async unpackMessage(t,r,i){let{unpackedMessage:o}=await t.unpack(r),s=o;if(o.type!==i)throw new Error("Invalid message type");return s}};var jT=class extends Xr{constructor(t,r,i){super();this._packerMgr=t;this._proofService=r;this._zkpVerifier=i}_supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1","authV2","credentialAtomicQueryV3-beta.1","linkedMultiQuery10-beta.1"];async handle(t,r){switch(t.type){case je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE:{let i=t,o=await this.handleContractInvoke(i,r);return this.createContractInvokeResponse(i,o)}default:return super.handle(t,r)}}async handleContractInvoke(t,r){if(t.type!==je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for contract invoke request");let{senderDid:i,ethSigner:o,challenge:s}=r;if(!r.ethSigner)throw new Error("Can't sign transaction. Provide Signer in options.");let{chain_id:a}=t.body.transaction_data;if(!Object.keys(ts).find(f=>ts[f]===a))throw new Error(`Invalid chain id ${a}`);let c=t.from?Ie.parse(t.from):void 0,{scope:u=[]}=t.body,d=await qm(i,u,c,this._proofService,{ethSigner:o,challenge:s??ht.bytesToInt(To(await o.getAddress())),supportedCircuits:this._supportedCircuits});switch(t.body.transaction_data.method_id.replace("0x","")){case"ade09fcd":{let f=await this._zkpVerifier.submitZKPResponseV2(o,t.body.transaction_data,d),p=new Map;for(let[w,y]of f)p.set(w,{responses:y});return t.body.transaction_data.txHash=f.keys().next().value,p}case"b68967e2":{let f=await this._zkpVerifier.submitZKPResponse(o,t.body.transaction_data,d),p=new Map;for(let[w,y]of f)p.set(w,{responses:[y]});return t.body.transaction_data.txHash=f.keys().next().value,p}case"06c86a91":{if(!t.to)throw new Error("failed message. empty 'to' field");let f=this.getFirstSupportedProfile(je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE,t.body.accept),p=Ie.parse(t.to),{authProof:w}=await OT(p,this._proofService,{supportedCircuits:this._supportedCircuits,acceptProfile:f,senderAddress:await o.getAddress(),zkpResponses:d}),y=await this._zkpVerifier.submitResponse(o,t.body.transaction_data,d,w);return t.body.transaction_data.txHash=y.keys().next().value,y}default:throw new Error("Not supported method id. Only 'b68967e2, ade09fcd and 06c86a91 are supported.'")}}getFirstSupportedProfile(t,r){if(r?.length)for(let i of r){let o=Ta(i),s=Number(t.split("/").at(-2));if(!(o.protocolVersion!=="iden3comm/v1"||o.protocolVersion==="iden3comm/v1"&&(s<1||s>=2))&&this._packerMgr.isProfileSupported(o.env,i))return o}return ub}async parseContractInvokeRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i.body.scope=i.body.scope||[],i}async createContractInvokeResponse(t,r){let i={id:t.id,thid:t.thid,type:je.CONTRACT_INVOKE_RESPONSE_MESSAGE_TYPE,from:t.to,to:t.from,body:{transaction_data:t.body.transaction_data,scope:[]},created_time:Bt(new Date)};for(let[o,s]of r){for(let a of s.responses)i.body.scope.push({txHash:o,...a});i.body={...i.body,crossChainProof:s.crossChainProof,authProof:s.authProof}}return i}async handleContractInvokeRequest(t,r,i){let o=await this.parseContractInvokeRequest(r);if(i.allowExpiredMessages||Qn(o),o.body.transaction_data.method_id!=="b68967e2")throw new Error("please use handle method to work with other method ids");if(o.type!==je.CONTRACT_INVOKE_REQUEST_MESSAGE_TYPE)throw new Error("Invalid message type for contract invoke request");let{ethSigner:s,challenge:a}=i;if(!s)throw new Error("Can't sign transaction. Provide Signer in options.");let{chain_id:l}=o.body.transaction_data;if(!Object.keys(ts).find(h=>ts[h]===l))throw new Error(`Invalid chain id ${l}`);let u=o.from?Ie.parse(o.from):void 0,d=await qm(t,o?.body?.scope,u,this._proofService,{ethSigner:s,challenge:a,supportedCircuits:this._supportedCircuits});return this._zkpVerifier.submitZKPResponse(s,o.body.transaction_data,d)}};var WT=class{constructor(e){this._options=e}async refreshCredential(e,t){if(!e.refreshService)throw new Error("refreshService not specified for W3CCredential");if(e.refreshService.type!=="Iden3RefreshService2023")throw new Error(`refresh service type ${e.refreshService.type} is not supported`);let r=e.credentialSubject.id;if(!r)throw new Error("self credentials do not support refresh");let o={senderDID:Ie.parse(r),provingMethodAlg:new ru(gi.provingMethodGroth16AuthV2Instance.methodAlg.alg,"authV2")},s={id:Et(),typ:"application/iden3-zkp-json",type:je.CREDENTIAL_REFRESH_MESSAGE_TYPE,thid:Et(),body:{id:e.id,reason:t?.reason??"credential is expired"},from:r,to:e.issuer},a=Me.encode(JSON.stringify(s)),l=await this._options.packageManager.pack("application/iden3-zkp-json",a,o),c=await fetch(e.refreshService.id,{method:"post",headers:{"Content-Type":"application/json"},body:l});if(c.status!==200)throw new Error(`could not refresh W3C credential, return status ${c.status}`);let u=await c.json();if(!u.body?.credential)throw new Error("no credential in CredentialIssuanceMessage response");return fr.fromJSON(u.body.credential)}};var ZT=class extends Xr{constructor(t,r){super();this._packerMgr=t;this._identityWallet=r}handle(t,r){if(!r.senderDid)throw new Error("DID is required");if(!r.mediaType)throw new Error("mediaType is required");switch(t.type){case je.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE:return this.handleRevocationStatusRequestMessage(t,r);default:return super.handle(t,r)}}async handleRevocationStatusRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body?.revocation_nonce)throw new Error("failed request. empty 'revocation_nonce' field");let i=Ie.parse(t.to),o=await this._identityWallet.generateNonRevocationMtpWithNonce(i,BigInt(t.body.revocation_nonce),r.treeState),s=o.treeState,a={issuer:{state:s?.state.string(),claimsTreeRoot:s.claimsRoot.string(),revocationTreeRoot:s.revocationRoot.string(),rootOfRoots:s.rootOfRoots.string()},mtp:o.proof},l=Et();return{id:l,typ:"application/iden3comm-plain-json",type:je.REVOCATION_STATUS_RESPONSE_MESSAGE_TYPE,thid:t.thid??l,body:a,from:r.senderDid.string(),to:t.from}}async parseRevocationStatusRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.REVOCATION_STATUS_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handleRevocationStatusRequest(t,r,i){if(i||(i={mediaType:"application/iden3comm-plain-json"}),i.mediaType==="application/iden3comm-signed-json"&&!i.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let o=await this.parseRevocationStatusRequest(r);i.allowExpiredMessages||Qn(o);let s=await this.handleRevocationStatusRequestMessage(o,{senderDid:t,mediaType:i.mediaType,packerOptions:i.packerOptions,treeState:i.treeState}),a=i.mediaType==="application/iden3comm-signed-json"?i.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg};if(!o.to)throw new Error("failed request. empty 'to' field");let l=Ie.parse(o.to);return this._packerMgr.pack(i.mediaType,Me.encode(JSON.stringify(s)),{senderDID:l,...a})}};function uwe(n,e,t){let r=Et();return{id:r,thid:r,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:je.PROPOSAL_REQUEST_MESSAGE_TYPE,body:t,created_time:Bt(new Date),expires_time:t?.expires_time?Bt(t.expires_time):void 0,attachments:t.attachments}}function dwe(n,e,t,r){let i=Et();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:je.PROPOSAL_MESSAGE_TYPE,body:{proposals:t||[]},created_time:Bt(new Date),expires_time:r?.expires_time?Bt(r.expires_time):void 0}}var XT=class extends Xr{constructor(t,r,i){super();this._packerMgr=t;this._identityWallet=r;this._params=i}async handle(t,r){switch(t.type){case je.PROPOSAL_REQUEST_MESSAGE_TYPE:return await this.handleProposalRequestMessage(t,r);default:return super.handle(t,r)}}async parseProposalRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.PROPOSAL_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handleProposalRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body?.credentials?.length)throw new Error("failed request. no 'credentials' in body");let i,o;for(let s=0;s<t.body.credentials.length;s++){let a=t.body.credentials[s],l=[];try{l=await this._identityWallet.credentialWallet.findByQuery({credentialSubject:{id:{$eq:t.from}},type:a.type,context:a.context,allowedIssuers:[t.to]})}catch(u){if(u.message!=="no credential satisfied query")throw u}if(l.length){let u=Et();i||(i={id:u,typ:this._params.packerParams.mediaType,type:je.CREDENTIAL_OFFER_MESSAGE_TYPE,thid:t.thid??u,body:{url:this._params.agentUrl,credentials:[]},from:t.to,to:t.from}),i.body.credentials.push(...l.map(d=>({id:d.id,description:""})));continue}let c=await this._params.proposalResolverFn(a.context,a.type,{msg:t});if(!c)throw new Error(`can't resolve Proposal for type: ${a.type}, context: ${a.context}`);if(!o){let u=Et();o={id:u,typ:this._params.packerParams.mediaType,type:je.PROPOSAL_MESSAGE_TYPE,thid:t.thid??u,body:{proposals:[]},from:t.to,to:t.from}}o.body?.proposals.push(c)}return o??i}async handleProposalRequest(t,r){if(this._params.packerParams.mediaType==="application/iden3comm-signed-json"&&!this._params.packerParams.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let i=await this.parseProposalRequest(t);if(!i.from)throw new Error("failed request. empty 'from' field");r?.allowExpiredMessages||Qn(i);let o=Ie.parse(i.from),s=await this.handleProposalRequestMessage(i),a=Me.encode(JSON.stringify(s)),l=this._params.packerParams.mediaType==="application/iden3comm-signed-json"?this._params.packerParams.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg};return this._packerMgr.pack(this._params.packerParams.mediaType,a,{senderDID:o,...l})}async handleProposal(t,r){if(r?.allowExpiredMessages||Qn(t),r?.proposalRequest&&r.proposalRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.proposalRequest.from}, given ${t.to}`);return{proposal:t}}};function kY(n,e,t,r,i){let o=Et();return{id:o,thid:o,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:je.PAYMENT_REQUEST_MESSAGE_TYPE,body:{agent:t,payments:r},created_time:Bt(new Date),expires_time:i?.expires_time?Bt(i.expires_time):void 0}}async function _T(n,e){let t=n.type==="Iden3PaymentRailsRequestV1"?{recipient:n.recipient,amount:n.amount,expirationDate:Bt(new Date(n.expirationDate)),nonce:n.nonce,metadata:"0x"}:{tokenAddress:n.tokenAddress,recipient:n.recipient,amount:n.amount,expirationDate:Bt(new Date(n.expirationDate)),nonce:n.nonce,metadata:"0x"},r=Array.isArray(n.proof)?n.proof[0]:n.proof,o=await(await fetch(r.eip712.types)).json();delete o.EIP712Domain;let s=nn.verifyTypedData(r.eip712.domain,o,t,r.proofValue),{didDocument:a}=await e.resolve(r.verificationMethod);if(a?.verificationMethod){for(let l of a.verificationMethod)if(l.blockchainAccountId?.split(":").slice(-1)[0].toLowerCase()===s.toLowerCase())return s}else throw new Error("failed request. issuer DIDDocument does not contain any verificationMethods");throw new Error("failed request. no matching verificationMethod")}function OY(n,e,t,r){let i=Et();return{id:i,thid:i,from:n.string(),to:e.string(),typ:"application/iden3comm-plain-json",type:je.PAYMENT_MESSAGE_TYPE,body:{payments:t},created_time:Bt(new Date),expires_time:r?.expires_time?Bt(r.expires_time):void 0}}var $T=class extends Xr{constructor(t,r){super();this._packerMgr=t;this._params=r}async handle(t,r){switch(t.type){case je.PAYMENT_REQUEST_MESSAGE_TYPE:return await this.handlePaymentRequestMessage(t,r);case je.PAYMENT_MESSAGE_TYPE:return await this.handlePayment(t,r),null;default:return super.handle(t,r)}}async parsePaymentRequest(t){let{unpackedMessage:r}=await this._packerMgr.unpack(t),i=r;if(r.type!==je.PAYMENT_REQUEST_MESSAGE_TYPE)throw new Error("Invalid media type");return i}async handlePaymentRequestMessage(t,r){if(!t.to)throw new Error("failed request. empty 'to' field");if(!t.from)throw new Error("failed request. empty 'from' field");if(!t.body.payments?.length)throw new Error("failed request. no 'payments' in body");if(!r.paymentHandler)throw new Error("please provide payment handler in context");let i=Ie.parse(t.to),o=Ie.parse(t.from),s=[];for(let h=0;h<t.body.payments.length;h++){let{data:f}=t.body.payments[h],p=Array.isArray(f)?f.find(w=>w.type==="Iden3PaymentRequestCryptoV1"?w.id===r.nonce:w.nonce===r.nonce):f;if(!p)throw new Error(`failed request. no payment in request for nonce ${r.nonce}`);switch(p.type){case"Iden3PaymentRequestCryptoV1":s.push(await this.handleIden3PaymentRequestCryptoV1(p,r.paymentHandler));break;case"Iden3PaymentRailsRequestV1":s.push(await this.handleIden3PaymentRailsRequestV1(p,r.paymentHandler));break;case"Iden3PaymentRailsERC20RequestV1":s.push(await this.handleIden3PaymentRailsERC20RequestV1(p,r.paymentHandler,r.erc20TokenApproveHandler));break}}let a=OY(i,o,s),l=await this.packMessage(a,i),u=await(await fetch(t.body.agent,{method:"POST",body:l,headers:{"Content-Type":this._params.packerParams.mediaType==="application/iden3comm-plain-json"?"application/json":"application/octet-stream"}})).arrayBuffer();if(!u.byteLength)return null;let{unpackedMessage:d}=await this._packerMgr.unpack(new Uint8Array(u));return d}async handlePaymentRequest(t,r){if(this._params.packerParams.mediaType==="application/iden3comm-signed-json"&&!this._params.packerParams.packerOptions)throw new Error("jws packer options are required for application/iden3comm-signed-json");let i=await this.parsePaymentRequest(t);if(!i.from)throw new Error("failed request. empty 'from' field");if(!i.to)throw new Error("failed request. empty 'to' field");r?.allowExpiredMessages||Qn(i);let o=await this.handlePaymentRequestMessage(i,r);if(!o)return null;let s=Ie.parse(i.to);return this.packMessage(o,s)}async handlePayment(t,r){if(r?.allowExpiredMessages||Qn(t),r.paymentRequest.from!==t.to)throw new Error(`sender of the request is not a target of response - expected ${r.paymentRequest.from}, given ${t.to}`);if(!t.body.payments.length)throw new Error("failed request. empty 'payments' field in body");if(!r.paymentValidationHandler)throw new Error("please provide payment validation handler in options");for(let i=0;i<t.body.payments.length;i++){let o=t.body.payments[i],s=o.type==="Iden3PaymentCryptoV1"?o.id:o.nonce,l=r.paymentRequest.body.payments.map(c=>Array.isArray(c.data)?c.data:[c.data]).flat().find(c=>c.type==="Iden3PaymentRequestCryptoV1"?c.id===s:c.nonce===s);if(!l)throw new Error(`can't find payment request for payment ${o.type==="Iden3PaymentCryptoV1"?"id":"nonce"} ${s}`);await r.paymentValidationHandler(o.paymentData.txId,l)}}async createPaymentRailsV1(t,r,i,o,s){let a=[];for(let l=0;l<s.length;l++){let{credentials:c,description:u}=s[l],d=[];for(let h=0;h<s[l].options.length;h++){let{nonce:f,amount:p,chainId:w,optionId:y,expirationDate:v}=s[l].options[h],B=this._params.multiChainPaymentConfig?.find(b=>b.chainId===w);if(!B)throw new Error(`failed request. no config for chain ${w}`);let{recipient:U,paymentRails:k,options:F}=B,P=F.find(b=>b.id===y);if(!P)throw new Error(`failed request. no option for id ${y}`);if(P.type==="Iden3PaymentRailsERC20RequestV1"&&!P.contractAddress)throw new Error(`failed request. no token address for option id ${y}`);let I=v??new Date(new Date().setHours(new Date().getHours()+1)),D=`https://schema.iden3.io/core/json/${P.type}.json`,K=await(await fetch(D)).json();delete K.EIP712Domain;let q=P.type==="Iden3PaymentRailsRequestV1"?{recipient:U,amount:p,expirationDate:Bt(I),nonce:f,metadata:"0x"}:{tokenAddress:P.contractAddress,recipient:U,amount:p,expirationDate:Bt(I),nonce:f,metadata:"0x"},G={name:"MCPayment",version:"1.0.0",chainId:w,verifyingContract:k},x=await o.signTypedData(G,K,q),S=[{type:"EthereumEip712Signature2021",proofPurpose:"assertionMethod",proofValue:x,verificationMethod:`did:pkh:eip155:${w}:${await o.getAddress()}`,created:new Date().toISOString(),eip712:{types:D,primaryType:"Iden3PaymentRailsRequestV1",domain:G}}],M={type:"Iden3PaymentRailsRequestV1","@context":[`https://schema.iden3.io/core/jsonld/payment.jsonld#${P.type}`,"https://w3id.org/security/suites/eip712sig-2021/v1"],recipient:U,amount:p.toString(),expirationDate:I.toISOString(),nonce:f.toString(),metadata:"0x",proof:S};d.push(P.type==="Iden3PaymentRailsRequestV1"?M:{...M,type:P.type,tokenAddress:P.contractAddress||"",features:P.features||[]})}a.push({data:d,credentials:c,description:u})}return kY(t,r,i,a)}async packMessage(t,r){let i=Me.encode(JSON.stringify(t)),o=this._params.packerParams.mediaType==="application/iden3comm-signed-json"?this._params.packerParams.packerOptions:{provingMethodAlg:gi.provingMethodGroth16AuthV2Instance.methodAlg};return await this._packerMgr.pack(this._params.packerParams.mediaType,i,{senderDID:r,...o})}async handleIden3PaymentRequestCryptoV1(t,r){if(t.expiration&&new Date(t.expiration)<new Date)throw new Error("failed request. expired request");let i=await r(t);return{id:t.id,"@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentCryptoV1",type:"Iden3PaymentCryptoV1",paymentData:{txId:i}}}async handleIden3PaymentRailsRequestV1(t,r){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");let i=await _T(t,this._params.documentResolver);if(this._params.allowedSigners&&!this._params.allowedSigners.includes(i))throw new Error("failed request. signer is not in the allowed signers list");let o=await r(t),s=Array.isArray(t.proof)?t.proof[0]:t.proof;return{nonce:t.nonce,type:"Iden3PaymentRailsV1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsV1",paymentData:{txId:o,chainId:s.eip712.domain.chainId}}}async handleIden3PaymentRailsERC20RequestV1(t,r,i){if(t.expirationDate&&new Date(t.expirationDate)<new Date)throw new Error("failed request. expired request");let o=await _T(t,this._params.documentResolver);if(this._params.allowedSigners&&!this._params.allowedSigners.includes(o))throw new Error("failed request. signer is not in the allowed signers list");if(!t.features?.includes("EIP-2612")&&!i)throw new Error("please provide erc20TokenApproveHandler in context for ERC-20 payment type");i&&await i(t);let s=await r(t),a=Array.isArray(t.proof)?t.proof[0]:t.proof;return{nonce:t.nonce,type:"Iden3PaymentRailsERC20V1","@context":"https://schema.iden3.io/core/jsonld/payment.jsonld#Iden3PaymentRailsERC20V1",paymentData:{txId:s,chainId:a.eip712.domain.chainId,tokenAddress:t.tokenAddress}}}};function fwe(n,e){let t=Et();return{id:t,thid:t,typ:"application/iden3comm-plain-json",type:je.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE,body:{queries:n},from:e?.from,to:e?.to,created_time:Bt(new Date),expires_time:e?.expires_time}}function GY(n,e){let t=Et();return{id:t,typ:"application/iden3comm-plain-json",thid:t,type:je.DISCOVERY_PROTOCOL_DISCLOSE_MESSAGE_TYPE,body:{disclosures:n},from:e?.from,to:e?.to,created_time:Bt(new Date),expires_time:e?.expires_time}}var eP=class extends Xr{constructor(t){super();this._options=t;let r=["id","typ","type","thid","body","from","to","created_time","expires_time"];t.headers||(t.headers=r)}async handle(t,r){switch(t.type){case je.DISCOVERY_PROTOCOL_QUERIES_MESSAGE_TYPE:return await this.handleDiscoveryQuery(t,r);default:return super.handle(t,r)}}async handleDiscoveryQuery(t,r){r?.allowExpiredMessages||Qn(t);let i=[];for(let o of t.body.queries)i.push(...this.handleQuery(o));return Promise.resolve(GY(i,{to:t.from,from:t.to,expires_time:r?.disclosureExpiresDate?Bt(r.disclosureExpiresDate):void 0}))}handleQuery(t){let r=[];switch(t["feature-type"]){case"accept":r=this.handleAcceptQuery();break;case"protocol":r=this.handleProtocolQuery();break;case"goal-code":r=this.handleGoalCodeQuery();break;case"header":r=this.handleHeaderQuery();break}return this.handleMatch(r,t.match)}handleAcceptQuery(){return this._options.packageManager.getSupportedProfiles().map(r=>({"feature-type":"accept",id:r}))}handleProtocolQuery(){return this._options.protocols?.map(t=>({"feature-type":"protocol",id:t}))??[]}handleGoalCodeQuery(){return this._options.goalCodes?.map(t=>({"feature-type":"goal-code",id:t}))??[]}handleHeaderQuery(){return this._options.headers?.map(t=>({"feature-type":"header",id:t}))??[]}handleMatch(t,r){if(!r||r==="*")return t;let i=this.wildcardToRegExp(r);return t.filter(o=>i.test(o.id))}wildcardToRegExp(t){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`)}};function hwe(n,e,t){return{id:Et(),pthid:n,typ:"application/iden3comm-plain-json",type:je.PROBLEM_REPORT_MESSAGE_TYPE,ack:t?.ack,body:{code:e,comment:t?.comment,args:t?.args,escalate_to:t?.escalate_to},from:t?.from,to:t?.to}}var iu={url:"http://localhost:8545",defaultGasLimit:6e5,minGasPrice:"0",maxGasPrice:"100000000000",confirmationBlockCount:5,confirmationTimeout:6e5,contractAddress:"",receiptTimeout:6e5,rpcResponseTimeout:5e3,waitReceiptCycleTime:3e4,waitBlockCycleTime:3e3},pb=class{constructor(e,t){this.ethConfig=e;let r=Array.isArray(e)?e[0]:e;this.provider=new Tt(r.url),this.stateContract=new $t(r.contractAddress,eB,this.provider),this._transactionService=new _o(this.getRpcProvider()),this._latestStateCacheOptions={ttl:t?.latestStateCacheOptions?.ttl??yi.DEFAULT_PROOF_VERIFY_DELAY/2,maxSize:t?.latestStateCacheOptions?.maxSize??v0},this._stateCacheOptions={notReplacedTtl:t?.stateCacheOptions?.notReplacedTtl??yi.DEFAULT_PROOF_VERIFY_DELAY/2,replacedTtl:t?.stateCacheOptions?.replacedTtl??yi.DEFAULT_PROOF_VERIFY_DELAY,maxSize:t?.stateCacheOptions?.maxSize??v0},this._rootCacheOptions={replacedTtl:t?.rootCacheOptions?.replacedTtl??yi.DEFAULT_AUTH_VERIFY_DELAY,notReplacedTtl:t?.rootCacheOptions?.notReplacedTtl??yi.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.rootCacheOptions?.maxSize??v0},this._gistProofCacheOptions={ttl:yi.DEFAULT_AUTH_VERIFY_DELAY/2,maxSize:t?.gistProofCacheOptions?.maxSize??v0},this._latestStateResolveCache=t?.latestStateCacheOptions?.cache??Dm({maxSize:this._latestStateCacheOptions.maxSize,ttl:this._latestStateCacheOptions.ttl}),this._stateResolveCache=t?.stateCacheOptions?.cache??Dm({maxSize:this._stateCacheOptions.maxSize,ttl:this._stateCacheOptions.replacedTtl}),this._rootResolveCache=t?.rootCacheOptions?.cache??Dm({maxSize:this._rootCacheOptions.maxSize,ttl:this._rootCacheOptions.replacedTtl}),this._gistProofResolveCache=t?.gistProofCacheOptions?.cache??Dm({maxSize:this._gistProofCacheOptions.maxSize,ttl:this._gistProofCacheOptions.ttl}),this._disableCache=t?.disableCache??!1}stateContract;provider;_transactionService;_latestStateResolveCache;_stateResolveCache;_rootResolveCache;_gistProofResolveCache;_latestStateCacheOptions;_stateCacheOptions;_rootCacheOptions;_gistProofCacheOptions;_disableCache=!1;async getLatestStateById(e){let t=this.getLatestStateCacheKey(e);if(!this._disableCache){let s=await this._latestStateResolveCache?.get(t);if(s)return s}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=await r.getStateInfoById(e),o={id:BigInt(i[0]),state:BigInt(i[1]),replacedByState:BigInt(i[2]),createdAtTimestamp:BigInt(i[3]),replacedAtTimestamp:BigInt(i[4]),createdAtBlock:BigInt(i[5]),replacedAtBlock:BigInt(i[6])};return!this._disableCache&&await this._latestStateResolveCache?.set(t,o,this._latestStateCacheOptions.ttl),o}async getStateInfoByIdAndState(e,t){let r=this.getStateCacheKey(e,t);if(!this._disableCache){let l=await this._stateResolveCache?.get(r);if(l)return l}let{stateContract:i}=this.getStateContractAndProviderForId(e),o=await i.getStateInfoByIdAndState(e,t),s={id:BigInt(o[0]),state:BigInt(o[1]),replacedByState:BigInt(o[2]),createdAtTimestamp:BigInt(o[3]),replacedAtTimestamp:BigInt(o[4]),createdAtBlock:BigInt(o[5]),replacedAtBlock:BigInt(o[6])},a=s.replacedAtTimestamp===0n?this._stateCacheOptions.notReplacedTtl:this._stateCacheOptions.replacedTtl;return!this._disableCache&&await this._stateResolveCache?.set(r,s,a),s}async publishState(e,t){let r=new G2;r.pubSignalsUnmarshal(Me.encode(JSON.stringify(e.pub_signals)));let{userId:i,oldUserState:o,newUserState:s,isOldStateGenesis:a}=r,{stateContract:l,provider:c}=this.getStateContractAndProviderForId(i.bigInt()),u=l.connect(t),d=Zh(e.proof),h=[i.bigInt().toString(),o.bigInt().toString(),s.bigInt().toString(),a,d.a,d.b,d.c],f=await c.getFeeData(),p=iu.maxFeePerGas?BigInt(iu.maxFeePerGas):f.maxFeePerGas,w=iu.maxPriorityFeePerGas?BigInt(iu.maxPriorityFeePerGas):f.maxPriorityFeePerGas,y=await u.transitState.estimateGas(...h),v=await u.transitState.populateTransaction(...h),B={to:v.to,data:v.data,gasLimit:y,maxFeePerGas:p,maxPriorityFeePerGas:w},{txnHash:U}=await this._transactionService.sendTransactionRequest(t,B);return U}async publishStateGeneric(e,t){let{userId:r,oldUserState:i,newUserState:o,isOldStateGenesis:s,methodId:a,methodParams:l}=t,{stateContract:c,provider:u}=this.getStateContractAndProviderForId(r.bigInt()),d=c.connect(e),h=await u.getFeeData(),f=iu.maxFeePerGas?BigInt(iu.maxFeePerGas):h.maxFeePerGas,p=iu.maxPriorityFeePerGas?BigInt(iu.maxPriorityFeePerGas):h.maxPriorityFeePerGas,w=[r.bigInt().toString(),i.bigInt().toString(),o.bigInt().toString(),s,a,l],y=await d.transitStateGeneric.estimateGas(...w),v=await d.transitStateGeneric.populateTransaction(...w),B={to:v.to,data:v.data,gasLimit:y,maxFeePerGas:f,maxPriorityFeePerGas:p},{txnHash:U}=await this._transactionService.sendTransactionRequest(e,B);return U}async getGISTProof(e){let t=this.getGistProofCacheKey(e);if(!this._disableCache){let s=await this._gistProofResolveCache?.get(t);if(s)return s}let{stateContract:r}=this.getStateContractAndProviderForId(e),i=await r.getGISTProof(e),o={root:BigInt(i.root.toString()),existence:i.existence,siblings:i.siblings?.map(s=>BigInt(s.toString())),index:BigInt(i.index.toString()),value:BigInt(i.value.toString()),auxExistence:i.auxExistence,auxIndex:BigInt(i.auxIndex.toString()),auxValue:BigInt(i.auxValue.toString())};return!this._disableCache&&await this._gistProofResolveCache?.set(t,o,this._gistProofCacheOptions.ttl),o}async getGISTRootInfo(e,t){let r=this.getRootCacheKey(e);if(!this._disableCache){let l=await this._rootResolveCache?.get(r);if(l)return l}let{stateContract:i}=this.getStateContractAndProviderForId(t),o=await i.getGISTRootInfo(e),s={root:BigInt(o.root.toString()),replacedByRoot:BigInt(o.replacedByRoot.toString()),createdAtTimestamp:BigInt(o.createdAtTimestamp.toString()),replacedAtTimestamp:BigInt(o.replacedAtTimestamp.toString()),createdAtBlock:BigInt(o.createdAtBlock.toString()),replacedAtBlock:BigInt(o.replacedAtBlock.toString())},a=s.replacedAtTimestamp==0n?this._rootCacheOptions.notReplacedTtl:this._rootCacheOptions.replacedTtl;return!this._disableCache&&await this._rootResolveCache?.set(r,s,a),s}getRpcProvider(){return this.provider}enableCache(){this._disableCache=!1}disableCache(){this._disableCache=!0}getStateContractAndProviderForId(e){let t=Je.fromBigInt(e),r=Zm(Ie.blockchainFromId(t),Ie.networkIdFromId(t)),i=this.networkByChainId(r),o=new Tt(i.url);return{stateContract:new $t(i.contractAddress,eB,o),provider:o}}networkByChainId(e){let r=(Array.isArray(this.ethConfig)?this.ethConfig:[this.ethConfig]).find(i=>i.chainId===e);if(!r)throw new Error(`chainId "${e}" not supported`);return r}getGistProofCacheKey(e){return`gist-${e.toString()}`}getLatestStateCacheKey(e){return`latest-${e.toString()}`}getStateCacheKey(e,t){return`${e.toString()}-${t.toString()}`}getRootCacheKey(e){return e.toString()}};var tP=[{inputs:[],name:"InvalidInitialization",type:"error"},{inputs:[{internalType:"string",name:"message",type:"string"},{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256",name:"linkID",type:"uint256"},{internalType:"uint64",name:"requestIdToCompare",type:"uint64"},{internalType:"uint256",name:"linkIdToCompare",type:"uint256"}],name:"LinkedProofError",type:"error"},{inputs:[],name:"NotInitializing",type:"error"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"OwnableInvalidOwner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"OwnableUnauthorizedAccount",type:"error"},{anonymous:!1,inputs:[{indexed:!1,internalType:"uint64",name:"version",type:"uint64"}],name:"Initialized",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferStarted",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"previousOwner",type:"address"},{indexed:!0,internalType:"address",name:"newOwner",type:"address"}],name:"OwnershipTransferred",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint64",name:"requestId",type:"uint64"},{indexed:!0,internalType:"address",name:"requestOwner",type:"address"},{indexed:!1,internalType:"string",name:"metadata",type:"string"},{indexed:!1,internalType:"address",name:"validator",type:"address"},{indexed:!1,internalType:"bytes",name:"data",type:"bytes"}],name:"ZKPRequestSet",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"uint64",name:"requestId",type:"uint64"},{indexed:!0,internalType:"address",name:"caller",type:"address"}],name:"ZKPResponseSubmitted",type:"event"},{inputs:[],name:"REQUESTS_RETURN_LIMIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"acceptOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"addValidatorToWhitelist",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"disableZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"enableZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getProofStatus",outputs:[{components:[{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"blockNumber",type:"uint256"},{internalType:"uint256",name:"blockTimestamp",type:"uint256"}],internalType:"struct IZKPVerifier.ProofStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"user",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"string",name:"key",type:"string"}],name:"getProofStorageField",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getRequestOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"getZKPRequest",outputs:[{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest",name:"zkpRequest",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"startIndex",type:"uint256"},{internalType:"uint256",name:"length",type:"uint256"}],name:"getZKPRequests",outputs:[{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getZKPRequestsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IStateCrossChain",name:"stateCrossChain",type:"address"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64",name:"requestId",type:"uint64"}],name:"isProofVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"isWhitelistedValidator",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"isZKPRequestEnabled",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"owner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"pendingOwner",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract ICircuitValidator",name:"validator",type:"address"}],name:"removeValidatorFromWhitelist",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"renounceOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"}],name:"requestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"address",name:"requestOwner",type:"address"}],name:"setRequestOwner",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{components:[{internalType:"string",name:"metadata",type:"string"},{internalType:"contract ICircuitValidator",name:"validator",type:"address"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct IZKPVerifier.ZKPRequest",name:"request",type:"tuple"}],name:"setZKPRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256[]",name:"inputs",type:"uint256[]"},{internalType:"uint256[2]",name:"a",type:"uint256[2]"},{internalType:"uint256[2][2]",name:"b",type:"uint256[2][2]"},{internalType:"uint256[2]",name:"c",type:"uint256[2]"}],name:"submitZKPResponse",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"bytes",name:"zkProof",type:"bytes"},{internalType:"bytes",name:"data",type:"bytes"}],internalType:"struct ZKPResponse[]",name:"responses",type:"tuple[]"},{internalType:"bytes",name:"crossChainProof",type:"bytes"}],name:"submitZKPResponseV2",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"newOwner",type:"address"}],name:"transferOwnership",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint64[]",name:"requestIds",type:"uint64[]"}],name:"verifyLinkedProofs",outputs:[],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"requestId",type:"uint64"},{internalType:"uint256[]",name:"inputs",type:"uint256[]"},{internalType:"uint256[2]",name:"a",type:"uint256[2]"},{internalType:"uint256[2][2]",name:"b",type:"uint256[2][2]"},{internalType:"uint256[2]",name:"c",type:"uint256[2]"},{internalType:"address",name:"sender",type:"address"}],name:"verifyZKPResponse",outputs:[{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"inputValue",type:"uint256"}],internalType:"struct ICircuitValidator.KeyToInputValue[]",name:"",type:"tuple[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"}];var nP=[{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"address",name:"userAddress",type:"address"}],name:"areMultiRequestProofsVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"groupID",type:"uint256"}],name:"getGroupedRequests",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.RequestInfo[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getGroupsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"}],name:"getMultiRequest",outputs:[{components:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"uint256[]",name:"requestIds",type:"uint256[]"},{internalType:"uint256[]",name:"groupIds",type:"uint256[]"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.MultiRequest",name:"multiRequest",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"address",name:"userAddress",type:"address"}],name:"getMultiRequestProofsStatus",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct IVerifier.RequestProofStatus[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"}],name:"getRequest",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.RequestInfo",name:"request",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"requestId",type:"uint256"}],name:"getRequestProofStatus",outputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bool",name:"isVerified",type:"bool"},{internalType:"string",name:"validatorVersion",type:"string"},{internalType:"uint256",name:"timestamp",type:"uint256"}],internalType:"struct IVerifier.RequestProofStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRequestsCount",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"address",name:"sender",type:"address"},{internalType:"string",name:"responseFieldName",type:"string"}],name:"getResponseFieldValue",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"address",name:"sender",type:"address"}],name:"getResponseFields",outputs:[{components:[{internalType:"string",name:"name",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct IRequestValidator.ResponseField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"groupId",type:"uint256"}],name:"groupIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"requestId",type:"uint256"}],name:"isRequestProofVerified",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"multiRequestId",type:"uint256"}],name:"multiRequestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"requestId",type:"uint256"}],name:"requestIdExists",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[{components:[{internalType:"string",name:"authMethod",type:"string"},{internalType:"contract IAuthValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"}],internalType:"struct IVerifier.AuthMethod",name:"authMethod",type:"tuple"}],name:"setAuthMethod",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint256",name:"multiRequestId",type:"uint256"},{internalType:"uint256[]",name:"requestIds",type:"uint256[]"},{internalType:"uint256[]",name:"groupIds",type:"uint256[]"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.MultiRequest",name:"multiRequest",type:"tuple"}],name:"setMultiRequest",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"string",name:"metadata",type:"string"},{internalType:"contract IRequestValidator",name:"validator",type:"address"},{internalType:"bytes",name:"params",type:"bytes"},{internalType:"address",name:"creator",type:"address"}],internalType:"struct IVerifier.Request[]",name:"requests",type:"tuple[]"}],name:"setRequests",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"string",name:"authMethod",type:"string"},{internalType:"bytes",name:"proof",type:"bytes"}],internalType:"struct IVerifier.AuthResponse",name:"authResponse",type:"tuple"},{components:[{internalType:"uint256",name:"requestId",type:"uint256"},{internalType:"bytes",name:"proof",type:"bytes"},{internalType:"bytes",name:"metadata",type:"bytes"}],internalType:"struct IVerifier.Response[]",name:"responses",type:"tuple[]"},{internalType:"bytes",name:"crossChainProofs",type:"bytes"}],name:"submitResponse",outputs:[],stateMutability:"nonpayable",type:"function"}];var rP=10000000n,NY=(r=>(r.SubmitZKPResponseV1="b68967e2",r.SubmitZKPResponseV2="ade09fcd",r.SubmitResponse="06c86a91",r))(NY||{}),UY=function(n){return[{authMethod:n.authProof.raw.authMethod,proof:n.authProof.encoded},n.proofs.map(e=>({requestId:e.requestId,proof:e.encoded,metadata:e.metadata})),n.crossChainProof.encoded]},iP=class n{constructor(e,t){this._configs=e;this._opts=t}static _supportedCircuits=["authV2","credentialAtomicQueryMTPV2OnChain","credentialAtomicQuerySigV2OnChain","credentialAtomicQueryV3OnChain-beta.1"];static _supportedCircuitsPubSignalsMap={credentialAtomicQueryMTPV2OnChain:S2,credentialAtomicQuerySigV2OnChain:F2,"credentialAtomicQueryV3OnChain-beta.1":R2,authV2:La};static async prepareTxArgsSubmitV1(e,t){if(e.method_id.replace("0x","")!=="b68967e2")throw new Error("prepareTxArgsSubmitV1 function doesn't implement requested method id. Only '0xb68967e2' is supported.");let r=t.id,i=t.pub_signals,o=Zh(t.proof);return[r,i,o.a,o.b,o.c]}async prepareTxArgsSubmitV1(e,t){return n.prepareTxArgsSubmitV1(e,t)}async submitZKPResponse(e,t,r){let i=this._configs.find(d=>d.chainId==t.chain_id);if(!i)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="b68967e2")throw new Error("submitZKPResponse function doesn't implement requested method id. Only '0xb68967e2' is supported.");let o=new Tt(i.url,i.chainId);e=e.connect(o);let s=new Map,a=await o.getFeeData(),l=i.maxFeePerGas?BigInt(i.maxFeePerGas):a.maxFeePerGas,c=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,u=new $t(t.contract_address,tP);for(let d of r){let h=await this.prepareTxArgsSubmitV1(t,d),f=await u.submitZKPResponse.populateTransaction(...h),p={to:t.contract_address,data:f.data,maxFeePerGas:l,maxPriorityFeePerGas:c},w;try{w=await e.estimateGas(p)}catch{w=rP}p.gasLimit=w;let y=new _o(o),{txnHash:v}=await y.sendTransactionRequest(e,p);s.set(v,d)}return s}async submitZKPResponseV2(e,t,r){let i=this._configs.find(y=>y.chainId==t.chain_id);if(!i)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="ade09fcd")throw new Error("submitZKPResponseV2 function doesn't implement requested method id. Only '0xade09fcd' is supported.");if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");let o=new Tt(i.url,i.chainId);e=e.connect(o);let s=await this.prepareTxArgsSubmitV2(t,r),a=await o.getFeeData(),l=i.maxFeePerGas?BigInt(i.maxFeePerGas):a.maxFeePerGas,c=i.maxPriorityFeePerGas?BigInt(i.maxPriorityFeePerGas):a.maxPriorityFeePerGas,d=await new $t(t.contract_address,tP).submitZKPResponseV2.populateTransaction(...s),h={to:t.contract_address,data:d.data,maxFeePerGas:l,maxPriorityFeePerGas:c},f;try{f=await e.estimateGas(h)}catch{f=rP}h.gasLimit=f;let p=new _o(o),{txnHash:w}=await p.sendTransactionRequest(e,h);return new Map().set(w,r)}async submitResponse(e,t,r,i){let o=this._configs.find(v=>v.chainId==t.chain_id);if(!o)throw new Error(`config for chain id ${t.chain_id} was not found`);if(t.method_id.replace("0x","")!=="06c86a91")throw new Error("submitResponse function doesn't implement requested method id. Only '0x06c86a91' is supported.");if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");let s=new Tt(o.url,o.chainId);e=e.connect(s);let a=await this.prepareTxArgsSubmit(t,r,i),l=await s.getFeeData(),c=o.maxFeePerGas?BigInt(o.maxFeePerGas):l.maxFeePerGas,u=o.maxPriorityFeePerGas?BigInt(o.maxPriorityFeePerGas):l.maxPriorityFeePerGas,h=await new $t(t.contract_address,nP).submitResponse.populateTransaction(...a.txDataArgs),f={to:t.contract_address,data:h.data,maxFeePerGas:c,maxPriorityFeePerGas:u},p;try{p=await e.estimateGas(f)}catch{p=rP}f.gasLimit=p;let w=new _o(s),{txnHash:y}=await w.sendTransactionRequest(e,f);return new Map().set(y,{authProof:a.result.authProof.raw,crossChainProof:a.result.crossChainProof.raw,responses:a.result.proofs.map(v=>v.proof)})}static async prepareTxArgsSubmit(e,t,r,i){if(t.method_id.replace("0x","")!=="06c86a91")throw new Error("submit cross chain doesn't implement requested method id. Only '0x06c86a91' is supported.");let o=[],s=[],a=[],l="0x",c="";switch(i.authMethod){case"authV2":{let f=Zh(i.zkp.proof);c=tA(i.zkp.pub_signals,f.a,f.b,f.c);break}case"ethIdentity":{c=HY(i.userDid);break}default:throw new Error("auth proof must use method AuthV2 or ethIdentity")}for(let f of r){this.checkSupportedCircuit(f.circuitId);let{requestId:p,zkProofEncoded:w,metadata:y}=db(f);a.push({proof:f,requestId:p,encoded:w,metadata:y})}let u=r.map(f=>({circuitId:f.circuitId,pub_signals:f.pub_signals}));i.authMethod=="authV2"&&u.push({circuitId:i.zkp.circuitId,pub_signals:i.zkp.pub_signals});for(let f of u){let{gistUpdateResolutions:p,stateUpdateResolutions:w}=this.getUpdateResolutions(e,t.chain_id,f.circuitId,f.pub_signals);p.length>0&&o.push(...await Promise.all(p)),w.length>0&&s.push(...await Promise.all(w))}let d=o.length||s.length?this.packCrossChainProofs(o,s):l,h={authProof:{raw:i,encoded:c},proofs:a,crossChainProof:{raw:{globalStateProofs:o||[],identityStateProofs:s||[]},encoded:d}};return{result:h,txDataArgs:UY(h)}}async prepareTxArgsSubmit(e,t,r){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmit(this._opts.didResolverUrl,e,t,r)}static checkSupportedCircuit(e){if(!this._supportedCircuits.includes(e))throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`)}static getCrossChainResolvers(e,t,r,i){return[...new Set(e.map(o=>JSON.stringify({id:o.id.string(),[r]:r==="gist"?o.root?.string():o.state?.string()})))].reduce((o,s)=>{let a=JSON.parse(s),l=Je.fromString(a.id),c=Xm(Ie.parseFromId(l));if(t===c)return o;let u=this.resolveDidDocumentEip712MessageAndSignature(Ie.parseFromId(Je.fromString(a.id)),i,{[r]:me.fromString(a[r])});return[...o,u]},[])}static async prepareTxArgsSubmitV2(e,t,r){if(t.method_id.replace("0x","")!=="ade09fcd")throw new Error("submit cross chain doesn't implement requested method id. Only '0xade09fcd' is supported.");let i=[],o=[],s=[],a="0x";for(let c of r){this.checkSupportedCircuit(c.circuitId);let{requestId:u,zkProofEncoded:d,metadata:h}=db(c);s.push({requestId:u,zkProof:d,data:h});let{gistUpdateResolutions:f,stateUpdateResolutions:p}=this.getUpdateResolutions(e,t.chain_id,c.circuitId,c.pub_signals);f.length>0&&i.push(...await Promise.all(f)),p.length>0&&o.push(...await Promise.all(p))}let l=i.length||o.length?this.packCrossChainProofs(i,o):a;return[s,l]}async prepareTxArgsSubmitV2(e,t){if(!this._opts?.didResolverUrl)throw new Error("did resolver url required for crosschain verification");return n.prepareTxArgsSubmitV2(this._opts.didResolverUrl,e,t)}static getUpdateResolutions(e,t,r,i){let o=this.getOnChainGistRootStatePubSignals(r,i),s=this.getCrossChainResolvers(o.gists,t,"gist",e),a=this.getCrossChainResolvers(o.states,t,"state",e);return{gistUpdateResolutions:s,stateUpdateResolutions:a}}static packCrossChainProofs(e,t){let r=[];for(let i of e)r.push({proofType:"globalStateProof",proof:this.packGlobalStateMsg(i)});for(let i of t)r.push({proofType:"stateProof",proof:this.packIdentityStateMsg(i)});return new nn.AbiCoder().encode(["tuple(string proofType,bytes proof)[]"],[r])}static packGlobalStateMsg(e){return new nn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,bytes2 idType,uint256 root,uint256 replacedAtTimestamp) globalStateMsg,bytes signature,)"],[e])}static packIdentityStateMsg(e){return new nn.AbiCoder().encode(["tuple(tuple(uint256 timestamp,uint256 id,uint256 state,uint256 replacedAtTimestamp) idStateMsg,bytes signature,)"],[e])}static getOnChainGistRootStatePubSignals(e,t){let r=this._supportedCircuitsPubSignalsMap[e];if(!r)throw new Error(`Circuit ${e} not supported by OnChainZKPVerifier`);let i=new r,o=Me.encode(JSON.stringify(t));return i.pubSignalsUnmarshal(o),i.getStatesInfo()}static async resolveDidDocumentEip712MessageAndSignature(e,t,r){let i=await Kf(e,t,{...r,signature:"EthereumEip712Signature2021"});if(!i.didResolutionMetadata.proof?.length)throw new Error("No proof found in resolved DID document");let o=i.didResolutionMetadata.proof[0].eip712.message,s=i.didResolutionMetadata.proof[0].proofValue;return r?.gist&&!r.state?{globalStateMsg:{timestamp:o.timestamp,idType:o.idType,root:o.root,replacedAtTimestamp:o.replacedAtTimestamp},signature:s}:{idStateMsg:{timestamp:o.timestamp,id:o.id,state:o.state,replacedAtTimestamp:o.replacedAtTimestamp},signature:s}}},HY=n=>`0x${xi(ht.intToBytes(Ie.idFromDID(n).bigInt()))}`;var oP=[{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"},{internalType:"uint256",name:"_credentialId",type:"uint256"}],name:"getCredential",outputs:[{components:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"string[]",name:"context",type:"string[]"},{internalType:"string",name:"_type",type:"string"},{internalType:"uint64",name:"issuanceDate",type:"uint64"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.CredentialSchema",name:"credentialSchema",type:"tuple"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.DisplayMethod",name:"displayMethod",type:"tuple"}],internalType:"struct INonMerklizedIssuer.CredentialData",name:"",type:"tuple"},{internalType:"uint256[8]",name:"",type:"uint256[8]"},{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct INonMerklizedIssuer.SubjectField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCredentialAdapterVersion",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"}],name:"getUserCredentialIds",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"}];var sP=[{inputs:[],name:"CREDENTIAL_ADAPTER_VERSION",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"}],name:"getClaimProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getClaimProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimIndexHash",type:"uint256"}],name:"getClaimProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getClaimsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"},{internalType:"uint256",name:"_credentialId",type:"uint256"}],name:"getCredential",outputs:[{components:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"string[]",name:"context",type:"string[]"},{internalType:"string",name:"_type",type:"string"},{internalType:"uint64",name:"issuanceDate",type:"uint64"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.CredentialSchema",name:"credentialSchema",type:"tuple"},{components:[{internalType:"string",name:"id",type:"string"},{internalType:"string",name:"_type",type:"string"}],internalType:"struct INonMerklizedIssuer.DisplayMethod",name:"displayMethod",type:"tuple"}],internalType:"struct INonMerklizedIssuer.CredentialData",name:"",type:"tuple"},{internalType:"uint256[8]",name:"",type:"uint256[8]"},{components:[{internalType:"string",name:"key",type:"string"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bytes",name:"rawValue",type:"bytes"}],internalType:"struct INonMerklizedIssuer.SubjectField[]",name:"",type:"tuple[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"getCredentialAdapterVersion",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[],name:"getId",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getIsOldStateGenesis",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedClaimsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedRevocationsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedRootsRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getLatestPublishedState",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"}],name:"getRevocationProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getRevocationProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint64",name:"revocationNonce",type:"uint64"}],name:"getRevocationProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatus",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"id",type:"uint256"},{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint64",name:"nonce",type:"uint64"}],name:"getRevocationStatusByIdAndState",outputs:[{components:[{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"revocationTreeRoot",type:"uint256"},{internalType:"uint256",name:"rootOfRoots",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.IdentityStateRoots",name:"issuer",type:"tuple"},{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct IOnchainCredentialStatusResolver.Proof",name:"mtp",type:"tuple"}],internalType:"struct IOnchainCredentialStatusResolver.CredentialStatus",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRevocationsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"rootsTreeRoot",type:"uint256"}],name:"getRootProof",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"claimsTreeRoot",type:"uint256"},{internalType:"uint256",name:"root",type:"uint256"}],name:"getRootProofByRoot",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"rootsTreeRoot",type:"uint256"}],name:"getRootProofWithStateInfo",outputs:[{components:[{internalType:"uint256",name:"root",type:"uint256"},{internalType:"bool",name:"existence",type:"bool"},{internalType:"uint256[]",name:"siblings",type:"uint256[]"},{internalType:"uint256",name:"index",type:"uint256"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"bool",name:"auxExistence",type:"bool"},{internalType:"uint256",name:"auxIndex",type:"uint256"},{internalType:"uint256",name:"auxValue",type:"uint256"}],internalType:"struct SmtLib.Proof",name:"",type:"tuple"},{components:[{internalType:"uint256",name:"state",type:"uint256"},{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.StateInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint256",name:"state",type:"uint256"}],name:"getRootsByState",outputs:[{components:[{internalType:"uint256",name:"claimsRoot",type:"uint256"},{internalType:"uint256",name:"revocationsRoot",type:"uint256"},{internalType:"uint256",name:"rootsRoot",type:"uint256"}],internalType:"struct IdentityLib.Roots",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[],name:"getRootsTreeRoot",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getSmtDepth",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"uint256",name:"_userId",type:"uint256"}],name:"getUserCredentialIds",outputs:[{internalType:"uint256[]",name:"",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"_stateContractAddr",type:"address"},{internalType:"bytes2",name:"idType",type:"bytes2"}],name:"initialize",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes4",name:"interfaceId",type:"bytes4"}],name:"supportsInterface",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"view",type:"function"}],Vm=class{static abi=sP;static createInterface(){return new ca(sP)}static connect(e,t){return new $t(e,sP,t)}};var wb=class{_contract;_contractAddress;_chainId;_issuerDid;_merklizationOptions;constructor(e,t,r){if(!e.chainId)throw new Error("Chain ID is required");this._chainId=e.chainId,this._contractAddress=nn.getAddress(nn.hexlify(Je.ethAddressFromId(Ie.idFromDID(t)))),this._contract=Vm.connect(this._contractAddress,new nn.JsonRpcProvider(e.url)),this._issuerDid=t,this._merklizationOptions=r?.merklizationOptions}async isInterfaceSupported(){let e=[{name:"Interface detection ERC-165",value:"0x01ffc9a7"},{name:"Interface non-merklized issuer",value:"0x58874949"},{name:"Interface get credential",value:"0x5d1ca631"}],r=(await Promise.all(e.map(async i=>await this._contract.supportsInterface(i.value)?null:i.name))).filter(i=>i!==null);if(r.length>0)throw new Error(`Unsupported interfaces: ${r.join(", ")}`)}async getCredential(e,t){let[r,i,o]=await this._contract.getCredential(e.bigInt(),t);return{credentialData:r,coreClaimBigInts:i,credentialSubjectFields:o}}async getUserCredentialsIds(e){return this._contract.getUserCredentialIds(e.bigInt())}async convertOnChainInfoToW3CCredential(e,t,r){let i=new er().unMarshalJson(JSON.stringify(t.map(c=>c.toString()))),o=await this.convertCredentialSubject(i,e.context,e._type,r),s={id:this.credentialId(e.id),credentialSchema:e.credentialSchema.id,type:e._type,credentialSubject:o,expiration:i.getExpirationDate()?.getTime(),displayMethod:this.convertDisplayMethod(e.displayMethod),context:e.context,revocationOpts:{id:this._contractAddress,nonce:Number(i.getRevocationNonce()),type:"Iden3OnchainSparseMerkleTreeProof2023"},issuanceDate:ns(Number(e.issuanceDate)).getTime()},a=await this.existenceProof(i),l=fr.fromCredentialRequest(this._issuerDid,s);return l.proof=[a],l}credentialId(e){return`urn:iden3:onchain:${this._chainId}:${this._contractAddress}:${e}`}async convertCredentialSubject(e,t,r,i){let o=JSON.stringify({"@context":t}),s={};for(let c of i){let u=await rr.newTypeFromContext(o,`${r}.${c.key}`,this._merklizationOptions);switch(u){case"http://www.w3.org/2001/XMLSchema#boolean":{switch(c.rawValue.toString()){case"18586133768512220936620570745912940619677854269274689475585506675881198879027":s[c.key]=!0;break;case"19014214495641488759237505126948346942972912379615652741039992445865937985820":s[c.key]=!1;break}break}case("http://www.w3.org/2001/XMLSchema#nonNegativeInteger","http://www.w3.org/2001/XMLSchema#nonPositiveInteger","http://www.w3.org/2001/XMLSchema#negativeInteger","http://www.w3.org/2001/XMLSchema#positiveInteger"):{s[c.key]=c.value.toString();break}case"http://www.w3.org/2001/XMLSchema#integer":{s[c.key]=Number(c.value);break}case"http://www.w3.org/2001/XMLSchema#string":{this.validateSourceValue(u,c.value,c.rawValue),s[c.key]=c.rawValue;break}case"http://www.w3.org/2001/XMLSchema#dateTime":{let d=BigInt(c.rawValue),h=ns(Number(d)).toISOString();this.validateSourceValue(u,c.value,h),s[c.key]=h;break}case"http://www.w3.org/2001/XMLSchema#double":{let d=Number(c.rawValue);this.validateSourceValue(u,c.value,d),s[c.key]=d;break}default:throw new Error(`Unsupported data type ${u}`)}}s.type=r;let a=e.getId(),l=Ie.parseFromId(a);return s.id=l.string(),s}async existenceProof(e){let[t,r]=await this._contract.getClaimProofWithStateInfo(e.hIndex());if(!t.existence)throw new Error("Claim does not exist");let i=me.fromBigInt(r.state),o=me.fromBigInt(r.claimsRoot),s=me.fromBigInt(r.revocationsRoot),a=me.fromBigInt(r.rootsRoot),l=new yt({siblings:t.siblings.map(c=>me.fromBigInt(c)),existence:t.existence,nodeAux:t.auxExistence?{key:me.fromBigInt(t.auxIndex),value:me.fromBigInt(t.auxValue)}:void 0});return new ha({issuerData:{id:this._issuerDid,state:{value:i,claimsTreeRoot:o,revocationTreeRoot:s,rootOfRoots:a}},mtp:l,coreClaim:e})}async validateSourceValue(e,t,r){if(await yc.hashValue(e,r)!==t)throw new Error(`Invalid source value for ${e} type`)}convertDisplayMethod(e){if(!(!e.id||!e._type))switch(e._type){case"Iden3BasicDisplayMethodV1":return{id:e.id,type:"Iden3BasicDisplayMethodV1"};default:throw new Error(`Unsupported display method type ${e._type}`)}}};var aP=class{_ethConnectionConfig;_onchainIssuerOptions;constructor(e,t){this._ethConnectionConfig=e,this._onchainIssuerOptions=t}async getCredential(e,t,r){let{contract:i,connection:o}=this.getContractConnection(e),s=await i.getCredentialAdapterVersion();switch(s){case"0.0.1":{let a=new wb(o,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});await a.isInterfaceSupported();let{credentialData:l,coreClaimBigInts:c,credentialSubjectFields:u}=await a.getCredential(Ie.idFromDID(t),r);return await a.convertOnChainInfoToW3CCredential(l,c,u)}default:throw new Error(`Unsupported adapter version ${s}`)}}async getUserCredentialIds(e,t){let{contract:r,connection:i}=this.getContractConnection(e),o=await r.getCredentialAdapterVersion();switch(o){case"0.0.1":{let s=new wb(i,e,{merklizationOptions:this._onchainIssuerOptions?.merklizationOptions});return await s.isInterfaceSupported(),await s.getUserCredentialsIds(Ie.idFromDID(t))}default:throw new Error(`Unsupported adapter version ${o}`)}}getContractConnection(e){let t=Ie.idFromDID(e),r=Xm(e),i=nn.getAddress(nn.hexlify(Je.ethAddressFromId(t))),o=this._ethConnectionConfig.find(a=>a.chainId===r);if(!o)throw new Error(`No connection found for chain ID ${r}`);if(!o.url)throw new Error(`No URL found for chain ID ${r}`);return{contract:new $t(i,oP,new nn.JsonRpcProvider(o.url)),connection:o}}};var cP=class{constructor(e){this.resolverUrl=e}async getLatestStateById(e){return this.getStateInfo(e)}async getStateInfoByIdAndState(e,t){return this.getStateInfo(e,t)}async getGISTProof(e){let{didDocument:t}=await Kf(Ie.parseFromId(Je.fromBigInt(e)),this.resolverUrl),{global:r}=this.getIden3StateInfo2023(t);if(!r)throw new Error("GIST root not found");let{proof:i}=r;if(!i)throw new Error("GIST proof not found");return{root:r.root,existence:i.existence,siblings:i.siblings?.map(o=>BigInt(o)),index:BigInt(0),value:BigInt(0),auxExistence:!!i.node_aux,auxIndex:i.node_aux?BigInt(i.node_aux.key):BigInt(0),auxValue:i.node_aux?BigInt(i.node_aux.value):BigInt(0)}}async getGISTRootInfo(e,t){let{didDocument:r}=await Kf(Ie.parseFromId(Je.fromBigInt(t)),this.resolverUrl,{gist:me.fromBigInt(e)}),{global:i}=this.getIden3StateInfo2023(r);if(!i)throw new Error("GIST root not found");return i}getRpcProvider(){return new Tt}publishState(){throw new Error("publishState method not implemented.")}publishStateGeneric(){throw new Error("publishStateGeneric method not implemented.")}async getStateInfo(e,t){let r=t?{state:me.fromBigInt(t)}:void 0,{didDocument:i}=await Kf(Ie.parseFromId(Je.fromBigInt(e)),this.resolverUrl,r),{info:o}=this.getIden3StateInfo2023(i);return{...o}}getIden3StateInfo2023(e){let t=e.verificationMethod?.find(r=>r.type==="Iden3StateInfo2023");if(!t)throw new Error("Iden3StateInfo2023 verification method not found");return t}};var KY=[{inputs:[],name:"ECDSAInvalidSignature",type:"error"},{inputs:[{internalType:"uint256",name:"length",type:"uint256"}],name:"ECDSAInvalidSignatureLength",type:"error"},{inputs:[{internalType:"bytes32",name:"s",type:"bytes32"}],name:"ECDSAInvalidSignatureS",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"allowance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientAllowance",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC20InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC20InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC20InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"}],name:"ERC20InvalidSpender",type:"error"},{inputs:[{internalType:"uint256",name:"deadline",type:"uint256"}],name:"ERC2612ExpiredSignature",type:"error"},{inputs:[{internalType:"address",name:"signer",type:"address"},{internalType:"address",name:"owner",type:"address"}],name:"ERC2612InvalidSigner",type:"error"},{inputs:[{internalType:"address",name:"account",type:"address"},{internalType:"uint256",name:"currentNonce",type:"uint256"}],name:"InvalidAccountNonce",type:"error"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[],name:"DOMAIN_SEPARATOR",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"}],name:"nonces",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"},{internalType:"uint256",name:"deadline",type:"uint256"},{internalType:"uint8",name:"v",type:"uint8"},{internalType:"bytes32",name:"r",type:"bytes32"},{internalType:"bytes32",name:"s",type:"bytes32"}],name:"permit",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];var JY=[{inputs:[{internalType:"uint256",name:"initialSupply",type:"uint256"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"allowance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientAllowance",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"},{internalType:"uint256",name:"balance",type:"uint256"},{internalType:"uint256",name:"needed",type:"uint256"}],name:"ERC20InsufficientBalance",type:"error"},{inputs:[{internalType:"address",name:"approver",type:"address"}],name:"ERC20InvalidApprover",type:"error"},{inputs:[{internalType:"address",name:"receiver",type:"address"}],name:"ERC20InvalidReceiver",type:"error"},{inputs:[{internalType:"address",name:"sender",type:"address"}],name:"ERC20InvalidSender",type:"error"},{inputs:[{internalType:"address",name:"spender",type:"address"}],name:"ERC20InvalidSpender",type:"error"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"owner",type:"address"},{indexed:!0,internalType:"address",name:"spender",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Approval",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"from",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"value",type:"uint256"}],name:"Transfer",type:"event"},{inputs:[{internalType:"address",name:"owner",type:"address"},{internalType:"address",name:"spender",type:"address"}],name:"allowance",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"spender",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"approve",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"account",type:"address"}],name:"balanceOf",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"name",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"symbol",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"totalSupply",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transfer",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"from",type:"address"},{internalType:"address",name:"to",type:"address"},{internalType:"uint256",name:"value",type:"uint256"}],name:"transferFrom",outputs:[{internalType:"bool",name:"",type:"bool"}],stateMutability:"nonpayable",type:"function"}];async function xwe(n,e,t,r,i){let o=new $t(e,KY,n),s=await o.nonces(await n.getAddress()),a=await o.eip712Domain(),l={name:a[1],version:a[2],chainId:a[3],verifyingContract:e},c={Permit:[{name:"owner",type:"address"},{name:"spender",type:"address"},{name:"value",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"}]},u={owner:await n.getAddress(),spender:t,value:r,nonce:s,deadline:i};return n.signTypedData(l,c,u)}async function Awe(n,e){return new $t(n,JY,e).decimals()}var jY=(t=>(t.NotDefinedQueryKey="not defined query key",t.NotDefinedComparator="not defined comparator",t))(jY||{}),WY=(o=>(o[o.BigInt=0]="BigInt",o[o.Boolean=1]="Boolean",o[o.Double=2]="Double",o[o.DateTime=3]="DateTime",o[o.String=4]="String",o))(WY||{}),lP=[!0,1,"true"],uP=[!1,0,"false"],qY=(n,e)=>Array.isArray(n)&&Array.isArray(e)?n.length===e.length&&n.every((t,r)=>t===e[r]):!Array.isArray(n)&&Array.isArray(e)?e.includes(n):Array.isArray(n)&&!Array.isArray(e)?n.includes(e):(n=n,e=e,lP.includes(n)&&lP.includes(e)||uP.includes(n)&&uP.includes(e)?!0:n===e),QY=(n,e)=>XY(n,e,(r,i)=>{switch(_Y(r.toString())){case 0:case 1:return BigInt(r)>BigInt(i);case 3:return Date.parse(r.toString())>Date.parse(i.toString());case 2:case 4:default:return r>i}}),VY=(n,e)=>XY(n,e,(r,i)=>{switch(_Y(r.toString())){case 0:case 1:return BigInt(r)>=BigInt(i);case 3:return Date.parse(r.toString())>=Date.parse(i.toString());case 2:case 4:default:return r>=i}}),vwe=(n,e)=>!!(lP.includes(e)&&typeof n<"u"||uP.includes(e)&&(n===void 0||Array.isArray(n)&&!n.length)),YY=(n,e)=>Array.isArray(n)&&Array.isArray(e)?n.every(t=>e.includes(t)):!Array.isArray(n)&&Array.isArray(e)?e.includes(n):Array.isArray(n)&&!Array.isArray(e)?n.includes(e):!1,zY=(n,e)=>{if(!Array.isArray(e)||e.length!==2)throw new Error("$between/$nonbetween operator value should be 2 elements array");let[t,r]=e.map(BigInt),i=o=>o>=t&&o<=r;return Array.isArray(n)?n.map(BigInt).every(i):i(BigInt(n))},Dc={$noop:()=>!0,$sd:()=>!0,$exists:(n,e)=>vwe(n,e),$eq:(n,e)=>qY(n,e),$in:(n,e)=>YY(n,e),$nin:(n,e)=>!YY(n,e),$gt:(n,e)=>QY(n,e),$lt:(n,e)=>!VY(n,e),$ne:(n,e)=>!qY(n,e),$gte:(n,e)=>VY(n,e),$lte:(n,e)=>!QY(n,e),$between:(n,e)=>zY(n,e),$nonbetween:(n,e)=>!zY(n,e)},ZY=(n,e,t=null)=>{let r=e.split("."),i=n;for(let o of r){if(i==null)return t;i=i[o]}return i},Pa=class{constructor(e,t,r,i=!1){this.path=e;this.operatorFunc=t;this.value=r;this.isReverseParams=i}execute(e){if(!this.operatorFunc)throw new Error("not defined comparator");let t=ZY(e,this.path);return t==null&&this.operatorFunc!==Dc.$exists?!1:this.isReverseParams?this.operatorFunc(this.value,t):this.operatorFunc(t,this.value)}},dP=n=>Object.keys(n).reduce((e,t)=>{let r=n[t];switch(t){case"claimId":return e.concat(new Pa("id",Dc.$eq,r));case"allowedIssuers":return(r||["*"]).includes("*")?e:e.concat(new Pa("issuer",Dc.$in,r));case"type":return e.concat(new Pa("type",Dc.$in,r,!0));case"context":return e.concat(new Pa("@context",Dc.$in,r,!0));case"credentialSubjectId":return e.concat(new Pa("credentialSubject.id",Dc.$eq,r));case"schema":return e.concat(new Pa("credentialSchema.id",Dc.$eq,r));case"credentialSubject":{let i=Object.keys(r).reduce((o,s)=>{let a=r[s];if(typeof a=="object"&&Object.keys(a).length===0)return o.concat([new Pa(`credentialSubject.${s}`,Dc.$noop,null)]);let l=Object.keys(a).map(c=>{let u=a[c],d=`credentialSubject.${s}`;return new Pa(d,Dc[c],u)});return o.concat(l)},[]);return e.concat(i)}case"proofType":case"groupId":case"skipClaimRevocationCheck":return e;default:throw new Error(`${t} : not defined query key`)}},[]),XY=(n,e,t)=>Array.isArray(n)&&Array.isArray(e)?n.every((r,i)=>t(r,e[i])):!Array.isArray(n)&&Array.isArray(e)?e.every(r=>t(n,r)):Array.isArray(n)&&!Array.isArray(e)?n.every(r=>t(r,e)):t(n,e),Cwe=/^[+-]?\d+$/,Swe=/^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$/,Dwe=/^([0-9]+)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[Tt]([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(\.[0-9]+)?(([Zz])|([\+|\-]([01][0-9]|2[0-3]):[0-5][0-9]))$/,Lwe=/^(true)|(false)$/,Bwe=/^\d{4}-\d{2}-\d{2}$/,_Y=n=>Cwe.test(n)?0:Swe.test(n)?2:Dwe.test(n)||Bwe.test(n)?3:Lwe.test(n)?1:4;var fP=class{constructor(e){this._localStorageKey=e;localStorage.getItem(this._localStorageKey)||localStorage.setItem(e,JSON.stringify([]))}async save(e,t,r="id"){if(localStorage){let i=localStorage.getItem(this._localStorageKey),o=[];i&&(o=JSON.parse(i));let s=o.findIndex(a=>a[r]===e);s===-1?o.push(t):o[s]=t,localStorage.setItem(this._localStorageKey,JSON.stringify(o))}}async get(e,t="id"){let r=localStorage.getItem(this._localStorageKey),i=[];return r&&(i=JSON.parse(r)),i.find(o=>o[t]===e)}async load(){let e=localStorage.getItem(this._localStorageKey);return e&&JSON.parse(e)}async delete(e,t="id"){let r=localStorage.getItem(this._localStorageKey),i=[];r&&(i=JSON.parse(r));let o=i.filter(s=>s[t]!==e);if(i.length===o.length)throw new Error(`item not found to delete: ${e}`);localStorage.setItem(this._localStorageKey,JSON.stringify(o))}};var hP=class n{constructor(e){this._mtDepth=e}static storageKeyMeta="merkle-tree-meta";async createIdentityMerkleTrees(e){e||(e=`${Et()}`);let t=localStorage.getItem(n.storageKeyMeta);if(t){let i=JSON.parse(t);if(i.find(l=>l.treeId===`${e}+${l.type}`))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let s=i.filter(l=>l.identifier===e);if(s.length>0)return s;let a=U2(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify([...i,...a])),[...i,...a]}let r=U2(e);return localStorage.setItem(n.storageKeyMeta,JSON.stringify(r)),r}async getIdentityMerkleTreesInfo(e){let t=localStorage.getItem(n.storageKeyMeta);if(t)return JSON.parse(t).filter(i=>i.identifier===e);throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=this.getMeta(e,t);return new os(new ig(Ua(r.treeId)),!0,this._mtDepth)}getMeta(e,t){let r=localStorage.getItem(n.storageKeyMeta),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let s=JSON.parse(r).filter(a=>a.identifier===e&&a.type===t)[0];if(!s)throw i;return s}async addToMerkleTree(e,t,r,i){let o=this.getMeta(e,t);await new os(new ig(Ua(o.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=localStorage.getItem(n.storageKeyMeta);if(!r)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=JSON.parse(r),o=i.filter(a=>a.identifier===e).map(a=>({...a,identifier:t}));if(o.length===0)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=[...i.filter(a=>a.identifier!==e),...o];localStorage.setItem(n.storageKeyMeta,JSON.stringify(s))}};var pP=class{constructor(e){this._storageKey=e;this._store=gu(`${e}-db`,e)}_store;async save(e,t,r="id"){return yu(e,t,this._store)}async get(e,t="id"){return Ga(e,this._store)}async load(){return m5(this._store)}async delete(e,t="id"){return Jb(e,this._store)}};var mP=class n{constructor(e){this._mtDepth=e;this._merkleTreeMetaStore=gu(`${n.storageKeyMeta}-db`,n.storageKeyMeta),this._bindingStore=gu(`${n.storageBindingKeyMeta}-db`,n.storageBindingKeyMeta)}static storageKeyMeta="merkle-tree-meta";static storageBindingKeyMeta="binding-did";_merkleTreeMetaStore;_bindingStore;async createIdentityMerkleTrees(e){if(e||(e=`${Et()}`),await Ga(e,this._bindingStore))throw new Error(`Present merkle tree meta information in the store for current identifier ${e}`);let r=U2(e);return await yu(e,r,this._merkleTreeMetaStore),r}async getIdentityMerkleTreesInfo(e){let t=await Ga(e,this._merkleTreeMetaStore);if(t)return t;throw new Error(`Merkle tree meta not found for identifier ${e}`)}async getMerkleTreeByIdentifierAndType(e,t){let r=await Ga(e,this._merkleTreeMetaStore),i=new Error(`Merkle tree not found for identifier ${e} and type ${t}`);if(!r)throw i;let o=r.find(s=>s.identifier===e&&s.type===t);if(!o)throw i;return new os(new og(Ua(o.treeId)),!0,this._mtDepth)}async addToMerkleTree(e,t,r,i){let o=await Ga(e,this._merkleTreeMetaStore);if(!o)throw new Error(`Merkle tree meta not found for identifier ${e}`);let s=o.find(l=>l.identifier===e&&l.type===t);if(!s)throw new Error(`Merkle tree not found for identifier ${e} and type ${t}`);await new os(new og(Ua(s.treeId)),!0,this._mtDepth).add(r,i)}async bindMerkleTreeToNewIdentifier(e,t){let r=await Ga(e,this._merkleTreeMetaStore);if(!r||!r?.length)throw new Error(`Merkle tree meta not found for identifier ${e}`);let i=r.map(o=>({...o,identifier:t}));await Jb(e,this._merkleTreeMetaStore),await yu(t,i,this._merkleTreeMetaStore),await yu(e,t,this._bindingStore)}};var gP=class{constructor(e){this._dataSource=e}static storageKey="circuits";async loadCircuitData(e){let t=await this._dataSource.get(e.toString(),"circuitId");if(!t)throw new Error(`item not found: ${e}`);return t}async saveCircuitData(e,t){await this._dataSource.save(e.toString(),t,"circuitId")}};var yP=class{constructor(e){this._dataSource=e}static storageKey="credentials";async listCredentials(){return(await this._dataSource.load()).filter(t=>t!==void 0).map(t=>t&&fr.fromJSON(t))}async saveCredential(e){return this._dataSource.save(e.id,e.toJSON())}async saveAllCredentials(e){for(let t of e)await this.saveCredential(t)}async removeCredential(e){return this._dataSource.delete(e)}async findCredentialById(e){let t=await this._dataSource.get(e);return t&&fr.fromJSON(t)}async findCredentialsByQuery(e){let t=dP(e);return(await this._dataSource.load()).filter(o=>t.every(s=>s.execute(o))).filter(o=>o!==void 0).map(o=>fr.fromJSON(o))}};var wP=class{constructor(e,t){this._identityDataSource=e;this._profileDataSource=t}static identitiesStorageKey="identities";static profilesStorageKey="profiles";async saveProfile(e){let r=(await this._profileDataSource.load()).filter(o=>o.genesisIdentifier===e.genesisIdentifier),i=r.length?[...r,e]:[e];for(let o=0;o<i.length;o++){let s=i[o];await this._profileDataSource.save(s.id,s)}}async getProfileByVerifier(e){return this._profileDataSource.get(e,"verifier")}async getProfilesByVerifier(e,t){return(await this._profileDataSource.load()).filter(r=>r.verifier===e&&(!t||t.every(i=>r.tags?.includes(i))))}async getProfileById(e){return this._profileDataSource.get(e)}async getProfilesByGenesisIdentifier(e){return(await this._profileDataSource.load()).filter(t=>t.genesisIdentifier===e)}async getAllIdentities(){return this._identityDataSource.load()}async saveIdentity(e){return this._identityDataSource.save(e.did,e,"did")}async getIdentity(e){return this._identityDataSource.get(e,"did")}};var bP=class{constructor(e){this.opts=e;this._verificationKeyPath=this.opts.verificationFileName??this._verificationKeyPath,this._provingKeyPath=this.opts.provingFileName??this._provingKeyPath,this._wasmFilePath=this.opts.wasmFileName??this._wasmFilePath}_verificationKeyPath="verification_key.json";_provingKeyPath="circuit_final.zkey";_wasmFilePath="circuit.wasm";_fs=null;_browserNotSupportedError=new Error("File system operations are not supported in browser environment");async getFs(){return this._fs?this._fs:(this._fs={existsSync:()=>{throw this._browserNotSupportedError},readFileSync:()=>{throw this._browserNotSupportedError},writeFileSync:()=>{throw this._browserNotSupportedError},mkdirSync:()=>{throw this._browserNotSupportedError}},this._fs)}async loadCircuitData(e){let t=await this.loadCircuitFile(e,this._verificationKeyPath),r=await this.loadCircuitFile(e,this._provingKeyPath),i=await this.loadCircuitFile(e,this._wasmFilePath);return{circuitId:e,wasm:i,provingKey:r,verificationKey:t}}async loadCircuitFile(e,t){let r=`${this.opts.dirname}/${e}/${t}`,i=await this.getFs();if(i.existsSync(r)){let o=i.readFileSync(r);return new Uint8Array(o)}return null}async writeCircuitFile(e,t,r,i){let o=`${this.opts.dirname}/${e}`,s=`${o}/${t}`,a=await this.getFs();a.mkdirSync(o,{recursive:!0}),a.writeFileSync(s,r,i)}async saveCircuitData(e,t){t.verificationKey&&await this.writeCircuitFile(e,this._verificationKeyPath,t.verificationKey,"utf-8"),t.provingKey&&await this.writeCircuitFile(e,this._provingKeyPath,t.provingKey),t.wasm&&await this.writeCircuitFile(e,this._wasmFilePath,t.wasm)}};var Lc=n=>{if(!n){let e=an.hash(new Array(3).fill(0n));return{proof:new yt,treeState:{state:me.fromBigInt(e),claimsRoot:Le,revocationRoot:Le,rootOfRoots:Le}}}return{proof:n.mtp,treeState:Z6(n.issuer.state,n.issuer.claimsTreeRoot,n.issuer.revocationTreeRoot,n.issuer.rootOfRoots)}},lp=n=>{let e=!1,t;n.existence?e=!0:n.auxExistence&&(t={key:me.fromBigInt(n.auxIndex),value:me.fromBigInt(n.auxValue)});let r=n.siblings.map(s=>me.fromBigInt(s)),i=new yt({siblings:r,nodeAux:t,existence:e});return{root:me.fromBigInt(n.root),proof:i}},_A=n=>{if(!n)return[{operator:Jt.$noop,fieldName:""}];let e=[],t=Object.entries(n);if(!t.length)throw new Error("query must have at least 1 predicate");for(let[r,i]of t){let o=Object.entries(i);if(o.length===0){e.push({operator:Jt.$sd,fieldName:r});continue}for(let[a,l]of o){if(!Jt[a])throw new Error("operator is not supported by lib");let c=Jt[a];e.push({operator:c,fieldName:r,operatorValue:l})}}return e},$A=async(n,e,t,r)=>{let i={...n,slotIndex:0,merklizedSchema:!1,datatype:"",claimPathKey:BigInt(0),values:[],path:new rr};if(!n.fieldName&&n.operator!==0)throw new Error("query must have a field name if operator is not $noop");if(n.fieldName&&(i.datatype=await rr.newTypeFromContext(e,`${t}.${n.fieldName}`,r)),await Nw(JSON.parse(e),r,t)||(i.merklizedSchema=!0),!i.merklizedSchema)i.slotIndex=await Gw(n.fieldName,t,Me.encode(e));else try{let s=await fD(e,t,n.fieldName,r);i.claimPathKey=await s.mtEntry(),i.path=s}catch(s){throw new Error(`field does not exist in the schema ${s.message}`)}if(n.operatorValue!==void 0){if(!_6(i.datatype,n.operator))throw new Error(`operator ${n.operator} is not supported for datatype ${i.datatype}`);if((n.operator===0||n.operator===16)&&n.operatorValue)throw new Error(`operator value should be undefined for ${n.operator} operator`);let s;switch(n.operator){case 0:case 16:s=[];break;case 11:s=Twe(n.operatorValue);break;default:s=await e3(n.operatorValue,i.datatype)}i.values=s}return i},bb=async(n,e,t,r)=>{let i=_A(t);return Promise.all(i.map(o=>$A(o,e,n,r)))},e3=async(n,e)=>{let t=[];if(Array.isArray(n))for(let r=0;r<n.length;r++)t[r]=await yc.hashValue(e,n[r]);else t[0]=await yc.hashValue(e,n);return t},Twe=n=>{if(typeof n=="boolean")return[BigInt(n)];throw new Error("exists operator value must be true or false")};async function xP(n,e){e=e||{};let t;try{t=await WebAssembly.compile(n)}catch(u){throw new Error(u)}let r="",i="",o=await WebAssembly.instantiate(t,{runtime:{exceptionHandler:function(u){let d;throw u==1?d=`Signal not found.
414
414
  `:u==2?d=`Too many signals set.
415
415
  `:u==3?d=`Signal already set.
416
416
  `:u==4?d=`Assert Failed.