@did-btcr2/method 0.51.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.mjs CHANGED
@@ -1,6 +1,6 @@
1
- var rI=Object.create;var ey=Object.defineProperty;var nI=Object.getOwnPropertyDescriptor;var iI=Object.getOwnPropertyNames;var oI=Object.getPrototypeOf,sI=Object.prototype.hasOwnProperty;var cI=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Sf=(t,e)=>{for(var r in e)ey(t,r,{get:e[r],enumerable:!0})},aI=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of iI(e))!sI.call(t,i)&&i!==r&&ey(t,i,{get:()=>e[i],enumerable:!(n=nI(e,i))||n.enumerable});return t};var Pn=(t,e,r)=>(r=t!=null?rI(oI(t)):{},aI(e||!t||!t.__esModule?ey(r,"default",{value:t,enumerable:!0}):r,t));var nx=oe(Af=>{"use strict";l();Af.byteLength=dI;Af.toByteArray=lI;Af.fromByteArray=yI;var Mn=[],Wr=[],uI=typeof Uint8Array<"u"?Uint8Array:Array,ty="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(hs=0,tx=ty.length;hs<tx;++hs)Mn[hs]=ty[hs],Wr[ty.charCodeAt(hs)]=hs;var hs,tx;Wr[45]=62;Wr[95]=63;function rx(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function dI(t){var e=rx(t),r=e[0],n=e[1];return(r+n)*3/4-n}function fI(t,e,r){return(e+r)*3/4-r}function lI(t){var e,r=rx(t),n=r[0],i=r[1],o=new uI(fI(t,n,i)),s=0,c=i>0?n-4:n,a;for(a=0;a<c;a+=4)e=Wr[t.charCodeAt(a)]<<18|Wr[t.charCodeAt(a+1)]<<12|Wr[t.charCodeAt(a+2)]<<6|Wr[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Wr[t.charCodeAt(a)]<<2|Wr[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=Wr[t.charCodeAt(a)]<<10|Wr[t.charCodeAt(a+1)]<<4|Wr[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function hI(t){return Mn[t>>18&63]+Mn[t>>12&63]+Mn[t>>6&63]+Mn[t&63]}function pI(t,e,r){for(var n,i=[],o=e;o<r;o+=3)n=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),i.push(hI(n));return i.join("")}function yI(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(pI(t,s,s+o>c?c:s+o));return n===1?(e=t[r-1],i.push(Mn[e>>2]+Mn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Mn[e>>10]+Mn[e>>4&63]+Mn[e<<2&63]+"=")),i.join("")}});var ix=oe(ry=>{l();ry.read=function(t,e,r,n,i){var o,s,c=i*8-n-1,a=(1<<c)-1,u=a>>1,d=-7,f=r?i-1:0,h=r?-1:1,p=t[e+f];for(f+=h,o=p&(1<<-d)-1,p>>=-d,d+=c;d>0;o=o*256+t[e+f],f+=h,d-=8);for(s=o&(1<<-d)-1,o>>=-d,d+=n;d>0;s=s*256+t[e+f],f+=h,d-=8);if(o===0)o=1-u;else{if(o===a)return s?NaN:(p?-1:1)*(1/0);s=s+Math.pow(2,n),o=o-u}return(p?-1:1)*s*Math.pow(2,o-n)};ry.write=function(t,e,r,n,i,o){var s,c,a,u=o*8-i-1,d=(1<<u)-1,f=d>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,g=n?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(c=isNaN(e)?1:0,s=d):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),s+f>=1?e+=h/a:e+=h*Math.pow(2,1-f),e*a>=2&&(s++,a/=2),s+f>=d?(c=0,s=d):s+f>=1?(c=(e*a-1)*Math.pow(2,i),s=s+f):(c=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=c&255,p+=g,c/=256,i-=8);for(s=s<<i|c,u+=i;u>0;t[r+p]=s&255,p+=g,s/=256,u-=8);t[r+p-g]|=y*128}});var Sr=oe(Ic=>{"use strict";l();var ny=nx(),Bc=ix(),ox=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Ic.Buffer=F;Ic.SlowBuffer=EI;Ic.INSPECT_MAX_BYTES=50;var Tf=2147483647;Ic.kMaxLength=Tf;F.TYPED_ARRAY_SUPPORT=gI();!F.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function gI(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(F.prototype,"parent",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.buffer}});Object.defineProperty(F.prototype,"offset",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.byteOffset}});function wi(t){if(t>Tf)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,F.prototype),e}function F(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return cy(t)}return ax(t,e,r)}F.poolSize=8192;function ax(t,e,r){if(typeof t=="string")return wI(t,e);if(ArrayBuffer.isView(t))return bI(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Kn(t,ArrayBuffer)||t&&Kn(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Kn(t,SharedArrayBuffer)||t&&Kn(t.buffer,SharedArrayBuffer)))return oy(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return F.from(n,e,r);var i=xI(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return F.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}F.from=function(t,e,r){return ax(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function ux(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function mI(t,e,r){return ux(t),t<=0?wi(t):e!==void 0?typeof r=="string"?wi(t).fill(e,r):wi(t).fill(e):wi(t)}F.alloc=function(t,e,r){return mI(t,e,r)};function cy(t){return ux(t),wi(t<0?0:ay(t)|0)}F.allocUnsafe=function(t){return cy(t)};F.allocUnsafeSlow=function(t){return cy(t)};function wI(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=dx(t,e)|0,n=wi(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function iy(t){for(var e=t.length<0?0:ay(t.length)|0,r=wi(e),n=0;n<e;n+=1)r[n]=t[n]&255;return r}function bI(t){if(Kn(t,Uint8Array)){var e=new Uint8Array(t);return oy(e.buffer,e.byteOffset,e.byteLength)}return iy(t)}function oy(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');var n;return e===void 0&&r===void 0?n=new Uint8Array(t):r===void 0?n=new Uint8Array(t,e):n=new Uint8Array(t,e,r),Object.setPrototypeOf(n,F.prototype),n}function xI(t){if(F.isBuffer(t)){var e=ay(t.length)|0,r=wi(e);return r.length===0||t.copy(r,0,0,e),r}if(t.length!==void 0)return typeof t.length!="number"||uy(t.length)?wi(0):iy(t);if(t.type==="Buffer"&&Array.isArray(t.data))return iy(t.data)}function ay(t){if(t>=Tf)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Tf.toString(16)+" bytes");return t|0}function EI(t){return+t!=t&&(t=0),F.alloc(+t)}F.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==F.prototype};F.compare=function(e,r){if(Kn(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),Kn(r,Uint8Array)&&(r=F.from(r,r.offset,r.byteLength)),!F.isBuffer(e)||!F.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,o=0,s=Math.min(n,i);o<s;++o)if(e[o]!==r[o]){n=e[o],i=r[o];break}return n<i?-1:i<n?1:0};F.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};F.concat=function(e,r){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return F.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;var i=F.allocUnsafe(r),o=0;for(n=0;n<e.length;++n){var s=e[n];if(Kn(s,Uint8Array))o+s.length>i.length?F.from(s).copy(i,o):Uint8Array.prototype.set.call(i,s,o);else if(F.isBuffer(s))s.copy(i,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return i};function dx(t,e){if(F.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Kn(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return sy(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return gx(t).length;default:if(i)return n?-1:sy(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=dx;function vI(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return DI(this,e,r);case"utf8":case"utf-8":return lx(this,e,r);case"ascii":return UI(this,e,r);case"latin1":case"binary":return OI(this,e,r);case"base64":return II(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return kI(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function ps(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}F.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<e;r+=2)ps(this,r,r+1);return this};F.prototype.swap32=function(){var e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<e;r+=4)ps(this,r,r+3),ps(this,r+1,r+2);return this};F.prototype.swap64=function(){var e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<e;r+=8)ps(this,r,r+7),ps(this,r+1,r+6),ps(this,r+2,r+5),ps(this,r+3,r+4);return this};F.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?lx(this,0,e):vI.apply(this,arguments)};F.prototype.toLocaleString=F.prototype.toString;F.prototype.equals=function(e){if(!F.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:F.compare(this,e)===0};F.prototype.inspect=function(){var e="",r=Ic.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};ox&&(F.prototype[ox]=F.prototype.inspect);F.prototype.compare=function(e,r,n,i,o){if(Kn(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),!F.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),o===void 0&&(o=this.length),r<0||n>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&r>=n)return 0;if(i>=o)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,o>>>=0,this===e)return 0;for(var s=o-i,c=n-r,a=Math.min(s,c),u=this.slice(i,o),d=e.slice(r,n),f=0;f<a;++f)if(u[f]!==d[f]){s=u[f],c=d[f];break}return s<c?-1:c<s?1:0};function fx(t,e,r,n,i){if(t.length===0)return-1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,uy(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=F.from(e,n)),F.isBuffer(e))return e.length===0?-1:sx(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):sx(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function sx(t,e,r,n,i){var o=1,s=t.length,c=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;o=2,s/=2,c/=2,r/=2}function a(p,g){return o===1?p[g]:p.readUInt16BE(g*o)}var u;if(i){var d=-1;for(u=r;u<s;u++)if(a(t,u)===a(e,d===-1?0:u-d)){if(d===-1&&(d=u),u-d+1===c)return d*o}else d!==-1&&(u-=u-d),d=-1}else for(r+c>s&&(r=s-c),u=r;u>=0;u--){for(var f=!0,h=0;h<c;h++)if(a(t,u+h)!==a(e,h)){f=!1;break}if(f)return u}return-1}F.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};F.prototype.indexOf=function(e,r,n){return fx(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return fx(this,e,r,n,!1)};function SI(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var o=e.length;n>o/2&&(n=o/2);for(var s=0;s<n;++s){var c=parseInt(e.substr(s*2,2),16);if(uy(c))return s;t[r+s]=c}return s}function AI(t,e,r,n){return _f(sy(e,t.length-r),t,r,n)}function TI(t,e,r,n){return _f(LI(e),t,r,n)}function _I(t,e,r,n){return _f(gx(e),t,r,n)}function BI(t,e,r,n){return _f(PI(e,t.length-r),t,r,n)}F.prototype.write=function(e,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var o=this.length-r;if((n===void 0||n>o)&&(n=o),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var s=!1;;)switch(i){case"hex":return SI(this,e,r,n);case"utf8":case"utf-8":return AI(this,e,r,n);case"ascii":case"latin1":case"binary":return TI(this,e,r,n);case"base64":return _I(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return BI(this,e,r,n);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}};F.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function II(t,e,r){return e===0&&r===t.length?ny.fromByteArray(t):ny.fromByteArray(t.slice(e,r))}function lx(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var o=t[i],s=null,c=o>239?4:o>223?3:o>191?2:1;if(i+c<=r){var a,u,d,f;switch(c){case 1:o<128&&(s=o);break;case 2:a=t[i+1],(a&192)===128&&(f=(o&31)<<6|a&63,f>127&&(s=f));break;case 3:a=t[i+1],u=t[i+2],(a&192)===128&&(u&192)===128&&(f=(o&15)<<12|(a&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:a=t[i+1],u=t[i+2],d=t[i+3],(a&192)===128&&(u&192)===128&&(d&192)===128&&(f=(o&15)<<18|(a&63)<<12|(u&63)<<6|d&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,c=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),i+=c}return RI(n)}var cx=4096;function RI(t){var e=t.length;if(e<=cx)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=cx));return r}function UI(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]&127);return n}function OI(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function DI(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",o=e;o<r;++o)i+=MI[t[o]];return i}function kI(t,e,r){for(var n=t.slice(e,r),i="",o=0;o<n.length-1;o+=2)i+=String.fromCharCode(n[o]+n[o+1]*256);return i}F.prototype.slice=function(e,r){var n=this.length;e=~~e,r=r===void 0?n:~~r,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<e&&(r=e);var i=this.subarray(e,r);return Object.setPrototypeOf(i,F.prototype),i};function Rt(t,e,r){if(t%1!==0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}F.prototype.readUintLE=F.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Rt(e,r,this.length);for(var i=this[e],o=1,s=0;++s<r&&(o*=256);)i+=this[e+s]*o;return i};F.prototype.readUintBE=F.prototype.readUIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Rt(e,r,this.length);for(var i=this[e+--r],o=1;r>0&&(o*=256);)i+=this[e+--r]*o;return i};F.prototype.readUint8=F.prototype.readUInt8=function(e,r){return e=e>>>0,r||Rt(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Rt(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Rt(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};F.prototype.readUint32BE=F.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};F.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Rt(e,r,this.length);for(var i=this[e],o=1,s=0;++s<r&&(o*=256);)i+=this[e+s]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*r)),i};F.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Rt(e,r,this.length);for(var i=r,o=1,s=this[e+--i];i>0&&(o*=256);)s+=this[e+--i]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*r)),s};F.prototype.readInt8=function(e,r){return e=e>>>0,r||Rt(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Rt(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};F.prototype.readInt16BE=function(e,r){e=e>>>0,r||Rt(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};F.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};F.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};F.prototype.readFloatLE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),Bc.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),Bc.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Rt(e,8,this.length),Bc.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Rt(e,8,this.length),Bc.read(this,e,!1,52,8)};function ur(t,e,r,n,i,o){if(!F.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<o)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}F.prototype.writeUintLE=F.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var o=Math.pow(2,8*n)-1;ur(this,e,r,n,o,0)}var s=1,c=0;for(this[r]=e&255;++c<n&&(s*=256);)this[r+c]=e/s&255;return r+n};F.prototype.writeUintBE=F.prototype.writeUIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var o=Math.pow(2,8*n)-1;ur(this,e,r,n,o,0)}var s=n-1,c=1;for(this[r+s]=e&255;--s>=0&&(c*=256);)this[r+s]=e/c&255;return r+n};F.prototype.writeUint8=F.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,1,255,0),this[r]=e&255,r+1};F.prototype.writeUint16LE=F.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeUint16BE=F.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeUint32LE=F.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};F.prototype.writeUint32BE=F.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};F.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var o=Math.pow(2,8*n-1);ur(this,e,r,n,o-1,-o)}var s=0,c=1,a=0;for(this[r]=e&255;++s<n&&(c*=256);)e<0&&a===0&&this[r+s-1]!==0&&(a=1),this[r+s]=(e/c>>0)-a&255;return r+n};F.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var o=Math.pow(2,8*n-1);ur(this,e,r,n,o-1,-o)}var s=n-1,c=1,a=0;for(this[r+s]=e&255;--s>=0&&(c*=256);)e<0&&a===0&&this[r+s+1]!==0&&(a=1),this[r+s]=(e/c>>0)-a&255;return r+n};F.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};F.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};F.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function hx(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function px(t,e,r,n,i){return e=+e,r=r>>>0,i||hx(t,e,r,4,34028234663852886e22,-34028234663852886e22),Bc.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return px(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return px(this,e,r,!1,n)};function yx(t,e,r,n,i){return e=+e,r=r>>>0,i||hx(t,e,r,8,17976931348623157e292,-17976931348623157e292),Bc.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return yx(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return yx(this,e,r,!1,n)};F.prototype.copy=function(e,r,n,i){if(!F.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r<i-n&&(i=e.length-r+n);var o=i-n;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),r),o};F.prototype.fill=function(e,r,n,i){if(typeof e=="string"){if(typeof r=="string"?(i=r,r=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!F.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(e.length===1){var o=e.charCodeAt(0);(i==="utf8"&&o<128||i==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var s;if(typeof e=="number")for(s=r;s<n;++s)this[s]=e;else{var c=F.isBuffer(e)?e:F.from(e,i),a=c.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-r;++s)this[s+r]=c[s%a]}return this};var NI=/[^+/0-9A-Za-z-_]/g;function CI(t){if(t=t.split("=")[0],t=t.trim().replace(NI,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function sy(t,e){e=e||1/0;for(var r,n=t.length,i=null,o=[],s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return o}function LI(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function PI(t,e){for(var r,n,i,o=[],s=0;s<t.length&&!((e-=2)<0);++s)r=t.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}function gx(t){return ny.toByteArray(CI(t))}function _f(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Kn(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function uy(t){return t!==t}var MI=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var Ei=oe((PL,xx)=>{l();var at=xx.exports={},$n,Hn;function dy(){throw new Error("setTimeout has not been defined")}function fy(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?$n=setTimeout:$n=dy}catch{$n=dy}try{typeof clearTimeout=="function"?Hn=clearTimeout:Hn=fy}catch{Hn=fy}})();function mx(t){if($n===setTimeout)return setTimeout(t,0);if(($n===dy||!$n)&&setTimeout)return $n=setTimeout,setTimeout(t,0);try{return $n(t,0)}catch{try{return $n.call(null,t,0)}catch{return $n.call(this,t,0)}}}function KI(t){if(Hn===clearTimeout)return clearTimeout(t);if((Hn===fy||!Hn)&&clearTimeout)return Hn=clearTimeout,clearTimeout(t);try{return Hn(t)}catch{try{return Hn.call(null,t)}catch{return Hn.call(this,t)}}}var bi=[],Rc=!1,ys,Bf=-1;function $I(){!Rc||!ys||(Rc=!1,ys.length?bi=ys.concat(bi):Bf=-1,bi.length&&wx())}function wx(){if(!Rc){var t=mx($I);Rc=!0;for(var e=bi.length;e;){for(ys=bi,bi=[];++Bf<e;)ys&&ys[Bf].run();Bf=-1,e=bi.length}ys=null,Rc=!1,KI(t)}}at.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];bi.push(new bx(t,e)),bi.length===1&&!Rc&&mx(wx)};function bx(t,e){this.fun=t,this.array=e}bx.prototype.run=function(){this.fun.apply(null,this.array)};at.title="browser";at.browser=!0;at.env={};at.argv=[];at.version="";at.versions={};function xi(){}at.on=xi;at.addListener=xi;at.once=xi;at.off=xi;at.removeListener=xi;at.removeAllListeners=xi;at.emit=xi;at.prependListener=xi;at.prependOnceListener=xi;at.listeners=function(t){return[]};at.binding=function(t){throw new Error("process.binding is not supported")};at.cwd=function(){return"/"};at.chdir=function(t){throw new Error("process.chdir is not supported")};at.umask=function(){return 0}});var b,w,KL,l=cI(()=>{b=Pn(Sr()),w=Pn(Ei()),KL=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object)});var jv=oe((mH,Fv)=>{l();var XR=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Cl=()=>XR.now(),QR=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),H0=t=>t===1/0||QR(t),V0=class t{constructor({max:e=1/0,ttl:r,updateAgeOnGet:n=!1,checkAgeOnGet:i=!1,noUpdateTTL:o=!1,dispose:s,noDisposeOnSet:c=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,r!==void 0&&!H0(r))throw new TypeError("ttl must be positive integer or Infinity if set");if(!H0(e))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=r,this.max=e,this.updateAgeOnGet=!!n,this.checkAgeOnGet=!!i,this.noUpdateTTL=!!o,this.noDisposeOnSet=!!c,s!==void 0){if(typeof s!="function")throw new TypeError("dispose must be function if set");this.dispose=s}this.timer=void 0,this.timerExpiration=void 0}setTimer(e,r){if(this.timerExpiration<e)return;this.timer&&clearTimeout(this.timer);let n=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let i in this.expirations){this.setTimer(i,i-Cl());break}},r);n.unref&&n.unref(),this.timerExpiration=e,this.timer=n}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return w.default.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let e=this.dispose!==t.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[r,n]of e)this.dispose(n,r,"delete")}setTTL(e,r=this.ttl){let n=this.expirationMap.get(e);if(n!==void 0){let i=this.expirations[n];!i||i.length<=1?delete this.expirations[n]:this.expirations[n]=i.filter(o=>o!==e)}if(r!==1/0){let i=Math.floor(Cl()+r);this.expirationMap.set(e,i),this.expirations[i]||(this.expirations[i]=[],this.setTimer(i,r)),this.expirations[i].push(e)}else this.expirationMap.set(e,1/0)}set(e,r,{ttl:n=this.ttl,noUpdateTTL:i=this.noUpdateTTL,noDisposeOnSet:o=this.noDisposeOnSet}={}){if(!H0(n))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(e)){i||this.setTTL(e,n);let s=this.data.get(e);s!==r&&(this.data.set(e,r),o||this.dispose(s,e,"set"))}else this.setTTL(e,n),this.data.set(e,r);for(;this.size>this.max;)this.purgeToCapacity();return this}has(e){return this.data.has(e)}getRemainingTTL(e){let r=this.expirationMap.get(e);return r===1/0?r:r!==void 0?Math.max(0,Math.ceil(r-Cl())):0}get(e,{updateAgeOnGet:r=this.updateAgeOnGet,ttl:n=this.ttl,checkAgeOnGet:i=this.checkAgeOnGet}={}){let o=this.data.get(e);if(i&&this.getRemainingTTL(e)===0){this.delete(e);return}return r&&this.setTTL(e,n),o}dispose(e,r){}delete(e){let r=this.expirationMap.get(e);if(r!==void 0){let n=this.data.get(e);this.data.delete(e),this.expirationMap.delete(e);let i=this.expirations[r];return i&&(i.length<=1?delete this.expirations[r]:this.expirations[r]=i.filter(o=>o!==e)),this.dispose(n,e,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let e in this.expirations){let r=this.expirations[e];if(this.size-r.length>=this.max){delete this.expirations[e];let n=[];for(let i of r)n.push([i,this.data.get(i)]),this.data.delete(i),this.expirationMap.delete(i);for(let[i,o]of n)this.dispose(o,i,"evict")}else{let n=this.size-this.max,i=[];for(let o of r.splice(0,n))i.push([o,this.data.get(o)]),this.data.delete(o),this.expirationMap.delete(o);for(let[o,s]of i)this.dispose(s,o,"evict");return}}}get size(){return this.data.size}purgeStale(){let e=Math.ceil(Cl());for(let r in this.expirations){if(r==="Infinity"||r>e)return;let n=[...this.expirations[r]||[]],i=[];delete this.expirations[r];for(let o of n)i.push([o,this.data.get(o)]),this.data.delete(o),this.expirationMap.delete(o);for(let[o,s]of i)this.dispose(s,o,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let e in this.expirations)for(let r of this.expirations[e])yield[r,this.data.get(r)]}*keys(){for(let e in this.expirations)for(let r of this.expirations[e])yield r}*values(){for(let e in this.expirations)for(let r of this.expirations[e])yield this.data.get(r)}[Symbol.iterator](){return this.entries()}};Fv.exports=V0});var a1=oe(c1=>{"use strict";l();c1.supports=function(...e){let r=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(r,{snapshots:r.snapshots||!1,permanence:r.permanence||!1,seek:r.seek||!1,clear:r.clear||!1,getMany:r.getMany||!1,keyIterator:r.keyIterator||!1,valueIterator:r.valueIterator||!1,iteratorNextv:r.iteratorNextv||!1,iteratorAll:r.iteratorAll||!1,status:r.status||!1,createIfMissing:r.createIfMissing||!1,errorIfExists:r.errorIfExists||!1,deferredOpen:r.deferredOpen||!1,promises:r.promises||!1,streams:r.streams||!1,encodings:Object.assign({},r.encodings),events:Object.assign({},r.events),additionalMethods:Object.assign({},r.additionalMethods)})}});var En=oe((HV,u1)=>{"use strict";l();u1.exports=class extends Error{constructor(e,r){super(e||""),typeof r=="object"&&r!==null&&(r.code&&(this.code=String(r.code)),r.expected&&(this.expected=!0),r.transient&&(this.transient=!0),r.cause&&(this.cause=r.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}});var ng=oe((qV,d1)=>{"use strict";l();var rg=null;d1.exports=function(){return rg===null&&(rg={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),rg}});var sg=oe(f1=>{"use strict";l();var ig=En(),D6=new Set(["buffer","view","utf8"]),og=class{constructor(e){if(this.encode=e.encode||this.encode,this.decode=e.decode||this.decode,this.name=e.name||this.name,this.format=e.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!D6.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");e.createViewTranscoder&&(this.createViewTranscoder=e.createViewTranscoder),e.createBufferTranscoder&&(this.createBufferTranscoder=e.createBufferTranscoder),e.createUTF8Transcoder&&(this.createUTF8Transcoder=e.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new ig(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new ig(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new ig(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};f1.Encoding=og});var dg=oe(Pl=>{"use strict";l();var{Buffer:ag}=Sr()||{},{Encoding:ug}=sg(),k6=ng(),nd=class extends ug{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new id({encode:this.encode,decode:e=>this.decode(ag.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},id=class extends ug{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new nd({encode:e=>{let r=this.encode(e);return ag.from(r.buffer,r.byteOffset,r.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},cg=class extends ug{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new nd({encode:e=>ag.from(this.encode(e),"utf8"),decode:e=>this.decode(e.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:e,textDecoder:r}=k6();return new id({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(r.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};Pl.BufferFormat=nd;Pl.ViewFormat=id;Pl.UTF8Format=cg});var y1=oe(Ms=>{"use strict";l();var{Buffer:Yt}=Sr()||{Buffer:{isBuffer:()=>!1}},{textEncoder:h1,textDecoder:l1}=ng()(),{BufferFormat:od,ViewFormat:fg,UTF8Format:p1}=dg(),Ml=t=>t;Ms.utf8=new p1({encode:function(t){return Yt.isBuffer(t)?t.toString("utf8"):ArrayBuffer.isView(t)?l1.decode(t):String(t)},decode:Ml,name:"utf8",createViewTranscoder(){return new fg({encode:function(t){return ArrayBuffer.isView(t)?t:h1.encode(t)},decode:function(t){return l1.decode(t)},name:`${this.name}+view`})},createBufferTranscoder(){return new od({encode:function(t){return Yt.isBuffer(t)?t:ArrayBuffer.isView(t)?Yt.from(t.buffer,t.byteOffset,t.byteLength):Yt.from(String(t),"utf8")},decode:function(t){return t.toString("utf8")},name:`${this.name}+buffer`})}});Ms.json=new p1({encode:JSON.stringify,decode:JSON.parse,name:"json"});Ms.buffer=new od({encode:function(t){return Yt.isBuffer(t)?t:ArrayBuffer.isView(t)?Yt.from(t.buffer,t.byteOffset,t.byteLength):Yt.from(String(t),"utf8")},decode:Ml,name:"buffer",createViewTranscoder(){return new fg({encode:function(t){return ArrayBuffer.isView(t)?t:Yt.from(String(t),"utf8")},decode:function(t){return Yt.from(t.buffer,t.byteOffset,t.byteLength)},name:`${this.name}+view`})}});Ms.view=new fg({encode:function(t){return ArrayBuffer.isView(t)?t:h1.encode(t)},decode:Ml,name:"view",createBufferTranscoder(){return new od({encode:function(t){return Yt.isBuffer(t)?t:ArrayBuffer.isView(t)?Yt.from(t.buffer,t.byteOffset,t.byteLength):Yt.from(String(t),"utf8")},decode:Ml,name:`${this.name}+buffer`})}});Ms.hex=new od({encode:function(t){return Yt.isBuffer(t)?t:Yt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Ms.base64=new od({encode:function(t){return Yt.isBuffer(t)?t:Yt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var w1=oe(m1=>{"use strict";l();var g1=En(),$l=y1(),{Encoding:N6}=sg(),{BufferFormat:C6,ViewFormat:L6,UTF8Format:P6}=dg(),sd=Symbol("formats"),Kl=Symbol("encodings"),M6=new Set(["buffer","view","utf8"]),lg=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>M6.has(r)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[Kl]=new Map,this[sd]=new Set(e);for(let r in $l)try{this.encoding(r)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[Kl].values()))}encoding(e){let r=this[Kl].get(e);if(r===void 0){if(typeof e=="string"&&e!==""){if(r=V6[e],!r)throw new g1(`Encoding '${e}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof e!="object"||e===null)throw new TypeError("First argument 'encoding' must be a string or object");r=K6(e)}let{name:n,format:i}=r;if(!this[sd].has(i))if(this[sd].has("view"))r=r.createViewTranscoder();else if(this[sd].has("buffer"))r=r.createBufferTranscoder();else if(this[sd].has("utf8"))r=r.createUTF8Transcoder();else throw new g1(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,r.name,r.commonName])this[Kl].set(o,r)}return r}};m1.Transcoder=lg;function K6(t){if(t instanceof N6)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${q6++}`;switch($6(t)){case"view":return new L6({...t,name:r});case"utf8":return new P6({...t,name:r});case"buffer":return new C6({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function $6(t){return"format"in t&&t.format!==void 0?t.format:"buffer"in t&&typeof t.buffer=="boolean"?t.buffer?"buffer":"utf8":"code"in t&&Number.isInteger(t.code)?"view":"buffer"}var H6={binary:$l.buffer,"utf-8":$l.utf8},V6={...$l,...H6},q6=0});var aa=oe((QV,hg)=>{"use strict";l();var ca=typeof Reflect=="object"?Reflect:null,b1=ca&&typeof ca.apply=="function"?ca.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Hl;ca&&typeof ca.ownKeys=="function"?Hl=ca.ownKeys:Object.getOwnPropertySymbols?Hl=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Hl=function(e){return Object.getOwnPropertyNames(e)};function F6(t){console&&console.warn&&console.warn(t)}var E1=Number.isNaN||function(e){return e!==e};function Ce(){Ce.init.call(this)}hg.exports=Ce;hg.exports.once=z6;Ce.EventEmitter=Ce;Ce.prototype._events=void 0;Ce.prototype._eventsCount=0;Ce.prototype._maxListeners=void 0;var x1=10;function Vl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Ce,"defaultMaxListeners",{enumerable:!0,get:function(){return x1},set:function(t){if(typeof t!="number"||t<0||E1(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");x1=t}});Ce.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Ce.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||E1(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function v1(t){return t._maxListeners===void 0?Ce.defaultMaxListeners:t._maxListeners}Ce.prototype.getMaxListeners=function(){return v1(this)};Ce.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(r.length>0&&(s=r[0]),s instanceof Error)throw s;var c=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw c.context=s,c}var a=o[e];if(a===void 0)return!1;if(typeof a=="function")b1(a,this,r);else for(var u=a.length,d=B1(a,u),n=0;n<u;++n)b1(d[n],this,r);return!0};function S1(t,e,r,n){var i,o,s;if(Vl(r),o=t._events,o===void 0?(o=t._events=Object.create(null),t._eventsCount=0):(o.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),o=t._events),s=o[e]),s===void 0)s=o[e]=r,++t._eventsCount;else if(typeof s=="function"?s=o[e]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),i=v1(t),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=s.length,F6(c)}return t}Ce.prototype.addListener=function(e,r){return S1(this,e,r,!1)};Ce.prototype.on=Ce.prototype.addListener;Ce.prototype.prependListener=function(e,r){return S1(this,e,r,!0)};function j6(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function A1(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=j6.bind(n);return i.listener=r,n.wrapFn=i,i}Ce.prototype.once=function(e,r){return Vl(r),this.on(e,A1(this,e,r)),this};Ce.prototype.prependOnceListener=function(e,r){return Vl(r),this.prependListener(e,A1(this,e,r)),this};Ce.prototype.removeListener=function(e,r){var n,i,o,s,c;if(Vl(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===r||n[s].listener===r){c=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():W6(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||r)}return this};Ce.prototype.off=Ce.prototype.removeListener;Ce.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function T1(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?G6(i):B1(i,i.length)}Ce.prototype.listeners=function(e){return T1(this,e,!0)};Ce.prototype.rawListeners=function(e){return T1(this,e,!1)};Ce.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):_1.call(t,e)};Ce.prototype.listenerCount=_1;function _1(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ce.prototype.eventNames=function(){return this._eventsCount>0?Hl(this._events):[]};function B1(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function W6(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function G6(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function z6(t,e){return new Promise(function(r,n){function i(s){t.removeListener(e,o),n(s)}function o(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}I1(t,e,o,{once:!0}),e!=="error"&&Y6(t,i,{once:!0})})}function Y6(t,e,r){typeof t.on=="function"&&I1(t,"error",e,r)}function I1(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(o){n.once&&t.removeEventListener(e,i),r(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}});var U1=oe((tq,R1)=>{l();R1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var cd=oe(pg=>{"use strict";l();var O1=U1();pg.fromCallback=function(t,e){if(t===void 0){var r=new Promise(function(n,i){t=function(o,s){o?i(o):n(s)}});t[e!==void 0?e:"promise"]=r}else if(typeof t!="function")throw new TypeError("Callback must be a function");return t};pg.fromPromise=function(t,e){if(e===void 0)return t;t.then(function(r){O1(()=>e(null,r))}).catch(function(r){O1(()=>e(r))})}});var ql=oe(yg=>{"use strict";l();yg.getCallback=function(t,e){return typeof t=="function"?t:e};yg.getOptions=function(t,e){return typeof t=="object"&&t!==null?t:e!==void 0?e:{}}});var Po=oe(Gl=>{"use strict";l();var{fromCallback:gg}=cd(),Or=En(),{getOptions:mg,getCallback:D1}=ql(),Ks=Symbol("promise"),ua=Symbol("callback"),Xn=Symbol("working"),$s=Symbol("handleOne"),Mi=Symbol("handleMany"),wg=Symbol("autoClose"),Co=Symbol("finishWork"),Qn=Symbol("returnMany"),Do=Symbol("closing"),ad=Symbol("handleClose"),Fl=Symbol("closed"),ud=Symbol("closeCallbacks"),No=Symbol("keyEncoding"),Hs=Symbol("valueEncoding"),bg=Symbol("abortOnClose"),jl=Symbol("legacy"),xg=Symbol("keys"),Eg=Symbol("values"),ko=Symbol("limit"),Xr=Symbol("count"),Wl=Object.freeze({}),J6=()=>{},k1=!1,dd=class{constructor(e,r,n){if(typeof e!="object"||e===null){let i=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${i}`)}if(typeof r!="object"||r===null)throw new TypeError("The second argument must be an options object");this[Fl]=!1,this[ud]=[],this[Xn]=!1,this[Do]=!1,this[wg]=!1,this[ua]=null,this[$s]=this[$s].bind(this),this[Mi]=this[Mi].bind(this),this[ad]=this[ad].bind(this),this[No]=r[No],this[Hs]=r[Hs],this[jl]=n,this[ko]=Number.isInteger(r.limit)&&r.limit>=0?r.limit:1/0,this[Xr]=0,this[bg]=!!r.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[Xr]}get limit(){return this[ko]}next(e){let r;if(e===void 0)r=new Promise((n,i)=>{e=(o,s,c)=>{o?i(o):this[jl]?s===void 0&&c===void 0?n():n([s,c]):n(s)}});else if(typeof e!="function")throw new TypeError("Callback must be a function");return this[Do]?this.nextTick(e,new Or("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(e,new Or("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[ua]=e,this[Xr]>=this[ko]?this.nextTick(this[$s],null):this._next(this[$s])),r}_next(e){this.nextTick(e)}nextv(e,r,n){return n=D1(r,n),n=gg(n,Ks),r=mg(r,Wl),Number.isInteger(e)?(this[Do]?this.nextTick(n,new Or("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(n,new Or("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[ko]<1/0&&(e=Math.min(e,this[ko]-this[Xr])),this[Xn]=!0,this[ua]=n,e<=0?this.nextTick(this[Mi],null,[]):this._nextv(e,r,this[Mi])),n[Ks]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[Ks])}_nextv(e,r,n){let i=[],o=(s,c,a)=>{if(s)return n(s);if(this[jl]?c===void 0&&a===void 0:c===void 0)return n(null,i);i.push(this[jl]?[c,a]:c),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,r){return r=D1(e,r),r=gg(r,Ks),e=mg(e,Wl),this[Do]?this.nextTick(r,new Or("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(r,new Or("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[ua]=r,this[wg]=!0,this[Xr]>=this[ko]?this.nextTick(this[Mi],null,[]):this._all(e,this[Mi])),r[Ks]}_all(e,r){let n=this[Xr],i=[],o=()=>{let c=this[ko]<1/0?Math.min(1e3,this[ko]-n):1e3;c<=0?this.nextTick(r,null,i):this._nextv(c,Wl,s)},s=(c,a)=>{c?r(c):a.length===0?r(null,i):(i.push.apply(i,a),n+=a.length,o())};o()}[Co](){let e=this[ua];return this[bg]&&e===null?J6:(this[Xn]=!1,this[ua]=null,this[Do]&&this._close(this[ad]),e)}[Qn](e,r,n){this[wg]?this.close(e.bind(null,r,n)):e(r,n)}seek(e,r){if(r=mg(r,Wl),!this[Do]){if(this[Xn])throw new Or("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(r.keyEncoding||this[No]),i=n.format;r.keyEncoding!==i&&(r={...r,keyEncoding:i});let o=this.db.prefixKey(n.encode(e),i);this._seek(o,r)}}}_seek(e,r){throw new Or("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=gg(e,Ks),this[Fl]?this.nextTick(e):this[Do]?this[ud].push(e):(this[Do]=!0,this[ud].push(e),this[Xn]?this[bg]&&this[Co]()(new Or("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[ad])),e[Ks]}_close(e){this.nextTick(e)}[ad](){this[Fl]=!0,this.db.detachResource(this);let e=this[ud];this[ud]=[];for(let r of e)r()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[Fl]||await this.close()}}},da=class extends dd{constructor(e,r){super(e,r,!0),this[xg]=r.keys!==!1,this[Eg]=r.values!==!1}[$s](e,r,n){let i=this[Co]();if(e)return i(e);try{r=this[xg]&&r!==void 0?this[No].decode(r):void 0,n=this[Eg]&&n!==void 0?this[Hs].decode(n):void 0}catch(o){return i(new Lo("entry",o))}r===void 0&&n===void 0||this[Xr]++,i(null,r,n)}[Mi](e,r){let n=this[Co]();if(e)return this[Qn](n,e);try{for(let i of r){let o=i[0],s=i[1];i[0]=this[xg]&&o!==void 0?this[No].decode(o):void 0,i[1]=this[Eg]&&s!==void 0?this[Hs].decode(s):void 0}}catch(i){return this[Qn](n,new Lo("entries",i))}this[Xr]+=r.length,this[Qn](n,null,r)}end(e){return!k1&&typeof console<"u"&&(k1=!0,console.warn(new Or("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(e)}},vg=class extends dd{constructor(e,r){super(e,r,!1)}[$s](e,r){let n=this[Co]();if(e)return n(e);try{r=r!==void 0?this[No].decode(r):void 0}catch(i){return n(new Lo("key",i))}r!==void 0&&this[Xr]++,n(null,r)}[Mi](e,r){let n=this[Co]();if(e)return this[Qn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[No].decode(o):void 0}}catch(i){return this[Qn](n,new Lo("keys",i))}this[Xr]+=r.length,this[Qn](n,null,r)}},Sg=class extends dd{constructor(e,r){super(e,r,!1)}[$s](e,r){let n=this[Co]();if(e)return n(e);try{r=r!==void 0?this[Hs].decode(r):void 0}catch(i){return n(new Lo("value",i))}r!==void 0&&this[Xr]++,n(null,r)}[Mi](e,r){let n=this[Co]();if(e)return this[Qn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Hs].decode(o):void 0}}catch(i){return this[Qn](n,new Lo("values",i))}this[Xr]+=r.length,this[Qn](n,null,r)}},Lo=class extends Or{constructor(e,r){super(`Iterator could not decode ${e}`,{code:"LEVEL_DECODE_ERROR",cause:r})}};for(let t of["_ended property","_nexting property","_end method"])Object.defineProperty(da.prototype,t.split(" ")[0],{get(){throw new Or(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new Or(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})}});da.keyEncoding=No;da.valueEncoding=Hs;Gl.AbstractIterator=da;Gl.AbstractKeyIterator=vg;Gl.AbstractValueIterator=Sg});var N1=oe(Ag=>{"use strict";l();var{AbstractKeyIterator:Z6,AbstractValueIterator:X6}=Po(),Vs=Symbol("iterator"),fd=Symbol("callback"),fa=Symbol("handleOne"),qs=Symbol("handleMany"),ld=class extends Z6{constructor(e,r){super(e,r),this[Vs]=e.iterator({...r,keys:!0,values:!1}),this[fa]=this[fa].bind(this),this[qs]=this[qs].bind(this)}},zl=class extends X6{constructor(e,r){super(e,r),this[Vs]=e.iterator({...r,keys:!1,values:!0}),this[fa]=this[fa].bind(this),this[qs]=this[qs].bind(this)}};for(let t of[ld,zl]){let e=t===ld,r=e?n=>n[0]:n=>n[1];t.prototype._next=function(n){this[fd]=n,this[Vs].next(this[fa])},t.prototype[fa]=function(n,i,o){let s=this[fd];n?s(n):s(null,e?i:o)},t.prototype._nextv=function(n,i,o){this[fd]=o,this[Vs].nextv(n,i,this[qs])},t.prototype._all=function(n,i){this[fd]=i,this[Vs].all(n,this[qs])},t.prototype[qs]=function(n,i){let o=this[fd];n?o(n):o(null,i.map(r))},t.prototype._seek=function(n,i){this[Vs].seek(n,i)},t.prototype._close=function(n){this[Vs].close(n)}}Ag.DefaultKeyIterator=ld;Ag.DefaultValueIterator=zl});var C1=oe(eh=>{"use strict";l();var{AbstractIterator:Q6,AbstractKeyIterator:eU,AbstractValueIterator:tU}=Po(),Tg=En(),hr=Symbol("nut"),Xl=Symbol("undefer"),Ql=Symbol("factory"),Yl=class extends Q6{constructor(e,r){super(e,r),this[hr]=null,this[Ql]=()=>e.iterator(r),this.db.defer(()=>this[Xl]())}},Jl=class extends eU{constructor(e,r){super(e,r),this[hr]=null,this[Ql]=()=>e.keys(r),this.db.defer(()=>this[Xl]())}},Zl=class extends tU{constructor(e,r){super(e,r),this[hr]=null,this[Ql]=()=>e.values(r),this.db.defer(()=>this[Xl]())}};for(let t of[Yl,Jl,Zl])t.prototype[Xl]=function(){this.db.status==="open"&&(this[hr]=this[Ql]())},t.prototype._next=function(e){this[hr]!==null?this[hr].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new Tg("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._nextv=function(e,r,n){this[hr]!==null?this[hr].nextv(e,r,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,r,n)):this.nextTick(n,new Tg("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._all=function(e,r){this[hr]!==null?this[hr].all(r):this.db.status==="opening"?this.db.defer(()=>this._all(e,r)):this.nextTick(r,new Tg("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._seek=function(e,r){this[hr]!==null?this[hr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[hr]!==null?this[hr].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};eh.DeferredIterator=Yl;eh.DeferredKeyIterator=Jl;eh.DeferredValueIterator=Zl});var Bg=oe(P1=>{"use strict";l();var{fromCallback:L1}=cd(),th=En(),{getCallback:rU,getOptions:nU}=ql(),rh=Symbol("promise"),Qr=Symbol("status"),la=Symbol("operations"),hd=Symbol("finishClose"),ha=Symbol("closeCallbacks"),_g=class{constructor(e){if(typeof e!="object"||e===null){let r=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${r}`)}this[la]=[],this[ha]=[],this[Qr]="open",this[hd]=this[hd].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[la].length}put(e,r,n){if(this[Qr]!=="open")throw new th("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let i=this.db._checkKey(e)||this.db._checkValue(r);if(i)throw i;let o=n&&n.sublevel!=null?n.sublevel:this.db,s=n,c=o.keyEncoding(n&&n.keyEncoding),a=o.valueEncoding(n&&n.valueEncoding),u=c.format;n={...n,keyEncoding:u,valueEncoding:a.format},o!==this.db&&(n.sublevel=null);let d=o.prefixKey(c.encode(e),u),f=a.encode(r);return this._put(d,f,n),this[la].push({...s,type:"put",key:e,value:r}),this}_put(e,r,n){}del(e,r){if(this[Qr]!=="open")throw new th("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let n=this.db._checkKey(e);if(n)throw n;let i=r&&r.sublevel!=null?r.sublevel:this.db,o=r,s=i.keyEncoding(r&&r.keyEncoding),c=s.format;return r={...r,keyEncoding:c},i!==this.db&&(r.sublevel=null),this._del(i.prefixKey(s.encode(e),c),r),this[la].push({...o,type:"del",key:e}),this}_del(e,r){}clear(){if(this[Qr]!=="open")throw new th("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[la]=[],this}_clear(){}write(e,r){return r=rU(e,r),r=L1(r,rh),e=nU(e),this[Qr]!=="open"?this.nextTick(r,new th("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(r):(this[Qr]="writing",this._write(e,n=>{this[Qr]="closing",this[ha].push(()=>r(n)),n||this.db.emit("batch",this[la]),this._close(this[hd])})),r[rh]}_write(e,r){}close(e){return e=L1(e,rh),this[Qr]==="closing"?this[ha].push(e):this[Qr]==="closed"?this.nextTick(e):(this[ha].push(e),this[Qr]!=="writing"&&(this[Qr]="closing",this._close(this[hd]))),e[rh]}_close(e){this.nextTick(e)}[hd](){this[Qr]="closed",this.db.detachResource(this);let e=this[ha];this[ha]=[];for(let r of e)r()}};P1.AbstractChainedBatch=_g});var K1=oe(M1=>{"use strict";l();var{AbstractChainedBatch:iU}=Bg(),oU=En(),pa=Symbol("encoded"),Ig=class extends iU{constructor(e){super(e),this[pa]=[]}_put(e,r,n){this[pa].push({...n,type:"put",key:e,value:r})}_del(e,r){this[pa].push({...r,type:"del",key:e})}_clear(){this[pa]=[]}_write(e,r){this.db.status==="opening"?this.db.defer(()=>this._write(e,r)):this.db.status==="open"?this[pa].length===0?this.nextTick(r):this.db._batch(this[pa],e,r):this.nextTick(r,new oU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};M1.DefaultChainedBatch=Ig});var V1=oe((mq,H1)=>{"use strict";l();var $1=En(),sU=Object.prototype.hasOwnProperty,cU=new Set(["lt","lte","gt","gte"]);H1.exports=function(t,e){let r={};for(let n in t)if(sU.call(t,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new $1(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new $1("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});cU.has(n)?r[n]=e.encode(t[n]):r[n]=t[n]}return r.reverse=!!r.reverse,r.limit=Number.isInteger(r.limit)&&r.limit>=0?r.limit:-1,r}});var Rg=oe((bq,F1)=>{l();var q1;F1.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):t=>(q1||(q1=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var G1=oe((Eq,W1)=>{"use strict";l();var j1=Rg();W1.exports=function(t,...e){e.length===0?j1(t):j1(()=>t(...e))}});var z1=oe(nh=>{"use strict";l();var{AbstractIterator:aU,AbstractKeyIterator:uU,AbstractValueIterator:dU}=Po(),ya=Symbol("unfix"),vn=Symbol("iterator"),Fs=Symbol("handleOne"),Mo=Symbol("handleMany"),Ki=Symbol("callback"),pd=class extends aU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ya]=i,this[Fs]=this[Fs].bind(this),this[Mo]=this[Mo].bind(this),this[Ki]=null}[Fs](e,r,n){let i=this[Ki];if(e)return i(e);r!==void 0&&(r=this[ya](r)),i(e,r,n)}[Mo](e,r){let n=this[Ki];if(e)return n(e);for(let i of r){let o=i[0];o!==void 0&&(i[0]=this[ya](o))}n(e,r)}},yd=class extends uU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ya]=i,this[Fs]=this[Fs].bind(this),this[Mo]=this[Mo].bind(this),this[Ki]=null}[Fs](e,r){let n=this[Ki];if(e)return n(e);r!==void 0&&(r=this[ya](r)),n(e,r)}[Mo](e,r){let n=this[Ki];if(e)return n(e);for(let i=0;i<r.length;i++){let o=r[i];o!==void 0&&(r[i]=this[ya](o))}n(e,r)}},gd=class extends dU{constructor(e,r,n){super(e,r),this[vn]=n}};for(let t of[pd,yd])t.prototype._next=function(e){this[Ki]=e,this[vn].next(this[Fs])},t.prototype._nextv=function(e,r,n){this[Ki]=n,this[vn].nextv(e,r,this[Mo])},t.prototype._all=function(e,r){this[Ki]=r,this[vn].all(e,this[Mo])};for(let t of[gd])t.prototype._next=function(e){this[vn].next(e)},t.prototype._nextv=function(e,r,n){this[vn].nextv(e,r,n)},t.prototype._all=function(e,r){this[vn].all(e,r)};for(let t of[pd,yd,gd])t.prototype._seek=function(e,r){this[vn].seek(e,r)},t.prototype._close=function(e){this[vn].close(e)};nh.AbstractSublevelIterator=pd;nh.AbstractSublevelKeyIterator=yd;nh.AbstractSublevelValueIterator=gd});var X1=oe((Tq,Z1)=>{"use strict";l();var Ug=En(),{Buffer:kg}=Sr()||{},{AbstractSublevelIterator:fU,AbstractSublevelKeyIterator:lU,AbstractSublevelValueIterator:hU}=z1(),$i=Symbol("prefix"),Y1=Symbol("upperBound"),md=Symbol("prefixRange"),Dr=Symbol("parent"),Og=Symbol("unfix"),J1=new TextEncoder,pU={separator:"!"};Z1.exports=function({AbstractLevel:t}){class e extends t{static defaults(n){if(typeof n=="string")throw new Ug("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new Ug("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?pU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=gU(i,s);let u=s.charCodeAt(0)+1,d=n[Dr]||n;if(!J1.encode(i).every(p=>p>u&&p<127))throw new Ug(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(yU(d,c),a);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[Dr]=d,this[$i]=new ih(f),this[Y1]=new ih(h),this[Og]=new Ng,this.nextTick=d.nextTick}prefixKey(n,i){if(i==="utf8")return this[$i].utf8+n;if(n.byteLength===0)return this[$i][i];if(i==="view"){let o=this[$i].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[$i].buffer;return kg.concat([o,n],o.byteLength+n.byteLength)}}[md](n,i){n.gte!==void 0?n.gte=this.prefixKey(n.gte,i):n.gt!==void 0?n.gt=this.prefixKey(n.gt,i):n.gte=this[$i][i],n.lte!==void 0?n.lte=this.prefixKey(n.lte,i):n.lt!==void 0?n.lt=this.prefixKey(n.lt,i):n.lte=this[Y1][i]}get prefix(){return this[$i].utf8}get db(){return this[Dr]}_open(n,i){this[Dr].open({passive:!0},i)}_put(n,i,o,s){this[Dr].put(n,i,o,s)}_get(n,i,o){this[Dr].get(n,i,o)}_getMany(n,i,o){this[Dr].getMany(n,i,o)}_del(n,i,o){this[Dr].del(n,i,o)}_batch(n,i,o){this[Dr].batch(n,i,o)}_clear(n,i){this[md](n,n.keyEncoding),this[Dr].clear(n,i)}_iterator(n){this[md](n,n.keyEncoding);let i=this[Dr].iterator(n),o=this[Og].get(this[$i].utf8.length,n.keyEncoding);return new fU(this,n,i,o)}_keys(n){this[md](n,n.keyEncoding);let i=this[Dr].keys(n),o=this[Og].get(this[$i].utf8.length,n.keyEncoding);return new lU(this,n,i,o)}_values(n){this[md](n,n.keyEncoding);let i=this[Dr].values(n);return new hU(this,n,i)}}return{AbstractSublevel:e}};var yU=function(t,e){return{...t.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:Dg(t,"utf8"),buffer:Dg(t,"buffer"),view:Dg(t,"view")}}},Dg=function(t,e){return t.supports.encodings[e]?t.keyEncoding(e).name===e:!1},ih=class{constructor(e){this.utf8=e,this.view=J1.encode(e),this.buffer=kg?kg.from(this.view.buffer,0,this.view.byteLength):{}}},Ng=class{constructor(){this.cache=new Map}get(e,r){let n=this.cache.get(r);return n===void 0&&(r==="view"?n=(function(i,o){return o.subarray(i)}).bind(null,e):n=(function(i,o){return o.slice(i)}).bind(null,e),this.cache.set(r,n)),n}},gU=function(t,e){let r=0,n=t.length;for(;r<n&&t[r]===e;)r++;for(;n>r&&t[n-1]===e;)n--;return t.slice(r,n)}});var Kg=oe(Mg=>{"use strict";l();var{supports:mU}=a1(),{Transcoder:wU}=w1(),{EventEmitter:bU}=aa(),{fromCallback:Ko}=cd(),Sn=En(),{AbstractIterator:js}=Po(),{DefaultKeyIterator:xU,DefaultValueIterator:EU}=N1(),{DeferredIterator:vU,DeferredKeyIterator:SU,DeferredValueIterator:AU}=C1(),{DefaultChainedBatch:Q1}=K1(),{getCallback:Ws,getOptions:$o}=ql(),oh=V1(),pe=Symbol("promise"),Hi=Symbol("landed"),Gs=Symbol("resources"),Cg=Symbol("closeResources"),wd=Symbol("operations"),bd=Symbol("undefer"),sh=Symbol("deferOpen"),e2=Symbol("options"),we=Symbol("status"),zs=Symbol("defaultOptions"),ga=Symbol("transcoder"),ch=Symbol("keyEncoding"),Lg=Symbol("valueEncoding"),TU=()=>{},xd=class extends bU{constructor(e,r){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");r=$o(r);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=r;this[Gs]=new Set,this[wd]=[],this[sh]=!0,this[e2]=s,this[we]="opening",this.supports=mU(e,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:e.snapshots!==!1,permanence:e.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:e.encodings||{},events:Object.assign({},e.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[ga]=new wU(_U(this)),this[ch]=this[ga].encoding(n||"utf8"),this[Lg]=this[ga].encoding(i||"utf8");for(let c of this[ga].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[zs]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[ch].commonName,valueEncoding:this[Lg].commonName}),key:Object.freeze({keyEncoding:this[ch].commonName})},this.nextTick(()=>{this[sh]&&this.open({passive:!1},TU)})}get status(){return this[we]}keyEncoding(e){return this[ga].encoding(e??this[ch])}valueEncoding(e){return this[ga].encoding(e??this[Lg])}open(e,r){r=Ws(e,r),r=Ko(r,pe),e={...this[e2],...$o(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[we]==="closing"||this[we]==="opening"?this.once(Hi,i?()=>n(i):n):this[we]!=="open"?r(new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):r()};return e.passive?this[we]==="opening"?this.once(Hi,n):this.nextTick(n):this[we]==="closed"||this[sh]?(this[sh]=!1,this[we]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[we]="closed",this[Cg](()=>{this.emit(Hi),n(i)}),this[bd]();return}this[we]="open",this[bd](),this.emit(Hi),this[we]==="open"&&this.emit("open"),this[we]==="open"&&this.emit("ready"),n()})):this[we]==="open"?this.nextTick(n):this.once(Hi,()=>this.open(e,r)),r[pe]}_open(e,r){this.nextTick(r)}close(e){e=Ko(e,pe);let r=n=>{this[we]==="opening"||this[we]==="closing"?this.once(Hi,n?r(n):r):this[we]!=="closed"?e(new Sn("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:n})):e()};if(this[we]==="open"){this[we]="closing",this.emit("closing");let n=i=>{this[we]="open",this[bd](),this.emit(Hi),r(i)};this[Cg](()=>{this._close(i=>{if(i)return n(i);this[we]="closed",this[bd](),this.emit(Hi),this[we]==="closed"&&this.emit("closed"),r()})})}else this[we]==="closed"?this.nextTick(r):this.once(Hi,()=>this.close(e));return e[pe]}[Cg](e){if(this[Gs].size===0)return this.nextTick(e);let r=this[Gs].size,n=!0,i=()=>{--r===0&&(n?this.nextTick(e):e())};for(let o of this[Gs])o.close(i);n=!1,this[Gs].clear()}_close(e){this.nextTick(e)}get(e,r,n){if(n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].entry),this[we]==="opening")return this.defer(()=>this.get(e,r,n)),n[pe];if(ma(this,n))return n[pe];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[pe];let o=this.keyEncoding(r.keyEncoding),s=this.valueEncoding(r.valueEncoding),c=o.format,a=s.format;return(r.keyEncoding!==c||r.valueEncoding!==a)&&(r=Object.assign({},r,{keyEncoding:c,valueEncoding:a})),this._get(this.prefixKey(o.encode(e),c),r,(u,d)=>{if(u)return(u.code==="LEVEL_NOT_FOUND"||u.notFound||/NotFound/i.test(u))&&(u.code||(u.code="LEVEL_NOT_FOUND"),u.notFound||(u.notFound=!0),u.status||(u.status=404)),n(u);try{d=s.decode(d)}catch(f){return n(new Sn("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[pe]}_get(e,r,n){this.nextTick(n,new Error("NotFound"))}getMany(e,r,n){if(n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].entry),this[we]==="opening")return this.defer(()=>this.getMany(e,r,n)),n[pe];if(ma(this,n))return n[pe];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'keys' must be an array")),n[pe];if(e.length===0)return this.nextTick(n,null,[]),n[pe];let i=this.keyEncoding(r.keyEncoding),o=this.valueEncoding(r.valueEncoding),s=i.format,c=o.format;(r.keyEncoding!==s||r.valueEncoding!==c)&&(r=Object.assign({},r,{keyEncoding:s,valueEncoding:c}));let a=new Array(e.length);for(let u=0;u<e.length;u++){let d=e[u],f=this._checkKey(d);if(f)return this.nextTick(n,f),n[pe];a[u]=this.prefixKey(i.encode(d),s)}return this._getMany(a,r,(u,d)=>{if(u)return n(u);try{for(let f=0;f<d.length;f++)d[f]!==void 0&&(d[f]=o.decode(d[f]))}catch(f){return n(new Sn(`Could not decode one or more of ${d.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[pe]}_getMany(e,r,n){this.nextTick(n,null,new Array(e.length).fill(void 0))}put(e,r,n,i){if(i=Ws(n,i),i=Ko(i,pe),n=$o(n,this[zs].entry),this[we]==="opening")return this.defer(()=>this.put(e,r,n,i)),i[pe];if(ma(this,i))return i[pe];let o=this._checkKey(e)||this._checkValue(r);if(o)return this.nextTick(i,o),i[pe];let s=this.keyEncoding(n.keyEncoding),c=this.valueEncoding(n.valueEncoding),a=s.format,u=c.format;(n.keyEncoding!==a||n.valueEncoding!==u)&&(n=Object.assign({},n,{keyEncoding:a,valueEncoding:u}));let d=this.prefixKey(s.encode(e),a),f=c.encode(r);return this._put(d,f,n,h=>{if(h)return i(h);this.emit("put",e,r),i()}),i[pe]}_put(e,r,n,i){this.nextTick(i)}del(e,r,n){if(n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].key),this[we]==="opening")return this.defer(()=>this.del(e,r,n)),n[pe];if(ma(this,n))return n[pe];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[pe];let o=this.keyEncoding(r.keyEncoding),s=o.format;return r.keyEncoding!==s&&(r=Object.assign({},r,{keyEncoding:s})),this._del(this.prefixKey(o.encode(e),s),r,c=>{if(c)return n(c);this.emit("del",e),n()}),n[pe]}_del(e,r,n){this.nextTick(n)}batch(e,r,n){if(!arguments.length){if(this[we]==="opening")return new Q1(this);if(this[we]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].empty),this[we]==="opening")return this.defer(()=>this.batch(e,r,n)),n[pe];if(ma(this,n))return n[pe];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'operations' must be an array")),n[pe];if(e.length===0)return this.nextTick(n),n[pe];let i=new Array(e.length),{keyEncoding:o,valueEncoding:s,...c}=r;for(let a=0;a<e.length;a++){if(typeof e[a]!="object"||e[a]===null)return this.nextTick(n,new TypeError("A batch operation must be an object")),n[pe];let u=Object.assign({},e[a]);if(u.type!=="put"&&u.type!=="del")return this.nextTick(n,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),n[pe];let d=this._checkKey(u.key);if(d)return this.nextTick(n,d),n[pe];let f=u.sublevel!=null?u.sublevel:this,h=f.keyEncoding(u.keyEncoding||o),p=h.format;if(u.key=f.prefixKey(h.encode(u.key),p),u.keyEncoding=p,u.type==="put"){let g=this._checkValue(u.value);if(g)return this.nextTick(n,g),n[pe];let y=f.valueEncoding(u.valueEncoding||s);u.value=y.encode(u.value),u.valueEncoding=y.format}f!==this&&(u.sublevel=null),i[a]=u}return this._batch(i,c,a=>{if(a)return n(a);this.emit("batch",e),n()}),n[pe]}_batch(e,r,n){this.nextTick(n)}sublevel(e,r){return this._sublevel(e,Pg.defaults(r))}_sublevel(e,r){return new Pg(this,e,r)}prefixKey(e,r){return e}clear(e,r){if(r=Ws(e,r),r=Ko(r,pe),e=$o(e,this[zs].empty),this[we]==="opening")return this.defer(()=>this.clear(e,r)),r[pe];if(ma(this,r))return r[pe];let n=e,i=this.keyEncoding(e.keyEncoding);return e=oh(e,i),e.keyEncoding=i.format,e.limit===0?this.nextTick(r):this._clear(e,o=>{if(o)return r(o);this.emit("clear",n),r()}),r[pe]}_clear(e,r){this.nextTick(r)}iterator(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=oh(e,r),e.keys=e.keys!==!1,e.values=e.values!==!1,e[js.keyEncoding]=r,e[js.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[we]==="opening")return new vU(this,e);if(this[we]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new js(this,e)}keys(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=oh(e,r),e[js.keyEncoding]=r,e[js.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[we]==="opening")return new SU(this,e);if(this[we]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new xU(this,e)}values(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=oh(e,r),e[js.keyEncoding]=r,e[js.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[we]==="opening")return new AU(this,e);if(this[we]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new EU(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[wd].push(e)}[bd](){if(this[wd].length===0)return;let e=this[wd];this[wd]=[];for(let r of e)r()}attachResource(e){if(typeof e!="object"||e===null||typeof e.close!="function")throw new TypeError("The first argument must be a resource object");this[Gs].add(e)}detachResource(e){this[Gs].delete(e)}_chainedBatch(){return new Q1(this)}_checkKey(e){if(e==null)return new Sn("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(e){if(e==null)return new Sn("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};xd.prototype.nextTick=G1();var{AbstractSublevel:Pg}=X1()({AbstractLevel:xd});Mg.AbstractLevel=xd;Mg.AbstractSublevel=Pg;var ma=function(t,e){return t[we]!=="open"?(t.nextTick(e,new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},_U=function(t){return Object.keys(t.supports.encodings).filter(e=>!!t.supports.encodings[e])}});var $g=oe(Ys=>{"use strict";l();Ys.AbstractLevel=Kg().AbstractLevel;Ys.AbstractSublevel=Kg().AbstractSublevel;Ys.AbstractIterator=Po().AbstractIterator;Ys.AbstractKeyIterator=Po().AbstractKeyIterator;Ys.AbstractValueIterator=Po().AbstractValueIterator;Ys.AbstractChainedBatch=Bg().AbstractChainedBatch});var r2=oe((Oq,t2)=>{l();t2.exports=IU;var BU=Rg();function IU(t,e,r){if(typeof e!="number")throw new Error("second argument must be a Number");let n,i,o,s,c,a=!0,u;Array.isArray(t)?(n=[],o=i=t.length):(s=Object.keys(t),n={},o=i=s.length);function d(h){function p(){r&&r(h,n),r=null}a?BU(p):p()}function f(h,p,g){if(n[h]=g,p&&(c=!0),--o===0||p)d(p);else if(!c&&u<i){let y;s?(y=s[u],u+=1,t[y](function(E,S){f(y,E,S)})):(y=u,u+=1,t[y](function(E,S){f(y,E,S)}))}}u=e,o?s?s.some(function(h,p){return t[h](function(g,y){f(h,g,y)}),p===e-1}):t.some(function(h,p){return h(function(g,y){f(p,g,y)}),p===e-1}):d(null),a=!1}});var Hg=oe((kq,n2)=>{"use strict";l();n2.exports=function(e){let r=e.gte!==void 0?e.gte:e.gt!==void 0?e.gt:void 0,n=e.lte!==void 0?e.lte:e.lt!==void 0?e.lt:void 0,i=e.gte===void 0,o=e.lte===void 0;return r!==void 0&&n!==void 0?IDBKeyRange.bound(r,n,i,o):r!==void 0?IDBKeyRange.lowerBound(r,i):n!==void 0?IDBKeyRange.upperBound(n,o):null}});var Vg=oe((Cq,i2)=>{"use strict";l();var RU=new TextEncoder;i2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):RU.encode(t)}});var u2=oe(a2=>{"use strict";l();var{AbstractIterator:UU}=$g(),o2=Hg(),ah=Vg(),ei=Symbol("cache"),Vi=Symbol("finished"),kr=Symbol("options"),qi=Symbol("currentOptions"),Js=Symbol("position"),qg=Symbol("location"),wa=Symbol("first"),s2={},Fg=class extends UU{constructor(e,r,n){super(e,n),this[ei]=[],this[Vi]=this.limit===0,this[kr]=n,this[qi]={...n},this[Js]=void 0,this[qg]=r,this[wa]=!0}_nextv(e,r,n){if(this[wa]=!1,this[Vi])return this.nextTick(n,null,[]);if(this[ei].length>0)return e=Math.min(e,this[ei].length),this.nextTick(n,null,this[ei].splice(0,e));this[Js]!==void 0&&(this[kr].reverse?(this[qi].lt=this[Js],this[qi].lte=void 0):(this[qi].gt=this[Js],this[qi].gte=void 0));let i;try{i=o2(this[qi])}catch{return this[Vi]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[qg]],"readonly"),s=o.objectStore(this[qg]),c=[];if(this[kr].reverse){let a=!this[kr].values&&s.openKeyCursor?"openKeyCursor":"openCursor";s[a](i,"prev").onsuccess=u=>{let d=u.target.result;if(d){let{key:f,value:h}=d;this[Js]=f,c.push([this[kr].keys&&f!==void 0?ah(f):void 0,this[kr].values&&h!==void 0?ah(h):void 0]),c.length<e?d.continue():c2(o)}else this[Vi]=!0}}else{let a,u,d=()=>{if(a===void 0||u===void 0)return;let f=Math.max(a.length,u.length);f===0||e===1/0?this[Vi]=!0:this[Js]=a[f-1],c.length=f;for(let h=0;h<f;h++){let p=a[h],g=u[h];c[h]=[this[kr].keys&&p!==void 0?ah(p):void 0,this[kr].values&&g!==void 0?ah(g):void 0]}c2(o)};this[kr].keys||e<1/0?s.getAllKeys(i,e<1/0?e:void 0).onsuccess=f=>{a=f.target.result,d()}:(a=[],this.nextTick(d)),this[kr].values?s.getAll(i,e<1/0?e:void 0).onsuccess=f=>{u=f.target.result,d()}:(u=[],this.nextTick(d))}o.onabort=()=>{n(o.error||new Error("aborted by user")),n=null},o.oncomplete=()=>{n(null,c),n=null}}_next(e){if(this[ei].length>0){let[r,n]=this[ei].shift();this.nextTick(e,null,r,n)}else if(this[Vi])this.nextTick(e);else{let r=Math.min(100,this.limit-this.count);this[wa]&&(this[wa]=!1,r=1),this._nextv(r,s2,(n,i)=>{if(n)return e(n);this[ei]=i,this._next(e)})}}_all(e,r){this[wa]=!1;let n=this[ei].splice(0,this[ei].length),i=this.limit-this.count-n.length;if(i<=0)return this.nextTick(r,null,n);this._nextv(i,s2,(o,s)=>{if(o)return r(o);n.length>0&&(s=n.concat(s)),r(null,s)})}_seek(e,r){this[wa]=!0,this[ei]=[],this[Vi]=!1,this[Js]=void 0,this[qi]={...this[kr]};let n;try{n=o2(this[kr])}catch{this[Vi]=!0;return}n!==null&&!n.includes(e)?this[Vi]=!0:this[kr].reverse?this[qi].lte=e:this[qi].gte=e}};a2.Iterator=Fg;function c2(t){typeof t.commit=="function"&&t.commit()}});var f2=oe((Kq,d2)=>{"use strict";l();d2.exports=function(e,r,n,i,o){if(i.limit===0)return e.nextTick(o);let s=e.db.transaction([r],"readwrite"),c=s.objectStore(r),a=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let u=c.openKeyCursor?"openKeyCursor":"openCursor",d=i.reverse?"prev":"next";c[u](n,d).onsuccess=function(f){let h=f.target.result;h&&(c.delete(h.key).onsuccess=function(){(i.limit<=0||++a<i.limit)&&h.continue()})}}});var m2=oe(g2=>{"use strict";l();var{AbstractLevel:OU}=$g(),l2=En(),DU=r2(),{fromCallback:kU}=cd(),{Iterator:NU}=u2(),h2=Vg(),CU=f2(),LU=Hg(),y2="level-js-",Ed=Symbol("idb"),jg=Symbol("namePrefix"),Fi=Symbol("location"),Wg=Symbol("version"),Zs=Symbol("store"),vd=Symbol("onComplete"),p2=Symbol("promise"),uh=class extends OU{constructor(e,r,n){if(typeof r=="function"||typeof n=="function")throw new l2("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:i,version:o,...s}=r||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},s),typeof e!="string")throw new Error("constructor requires a location string argument");this[Fi]=e,this[jg]=i??y2,this[Wg]=parseInt(o||1,10),this[Ed]=null}get location(){return this[Fi]}get namePrefix(){return this[jg]}get version(){return this[Wg]}get db(){return this[Ed]}get type(){return"browser-level"}_open(e,r){let n=indexedDB.open(this[jg]+this[Fi],this[Wg]);n.onerror=function(){r(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[Ed]=n.result,r()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[Fi])||o.createObjectStore(this[Fi])}}[Zs](e){return this[Ed].transaction([this[Fi]],e).objectStore(this[Fi])}[vd](e,r){let n=e.transaction;n.onabort=function(){r(n.error||new Error("aborted by user"))},n.oncomplete=function(){r(null,e.result)}}_get(e,r,n){let i=this[Zs]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[vd](o,function(s,c){if(s)return n(s);if(c===void 0)return n(new l2("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,h2(c))})}_getMany(e,r,n){let i=this[Zs]("readonly"),o=e.map(s=>c=>{let a;try{a=i.get(s)}catch(u){return c(u)}a.onsuccess=()=>{let u=a.result;c(null,u===void 0?u:h2(u))},a.onerror=u=>{u.stopPropagation(),c(a.error)}});DU(o,16,n)}_del(e,r,n){let i=this[Zs]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[vd](o,n)}_put(e,r,n,i){let o=this[Zs]("readwrite"),s;try{s=o.put(r,e)}catch(c){return this.nextTick(i,c)}this[vd](s,i)}_iterator(e){return new NU(this,this[Fi],e)}_batch(e,r,n){let i=this[Zs]("readwrite"),o=i.transaction,s=0,c;o.onabort=function(){n(c||o.error||new Error("aborted by user"))},o.oncomplete=function(){n()};function a(){let u=e[s++],d=u.key,f;try{f=u.type==="del"?i.delete(d):i.put(u.value,d)}catch(h){c=h,o.abort();return}s<e.length?f.onsuccess=a:typeof o.commit=="function"&&o.commit()}a()}_clear(e,r){let n,i;try{n=LU(e)}catch{return this.nextTick(r)}if(e.limit>=0)return CU(this,this[Fi],n,e,r);try{let o=this[Zs]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(r,o)}this[vd](i,r)}_close(e){this[Ed].close(),this.nextTick(e)}};uh.destroy=function(t,e,r){typeof e=="function"&&(r=e,e=y2),r=kU(r,p2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[p2]};g2.BrowserLevel=uh});var Gg=oe(w2=>{l();w2.Level=m2().BrowserLevel});var nt=oe((Jq,b2)=>{"use strict";l();b2.exports={ArrayIsArray(t){return Array.isArray(t)},ArrayPrototypeIncludes(t,e){return t.includes(e)},ArrayPrototypeIndexOf(t,e){return t.indexOf(e)},ArrayPrototypeJoin(t,e){return t.join(e)},ArrayPrototypeMap(t,e){return t.map(e)},ArrayPrototypePop(t,e){return t.pop(e)},ArrayPrototypePush(t,e){return t.push(e)},ArrayPrototypeSlice(t,e,r){return t.slice(e,r)},Error,FunctionPrototypeCall(t,e,...r){return t.call(e,...r)},FunctionPrototypeSymbolHasInstance(t,e){return Function.prototype[Symbol.hasInstance].call(t,e)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(t,e){return Object.defineProperties(t,e)},ObjectDefineProperty(t,e,r){return Object.defineProperty(t,e,r)},ObjectGetOwnPropertyDescriptor(t,e){return Object.getOwnPropertyDescriptor(t,e)},ObjectKeys(t){return Object.keys(t)},ObjectSetPrototypeOf(t,e){return Object.setPrototypeOf(t,e)},Promise,PromisePrototypeCatch(t,e){return t.catch(e)},PromisePrototypeThen(t,e,r){return t.then(e,r)},PromiseReject(t){return Promise.reject(t)},PromiseResolve(t){return Promise.resolve(t)},ReflectApply:Reflect.apply,RegExpPrototypeTest(t,e){return t.test(e)},SafeSet:Set,String,StringPrototypeSlice(t,e,r){return t.slice(e,r)},StringPrototypeToLowerCase(t){return t.toLowerCase()},StringPrototypeToUpperCase(t){return t.toUpperCase()},StringPrototypeTrim(t){return t.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(t,e,r){return t.set(e,r)},Boolean,Uint8Array}});var ba=oe((Xq,fh)=>{"use strict";l();var{AbortController:x2,AbortSignal:MU}=typeof self<"u"?self:typeof window<"u"?window:void 0;fh.exports=x2;fh.exports.AbortSignal=MU;fh.exports.default=x2});var Jt=oe((eF,Yg)=>{"use strict";l();var KU=Sr(),{kResistStopPropagation:$U,SymbolDispose:HU}=nt(),VU=globalThis.AbortSignal||ba().AbortSignal,qU=globalThis.AbortController||ba().AbortController,FU=Object.getPrototypeOf(async function(){}).constructor,E2=globalThis.Blob||KU.Blob,jU=typeof E2<"u"?function(e){return e instanceof E2}:function(e){return!1},v2=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ERR_INVALID_ARG_TYPE(e,"AbortSignal",t)},WU=(t,e)=>{if(typeof t!="function")throw new ERR_INVALID_ARG_TYPE(e,"Function",t)},zg=class extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError(`Expected input to be an Array, got ${typeof e}`);let r="";for(let n=0;n<e.length;n++)r+=` ${e[n].stack}
2
- `;super(r),this.name="AggregateError",this.errors=e}};Yg.exports={AggregateError:zg,kEmptyObject:Object.freeze({}),once(t){let e=!1;return function(...r){e||(e=!0,t.apply(this,r))}},createDeferredPromise:function(){let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}},promisify(t){return new Promise((e,r)=>{t((n,...i)=>n?r(n):e(...i))})},debuglog(){return function(){}},format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let i=e.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}},types:{isAsyncFunction(t){return t instanceof FU},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:jU,deprecate(t,e){return t},addAbortListener:aa().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);v2(e,"signal"),WU(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[$U]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[HU](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:VU.any||function(e){if(e.length===1)return e[0];let r=new qU,n=()=>r.abort();return e.forEach(i=>{v2(i,"signals"),i.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(i=>i.removeEventListener("abort",n))},{once:!0}),r.signal}};Yg.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var ir=oe((rF,T2)=>{"use strict";l();var{format:GU,inspect:lh,AggregateError:zU}=Jt(),YU=globalThis.AggregateError||zU,JU=Symbol("kIsNodeError"),ZU=["string","function","number","object","Function","Object","boolean","bigint","symbol"],XU=/^([A-Z][a-z0-9]*)+$/,QU="__node_internal_",hh={};function Qs(t,e){if(!t)throw new hh.ERR_INTERNAL_ASSERTION(e)}function S2(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function e5(t,e,r){if(typeof e=="function")return Qs(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return Qs(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:GU(e,...r)}function Mt(t,e,r){r||(r=Error);class n extends r{constructor(...o){super(e5(t,e,o))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[JU]=!0,hh[t]=n}function A2(t){let e=QU+t.name;return Object.defineProperty(t,"name",{value:e}),t}function t5(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new YU([e,t],e.message);return r.code=e.code,r}return t||e}var Jg=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new hh.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Mt("ERR_ASSERTION","%s",Error);Mt("ERR_INVALID_ARG_TYPE",(t,e,r)=>{Qs(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let i=[],o=[],s=[];for(let a of e)Qs(typeof a=="string","All expected entries have to be of type string"),ZU.includes(a)?i.push(a.toLowerCase()):XU.test(a)?o.push(a):(Qs(a!=="object",'The value "object" should be written as "Object"'),s.push(a));if(o.length>0){let a=i.indexOf("object");a!==-1&&(i.splice(i,a,1),o.push("Object"))}if(i.length>0){switch(i.length){case 1:n+=`of type ${i[0]}`;break;case 2:n+=`one of type ${i[0]} or ${i[1]}`;break;default:{let a=i.pop();n+=`one of type ${i.join(", ")}, or ${a}`}}(o.length>0||s.length>0)&&(n+=" or ")}if(o.length>0){switch(o.length){case 1:n+=`an instance of ${o[0]}`;break;case 2:n+=`an instance of ${o[0]} or ${o[1]}`;break;default:{let a=o.pop();n+=`an instance of ${o.join(", ")}, or ${a}`}}s.length>0&&(n+=" or ")}switch(s.length){case 0:break;case 1:s[0].toLowerCase()!==s[0]&&(n+="an "),n+=`${s[0]}`;break;case 2:n+=`one of ${s[0]} or ${s[1]}`;break;default:{let a=s.pop();n+=`one of ${s.join(", ")}, or ${a}`}}if(r==null)n+=`. Received ${r}`;else if(typeof r=="function"&&r.name)n+=`. Received function ${r.name}`;else if(typeof r=="object"){var c;if((c=r.constructor)!==null&&c!==void 0&&c.name)n+=`. Received an instance of ${r.constructor.name}`;else{let a=lh(r,{depth:-1});n+=`. Received ${a}`}}else{let a=lh(r,{colors:!1});a.length>25&&(a=`${a.slice(0,25)}...`),n+=`. Received type ${typeof r} (${a})`}return n},TypeError);Mt("ERR_INVALID_ARG_VALUE",(t,e,r="is invalid")=>{let n=lh(e);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${t.includes(".")?"property":"argument"} '${t}' ${r}. Received ${n}`},TypeError);Mt("ERR_INVALID_RETURN_VALUE",(t,e,r)=>{var n;let i=r!=null&&(n=r.constructor)!==null&&n!==void 0&&n.name?`instance of ${r.constructor.name}`:`type ${typeof r}`;return`Expected ${t} to be returned from the "${e}" function but got ${i}.`},TypeError);Mt("ERR_MISSING_ARGS",(...t)=>{Qs(t.length>0,"At least one arg needs to be specified");let e,r=t.length;switch(t=(Array.isArray(t)?t:[t]).map(n=>`"${n}"`).join(" or "),r){case 1:e+=`The ${t[0]} argument`;break;case 2:e+=`The ${t[0]} and ${t[1]} arguments`;break;default:{let n=t.pop();e+=`The ${t.join(", ")}, and ${n} arguments`}break}return`${e} must be specified`},TypeError);Mt("ERR_OUT_OF_RANGE",(t,e,r)=>{Qs(e,'Missing "range" argument');let n;return Number.isInteger(r)&&Math.abs(r)>2**32?n=S2(String(r)):typeof r=="bigint"?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=S2(n)),n+="n"):n=lh(r),`The value of "${t}" is out of range. It must be ${e}. Received ${n}`},RangeError);Mt("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);Mt("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);Mt("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);Mt("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);Mt("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);Mt("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Mt("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);Mt("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);Mt("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);Mt("ERR_STREAM_WRITE_AFTER_END","write after end",Error);Mt("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);T2.exports={AbortError:Jg,aggregateTwoErrors:A2(t5),hideStackFrames:A2,codes:hh}});var Ea=oe((iF,C2)=>{"use strict";l();var{ArrayIsArray:Xg,ArrayPrototypeIncludes:R2,ArrayPrototypeJoin:U2,ArrayPrototypeMap:r5,NumberIsInteger:Qg,NumberIsNaN:n5,NumberMAX_SAFE_INTEGER:i5,NumberMIN_SAFE_INTEGER:o5,NumberParseInt:s5,ObjectPrototypeHasOwnProperty:c5,RegExpPrototypeExec:O2,String:a5,StringPrototypeToUpperCase:u5,StringPrototypeTrim:d5}=nt(),{hideStackFrames:en,codes:{ERR_SOCKET_BAD_PORT:f5,ERR_INVALID_ARG_TYPE:Zt,ERR_INVALID_ARG_VALUE:xa,ERR_OUT_OF_RANGE:ec,ERR_UNKNOWN_SIGNAL:_2}}=ir(),{normalizeEncoding:l5}=Jt(),{isAsyncFunction:h5,isArrayBufferView:p5}=Jt().types,B2={};function y5(t){return t===(t|0)}function g5(t){return t===t>>>0}var m5=/^[0-7]+$/,w5="must be a 32-bit unsigned integer or an octal string";function b5(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(O2(m5,t)===null)throw new xa(e,t,w5);t=s5(t,8)}return D2(t,e),t}var x5=en((t,e,r=o5,n=i5)=>{if(typeof t!="number")throw new Zt(e,"number",t);if(!Qg(t))throw new ec(e,"an integer",t);if(t<r||t>n)throw new ec(e,`>= ${r} && <= ${n}`,t)}),E5=en((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new Zt(e,"number",t);if(!Qg(t))throw new ec(e,"an integer",t);if(t<r||t>n)throw new ec(e,`>= ${r} && <= ${n}`,t)}),D2=en((t,e,r=!1)=>{if(typeof t!="number")throw new Zt(e,"number",t);if(!Qg(t))throw new ec(e,"an integer",t);let n=r?1:0,i=4294967295;if(t<n||t>i)throw new ec(e,`>= ${n} && <= ${i}`,t)});function em(t,e){if(typeof t!="string")throw new Zt(e,"string",t)}function v5(t,e,r=void 0,n){if(typeof t!="number")throw new Zt(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&n5(t))throw new ec(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var S5=en((t,e,r)=>{if(!R2(r,t)){let i="must be one of: "+U2(r5(r,o=>typeof o=="string"?`'${o}'`:a5(o)),", ");throw new xa(e,t,i)}});function k2(t,e){if(typeof t!="boolean")throw new Zt(e,"boolean",t)}function Zg(t,e,r){return t==null||!c5(t,e)?r:t[e]}var A5=en((t,e,r=null)=>{let n=Zg(r,"allowArray",!1),i=Zg(r,"allowFunction",!1);if(!Zg(r,"nullable",!1)&&t===null||!n&&Xg(t)||typeof t!="object"&&(!i||typeof t!="function"))throw new Zt(e,"Object",t)}),T5=en((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new Zt(e,"a dictionary",t)}),ph=en((t,e,r=0)=>{if(!Xg(t))throw new Zt(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new xa(e,t,n)}});function _5(t,e){ph(t,e);for(let r=0;r<t.length;r++)em(t[r],`${e}[${r}]`)}function B5(t,e){ph(t,e);for(let r=0;r<t.length;r++)k2(t[r],`${e}[${r}]`)}function I5(t,e){ph(t,e);for(let r=0;r<t.length;r++){let n=t[r],i=`${e}[${r}]`;if(n==null)throw new Zt(i,"AbortSignal",n);N2(n,i)}}function R5(t,e="signal"){if(em(t,e),B2[t]===void 0)throw B2[u5(t)]!==void 0?new _2(t+" (signals must use all capital letters)"):new _2(t)}var U5=en((t,e="buffer")=>{if(!p5(t))throw new Zt(e,["Buffer","TypedArray","DataView"],t)});function O5(t,e){let r=l5(e),n=t.length;if(r==="hex"&&n%2!==0)throw new xa("encoding",e,`is invalid for data of length ${n}`)}function D5(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&d5(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new f5(e,t,r);return t|0}var N2=en((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new Zt(e,"AbortSignal",t)}),k5=en((t,e)=>{if(typeof t!="function")throw new Zt(e,"Function",t)}),N5=en((t,e)=>{if(typeof t!="function"||h5(t))throw new Zt(e,"Function",t)}),C5=en((t,e)=>{if(t!==void 0)throw new Zt(e,"undefined",t)});function L5(t,e,r){if(!R2(r,t))throw new Zt(e,`('${U2(r,"|")}')`,t)}var P5=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function I2(t,e){if(typeof t>"u"||!O2(P5,t))throw new xa(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function M5(t){if(typeof t=="string")return I2(t,"hints"),t;if(Xg(t)){let e=t.length,r="";if(e===0)return r;for(let n=0;n<e;n++){let i=t[n];I2(i,"hints"),r+=i,n!==e-1&&(r+=", ")}return r}throw new xa("hints",t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}C2.exports={isInt32:y5,isUint32:g5,parseFileMode:b5,validateArray:ph,validateStringArray:_5,validateBooleanArray:B5,validateAbortSignalArray:I5,validateBoolean:k2,validateBuffer:U5,validateDictionary:T5,validateEncoding:O5,validateFunction:k5,validateInt32:E5,validateInteger:x5,validateNumber:v5,validateObject:A5,validateOneOf:S5,validatePlainFunction:N5,validatePort:D5,validateSignalName:R5,validateString:em,validateUint32:D2,validateUndefined:C5,validateUnion:L5,validateAbortSignal:N2,validateLinkHeaderValue:M5}});var ri=oe((sF,J2)=>{"use strict";l();var{SymbolAsyncIterator:L2,SymbolIterator:P2,SymbolFor:tc}=nt(),M2=tc("nodejs.stream.destroyed"),K2=tc("nodejs.stream.errored"),tm=tc("nodejs.stream.readable"),rm=tc("nodejs.stream.writable"),$2=tc("nodejs.stream.disturbed"),K5=tc("nodejs.webstream.isClosedPromise"),$5=tc("nodejs.webstream.controllerErrorFunction");function yh(t,e=!1){var r;return!!(t&&typeof t.pipe=="function"&&typeof t.on=="function"&&(!e||typeof t.pause=="function"&&typeof t.resume=="function")&&(!t._writableState||((r=t._readableState)===null||r===void 0?void 0:r.readable)!==!1)&&(!t._writableState||t._readableState))}function gh(t){var e;return!!(t&&typeof t.write=="function"&&typeof t.on=="function"&&(!t._readableState||((e=t._writableState)===null||e===void 0?void 0:e.writable)!==!1))}function H5(t){return!!(t&&typeof t.pipe=="function"&&t._readableState&&typeof t.on=="function"&&typeof t.write=="function")}function ti(t){return t&&(t._readableState||t._writableState||typeof t.write=="function"&&typeof t.on=="function"||typeof t.pipe=="function"&&typeof t.on=="function")}function H2(t){return!!(t&&!ti(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function V2(t){return!!(t&&!ti(t)&&typeof t.getWriter=="function"&&typeof t.abort=="function")}function q2(t){return!!(t&&!ti(t)&&typeof t.readable=="object"&&typeof t.writable=="object")}function V5(t){return H2(t)||V2(t)||q2(t)}function q5(t,e){return t==null?!1:e===!0?typeof t[L2]=="function":e===!1?typeof t[P2]=="function":typeof t[L2]=="function"||typeof t[P2]=="function"}function mh(t){if(!ti(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!!(t.destroyed||t[M2]||n!=null&&n.destroyed)}function F2(t){if(!gh(t))return null;if(t.writableEnded===!0)return!0;let e=t._writableState;return e!=null&&e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function F5(t,e){if(!gh(t))return null;if(t.writableFinished===!0)return!0;let r=t._writableState;return r!=null&&r.errored?!1:typeof r?.finished!="boolean"?null:!!(r.finished||e===!1&&r.ended===!0&&r.length===0)}function j5(t){if(!yh(t))return null;if(t.readableEnded===!0)return!0;let e=t._readableState;return!e||e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function j2(t,e){if(!yh(t))return null;let r=t._readableState;return r!=null&&r.errored?!1:typeof r?.endEmitted!="boolean"?null:!!(r.endEmitted||e===!1&&r.ended===!0&&r.length===0)}function W2(t){return t&&t[tm]!=null?t[tm]:typeof t?.readable!="boolean"?null:mh(t)?!1:yh(t)&&t.readable&&!j2(t)}function G2(t){return t&&t[rm]!=null?t[rm]:typeof t?.writable!="boolean"?null:mh(t)?!1:gh(t)&&t.writable&&!F2(t)}function W5(t,e){return ti(t)?mh(t)?!0:!(e?.readable!==!1&&W2(t)||e?.writable!==!1&&G2(t)):null}function G5(t){var e,r;return ti(t)?t.writableErrored?t.writableErrored:(e=(r=t._writableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function z5(t){var e,r;return ti(t)?t.readableErrored?t.readableErrored:(e=(r=t._readableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function Y5(t){if(!ti(t))return null;if(typeof t.closed=="boolean")return t.closed;let e=t._writableState,r=t._readableState;return typeof e?.closed=="boolean"||typeof r?.closed=="boolean"?e?.closed||r?.closed:typeof t._closed=="boolean"&&z2(t)?t._closed:null}function z2(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function Y2(t){return typeof t._sent100=="boolean"&&z2(t)}function J5(t){var e;return typeof t._consuming=="boolean"&&typeof t._dumped=="boolean"&&((e=t.req)===null||e===void 0?void 0:e.upgradeOrConnect)===void 0}function Z5(t){if(!ti(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&Y2(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function X5(t){var e;return!!(t&&((e=t[$2])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function Q5(t){var e,r,n,i,o,s,c,a,u,d;return!!(t&&((e=(r=(n=(i=(o=(s=t[K2])!==null&&s!==void 0?s:t.readableErrored)!==null&&o!==void 0?o:t.writableErrored)!==null&&i!==void 0?i:(c=t._readableState)===null||c===void 0?void 0:c.errorEmitted)!==null&&n!==void 0?n:(a=t._writableState)===null||a===void 0?void 0:a.errorEmitted)!==null&&r!==void 0?r:(u=t._readableState)===null||u===void 0?void 0:u.errored)!==null&&e!==void 0?e:!((d=t._writableState)===null||d===void 0)&&d.errored))}J2.exports={isDestroyed:mh,kIsDestroyed:M2,isDisturbed:X5,kIsDisturbed:$2,isErrored:Q5,kIsErrored:K2,isReadable:W2,kIsReadable:tm,kIsClosedPromise:K5,kControllerErrorFunction:$5,kIsWritable:rm,isClosed:Y5,isDuplexNodeStream:H5,isFinished:W5,isIterable:q5,isReadableNodeStream:yh,isReadableStream:H2,isReadableEnded:j5,isReadableFinished:j2,isReadableErrored:z5,isNodeStream:ti,isWebStream:V5,isWritable:G2,isWritableNodeStream:gh,isWritableStream:V2,isWritableEnded:F2,isWritableFinished:F5,isWritableErrored:G5,isServerRequest:J5,isServerResponse:Y2,willEmitClose:Z5,isTransformStream:q2}});var ji=oe((aF,cm)=>{l();var Ho=Ei(),{AbortError:oS,codes:e3}=ir(),{ERR_INVALID_ARG_TYPE:t3,ERR_STREAM_PREMATURE_CLOSE:Z2}=e3,{kEmptyObject:im,once:om}=Jt(),{validateAbortSignal:r3,validateFunction:n3,validateObject:i3,validateBoolean:o3}=Ea(),{Promise:s3,PromisePrototypeThen:c3,SymbolDispose:sS}=nt(),{isClosed:a3,isReadable:X2,isReadableNodeStream:nm,isReadableStream:u3,isReadableFinished:Q2,isReadableErrored:eS,isWritable:tS,isWritableNodeStream:rS,isWritableStream:d3,isWritableFinished:nS,isWritableErrored:iS,isNodeStream:f3,willEmitClose:l3,kIsClosedPromise:h3}=ri(),va;function p3(t){return t.setHeader&&typeof t.abort=="function"}var sm=()=>{};function cS(t,e,r){var n,i;if(arguments.length===2?(r=e,e=im):e==null?e=im:i3(e,"options"),n3(r,"callback"),r3(e.signal,"options.signal"),r=om(r),u3(t)||d3(t))return y3(t,e,r);if(!f3(t))throw new t3("stream",["ReadableStream","WritableStream","Stream"],t);let o=(n=e.readable)!==null&&n!==void 0?n:nm(t),s=(i=e.writable)!==null&&i!==void 0?i:rS(t),c=t._writableState,a=t._readableState,u=()=>{t.writable||h()},d=l3(t)&&nm(t)===o&&rS(t)===s,f=nS(t,!1),h=()=>{f=!0,t.destroyed&&(d=!1),!(d&&(!t.readable||o))&&(!o||p)&&r.call(t)},p=Q2(t,!1),g=()=>{p=!0,t.destroyed&&(d=!1),!(d&&(!t.writable||s))&&(!s||f)&&r.call(t)},y=T=>{r.call(t,T)},E=a3(t),S=()=>{E=!0;let T=iS(t)||eS(t);if(T&&typeof T!="boolean")return r.call(t,T);if(o&&!p&&nm(t,!0)&&!Q2(t,!1))return r.call(t,new Z2);if(s&&!f&&!nS(t,!1))return r.call(t,new Z2);r.call(t)},I=()=>{E=!0;let T=iS(t)||eS(t);if(T&&typeof T!="boolean")return r.call(t,T);r.call(t)},A=()=>{t.req.on("finish",h)};p3(t)?(t.on("complete",h),d||t.on("abort",S),t.req?A():t.on("request",A)):s&&!c&&(t.on("end",u),t.on("close",u)),!d&&typeof t.aborted=="boolean"&&t.on("aborted",S),t.on("end",g),t.on("finish",h),e.error!==!1&&t.on("error",y),t.on("close",S),E?Ho.nextTick(S):c!=null&&c.errorEmitted||a!=null&&a.errorEmitted?d||Ho.nextTick(I):(!o&&(!d||X2(t))&&(f||tS(t)===!1)||!s&&(!d||tS(t))&&(p||X2(t)===!1)||a&&t.req&&t.aborted)&&Ho.nextTick(I);let O=()=>{r=sm,t.removeListener("aborted",S),t.removeListener("complete",h),t.removeListener("abort",S),t.removeListener("request",A),t.req&&t.req.removeListener("finish",h),t.removeListener("end",u),t.removeListener("close",u),t.removeListener("finish",h),t.removeListener("end",g),t.removeListener("error",y),t.removeListener("close",S)};if(e.signal&&!E){let T=()=>{let M=r;O(),M.call(t,new oS(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)Ho.nextTick(T);else{va=va||Jt().addAbortListener;let M=va(e.signal,T),q=r;r=om((...j)=>{M[sS](),q.apply(t,j)})}}return O}function y3(t,e,r){let n=!1,i=sm;if(e.signal)if(i=()=>{n=!0,r.call(t,new oS(void 0,{cause:e.signal.reason}))},e.signal.aborted)Ho.nextTick(i);else{va=va||Jt().addAbortListener;let s=va(e.signal,i),c=r;r=om((...a)=>{s[sS](),c.apply(t,a)})}let o=(...s)=>{n||Ho.nextTick(()=>r.apply(t,s))};return c3(t[h3].promise,o,o),sm}function g3(t,e){var r;let n=!1;return e===null&&(e=im),(r=e)!==null&&r!==void 0&&r.cleanup&&(o3(e.cleanup,"cleanup"),n=e.cleanup),new s3((i,o)=>{let s=cS(t,e,c=>{n&&s(),c?o(c):i()})})}cm.exports=cS;cm.exports.finished=g3});var rc=oe((dF,yS)=>{"use strict";l();var ni=Ei(),{aggregateTwoErrors:m3,codes:{ERR_MULTIPLE_CALLBACK:w3},AbortError:b3}=ir(),{Symbol:dS}=nt(),{kIsDestroyed:x3,isDestroyed:E3,isFinished:v3,isServerRequest:S3}=ri(),fS=dS("kDestroy"),am=dS("kConstruct");function lS(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function A3(t,e){let r=this._readableState,n=this._writableState,i=n||r;return n!=null&&n.destroyed||r!=null&&r.destroyed?(typeof e=="function"&&e(),this):(lS(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?aS(this,t,e):this.once(fS,function(o){aS(this,m3(o,t),e)}),this)}function aS(t,e,r){let n=!1;function i(o){if(n)return;n=!0;let s=t._readableState,c=t._writableState;lS(o,c,s),c&&(c.closed=!0),s&&(s.closed=!0),typeof r=="function"&&r(o),o?ni.nextTick(T3,t,o):ni.nextTick(hS,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function T3(t,e){um(t,e),hS(t)}function hS(t){let e=t._readableState,r=t._writableState;r&&(r.closeEmitted=!0),e&&(e.closeEmitted=!0),(r!=null&&r.emitClose||e!=null&&e.emitClose)&&t.emit("close")}function um(t,e){let r=t._readableState,n=t._writableState;n!=null&&n.errorEmitted||r!=null&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),t.emit("error",e))}function _3(){let t=this._readableState,e=this._writableState;t&&(t.constructed=!0,t.closed=!1,t.closeEmitted=!1,t.destroyed=!1,t.errored=null,t.errorEmitted=!1,t.reading=!1,t.ended=t.readable===!1,t.endEmitted=t.readable===!1),e&&(e.constructed=!0,e.destroyed=!1,e.closed=!1,e.closeEmitted=!1,e.errored=null,e.errorEmitted=!1,e.finalCalled=!1,e.prefinished=!1,e.ended=e.writable===!1,e.ending=e.writable===!1,e.finished=e.writable===!1)}function dm(t,e,r){let n=t._readableState,i=t._writableState;if(i!=null&&i.destroyed||n!=null&&n.destroyed)return this;n!=null&&n.autoDestroy||i!=null&&i.autoDestroy?t.destroy(e):e&&(e.stack,i&&!i.errored&&(i.errored=e),n&&!n.errored&&(n.errored=e),r?ni.nextTick(um,t,e):um(t,e))}function B3(t,e){if(typeof t._construct!="function")return;let r=t._readableState,n=t._writableState;r&&(r.constructed=!1),n&&(n.constructed=!1),t.once(am,e),!(t.listenerCount(am)>1)&&ni.nextTick(I3,t)}function I3(t){let e=!1;function r(n){if(e){dm(t,n??new w3);return}e=!0;let i=t._readableState,o=t._writableState,s=o||i;i&&(i.constructed=!0),o&&(o.constructed=!0),s.destroyed?t.emit(fS,n):n?dm(t,n,!0):ni.nextTick(R3,t)}try{t._construct(n=>{ni.nextTick(r,n)})}catch(n){ni.nextTick(r,n)}}function R3(t){t.emit(am)}function uS(t){return t?.setHeader&&typeof t.abort=="function"}function pS(t){t.emit("close")}function U3(t,e){t.emit("error",e),ni.nextTick(pS,t)}function O3(t,e){!t||E3(t)||(!e&&!v3(t)&&(e=new b3),S3(t)?(t.socket=null,t.destroy(e)):uS(t)?t.abort():uS(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?ni.nextTick(U3,t,e):ni.nextTick(pS,t),t.destroyed||(t[x3]=!0))}yS.exports={construct:B3,destroyer:O3,destroy:A3,undestroy:_3,errorOrDestroy:dm}});var xh=oe((lF,mS)=>{"use strict";l();var{ArrayIsArray:D3,ObjectSetPrototypeOf:gS}=nt(),{EventEmitter:wh}=aa();function bh(t){wh.call(this,t)}gS(bh.prototype,wh.prototype);gS(bh,wh);bh.prototype.pipe=function(t,e){let r=this;function n(d){t.writable&&t.write(d)===!1&&r.pause&&r.pause()}r.on("data",n);function i(){r.readable&&r.resume&&r.resume()}t.on("drain",i),!t._isStdio&&(!e||e.end!==!1)&&(r.on("end",s),r.on("close",c));let o=!1;function s(){o||(o=!0,t.end())}function c(){o||(o=!0,typeof t.destroy=="function"&&t.destroy())}function a(d){u(),wh.listenerCount(this,"error")===0&&this.emit("error",d)}fm(r,"error",a),fm(t,"error",a);function u(){r.removeListener("data",n),t.removeListener("drain",i),r.removeListener("end",s),r.removeListener("close",c),r.removeListener("error",a),t.removeListener("error",a),r.removeListener("end",u),r.removeListener("close",u),t.removeListener("close",u)}return r.on("end",u),r.on("close",u),t.on("close",u),t.emit("pipe",r),t};function fm(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):D3(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}mS.exports={Stream:bh,prependListener:fm}});var Sd=oe((pF,Eh)=>{"use strict";l();var{SymbolDispose:k3}=nt(),{AbortError:wS,codes:N3}=ir(),{isNodeStream:bS,isWebStream:C3,kControllerErrorFunction:L3}=ri(),P3=ji(),{ERR_INVALID_ARG_TYPE:xS}=N3,lm,M3=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new xS(e,"AbortSignal",t)};Eh.exports.addAbortSignal=function(e,r){if(M3(e,"signal"),!bS(r)&&!C3(r))throw new xS("stream",["ReadableStream","WritableStream","Stream"],r);return Eh.exports.addAbortSignalNoValidate(e,r)};Eh.exports.addAbortSignalNoValidate=function(t,e){if(typeof t!="object"||!("aborted"in t))return e;let r=bS(e)?()=>{e.destroy(new wS(void 0,{cause:t.reason}))}:()=>{e[L3](new wS(void 0,{cause:t.reason}))};if(t.aborted)r();else{lm=lm||Jt().addAbortListener;let n=lm(t,r);P3(e,n[k3])}return e}});var SS=oe((mF,vS)=>{"use strict";l();var{StringPrototypeSlice:ES,SymbolIterator:K3,TypedArrayPrototypeSet:vh,Uint8Array:$3}=nt(),{Buffer:hm}=Sr(),{inspect:H3}=Jt();vS.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){let r={data:e,next:null};this.length>0?this.tail.next=r:this.head=r,this.tail=r,++this.length}unshift(e){let r={data:e,next:this.head};this.length===0&&(this.tail=r),this.head=r,++this.length}shift(){if(this.length===0)return;let e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(this.length===0)return"";let r=this.head,n=""+r.data;for(;(r=r.next)!==null;)n+=e+r.data;return n}concat(e){if(this.length===0)return hm.alloc(0);let r=hm.allocUnsafe(e>>>0),n=this.head,i=0;for(;n;)vh(r,n.data,i),i+=n.data.length,n=n.next;return r}consume(e,r){let n=this.head.data;if(e<n.length){let i=n.slice(0,e);return this.head.data=n.slice(e),i}return e===n.length?this.shift():r?this._getString(e):this._getBuffer(e)}first(){return this.head.data}*[K3](){for(let e=this.head;e;e=e.next)yield e.data}_getString(e){let r="",n=this.head,i=0;do{let o=n.data;if(e>o.length)r+=o,e-=o.length;else{e===o.length?(r+=o,++i,n.next?this.head=n.next:this.head=this.tail=null):(r+=ES(o,0,e),this.head=n,n.data=ES(o,e));break}++i}while((n=n.next)!==null);return this.length-=i,r}_getBuffer(e){let r=hm.allocUnsafe(e),n=e,i=this.head,o=0;do{let s=i.data;if(e>s.length)vh(r,s,n-e),e-=s.length;else{e===s.length?(vh(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(vh(r,new $3(s.buffer,s.byteOffset,e),n-e),this.head=i,i.data=s.slice(e));break}++o}while((i=i.next)!==null);return this.length-=o,r}[Symbol.for("nodejs.util.inspect.custom")](e,r){return H3(this,{...r,depth:0,customInspect:!1})}}});var Ad=oe((bF,BS)=>{"use strict";l();var{MathFloor:V3,NumberIsInteger:q3}=nt(),{validateInteger:F3}=Ea(),{ERR_INVALID_ARG_VALUE:j3}=ir().codes,AS=16*1024,TS=16;function W3(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function _S(t){return t?TS:AS}function G3(t,e){F3(e,"value",0),t?TS=e:AS=e}function z3(t,e,r,n){let i=W3(e,n,r);if(i!=null){if(!q3(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new j3(o,i)}return V3(i)}return _S(t.objectMode)}BS.exports={getHighWaterMark:z3,getDefaultHighWaterMark:_S,setDefaultHighWaterMark:G3}});var US=oe((pm,RS)=>{l();var Sh=Sr(),ii=Sh.Buffer;function IS(t,e){for(var r in t)e[r]=t[r]}ii.from&&ii.alloc&&ii.allocUnsafe&&ii.allocUnsafeSlow?RS.exports=Sh:(IS(Sh,pm),pm.Buffer=nc);function nc(t,e,r){return ii(t,e,r)}nc.prototype=Object.create(ii.prototype);IS(ii,nc);nc.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return ii(t,e,r)};nc.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=ii(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};nc.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ii(t)};nc.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Sh.SlowBuffer(t)}});var kS=oe(DS=>{"use strict";l();var gm=US().Buffer,OS=gm.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function Y3(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function J3(t){var e=Y3(t);if(typeof e!="string"&&(gm.isEncoding===OS||!OS(t)))throw new Error("Unknown encoding: "+t);return e||t}DS.StringDecoder=Td;function Td(t){this.encoding=J3(t);var e;switch(this.encoding){case"utf16le":this.text=rO,this.end=nO,e=4;break;case"utf8":this.fillLast=Q3,e=4;break;case"base64":this.text=iO,this.end=oO,e=3;break;default:this.write=sO,this.end=cO;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=gm.allocUnsafe(e)}Td.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<t.length?e?e+this.text(t,r):this.text(t,r):e||""};Td.prototype.end=tO;Td.prototype.text=eO;Td.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};function ym(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function Z3(t,e,r){var n=e.length-1;if(n<r)return 0;var i=ym(e[n]);return i>=0?(i>0&&(t.lastNeed=i-1),i):--n<r||i===-2?0:(i=ym(e[n]),i>=0?(i>0&&(t.lastNeed=i-2),i):--n<r||i===-2?0:(i=ym(e[n]),i>=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function X3(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function Q3(t){var e=this.lastTotal-this.lastNeed,r=X3(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function eO(t,e){var r=Z3(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function tO(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function rO(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function nO(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function iO(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function oO(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function sO(t){return t.toString(this.encoding)}function cO(t){return t&&t.length?this.write(t):""}});var mm=oe((AF,PS)=>{"use strict";l();var NS=Ei(),{PromisePrototypeThen:aO,SymbolAsyncIterator:CS,SymbolIterator:LS}=nt(),{Buffer:uO}=Sr(),{ERR_INVALID_ARG_TYPE:dO,ERR_STREAM_NULL_VALUES:fO}=ir().codes;function lO(t,e,r){let n;if(typeof e=="string"||e instanceof uO)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[CS])i=!0,n=e[CS]();else if(e&&e[LS])i=!1,n=e[LS]();else throw new dO("iterable",["Iterable"],e);let o=new t({objectMode:!0,highWaterMark:1,...r}),s=!1;o._read=function(){s||(s=!0,a())},o._destroy=function(u,d){aO(c(u),()=>NS.nextTick(d,u),f=>NS.nextTick(d,f||u))};async function c(u){let d=u!=null,f=typeof n.throw=="function";if(d&&f){let{value:h,done:p}=await n.throw(u);if(await h,p)return}if(typeof n.return=="function"){let{value:h}=await n.return();await h}}async function a(){for(;;){try{let{value:u,done:d}=i?await n.next():n.next();if(d)o.push(null);else{let f=u&&typeof u.then=="function"?await u:u;if(f===null)throw s=!1,new fO;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}PS.exports=lO});var Bd=oe((_F,tA)=>{l();var An=Ei(),{ArrayPrototypeIndexOf:hO,NumberIsInteger:pO,NumberIsNaN:yO,NumberParseInt:gO,ObjectDefineProperties:Tm,ObjectKeys:mO,ObjectSetPrototypeOf:$S,Promise:HS,SafeSet:wO,SymbolAsyncDispose:bO,SymbolAsyncIterator:xO,Symbol:EO}=nt();tA.exports=ye;ye.ReadableState=Bh;var{EventEmitter:vO}=aa(),{Stream:Vo,prependListener:SO}=xh(),{Buffer:wm}=Sr(),{addAbortSignal:AO}=Sd(),VS=ji(),be=Jt().debuglog("stream",t=>{be=t}),TO=SS(),Ta=rc(),{getHighWaterMark:_O,getDefaultHighWaterMark:BO}=Ad(),{aggregateTwoErrors:MS,codes:{ERR_INVALID_ARG_TYPE:IO,ERR_METHOD_NOT_IMPLEMENTED:RO,ERR_OUT_OF_RANGE:UO,ERR_STREAM_PUSH_AFTER_EOF:OO,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:DO},AbortError:kO}=ir(),{validateObject:NO}=Ea(),ic=EO("kPaused"),{StringDecoder:qS}=kS(),CO=mm();$S(ye.prototype,Vo.prototype);$S(ye,Vo);var bm=()=>{},{errorOrDestroy:Sa}=Ta,Aa=1,LO=2,FS=4,_d=8,jS=16,Ah=32,Th=64,WS=128,PO=256,MO=512,KO=1024,Sm=2048,Am=4096,$O=8192,HO=16384,VO=32768,GS=65536,qO=1<<17,FO=1<<18;function St(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}Tm(Bh.prototype,{objectMode:St(Aa),ended:St(LO),endEmitted:St(FS),reading:St(_d),constructed:St(jS),sync:St(Ah),needReadable:St(Th),emittedReadable:St(WS),readableListening:St(PO),resumeScheduled:St(MO),errorEmitted:St(KO),emitClose:St(Sm),autoDestroy:St(Am),destroyed:St($O),closed:St(HO),closeEmitted:St(VO),multiAwaitDrain:St(GS),readingMore:St(qO),dataEmitted:St(FO)});function Bh(t,e,r){typeof r!="boolean"&&(r=e instanceof oi()),this.state=Sm|Am|jS|Ah,t&&t.objectMode&&(this.state|=Aa),r&&t&&t.readableObjectMode&&(this.state|=Aa),this.highWaterMark=t?_O(this,t,"readableHighWaterMark",r):BO(!1),this.buffer=new TO,this.length=0,this.pipes=[],this.flowing=null,this[ic]=null,t&&t.emitClose===!1&&(this.state&=~Sm),t&&t.autoDestroy===!1&&(this.state&=~Am),this.errored=null,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,t&&t.encoding&&(this.decoder=new qS(t.encoding),this.encoding=t.encoding)}function ye(t){if(!(this instanceof ye))return new ye(t);let e=this instanceof oi();this._readableState=new Bh(t,this,e),t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&!e&&AO(t.signal,this)),Vo.call(this,t),Ta.construct(this,()=>{this._readableState.needReadable&&_h(this,this._readableState)})}ye.prototype.destroy=Ta.destroy;ye.prototype._undestroy=Ta.undestroy;ye.prototype._destroy=function(t,e){e(t)};ye.prototype[vO.captureRejectionSymbol]=function(t){this.destroy(t)};ye.prototype[bO]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new kO,this.destroy(t)),new HS((e,r)=>VS(this,n=>n&&n!==t?r(n):e(null)))};ye.prototype.push=function(t,e){return zS(this,t,e,!1)};ye.prototype.unshift=function(t,e){return zS(this,t,e,!0)};function zS(t,e,r,n){be("readableAddChunk",e);let i=t._readableState,o;if(i.state&Aa||(typeof e=="string"?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?e=wm.from(e,r).toString(i.encoding):(e=wm.from(e,r),r=""))):e instanceof wm?r="":Vo._isUint8Array(e)?(e=Vo._uint8ArrayToBuffer(e),r=""):e!=null&&(o=new IO("chunk",["string","Buffer","Uint8Array"],e))),o)Sa(t,o);else if(e===null)i.state&=~_d,GO(t,i);else if(i.state&Aa||e&&e.length>0)if(n)if(i.state&FS)Sa(t,new DO);else{if(i.destroyed||i.errored)return!1;xm(t,i,e,!0)}else if(i.ended)Sa(t,new OO);else{if(i.destroyed||i.errored)return!1;i.state&=~_d,i.decoder&&!r?(e=i.decoder.write(e),i.objectMode||e.length!==0?xm(t,i,e,!1):_h(t,i)):xm(t,i,e,!1)}else n||(i.state&=~_d,_h(t,i));return!i.ended&&(i.length<i.highWaterMark||i.length===0)}function xm(t,e,r,n){e.flowing&&e.length===0&&!e.sync&&t.listenerCount("data")>0?(e.state&GS?e.awaitDrainWriters.clear():e.awaitDrainWriters=null,e.dataEmitted=!0,t.emit("data",r)):(e.length+=e.objectMode?1:r.length,n?e.buffer.unshift(r):e.buffer.push(r),e.state&Th&&Ih(t)),_h(t,e)}ye.prototype.isPaused=function(){let t=this._readableState;return t[ic]===!0||t.flowing===!1};ye.prototype.setEncoding=function(t){let e=new qS(t);this._readableState.decoder=e,this._readableState.encoding=this._readableState.decoder.encoding;let r=this._readableState.buffer,n="";for(let i of r)n+=e.write(i);return r.clear(),n!==""&&r.push(n),this._readableState.length=n.length,this};var jO=1073741824;function WO(t){if(t>jO)throw new UO("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function KS(t,e){return t<=0||e.length===0&&e.ended?0:e.state&Aa?1:yO(t)?e.flowing&&e.length?e.buffer.first().length:e.length:t<=e.length?t:e.ended?e.length:0}ye.prototype.read=function(t){be("read",t),t===void 0?t=NaN:pO(t)||(t=gO(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=WO(t)),t!==0&&(e.state&=~WS),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return be("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?Em(this):Ih(this),null;if(t=KS(t,e),t===0&&e.ended)return e.length===0&&Em(this),null;let n=(e.state&Th)!==0;if(be("need readable",n),(e.length===0||e.length-t<e.highWaterMark)&&(n=!0,be("length less than watermark",n)),e.ended||e.reading||e.destroyed||e.errored||!e.constructed)n=!1,be("reading, ended or constructing",n);else if(n){be("do read"),e.state|=_d|Ah,e.length===0&&(e.state|=Th);try{this._read(e.highWaterMark)}catch(o){Sa(this,o)}e.state&=~Ah,e.reading||(t=KS(r,e))}let i;return t>0?i=QS(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.multiAwaitDrain?e.awaitDrainWriters.clear():e.awaitDrainWriters=null),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Em(this)),i!==null&&!e.errorEmitted&&!e.closeEmitted&&(e.dataEmitted=!0,this.emit("data",i)),i};function GO(t,e){if(be("onEofChunk"),!e.ended){if(e.decoder){let r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?Ih(t):(e.needReadable=!1,e.emittedReadable=!0,YS(t))}}function Ih(t){let e=t._readableState;be("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(be("emitReadable",e.flowing),e.emittedReadable=!0,An.nextTick(YS,t))}function YS(t){let e=t._readableState;be("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&!e.errored&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,ZS(t)}function _h(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,An.nextTick(zO,t,e))}function zO(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&e.length===0);){let r=e.length;if(be("maybeReadMore read 0"),t.read(0),r===e.length)break}e.readingMore=!1}ye.prototype._read=function(t){throw new RO("_read()")};ye.prototype.pipe=function(t,e){let r=this,n=this._readableState;n.pipes.length===1&&(n.multiAwaitDrain||(n.multiAwaitDrain=!0,n.awaitDrainWriters=new wO(n.awaitDrainWriters?[n.awaitDrainWriters]:[]))),n.pipes.push(t),be("pipe count=%d opts=%j",n.pipes.length,e);let o=(!e||e.end!==!1)&&t!==An.stdout&&t!==An.stderr?c:E;n.endEmitted?An.nextTick(o):r.once("end",o),t.on("unpipe",s);function s(S,I){be("onunpipe"),S===r&&I&&I.hasUnpiped===!1&&(I.hasUnpiped=!0,d())}function c(){be("onend"),t.end()}let a,u=!1;function d(){be("cleanup"),t.removeListener("close",g),t.removeListener("finish",y),a&&t.removeListener("drain",a),t.removeListener("error",p),t.removeListener("unpipe",s),r.removeListener("end",c),r.removeListener("end",E),r.removeListener("data",h),u=!0,a&&n.awaitDrainWriters&&(!t._writableState||t._writableState.needDrain)&&a()}function f(){u||(n.pipes.length===1&&n.pipes[0]===t?(be("false write response, pause",0),n.awaitDrainWriters=t,n.multiAwaitDrain=!1):n.pipes.length>1&&n.pipes.includes(t)&&(be("false write response, pause",n.awaitDrainWriters.size),n.awaitDrainWriters.add(t)),r.pause()),a||(a=YO(r,t),t.on("drain",a))}r.on("data",h);function h(S){be("ondata");let I=t.write(S);be("dest.write",I),I===!1&&f()}function p(S){if(be("onerror",S),E(),t.removeListener("error",p),t.listenerCount("error")===0){let I=t._writableState||t._readableState;I&&!I.errorEmitted?Sa(t,S):t.emit("error",S)}}SO(t,"error",p);function g(){t.removeListener("finish",y),E()}t.once("close",g);function y(){be("onfinish"),t.removeListener("close",g),E()}t.once("finish",y);function E(){be("unpipe"),r.unpipe(t)}return t.emit("pipe",r),t.writableNeedDrain===!0?f():n.flowing||(be("pipe resume"),r.resume()),t};function YO(t,e){return function(){let n=t._readableState;n.awaitDrainWriters===e?(be("pipeOnDrain",1),n.awaitDrainWriters=null):n.multiAwaitDrain&&(be("pipeOnDrain",n.awaitDrainWriters.size),n.awaitDrainWriters.delete(e)),(!n.awaitDrainWriters||n.awaitDrainWriters.size===0)&&t.listenerCount("data")&&t.resume()}}ye.prototype.unpipe=function(t){let e=this._readableState,r={hasUnpiped:!1};if(e.pipes.length===0)return this;if(!t){let i=e.pipes;e.pipes=[],this.pause();for(let o=0;o<i.length;o++)i[o].emit("unpipe",this,{hasUnpiped:!1});return this}let n=hO(e.pipes,t);return n===-1?this:(e.pipes.splice(n,1),e.pipes.length===0&&this.pause(),t.emit("unpipe",this,r),this)};ye.prototype.on=function(t,e){let r=Vo.prototype.on.call(this,t,e),n=this._readableState;return t==="data"?(n.readableListening=this.listenerCount("readable")>0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,be("on readable",n.length,n.reading),n.length?Ih(this):n.reading||An.nextTick(JO,this)),r};ye.prototype.addListener=ye.prototype.on;ye.prototype.removeListener=function(t,e){let r=Vo.prototype.removeListener.call(this,t,e);return t==="readable"&&An.nextTick(JS,this),r};ye.prototype.off=ye.prototype.removeListener;ye.prototype.removeAllListeners=function(t){let e=Vo.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&An.nextTick(JS,this),e};function JS(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[ic]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function JO(t){be("readable nexttick read 0"),t.read(0)}ye.prototype.resume=function(){let t=this._readableState;return t.flowing||(be("resume"),t.flowing=!t.readableListening,ZO(this,t)),t[ic]=!1,this};function ZO(t,e){e.resumeScheduled||(e.resumeScheduled=!0,An.nextTick(XO,t,e))}function XO(t,e){be("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),ZS(t),e.flowing&&!e.reading&&t.read(0)}ye.prototype.pause=function(){return be("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(be("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[ic]=!0,this};function ZS(t){let e=t._readableState;for(be("flow",e.flowing);e.flowing&&t.read()!==null;);}ye.prototype.wrap=function(t){let e=!1;t.on("data",n=>{!this.push(n)&&t.pause&&(e=!0,t.pause())}),t.on("end",()=>{this.push(null)}),t.on("error",n=>{Sa(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=mO(t);for(let n=1;n<r.length;n++){let i=r[n];this[i]===void 0&&typeof t[i]=="function"&&(this[i]=t[i].bind(t))}return this};ye.prototype[xO]=function(){return XS(this)};ye.prototype.iterator=function(t){return t!==void 0&&NO(t,"options"),XS(this,t)};function XS(t,e){typeof t.read!="function"&&(t=ye.wrap(t,{objectMode:!0}));let r=QO(t,e);return r.stream=t,r}async function*QO(t,e){let r=bm;function n(s){this===t?(r(),r=bm):r=s}t.on("readable",n);let i,o=VS(t,{writable:!1},s=>{i=s?MS(i,s):null,r(),r=bm});try{for(;;){let s=t.destroyed?null:t.read();if(s!==null)yield s;else{if(i)throw i;if(i===null)return;await new HS(n)}}}catch(s){throw i=MS(i,s),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?Ta.destroyer(t,null):(t.off("readable",n),o())}}Tm(ye.prototype,{readable:{__proto__:null,get(){let t=this._readableState;return!!t&&t.readable!==!1&&!t.destroyed&&!t.errorEmitted&&!t.endEmitted},set(t){this._readableState&&(this._readableState.readable=!!t)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(t){this._readableState&&(this._readableState.flowing=t)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(t){this._readableState&&(this._readableState.destroyed=t)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});Tm(Bh.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[ic]!==!1},set(t){this[ic]=!!t}}});ye._fromList=QS;function QS(t,e){if(e.length===0)return null;let r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Em(t){let e=t._readableState;be("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,An.nextTick(eD,e,t))}function eD(t,e){if(be("endReadableNT",t.endEmitted,t.length),!t.errored&&!t.closeEmitted&&!t.endEmitted&&t.length===0){if(t.endEmitted=!0,e.emit("end"),e.writable&&e.allowHalfOpen===!1)An.nextTick(tD,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function tD(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}ye.from=function(t,e){return CO(ye,t,e)};var vm;function eA(){return vm===void 0&&(vm={}),vm}ye.fromWeb=function(t,e){return eA().newStreamReadableFromReadableStream(t,e)};ye.toWeb=function(t,e){return eA().newReadableStreamFromStreamReadable(t,e)};ye.wrap=function(t,e){var r,n;return new ye({objectMode:(r=(n=t.readableObjectMode)!==null&&n!==void 0?n:t.objectMode)!==null&&r!==void 0?r:!0,...e,destroy(i,o){Ta.destroyer(t,i),o(i)}}).wrap(t)}});var kh=oe((IF,hA)=>{l();var oc=Ei(),{ArrayPrototypeSlice:iA,Error:rD,FunctionPrototypeSymbolHasInstance:oA,ObjectDefineProperty:sA,ObjectDefineProperties:nD,ObjectSetPrototypeOf:cA,StringPrototypeToLowerCase:iD,Symbol:oD,SymbolHasInstance:sD}=nt();hA.exports=it;it.WritableState=Ud;var{EventEmitter:cD}=aa(),Id=xh().Stream,{Buffer:Rh}=Sr(),Dh=rc(),{addAbortSignal:aD}=Sd(),{getHighWaterMark:uD,getDefaultHighWaterMark:dD}=Ad(),{ERR_INVALID_ARG_TYPE:fD,ERR_METHOD_NOT_IMPLEMENTED:lD,ERR_MULTIPLE_CALLBACK:aA,ERR_STREAM_CANNOT_PIPE:hD,ERR_STREAM_DESTROYED:Rd,ERR_STREAM_ALREADY_FINISHED:pD,ERR_STREAM_NULL_VALUES:yD,ERR_STREAM_WRITE_AFTER_END:gD,ERR_UNKNOWN_ENCODING:uA}=ir().codes,{errorOrDestroy:_a}=Dh;cA(it.prototype,Id.prototype);cA(it,Id);function Im(){}var Ba=oD("kOnFinished");function Ud(t,e,r){typeof r!="boolean"&&(r=e instanceof oi()),this.objectMode=!!(t&&t.objectMode),r&&(this.objectMode=this.objectMode||!!(t&&t.writableObjectMode)),this.highWaterMark=t?uD(this,t,"writableHighWaterMark",r):dD(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let n=!!(t&&t.decodeStrings===!1);this.decodeStrings=!n,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=wD.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,Oh(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!t||t.emitClose!==!1,this.autoDestroy=!t||t.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[Ba]=[]}function Oh(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Ud.prototype.getBuffer=function(){return iA(this.buffered,this.bufferedIndex)};sA(Ud.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function it(t){let e=this instanceof oi();if(!e&&!oA(it,this))return new it(t);this._writableState=new Ud(t,this,e),t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&aD(t.signal,this)),Id.call(this,t),Dh.construct(this,()=>{let r=this._writableState;r.writing||Um(this,r),Om(this,r)})}sA(it,sD,{__proto__:null,value:function(t){return oA(this,t)?!0:this!==it?!1:t&&t._writableState instanceof Ud}});it.prototype.pipe=function(){_a(this,new hD)};function dA(t,e,r,n){let i=t._writableState;if(typeof r=="function")n=r,r=i.defaultEncoding;else{if(!r)r=i.defaultEncoding;else if(r!=="buffer"&&!Rh.isEncoding(r))throw new uA(r);typeof n!="function"&&(n=Im)}if(e===null)throw new yD;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=Rh.from(e,r),r="buffer");else if(e instanceof Rh)r="buffer";else if(Id._isUint8Array(e))e=Id._uint8ArrayToBuffer(e),r="buffer";else throw new fD("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new gD:i.destroyed&&(o=new Rd("write")),o?(oc.nextTick(n,o),_a(t,o,!0),o):(i.pendingcb++,mD(t,i,e,r,n))}it.prototype.write=function(t,e,r){return dA(this,t,e,r)===!0};it.prototype.cork=function(){this._writableState.corked++};it.prototype.uncork=function(){let t=this._writableState;t.corked&&(t.corked--,t.writing||Um(this,t))};it.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=iD(e)),!Rh.isEncoding(e))throw new uA(e);return this._writableState.defaultEncoding=e,this};function mD(t,e,r,n,i){let o=e.objectMode?1:r.length;e.length+=o;let s=e.length<e.highWaterMark;return s||(e.needDrain=!0),e.writing||e.corked||e.errored||!e.constructed?(e.buffered.push({chunk:r,encoding:n,callback:i}),e.allBuffers&&n!=="buffer"&&(e.allBuffers=!1),e.allNoop&&i!==Im&&(e.allNoop=!1)):(e.writelen=o,e.writecb=i,e.writing=!0,e.sync=!0,t._write(r,n,e.onwrite),e.sync=!1),s&&!e.errored&&!e.destroyed}function rA(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new Rd("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function nA(t,e,r,n){--e.pendingcb,n(r),Rm(e),_a(t,r)}function wD(t,e){let r=t._writableState,n=r.sync,i=r.writecb;if(typeof i!="function"){_a(t,new aA);return}r.writing=!1,r.writecb=null,r.length-=r.writelen,r.writelen=0,e?(e.stack,r.errored||(r.errored=e),t._readableState&&!t._readableState.errored&&(t._readableState.errored=e),n?oc.nextTick(nA,t,r,e,i):nA(t,r,e,i)):(r.buffered.length>r.bufferedIndex&&Um(t,r),n?r.afterWriteTickInfo!==null&&r.afterWriteTickInfo.cb===i?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:i,stream:t,state:r},oc.nextTick(bD,r.afterWriteTickInfo)):fA(t,r,1,i))}function bD({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,fA(t,e,r,n)}function fA(t,e,r,n){for(!e.ending&&!t.destroyed&&e.length===0&&e.needDrain&&(e.needDrain=!1,t.emit("drain"));r-- >0;)e.pendingcb--,n();e.destroyed&&Rm(e),Om(t,e)}function Rm(t){if(t.writing)return;for(let i=t.bufferedIndex;i<t.buffered.length;++i){var e;let{chunk:o,callback:s}=t.buffered[i],c=t.objectMode?1:o.length;t.length-=c,s((e=t.errored)!==null&&e!==void 0?e:new Rd("write"))}let r=t[Ba].splice(0);for(let i=0;i<r.length;i++){var n;r[i]((n=t.errored)!==null&&n!==void 0?n:new Rd("end"))}Oh(t)}function Um(t,e){if(e.corked||e.bufferProcessing||e.destroyed||!e.constructed)return;let{buffered:r,bufferedIndex:n,objectMode:i}=e,o=r.length-n;if(!o)return;let s=n;if(e.bufferProcessing=!0,o>1&&t._writev){e.pendingcb-=o-1;let c=e.allNoop?Im:u=>{for(let d=s;d<r.length;++d)r[d].callback(u)},a=e.allNoop&&s===0?r:iA(r,s);a.allBuffers=e.allBuffers,rA(t,e,!0,e.length,a,"",c),Oh(e)}else{do{let{chunk:c,encoding:a,callback:u}=r[s];r[s++]=null;let d=i?1:c.length;rA(t,e,!1,d,c,a,u)}while(s<r.length&&!e.writing);s===r.length?Oh(e):s>256?(r.splice(0,s),e.bufferedIndex=0):e.bufferedIndex=s}e.bufferProcessing=!1}it.prototype._write=function(t,e,r){if(this._writev)this._writev([{chunk:t,encoding:e}],r);else throw new lD("_write()")};it.prototype._writev=null;it.prototype.end=function(t,e,r){let n=this._writableState;typeof t=="function"?(r=t,t=null,e=null):typeof e=="function"&&(r=e,e=null);let i;if(t!=null){let o=dA(this,t,e);o instanceof rD&&(i=o)}return n.corked&&(n.corked=1,this.uncork()),i||(!n.errored&&!n.ending?(n.ending=!0,Om(this,n,!0),n.ended=!0):n.finished?i=new pD("end"):n.destroyed&&(i=new Rd("end"))),typeof r=="function"&&(i||n.finished?oc.nextTick(r,i):n[Ba].push(r)),this};function Uh(t){return t.ending&&!t.destroyed&&t.constructed&&t.length===0&&!t.errored&&t.buffered.length===0&&!t.finished&&!t.writing&&!t.errorEmitted&&!t.closeEmitted}function xD(t,e){let r=!1;function n(i){if(r){_a(t,i??aA());return}if(r=!0,e.pendingcb--,i){let o=e[Ba].splice(0);for(let s=0;s<o.length;s++)o[s](i);_a(t,i,e.sync)}else Uh(e)&&(e.prefinished=!0,t.emit("prefinish"),e.pendingcb++,oc.nextTick(Bm,t,e))}e.sync=!0,e.pendingcb++;try{t._final(n)}catch(i){n(i)}e.sync=!1}function ED(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,xD(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function Om(t,e,r){Uh(e)&&(ED(t,e),e.pendingcb===0&&(r?(e.pendingcb++,oc.nextTick((n,i)=>{Uh(i)?Bm(n,i):i.pendingcb--},t,e)):Uh(e)&&(e.pendingcb++,Bm(t,e))))}function Bm(t,e){e.pendingcb--,e.finished=!0;let r=e[Ba].splice(0);for(let n=0;n<r.length;n++)r[n]();if(t.emit("finish"),e.autoDestroy){let n=t._readableState;(!n||n.autoDestroy&&(n.endEmitted||n.readable===!1))&&t.destroy()}}nD(it.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(t){this._writableState&&(this._writableState.destroyed=t)}},writable:{__proto__:null,get(){let t=this._writableState;return!!t&&t.writable!==!1&&!t.destroyed&&!t.errored&&!t.ending&&!t.ended},set(t){this._writableState&&(this._writableState.writable=!!t)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let t=this._writableState;return t?!t.destroyed&&!t.ending&&t.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var vD=Dh.destroy;it.prototype.destroy=function(t,e){let r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[Ba].length)&&oc.nextTick(Rm,r),vD.call(this,t,e),this};it.prototype._undestroy=Dh.undestroy;it.prototype._destroy=function(t,e){e(t)};it.prototype[cD.captureRejectionSymbol]=function(t){this.destroy(t)};var _m;function lA(){return _m===void 0&&(_m={}),_m}it.fromWeb=function(t,e){return lA().newStreamWritableFromWritableStream(t,e)};it.toWeb=function(t){return lA().newWritableStreamFromStreamWritable(t)}});var IA=oe((UF,BA)=>{l();var Dm=Ei(),SD=Sr(),{isReadable:AD,isWritable:TD,isIterable:pA,isNodeStream:_D,isReadableNodeStream:yA,isWritableNodeStream:gA,isDuplexNodeStream:BD,isReadableStream:mA,isWritableStream:wA}=ri(),bA=ji(),{AbortError:TA,codes:{ERR_INVALID_ARG_TYPE:ID,ERR_INVALID_RETURN_VALUE:xA}}=ir(),{destroyer:Ra}=rc(),RD=oi(),_A=Bd(),UD=kh(),{createDeferredPromise:EA}=Jt(),vA=mm(),SA=globalThis.Blob||SD.Blob,OD=typeof SA<"u"?function(e){return e instanceof SA}:function(e){return!1},DD=globalThis.AbortController||ba().AbortController,{FunctionPrototypeCall:AA}=nt(),qo=class extends RD{constructor(e){super(e),e?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),e?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};BA.exports=function t(e,r){if(BD(e))return e;if(yA(e))return Ia({readable:e});if(gA(e))return Ia({writable:e});if(_D(e))return Ia({writable:!1,readable:!1});if(mA(e))return Ia({readable:_A.fromWeb(e)});if(wA(e))return Ia({writable:UD.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=kD(e);if(pA(i))return vA(qo,i,{objectMode:!0,write:o,final:s,destroy:c});let a=i?.then;if(typeof a=="function"){let u,d=AA(a,i,f=>{if(f!=null)throw new xA("nully","body",f)},f=>{Ra(u,f)});return u=new qo({objectMode:!0,readable:!1,write:o,final(f){s(async()=>{try{await d,Dm.nextTick(f,null)}catch(h){Dm.nextTick(f,h)}})},destroy:c})}throw new xA("Iterable, AsyncIterable or AsyncFunction",r,i)}if(OD(e))return t(e.arrayBuffer());if(pA(e))return vA(qo,e,{objectMode:!0,writable:!1});if(mA(e?.readable)&&wA(e?.writable))return qo.fromWeb(e);if(typeof e?.writable=="object"||typeof e?.readable=="object"){let i=e!=null&&e.readable?yA(e?.readable)?e?.readable:t(e.readable):void 0,o=e!=null&&e.writable?gA(e?.writable)?e?.writable:t(e.writable):void 0;return Ia({readable:i,writable:o})}let n=e?.then;if(typeof n=="function"){let i;return AA(n,e,o=>{o!=null&&i.push(o),i.push(null)},o=>{Ra(i,o)}),i=new qo({objectMode:!0,writable:!1,read(){}})}throw new ID(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function kD(t){let{promise:e,resolve:r}=EA(),n=new DD,i=n.signal;return{value:t(async function*(){for(;;){let s=e;e=null;let{chunk:c,done:a,cb:u}=await s;if(Dm.nextTick(u),a)return;if(i.aborted)throw new TA(void 0,{cause:i.reason});({promise:e,resolve:r}=EA()),yield c}}(),{signal:i}),write(s,c,a){let u=r;r=null,u({chunk:s,done:!1,cb:a})},final(s){let c=r;r=null,c({done:!0,cb:s})},destroy(s,c){n.abort(),c(s)}}}function Ia(t){let e=t.readable&&typeof t.readable.read!="function"?_A.wrap(t.readable):t.readable,r=t.writable,n=!!AD(e),i=!!TD(r),o,s,c,a,u;function d(f){let h=a;a=null,h?h(f):f&&u.destroy(f)}return u=new qo({readableObjectMode:!!(e!=null&&e.readableObjectMode),writableObjectMode:!!(r!=null&&r.writableObjectMode),readable:n,writable:i}),i&&(bA(r,f=>{i=!1,f&&Ra(e,f),d(f)}),u._write=function(f,h,p){r.write(f,h)?p():o=p},u._final=function(f){r.end(),s=f},r.on("drain",function(){if(o){let f=o;o=null,f()}}),r.on("finish",function(){if(s){let f=s;s=null,f()}})),n&&(bA(e,f=>{n=!1,f&&Ra(e,f),d(f)}),e.on("readable",function(){if(c){let f=c;c=null,f()}}),e.on("end",function(){u.push(null)}),u._read=function(){for(;;){let f=e.read();if(f===null){c=u._read;return}if(!u.push(f))return}}),u._destroy=function(f,h){!f&&a!==null&&(f=new TA),c=null,o=null,s=null,a===null?h(f):(a=h,Ra(r,f),Ra(e,f))},u}});var oi=oe((DF,OA)=>{"use strict";l();var{ObjectDefineProperties:ND,ObjectGetOwnPropertyDescriptor:Wi,ObjectKeys:CD,ObjectSetPrototypeOf:RA}=nt();OA.exports=Tn;var Cm=Bd(),tn=kh();RA(Tn.prototype,Cm.prototype);RA(Tn,Cm);{let t=CD(tn.prototype);for(let e=0;e<t.length;e++){let r=t[e];Tn.prototype[r]||(Tn.prototype[r]=tn.prototype[r])}}function Tn(t){if(!(this instanceof Tn))return new Tn(t);Cm.call(this,t),tn.call(this,t),t?(this.allowHalfOpen=t.allowHalfOpen!==!1,t.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),t.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}ND(Tn.prototype,{writable:{__proto__:null,...Wi(tn.prototype,"writable")},writableHighWaterMark:{__proto__:null,...Wi(tn.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...Wi(tn.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...Wi(tn.prototype,"writableBuffer")},writableLength:{__proto__:null,...Wi(tn.prototype,"writableLength")},writableFinished:{__proto__:null,...Wi(tn.prototype,"writableFinished")},writableCorked:{__proto__:null,...Wi(tn.prototype,"writableCorked")},writableEnded:{__proto__:null,...Wi(tn.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...Wi(tn.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(t){this._readableState&&this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}});var km;function UA(){return km===void 0&&(km={}),km}Tn.fromWeb=function(t,e){return UA().newStreamDuplexFromReadableWritablePair(t,e)};Tn.toWeb=function(t){return UA().newReadableWritablePairFromDuplex(t)};var Nm;Tn.from=function(t){return Nm||(Nm=IA()),Nm(t,"body")}});var Mm=oe((NF,kA)=>{"use strict";l();var{ObjectSetPrototypeOf:DA,Symbol:LD}=nt();kA.exports=Gi;var{ERR_METHOD_NOT_IMPLEMENTED:PD}=ir().codes,Pm=oi(),{getHighWaterMark:MD}=Ad();DA(Gi.prototype,Pm.prototype);DA(Gi,Pm);var Od=LD("kCallback");function Gi(t){if(!(this instanceof Gi))return new Gi(t);let e=t?MD(this,t,"readableHighWaterMark",!0):null;e===0&&(t={...t,highWaterMark:null,readableHighWaterMark:e,writableHighWaterMark:t.writableHighWaterMark||0}),Pm.call(this,t),this._readableState.sync=!1,this[Od]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",KD)}function Lm(t){typeof this._flush=="function"&&!this.destroyed?this._flush((e,r)=>{if(e){t?t(e):this.destroy(e);return}r!=null&&this.push(r),this.push(null),t&&t()}):(this.push(null),t&&t())}function KD(){this._final!==Lm&&Lm.call(this)}Gi.prototype._final=Lm;Gi.prototype._transform=function(t,e,r){throw new PD("_transform()")};Gi.prototype._write=function(t,e,r){let n=this._readableState,i=this._writableState,o=n.length;this._transform(t,e,(s,c)=>{if(s){r(s);return}c!=null&&this.push(c),i.ended||o===n.length||n.length<n.highWaterMark?r():this[Od]=r})};Gi.prototype._read=function(){if(this[Od]){let t=this[Od];this[Od]=null,t()}}});var $m=oe((LF,CA)=>{"use strict";l();var{ObjectSetPrototypeOf:NA}=nt();CA.exports=Ua;var Km=Mm();NA(Ua.prototype,Km.prototype);NA(Ua,Km);function Ua(t){if(!(this instanceof Ua))return new Ua(t);Km.call(this,t)}Ua.prototype._transform=function(t,e,r){r(null,t)}});var Ph=oe((MF,$A)=>{l();var Dd=Ei(),{ArrayIsArray:$D,Promise:HD,SymbolAsyncIterator:VD,SymbolDispose:qD}=nt(),Lh=ji(),{once:FD}=Jt(),jD=rc(),LA=oi(),{aggregateTwoErrors:WD,codes:{ERR_INVALID_ARG_TYPE:Ym,ERR_INVALID_RETURN_VALUE:Hm,ERR_MISSING_ARGS:GD,ERR_STREAM_DESTROYED:zD,ERR_STREAM_PREMATURE_CLOSE:YD},AbortError:JD}=ir(),{validateFunction:ZD,validateAbortSignal:XD}=Ea(),{isIterable:sc,isReadable:Vm,isReadableNodeStream:Ch,isNodeStream:PA,isTransformStream:Oa,isWebStream:QD,isReadableStream:qm,isReadableFinished:e4}=ri(),t4=globalThis.AbortController||ba().AbortController,Fm,jm,Wm;function MA(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=Lh(t,{readable:e,writable:r},o=>{n=!o});return{destroy:o=>{n||(n=!0,jD.destroyer(t,o||new zD("pipe")))},cleanup:i}}function r4(t){return ZD(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function Gm(t){if(sc(t))return t;if(Ch(t))return n4(t);throw new Ym("val",["Readable","Iterable","AsyncIterable"],t)}async function*n4(t){jm||(jm=Bd()),yield*jm.prototype[VD].call(t)}async function Nh(t,e,r,{end:n}){let i,o=null,s=u=>{if(u&&(i=u),o){let d=o;o=null,d()}},c=()=>new HD((u,d)=>{i?d(i):o=()=>{i?d(i):u()}});e.on("drain",s);let a=Lh(e,{readable:!1},s);try{e.writableNeedDrain&&await c();for await(let u of t)e.write(u)||await c();n&&(e.end(),await c()),r()}catch(u){r(i!==u?WD(i,u):u)}finally{a(),e.off("drain",s)}}async function zm(t,e,r,{end:n}){Oa(e)&&(e=e.writable);let i=e.getWriter();try{for await(let o of t)await i.ready,i.write(o).catch(()=>{});await i.ready,n&&await i.close(),r()}catch(o){try{await i.abort(o),r(o)}catch(s){r(s)}}}function i4(...t){return KA(t,FD(r4(t)))}function KA(t,e,r){if(t.length===1&&$D(t[0])&&(t=t[0]),t.length<2)throw new GD("streams");let n=new t4,i=n.signal,o=r?.signal,s=[];XD(o,"options.signal");function c(){g(new JD)}Wm=Wm||Jt().addAbortListener;let a;o&&(a=Wm(o,c));let u,d,f=[],h=0;function p(A){g(A,--h===0)}function g(A,O){var T;if(A&&(!u||u.code==="ERR_STREAM_PREMATURE_CLOSE")&&(u=A),!(!u&&!O)){for(;f.length;)f.shift()(u);(T=a)===null||T===void 0||T[qD](),n.abort(),O&&(u||s.forEach(M=>M()),Dd.nextTick(e,u,d))}}let y;for(let A=0;A<t.length;A++){let O=t[A],T=A<t.length-1,M=A>0,q=T||r?.end!==!1,j=A===t.length-1;if(PA(O)){let $=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&p(X)};var I=$;if(q){let{destroy:X,cleanup:Q}=MA(O,T,M);f.push(X),Vm(O)&&j&&s.push(Q)}O.on("error",$),Vm(O)&&j&&s.push(()=>{O.removeListener("error",$)})}if(A===0)if(typeof O=="function"){if(y=O({signal:i}),!sc(y))throw new Hm("Iterable, AsyncIterable or Stream","source",y)}else sc(O)||Ch(O)||Oa(O)?y=O:y=LA.from(O);else if(typeof O=="function"){if(Oa(y)){var E;y=Gm((E=y)===null||E===void 0?void 0:E.readable)}else y=Gm(y);if(y=O(y,{signal:i}),T){if(!sc(y,!0))throw new Hm("AsyncIterable",`transform[${A-1}]`,y)}else{var S;Fm||(Fm=$m());let $=new Fm({objectMode:!0}),X=(S=y)===null||S===void 0?void 0:S.then;if(typeof X=="function")h++,X.call(y,_=>{d=_,_!=null&&$.write(_),q&&$.end(),Dd.nextTick(p)},_=>{$.destroy(_),Dd.nextTick(p,_)});else if(sc(y,!0))h++,Nh(y,$,p,{end:q});else if(qm(y)||Oa(y)){let _=y.readable||y;h++,Nh(_,$,p,{end:q})}else throw new Hm("AsyncIterable or Promise","destination",y);y=$;let{destroy:Q,cleanup:G}=MA(y,!1,!0);f.push(Q),j&&s.push(G)}}else if(PA(O)){if(Ch(y)){h+=2;let $=o4(y,O,p,{end:q});Vm(O)&&j&&s.push($)}else if(Oa(y)||qm(y)){let $=y.readable||y;h++,Nh($,O,p,{end:q})}else if(sc(y))h++,Nh(y,O,p,{end:q});else throw new Ym("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else if(QD(O)){if(Ch(y))h++,zm(Gm(y),O,p,{end:q});else if(qm(y)||sc(y))h++,zm(y,O,p,{end:q});else if(Oa(y))h++,zm(y.readable,O,p,{end:q});else throw new Ym("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else y=LA.from(O)}return(i!=null&&i.aborted||o!=null&&o.aborted)&&Dd.nextTick(c),y}function o4(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new YD)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;e4(t)?Dd.nextTick(s):t.once("end",s)}else r();return Lh(t,{readable:!0,writable:!1},s=>{let c=t._readableState;s&&s.code==="ERR_STREAM_PREMATURE_CLOSE"&&c&&c.ended&&!c.errored&&!c.errorEmitted?t.once("end",r).once("error",r):r(s)}),Lh(e,{readable:!1,writable:!0},r)}$A.exports={pipelineImpl:KA,pipeline:i4}});var Zm=oe(($F,WA)=>{"use strict";l();var{pipeline:s4}=Ph(),Mh=oi(),{destroyer:c4}=rc(),{isNodeStream:Kh,isReadable:HA,isWritable:VA,isWebStream:Jm,isTransformStream:cc,isWritableStream:qA,isReadableStream:FA}=ri(),{AbortError:a4,codes:{ERR_INVALID_ARG_VALUE:jA,ERR_MISSING_ARGS:u4}}=ir(),d4=ji();WA.exports=function(...e){if(e.length===0)throw new u4("streams");if(e.length===1)return Mh.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=Mh.from(e[0])),typeof e[e.length-1]=="function"){let p=e.length-1;e[p]=Mh.from(e[p])}for(let p=0;p<e.length;++p)if(!(!Kh(e[p])&&!Jm(e[p]))){if(p<e.length-1&&!(HA(e[p])||FA(e[p])||cc(e[p])))throw new jA(`streams[${p}]`,r[p],"must be readable");if(p>0&&!(VA(e[p])||qA(e[p])||cc(e[p])))throw new jA(`streams[${p}]`,r[p],"must be writable")}let n,i,o,s,c;function a(p){let g=s;s=null,g?g(p):p?c.destroy(p):!h&&!f&&c.destroy()}let u=e[0],d=s4(e,a),f=!!(VA(u)||qA(u)||cc(u)),h=!!(HA(d)||FA(d)||cc(d));if(c=new Mh({writableObjectMode:!!(u!=null&&u.writableObjectMode),readableObjectMode:!!(d!=null&&d.readableObjectMode),writable:f,readable:h}),f){if(Kh(u))c._write=function(g,y,E){u.write(g,y)?E():n=E},c._final=function(g){u.end(),i=g},u.on("drain",function(){if(n){let g=n;n=null,g()}});else if(Jm(u)){let y=(cc(u)?u.writable:u).getWriter();c._write=async function(E,S,I){try{await y.ready,y.write(E).catch(()=>{}),I()}catch(A){I(A)}},c._final=async function(E){try{await y.ready,y.close().catch(()=>{}),i=E}catch(S){E(S)}}}let p=cc(d)?d.readable:d;d4(p,()=>{if(i){let g=i;i=null,g()}})}if(h){if(Kh(d))d.on("readable",function(){if(o){let p=o;o=null,p()}}),d.on("end",function(){c.push(null)}),c._read=function(){for(;;){let p=d.read();if(p===null){o=c._read;return}if(!c.push(p))return}};else if(Jm(d)){let g=(cc(d)?d.readable:d).getReader();c._read=async function(){for(;;)try{let{value:y,done:E}=await g.read();if(!c.push(y))return;if(E){c.push(null);return}}catch{return}}}}return c._destroy=function(p,g){!p&&s!==null&&(p=new a4),o=null,n=null,i=null,s===null?g(p):(s=g,Kh(d)&&c4(d,p))},c}});var rT=oe((VF,ew)=>{"use strict";l();var f4=globalThis.AbortController||ba().AbortController,{codes:{ERR_INVALID_ARG_VALUE:l4,ERR_INVALID_ARG_TYPE:kd,ERR_MISSING_ARGS:h4,ERR_OUT_OF_RANGE:p4},AbortError:si}=ir(),{validateAbortSignal:ac,validateInteger:GA,validateObject:uc}=Ea(),y4=nt().Symbol("kWeak"),g4=nt().Symbol("kResistStopPropagation"),{finished:m4}=ji(),w4=Zm(),{addAbortSignalNoValidate:b4}=Sd(),{isWritable:x4,isNodeStream:E4}=ri(),{deprecate:v4}=Jt(),{ArrayPrototypePush:S4,Boolean:A4,MathFloor:zA,Number:T4,NumberIsNaN:_4,Promise:YA,PromiseReject:JA,PromiseResolve:B4,PromisePrototypeThen:ZA,Symbol:QA}=nt(),$h=QA("kEmpty"),XA=QA("kEof");function I4(t,e){if(e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal"),E4(t)&&!x4(t))throw new l4("stream",t,"must be writable");let r=w4(this,t);return e!=null&&e.signal&&b4(e.signal,r),r}function Hh(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=zA(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=zA(e.highWaterMark)),GA(r,"options.concurrency",1),GA(n,"options.highWaterMark",0),n+=r,(async function*(){let o=Jt().AbortSignalAny([e?.signal].filter(A4)),s=this,c=[],a={signal:o},u,d,f=!1,h=0;function p(){f=!0,g()}function g(){h-=1,y()}function y(){d&&!f&&h<r&&c.length<n&&(d(),d=null)}async function E(){try{for await(let S of s){if(f)return;if(o.aborted)throw new si;try{if(S=t(S,a),S===$h)continue;S=B4(S)}catch(I){S=JA(I)}h+=1,ZA(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new YA(I=>{d=I})}c.push(XA)}catch(S){let I=JA(S);ZA(I,g,p),c.push(I)}finally{f=!0,u&&(u(),u=null)}}E();try{for(;;){for(;c.length>0;){let S=await c[0];if(S===XA)return;if(o.aborted)throw new si;S!==$h&&(yield S),c.shift(),y()}await new YA(S=>{u=S})}}finally{f=!0,d&&(d(),d=null)}}).call(this)}function R4(t=void 0){return t!=null&&uc(t,"options"),t?.signal!=null&&ac(t.signal,"options.signal"),(async function*(){let r=0;for await(let i of this){var n;if(t!=null&&(n=t.signal)!==null&&n!==void 0&&n.aborted)throw new si({cause:t.signal.reason});yield[r++,i]}}).call(this)}async function eT(t,e=void 0){for await(let r of Qm.call(this,t,e))return!0;return!1}async function U4(t,e=void 0){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);return!await eT.call(this,async(...r)=>!await t(...r),e)}async function O4(t,e){for await(let r of Qm.call(this,t,e))return r}async function D4(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),$h}for await(let n of Hh.call(this,r,e));}function Qm(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i)?n:$h}return Hh.call(this,r,e)}var Xm=class extends h4{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function k4(t,e,r){var n;if(typeof t!="function")throw new kd("reducer",["Function","AsyncFunction"],t);r!=null&&uc(r,"options"),r?.signal!=null&&ac(r.signal,"options.signal");let i=arguments.length>1;if(r!=null&&(n=r.signal)!==null&&n!==void 0&&n.aborted){let u=new si(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await m4(this.destroy(u)),u}let o=new f4,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[y4]:this,[g4]:!0};r.signal.addEventListener("abort",()=>o.abort(),u)}let c=!1;try{for await(let u of this){var a;if(c=!0,r!=null&&(a=r.signal)!==null&&a!==void 0&&a.aborted)throw new si;i?e=await t(e,u,{signal:s}):(e=u,i=!0)}if(!c&&!i)throw new Xm}finally{o.abort()}return e}async function N4(t){t!=null&&uc(t,"options"),t?.signal!=null&&ac(t.signal,"options.signal");let e=[];for await(let n of this){var r;if(t!=null&&(r=t.signal)!==null&&r!==void 0&&r.aborted)throw new si(void 0,{cause:t.signal.reason});S4(e,n)}return e}function C4(t,e){let r=Hh.call(this,t,e);return(async function*(){for await(let i of r)yield*i}).call(this)}function tT(t){if(t=T4(t),_4(t))return 0;if(t<0)throw new p4("number",">= 0",t);return t}function L4(t,e=void 0){return e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal"),t=tT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new si;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new si;t--<=0&&(yield o)}}).call(this)}function P4(t,e=void 0){return e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal"),t=tT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new si;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new si;if(t-- >0&&(yield o),t<=0)return}}).call(this)}ew.exports.streamReturningOperators={asIndexedPairs:v4(R4,"readable.asIndexedPairs will be removed in a future version."),drop:L4,filter:Qm,flatMap:C4,map:Hh,take:P4,compose:I4};ew.exports.promiseReturningOperators={every:U4,forEach:D4,reduce:k4,toArray:N4,some:eT,find:O4}});var tw=oe((FF,nT)=>{"use strict";l();var{ArrayPrototypePop:M4,Promise:K4}=nt(),{isIterable:$4,isNodeStream:H4,isWebStream:V4}=ri(),{pipelineImpl:q4}=Ph(),{finished:F4}=ji();rw();function j4(...t){return new K4((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!H4(o)&&!$4(o)&&!V4(o)){let s=M4(t);n=s.signal,i=s.end}q4(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}nT.exports={finished:F4,pipeline:j4}});var rw=oe((WF,lT)=>{l();var{Buffer:W4}=Sr(),{ObjectDefineProperty:zi,ObjectKeys:sT,ReflectApply:cT}=nt(),{promisify:{custom:aT}}=Jt(),{streamReturningOperators:iT,promiseReturningOperators:oT}=rT(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:uT}}=ir(),G4=Zm(),{setDefaultHighWaterMark:z4,getDefaultHighWaterMark:Y4}=Ad(),{pipeline:dT}=Ph(),{destroyer:J4}=rc(),fT=ji(),nw=tw(),Nd=ri(),qe=lT.exports=xh().Stream;qe.isDestroyed=Nd.isDestroyed;qe.isDisturbed=Nd.isDisturbed;qe.isErrored=Nd.isErrored;qe.isReadable=Nd.isReadable;qe.isWritable=Nd.isWritable;qe.Readable=Bd();for(let t of sT(iT)){let r=function(...n){if(new.target)throw uT();return qe.Readable.from(cT(e,this,n))};iw=r;let e=iT[t];zi(r,"name",{__proto__:null,value:e.name}),zi(r,"length",{__proto__:null,value:e.length}),zi(qe.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var iw;for(let t of sT(oT)){let r=function(...i){if(new.target)throw uT();return cT(e,this,i)};iw=r;let e=oT[t];zi(r,"name",{__proto__:null,value:e.name}),zi(r,"length",{__proto__:null,value:e.length}),zi(qe.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var iw;qe.Writable=kh();qe.Duplex=oi();qe.Transform=Mm();qe.PassThrough=$m();qe.pipeline=dT;var{addAbortSignal:Z4}=Sd();qe.addAbortSignal=Z4;qe.finished=fT;qe.destroy=J4;qe.compose=G4;qe.setDefaultHighWaterMark=z4;qe.getDefaultHighWaterMark=Y4;zi(qe,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return nw}});zi(dT,aT,{__proto__:null,enumerable:!0,get(){return nw.pipeline}});zi(fT,aT,{__proto__:null,enumerable:!0,get(){return nw.finished}});qe.Stream=qe;qe._isUint8Array=function(e){return e instanceof Uint8Array};qe._uint8ArrayToBuffer=function(e){return W4.from(e.buffer,e.byteOffset,e.byteLength)}});var ow=oe((zF,lt)=>{"use strict";l();var At=rw(),X4=tw(),Q4=At.Readable.destroy;lt.exports=At.Readable;lt.exports._uint8ArrayToBuffer=At._uint8ArrayToBuffer;lt.exports._isUint8Array=At._isUint8Array;lt.exports.isDisturbed=At.isDisturbed;lt.exports.isErrored=At.isErrored;lt.exports.isReadable=At.isReadable;lt.exports.Readable=At.Readable;lt.exports.Writable=At.Writable;lt.exports.Duplex=At.Duplex;lt.exports.Transform=At.Transform;lt.exports.PassThrough=At.PassThrough;lt.exports.addAbortSignal=At.addAbortSignal;lt.exports.finished=At.finished;lt.exports.destroy=At.destroy;lt.exports.destroy=Q4;lt.exports.pipeline=At.pipeline;lt.exports.compose=At.compose;Object.defineProperty(At,"promises",{configurable:!0,enumerable:!0,get(){return X4}});lt.exports.Stream=At.Stream;lt.exports.default=lt.exports});var N_=oe((Rp,k_)=>{l();(function(t,e){typeof Rp=="object"&&typeof k_<"u"?e(Rp):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(Rp,function(t){"use strict";function e(){for(var B=arguments.length,v=Array(B),k=0;k<B;k++)v[k]=arguments[k];if(v.length>1){v[0]=v[0].slice(0,-1);for(var K=v.length-1,H=1;H<K;++H)v[H]=v[H].slice(1,-1);return v[K]=v[K].slice(1),v.join("")}else return v[0]}function r(B){return"(?:"+B+")"}function n(B){return B===void 0?"undefined":B===null?"null":Object.prototype.toString.call(B).split(" ").pop().split("]").shift().toLowerCase()}function i(B){return B.toUpperCase()}function o(B){return B!=null?B instanceof Array?B:typeof B.length!="number"||B.split||B.setInterval||B.call?[B]:Array.prototype.slice.call(B):[]}function s(B,v){var k=B;if(v)for(var K in v)k[K]=v[K];return k}function c(B){var v="[A-Za-z]",k="[\\x0D]",K="[0-9]",H="[\\x22]",te=e(K,"[A-Fa-f]"),fe="[\\x0A]",Ee="[\\x20]",Re=r(r("%[EFef]"+te+"%"+te+te+"%"+te+te)+"|"+r("%[89A-Fa-f]"+te+"%"+te+te)+"|"+r("%"+te+te)),pt="[\\:\\/\\?\\#\\[\\]\\@]",xe="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Qe=e(pt,xe),yt=B?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",ze=B?"[\\uE000-\\uF8FF]":"[]",Se=e(v,K,"[\\-\\.\\_\\~]",yt),et=r(v+e(v,K,"[\\+\\-\\.]")+"*"),De=r(r(Re+"|"+e(Se,xe,"[\\:]"))+"*"),ds=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("[1-9]"+K)+"|"+K),Er=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("0?[1-9]"+K)+"|0?0?"+K),Fr=r(Er+"\\."+Er+"\\."+Er+"\\."+Er),Me=r(te+"{1,4}"),vr=r(r(Me+"\\:"+Me)+"|"+Fr),jr=r(r(Me+"\\:")+"{6}"+vr),Ln=r("\\:\\:"+r(Me+"\\:")+"{5}"+vr),fs=r(r(Me)+"?\\:\\:"+r(Me+"\\:")+"{4}"+vr),yi=r(r(r(Me+"\\:")+"{0,1}"+Me)+"?\\:\\:"+r(Me+"\\:")+"{3}"+vr),lu=r(r(r(Me+"\\:")+"{0,2}"+Me)+"?\\:\\:"+r(Me+"\\:")+"{2}"+vr),xf=r(r(r(Me+"\\:")+"{0,3}"+Me)+"?\\:\\:"+Me+"\\:"+vr),Ef=r(r(r(Me+"\\:")+"{0,4}"+Me)+"?\\:\\:"+vr),Ec=r(r(r(Me+"\\:")+"{0,5}"+Me)+"?\\:\\:"+Me),vc=r(r(r(Me+"\\:")+"{0,6}"+Me)+"?\\:\\:"),gi=r([jr,Ln,fs,yi,lu,xf,Ef,Ec,vc].join("|")),Sc=r(r(Se+"|"+Re)+"+"),Xp=r(gi+"\\%25"+Sc),ls=r(gi+r("\\%25|\\%(?!"+te+"{2})")+Sc),YB=r("[vV]"+te+"+\\."+e(Se,xe,"[\\:]")+"+"),JB=r("\\["+r(ls+"|"+gi+"|"+YB)+"\\]"),Zb=r(r(Re+"|"+e(Se,xe))+"*"),hu=r(JB+"|"+Fr+"(?!"+Zb+")|"+Zb),pu=r(K+"*"),Xb=r(r(De+"@")+"?"+hu+r("\\:"+pu)+"?"),yu=r(Re+"|"+e(Se,xe,"[\\:\\@]")),ZB=r(yu+"*"),Qb=r(yu+"+"),XB=r(r(Re+"|"+e(Se,xe,"[\\@]"))+"+"),mi=r(r("\\/"+ZB)+"*"),Ac=r("\\/"+r(Qb+mi)+"?"),Qp=r(XB+mi),vf=r(Qb+mi),Tc="(?!"+yu+")",vL=r(mi+"|"+Ac+"|"+Qp+"|"+vf+"|"+Tc),_c=r(r(yu+"|"+e("[\\/\\?]",ze))+"*"),gu=r(r(yu+"|[\\/\\?]")+"*"),ex=r(r("\\/\\/"+Xb+mi)+"|"+Ac+"|"+vf+"|"+Tc),QB=r(et+"\\:"+ex+r("\\?"+_c)+"?"+r("\\#"+gu)+"?"),eI=r(r("\\/\\/"+Xb+mi)+"|"+Ac+"|"+Qp+"|"+Tc),tI=r(eI+r("\\?"+_c)+"?"+r("\\#"+gu)+"?"),SL=r(QB+"|"+tI),AL=r(et+"\\:"+ex+r("\\?"+_c)+"?"),TL="^("+et+")\\:"+r(r("\\/\\/("+r("("+De+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?)")+"?("+mi+"|"+Ac+"|"+vf+"|"+Tc+")")+r("\\?("+_c+")")+"?"+r("\\#("+gu+")")+"?$",_L="^(){0}"+r(r("\\/\\/("+r("("+De+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?)")+"?("+mi+"|"+Ac+"|"+Qp+"|"+Tc+")")+r("\\?("+_c+")")+"?"+r("\\#("+gu+")")+"?$",BL="^("+et+")\\:"+r(r("\\/\\/("+r("("+De+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?)")+"?("+mi+"|"+Ac+"|"+vf+"|"+Tc+")")+r("\\?("+_c+")")+"?$",IL="^"+r("\\#("+gu+")")+"?$",RL="^"+r("("+De+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,K,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Se,xe),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Se,xe),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Se,xe),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Se,xe),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Se,xe,"[\\:\\@\\/\\?]",ze),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Se,xe,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Se,xe),"g"),UNRESERVED:new RegExp(Se,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Se,Qe),"g"),PCT_ENCODED:new RegExp(Re,"g"),IPV4ADDRESS:new RegExp("^("+Fr+")$"),IPV6ADDRESS:new RegExp("^\\[?("+gi+")"+r(r("\\%25|\\%(?!"+te+"{2})")+"("+Sc+")")+"?\\]?$")}}var a=c(!1),u=c(!0),d=function(){function B(v,k){var K=[],H=!0,te=!1,fe=void 0;try{for(var Ee=v[Symbol.iterator](),Re;!(H=(Re=Ee.next()).done)&&(K.push(Re.value),!(k&&K.length===k));H=!0);}catch(pt){te=!0,fe=pt}finally{try{!H&&Ee.return&&Ee.return()}finally{if(te)throw fe}}return K}return function(v,k){if(Array.isArray(v))return v;if(Symbol.iterator in Object(v))return B(v,k);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),f=function(B){if(Array.isArray(B)){for(var v=0,k=Array(B.length);v<B.length;v++)k[v]=B[v];return k}else return Array.from(B)},h=2147483647,p=36,g=1,y=26,E=38,S=700,I=72,A=128,O="-",T=/^xn--/,M=/[^\0-\x7E]/,q=/[\x2E\u3002\uFF0E\uFF61]/g,j={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},$=p-g,X=Math.floor,Q=String.fromCharCode;function G(B){throw new RangeError(j[B])}function _(B,v){for(var k=[],K=B.length;K--;)k[K]=v(B[K]);return k}function D(B,v){var k=B.split("@"),K="";k.length>1&&(K=k[0]+"@",B=k[1]),B=B.replace(q,".");var H=B.split("."),te=_(H,v).join(".");return K+te}function x(B){for(var v=[],k=0,K=B.length;k<K;){var H=B.charCodeAt(k++);if(H>=55296&&H<=56319&&k<K){var te=B.charCodeAt(k++);(te&64512)==56320?v.push(((H&1023)<<10)+(te&1023)+65536):(v.push(H),k--)}else v.push(H)}return v}var U=function(v){return String.fromCodePoint.apply(String,f(v))},L=function(v){return v-48<10?v-22:v-65<26?v-65:v-97<26?v-97:p},N=function(v,k){return v+22+75*(v<26)-((k!=0)<<5)},R=function(v,k,K){var H=0;for(v=K?X(v/S):v>>1,v+=X(v/k);v>$*y>>1;H+=p)v=X(v/$);return X(H+($+1)*v/(v+E))},C=function(v){var k=[],K=v.length,H=0,te=A,fe=I,Ee=v.lastIndexOf(O);Ee<0&&(Ee=0);for(var Re=0;Re<Ee;++Re)v.charCodeAt(Re)>=128&&G("not-basic"),k.push(v.charCodeAt(Re));for(var pt=Ee>0?Ee+1:0;pt<K;){for(var xe=H,Qe=1,yt=p;;yt+=p){pt>=K&&G("invalid-input");var ze=L(v.charCodeAt(pt++));(ze>=p||ze>X((h-H)/Qe))&&G("overflow"),H+=ze*Qe;var Se=yt<=fe?g:yt>=fe+y?y:yt-fe;if(ze<Se)break;var et=p-Se;Qe>X(h/et)&&G("overflow"),Qe*=et}var De=k.length+1;fe=R(H-xe,De,xe==0),X(H/De)>h-te&&G("overflow"),te+=X(H/De),H%=De,k.splice(H++,0,te)}return String.fromCodePoint.apply(String,k)},P=function(v){var k=[];v=x(v);var K=v.length,H=A,te=0,fe=I,Ee=!0,Re=!1,pt=void 0;try{for(var xe=v[Symbol.iterator](),Qe;!(Ee=(Qe=xe.next()).done);Ee=!0){var yt=Qe.value;yt<128&&k.push(Q(yt))}}catch(ls){Re=!0,pt=ls}finally{try{!Ee&&xe.return&&xe.return()}finally{if(Re)throw pt}}var ze=k.length,Se=ze;for(ze&&k.push(O);Se<K;){var et=h,De=!0,ds=!1,Er=void 0;try{for(var Fr=v[Symbol.iterator](),Me;!(De=(Me=Fr.next()).done);De=!0){var vr=Me.value;vr>=H&&vr<et&&(et=vr)}}catch(ls){ds=!0,Er=ls}finally{try{!De&&Fr.return&&Fr.return()}finally{if(ds)throw Er}}var jr=Se+1;et-H>X((h-te)/jr)&&G("overflow"),te+=(et-H)*jr,H=et;var Ln=!0,fs=!1,yi=void 0;try{for(var lu=v[Symbol.iterator](),xf;!(Ln=(xf=lu.next()).done);Ln=!0){var Ef=xf.value;if(Ef<H&&++te>h&&G("overflow"),Ef==H){for(var Ec=te,vc=p;;vc+=p){var gi=vc<=fe?g:vc>=fe+y?y:vc-fe;if(Ec<gi)break;var Sc=Ec-gi,Xp=p-gi;k.push(Q(N(gi+Sc%Xp,0))),Ec=X(Sc/Xp)}k.push(Q(N(Ec,0))),fe=R(te,jr,Se==ze),te=0,++Se}}}catch(ls){fs=!0,yi=ls}finally{try{!Ln&&lu.return&&lu.return()}finally{if(fs)throw yi}}++te,++H}return k.join("")},V=function(v){return D(v,function(k){return T.test(k)?C(k.slice(4).toLowerCase()):k})},J=function(v){return D(v,function(k){return M.test(k)?"xn--"+P(k):k})},z={version:"2.1.0",ucs2:{decode:x,encode:U},decode:C,encode:P,toASCII:J,toUnicode:V},W={};function Y(B){var v=B.charCodeAt(0),k=void 0;return v<16?k="%0"+v.toString(16).toUpperCase():v<128?k="%"+v.toString(16).toUpperCase():v<2048?k="%"+(v>>6|192).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase():k="%"+(v>>12|224).toString(16).toUpperCase()+"%"+(v>>6&63|128).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase(),k}function Z(B){for(var v="",k=0,K=B.length;k<K;){var H=parseInt(B.substr(k+1,2),16);if(H<128)v+=String.fromCharCode(H),k+=3;else if(H>=194&&H<224){if(K-k>=6){var te=parseInt(B.substr(k+4,2),16);v+=String.fromCharCode((H&31)<<6|te&63)}else v+=B.substr(k,6);k+=6}else if(H>=224){if(K-k>=9){var fe=parseInt(B.substr(k+4,2),16),Ee=parseInt(B.substr(k+7,2),16);v+=String.fromCharCode((H&15)<<12|(fe&63)<<6|Ee&63)}else v+=B.substr(k,9);k+=9}else v+=B.substr(k,3),k+=3}return v}function ue(B,v){function k(K){var H=Z(K);return H.match(v.UNRESERVED)?H:K}return B.scheme&&(B.scheme=String(B.scheme).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_SCHEME,"")),B.userinfo!==void 0&&(B.userinfo=String(B.userinfo).replace(v.PCT_ENCODED,k).replace(v.NOT_USERINFO,Y).replace(v.PCT_ENCODED,i)),B.host!==void 0&&(B.host=String(B.host).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_HOST,Y).replace(v.PCT_ENCODED,i)),B.path!==void 0&&(B.path=String(B.path).replace(v.PCT_ENCODED,k).replace(B.scheme?v.NOT_PATH:v.NOT_PATH_NOSCHEME,Y).replace(v.PCT_ENCODED,i)),B.query!==void 0&&(B.query=String(B.query).replace(v.PCT_ENCODED,k).replace(v.NOT_QUERY,Y).replace(v.PCT_ENCODED,i)),B.fragment!==void 0&&(B.fragment=String(B.fragment).replace(v.PCT_ENCODED,k).replace(v.NOT_FRAGMENT,Y).replace(v.PCT_ENCODED,i)),B}function ee(B){return B.replace(/^0*(.*)/,"$1")||"0"}function ce(B,v){var k=B.match(v.IPV4ADDRESS)||[],K=d(k,2),H=K[1];return H?H.split(".").map(ee).join("."):B}function Ie(B,v){var k=B.match(v.IPV6ADDRESS)||[],K=d(k,3),H=K[1],te=K[2];if(H){for(var fe=H.toLowerCase().split("::").reverse(),Ee=d(fe,2),Re=Ee[0],pt=Ee[1],xe=pt?pt.split(":").map(ee):[],Qe=Re.split(":").map(ee),yt=v.IPV4ADDRESS.test(Qe[Qe.length-1]),ze=yt?7:8,Se=Qe.length-ze,et=Array(ze),De=0;De<ze;++De)et[De]=xe[De]||Qe[Se+De]||"";yt&&(et[ze-1]=ce(et[ze-1],v));var ds=et.reduce(function(jr,Ln,fs){if(!Ln||Ln==="0"){var yi=jr[jr.length-1];yi&&yi.index+yi.length===fs?yi.length++:jr.push({index:fs,length:1})}return jr},[]),Er=ds.sort(function(jr,Ln){return Ln.length-jr.length})[0],Fr=void 0;if(Er&&Er.length>1){var Me=et.slice(0,Er.index),vr=et.slice(Er.index+Er.length);Fr=Me.join(":")+"::"+vr.join(":")}else Fr=et.join(":");return te&&(Fr+="%"+te),Fr}else return B}var Pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Ge="".match(/(){0}/)[1]===void 0;function wt(B){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k={},K=v.iri!==!1?u:a;v.reference==="suffix"&&(B=(v.scheme?v.scheme+":":"")+"//"+B);var H=B.match(Pe);if(H){Ge?(k.scheme=H[1],k.userinfo=H[3],k.host=H[4],k.port=parseInt(H[5],10),k.path=H[6]||"",k.query=H[7],k.fragment=H[8],isNaN(k.port)&&(k.port=H[5])):(k.scheme=H[1]||void 0,k.userinfo=B.indexOf("@")!==-1?H[3]:void 0,k.host=B.indexOf("//")!==-1?H[4]:void 0,k.port=parseInt(H[5],10),k.path=H[6]||"",k.query=B.indexOf("?")!==-1?H[7]:void 0,k.fragment=B.indexOf("#")!==-1?H[8]:void 0,isNaN(k.port)&&(k.port=B.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?H[4]:void 0)),k.host&&(k.host=Ie(ce(k.host,K),K)),k.scheme===void 0&&k.userinfo===void 0&&k.host===void 0&&k.port===void 0&&!k.path&&k.query===void 0?k.reference="same-document":k.scheme===void 0?k.reference="relative":k.fragment===void 0?k.reference="absolute":k.reference="uri",v.reference&&v.reference!=="suffix"&&v.reference!==k.reference&&(k.error=k.error||"URI is not a "+v.reference+" reference.");var te=W[(v.scheme||k.scheme||"").toLowerCase()];if(!v.unicodeSupport&&(!te||!te.unicodeSupport)){if(k.host&&(v.domainHost||te&&te.domainHost))try{k.host=z.toASCII(k.host.replace(K.PCT_ENCODED,Z).toLowerCase())}catch(fe){k.error=k.error||"Host's domain name can not be converted to ASCII via punycode: "+fe}ue(k,a)}else ue(k,K);te&&te.parse&&te.parse(k,v)}else k.error=k.error||"URI can not be parsed.";return k}function pi(B,v){var k=v.iri!==!1?u:a,K=[];return B.userinfo!==void 0&&(K.push(B.userinfo),K.push("@")),B.host!==void 0&&K.push(Ie(ce(String(B.host),k),k).replace(k.IPV6ADDRESS,function(H,te,fe){return"["+te+(fe?"%25"+fe:"")+"]"})),(typeof B.port=="number"||typeof B.port=="string")&&(K.push(":"),K.push(String(B.port))),K.length?K.join(""):void 0}var uo=/^\.\.?\//,au=/^\/\.(\/|$)/,pf=/^\/\.\.(\/|$)/,Yp=/^\/?(?:.|\n)*?(?=\/|$)/;function fo(B){for(var v=[];B.length;)if(B.match(uo))B=B.replace(uo,"");else if(B.match(au))B=B.replace(au,"/");else if(B.match(pf))B=B.replace(pf,"/"),v.pop();else if(B==="."||B==="..")B="";else{var k=B.match(Yp);if(k){var K=k[0];B=B.slice(K.length),v.push(K)}else throw new Error("Unexpected dot segment condition")}return v.join("")}function Vr(B){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k=v.iri?u:a,K=[],H=W[(v.scheme||B.scheme||"").toLowerCase()];if(H&&H.serialize&&H.serialize(B,v),B.host&&!k.IPV6ADDRESS.test(B.host)){if(v.domainHost||H&&H.domainHost)try{B.host=v.iri?z.toUnicode(B.host):z.toASCII(B.host.replace(k.PCT_ENCODED,Z).toLowerCase())}catch(Ee){B.error=B.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+Ee}}ue(B,k),v.reference!=="suffix"&&B.scheme&&(K.push(B.scheme),K.push(":"));var te=pi(B,v);if(te!==void 0&&(v.reference!=="suffix"&&K.push("//"),K.push(te),B.path&&B.path.charAt(0)!=="/"&&K.push("/")),B.path!==void 0){var fe=B.path;!v.absolutePath&&(!H||!H.absolutePath)&&(fe=fo(fe)),te===void 0&&(fe=fe.replace(/^\/\//,"/%2F")),K.push(fe)}return B.query!==void 0&&(K.push("?"),K.push(B.query)),B.fragment!==void 0&&(K.push("#"),K.push(B.fragment)),K.join("")}function uu(B,v){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},K=arguments[3],H={};return K||(B=wt(Vr(B,k),k),v=wt(Vr(v,k),k)),k=k||{},!k.tolerant&&v.scheme?(H.scheme=v.scheme,H.userinfo=v.userinfo,H.host=v.host,H.port=v.port,H.path=fo(v.path||""),H.query=v.query):(v.userinfo!==void 0||v.host!==void 0||v.port!==void 0?(H.userinfo=v.userinfo,H.host=v.host,H.port=v.port,H.path=fo(v.path||""),H.query=v.query):(v.path?(v.path.charAt(0)==="/"?H.path=fo(v.path):((B.userinfo!==void 0||B.host!==void 0||B.port!==void 0)&&!B.path?H.path="/"+v.path:B.path?H.path=B.path.slice(0,B.path.lastIndexOf("/")+1)+v.path:H.path=v.path,H.path=fo(H.path)),H.query=v.query):(H.path=B.path,v.query!==void 0?H.query=v.query:H.query=B.query),H.userinfo=B.userinfo,H.host=B.host,H.port=B.port),H.scheme=B.scheme),H.fragment=v.fragment,H}function yf(B,v,k){var K=s({scheme:"null"},k);return Vr(uu(wt(B,K),wt(v,K),K,!0),K)}function du(B,v){return typeof B=="string"?B=Vr(wt(B,v),v):n(B)==="object"&&(B=wt(Vr(B,v),v)),B}function gf(B,v,k){return typeof B=="string"?B=Vr(wt(B,k),k):n(B)==="object"&&(B=Vr(B,k)),typeof v=="string"?v=Vr(wt(v,k),k):n(v)==="object"&&(v=Vr(v,k)),B===v}function mf(B,v){return B&&B.toString().replace(!v||!v.iri?a.ESCAPE:u.ESCAPE,Y)}function qr(B,v){return B&&B.toString().replace(!v||!v.iri?a.PCT_ENCODED:u.PCT_ENCODED,Z)}var lo={scheme:"http",domainHost:!0,parse:function(v,k){return v.host||(v.error=v.error||"HTTP URIs must have a host."),v},serialize:function(v,k){var K=String(v.scheme).toLowerCase()==="https";return(v.port===(K?443:80)||v.port==="")&&(v.port=void 0),v.path||(v.path="/"),v}},fu={scheme:"https",domainHost:lo.domainHost,parse:lo.parse,serialize:lo.serialize};function wf(B){return typeof B.secure=="boolean"?B.secure:String(B.scheme).toLowerCase()==="wss"}var us={scheme:"ws",domainHost:!0,parse:function(v,k){var K=v;return K.secure=wf(K),K.resourceName=(K.path||"/")+(K.query?"?"+K.query:""),K.path=void 0,K.query=void 0,K},serialize:function(v,k){if((v.port===(wf(v)?443:80)||v.port==="")&&(v.port=void 0),typeof v.secure=="boolean"&&(v.scheme=v.secure?"wss":"ws",v.secure=void 0),v.resourceName){var K=v.resourceName.split("?"),H=d(K,2),te=H[0],fe=H[1];v.path=te&&te!=="/"?te:void 0,v.query=fe,v.resourceName=void 0}return v.fragment=void 0,v}},bf={scheme:"wss",domainHost:us.domainHost,parse:us.parse,serialize:us.serialize},Jp={},MB=!0,Wb="[A-Za-z0-9\\-\\.\\_\\~"+(MB?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Cn="[0-9A-Fa-f]",KB=r(r("%[EFef]"+Cn+"%"+Cn+Cn+"%"+Cn+Cn)+"|"+r("%[89A-Fa-f]"+Cn+"%"+Cn+Cn)+"|"+r("%"+Cn+Cn)),$B="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",HB="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",VB=e(HB,'[\\"\\\\]'),qB="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",FB=new RegExp(Wb,"g"),xc=new RegExp(KB,"g"),jB=new RegExp(e("[^]",$B,"[\\.]",'[\\"]',VB),"g"),Gb=new RegExp(e("[^]",Wb,qB),"g"),WB=Gb;function Zp(B){var v=Z(B);return v.match(FB)?v:B}var zb={scheme:"mailto",parse:function(v,k){var K=v,H=K.to=K.path?K.path.split(","):[];if(K.path=void 0,K.query){for(var te=!1,fe={},Ee=K.query.split("&"),Re=0,pt=Ee.length;Re<pt;++Re){var xe=Ee[Re].split("=");switch(xe[0]){case"to":for(var Qe=xe[1].split(","),yt=0,ze=Qe.length;yt<ze;++yt)H.push(Qe[yt]);break;case"subject":K.subject=qr(xe[1],k);break;case"body":K.body=qr(xe[1],k);break;default:te=!0,fe[qr(xe[0],k)]=qr(xe[1],k);break}}te&&(K.headers=fe)}K.query=void 0;for(var Se=0,et=H.length;Se<et;++Se){var De=H[Se].split("@");if(De[0]=qr(De[0]),k.unicodeSupport)De[1]=qr(De[1],k).toLowerCase();else try{De[1]=z.toASCII(qr(De[1],k).toLowerCase())}catch(ds){K.error=K.error||"Email address's domain name can not be converted to ASCII via punycode: "+ds}H[Se]=De.join("@")}return K},serialize:function(v,k){var K=v,H=o(v.to);if(H){for(var te=0,fe=H.length;te<fe;++te){var Ee=String(H[te]),Re=Ee.lastIndexOf("@"),pt=Ee.slice(0,Re).replace(xc,Zp).replace(xc,i).replace(jB,Y),xe=Ee.slice(Re+1);try{xe=k.iri?z.toUnicode(xe):z.toASCII(qr(xe,k).toLowerCase())}catch(Se){K.error=K.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Se}H[te]=pt+"@"+xe}K.path=H.join(",")}var Qe=v.headers=v.headers||{};v.subject&&(Qe.subject=v.subject),v.body&&(Qe.body=v.body);var yt=[];for(var ze in Qe)Qe[ze]!==Jp[ze]&&yt.push(ze.replace(xc,Zp).replace(xc,i).replace(Gb,Y)+"="+Qe[ze].replace(xc,Zp).replace(xc,i).replace(WB,Y));return yt.length&&(K.query=yt.join("&")),K}},GB=/^([^\:]+)\:(.*)/,Yb={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(GB),H=v;if(K){var te=k.scheme||H.scheme||"urn",fe=K[1].toLowerCase(),Ee=K[2],Re=te+":"+(k.nid||fe),pt=W[Re];H.nid=fe,H.nss=Ee,H.path=void 0,pt&&(H=pt.parse(H,k))}else H.error=H.error||"URN can not be parsed.";return H},serialize:function(v,k){var K=k.scheme||v.scheme||"urn",H=v.nid,te=K+":"+(k.nid||H),fe=W[te];fe&&(v=fe.serialize(v,k));var Ee=v,Re=v.nss;return Ee.path=(H||k.nid)+":"+Re,Ee}},zB=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Jb={scheme:"urn:uuid",parse:function(v,k){var K=v;return K.uuid=K.nss,K.nss=void 0,!k.tolerant&&(!K.uuid||!K.uuid.match(zB))&&(K.error=K.error||"UUID is not valid."),K},serialize:function(v,k){var K=v;return K.nss=(v.uuid||"").toLowerCase(),K}};W[lo.scheme]=lo,W[fu.scheme]=fu,W[us.scheme]=us,W[bf.scheme]=bf,W[zb.scheme]=zb,W[Yb.scheme]=Yb,W[Jb.scheme]=Jb,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=Z,t.parse=wt,t.removeDotSegments=fo,t.serialize=Vr,t.resolveComponents=uu,t.resolve=yf,t.normalize=du,t.equal=gf,t.escapeComponent=mf,t.unescapeComponent=qr,Object.defineProperty(t,"__esModule",{value:!0})})});var L_=oe((xZ,C_)=>{"use strict";l();C_.exports=function t(e){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");return e===null||typeof e!="object"?JSON.stringify(e):e.toJSON instanceof Function?t(e.toJSON()):Array.isArray(e)?`[${e.reduce((i,o,s)=>`${i}${s===0?"":","}${t(o===void 0||typeof o=="symbol"?null:o)}`,"")}]`:`{${Object.keys(e).sort().reduce((n,i)=>{if(e[i]===void 0||typeof e[i]=="symbol")return n;let o=n.length===0?"":",";return`${n}${o}${t(i)}:${t(e[i])}`},"")}}`}});var Y_=oe((SQ,z_)=>{l();var Za=1e3,Xa=Za*60,Qa=Xa*60,gc=Qa*24,NC=gc*7,CC=gc*365.25;z_.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return LC(t);if(r==="number"&&isFinite(t))return e.long?MC(t):PC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function LC(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*CC;case"weeks":case"week":case"w":return r*NC;case"days":case"day":case"d":return r*gc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Qa;case"minutes":case"minute":case"mins":case"min":case"m":return r*Xa;case"seconds":case"second":case"secs":case"sec":case"s":return r*Za;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function PC(t){var e=Math.abs(t);return e>=gc?Math.round(t/gc)+"d":e>=Qa?Math.round(t/Qa)+"h":e>=Xa?Math.round(t/Xa)+"m":e>=Za?Math.round(t/Za)+"s":t+"ms"}function MC(t){var e=Math.abs(t);return e>=gc?Np(t,e,gc,"day"):e>=Qa?Np(t,e,Qa,"hour"):e>=Xa?Np(t,e,Xa,"minute"):e>=Za?Np(t,e,Za,"second"):t+" ms"}function Np(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});l();l();l();l();var gs=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ms(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function mu(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function pn(t,...e){if(!ms(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function If(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mu(t.outputLen),mu(t.blockLen)}function Oc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function vx(t,e){pn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Vn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Rf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function yn(t,e){return t<<32-e|t>>>e}function wu(t,e){return t<<e|t>>>32-e>>>0}var Sx=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",HI=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ct(t){if(pn(t),Sx)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=HI[t[r]];return e}var vi={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ex(t){if(t>=vi._0&&t<=vi._9)return t-vi._0;if(t>=vi.A&&t<=vi.F)return t-(vi.A-10);if(t>=vi.a&&t<=vi.f)return t-(vi.a-10)}function Ar(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Sx)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=Ex(t.charCodeAt(o)),c=Ex(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function ws(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function bu(t){return typeof t=="string"&&(t=ws(t)),pn(t),t}function ut(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];pn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var Uc=class{};function Uf(t){let e=n=>t().update(bu(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Tr(t=32){if(gs&&typeof gs.getRandomValues=="function")return gs.getRandomValues(new Uint8Array(t));if(gs&&typeof gs.randomBytes=="function")return Uint8Array.from(gs.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}l();l();l();l();l();function VI(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}function ly(t,e,r){return t&e^~t&r}function hy(t,e,r){return t&e^t&r^e&r}var Dc=class extends Uc{constructor(e,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Rf(this.buffer)}update(e){Oc(this),e=bu(e),pn(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Rf(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Oc(this),vx(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Vn(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;VI(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Rf(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=c,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Si=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qI=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]),ho=new Uint32Array(64),py=class extends Dc{constructor(e=32){super(64,e,8,!1),this.A=Si[0]|0,this.B=Si[1]|0,this.C=Si[2]|0,this.D=Si[3]|0,this.E=Si[4]|0,this.F=Si[5]|0,this.G=Si[6]|0,this.H=Si[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)ho[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=ho[f-15],p=ho[f-2],g=yn(h,7)^yn(h,18)^h>>>3,y=yn(p,17)^yn(p,19)^p>>>10;ho[f]=y+ho[f-7]+g+ho[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=yn(c,6)^yn(c,11)^yn(c,25),p=d+h+ly(c,a,u)+qI[f]+ho[f]|0,y=(yn(n,2)^yn(n,13)^yn(n,22))+hy(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Vn(ho)}destroy(){this.set(0,0,0,0,0,0,0,0),Vn(this.buffer)}};var Oe=Uf(()=>new py);l();l();l();var Of=class extends Uc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,If(e);let n=bu(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);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),Vn(o)}update(e){return Oc(this),this.iHash.update(e),this}digestInto(e){Oc(this),pn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},yy=(t,e,r)=>new Of(t,e).update(r).digest();yy.create=(t,e)=>new Of(t,e);l();var wy=BigInt(0),my=BigInt(1);function xu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function po(t,e,r=""){let n=ms(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let s=r&&`"${r}" `,c=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+c+", got "+a)}return t}function Eu(t){let e=t.toString(16);return e.length&1?"0"+e:e}function Ax(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?wy:BigInt("0x"+t)}function Ai(t){return Ax(Ct(t))}function by(t){return pn(t),Ax(Ct(Uint8Array.from(t).reverse()))}function kc(t,e){return Ar(t.toString(16).padStart(e*2,"0"))}function xy(t,e){return kc(t,e).reverse()}function ot(t,e,r){let n;if(typeof e=="string")try{n=Ar(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(ms(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function vu(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var gy=t=>typeof t=="bigint"&&wy<=t;function Su(t,e,r){return gy(t)&&gy(e)&&gy(r)&&e<=t&&t<r}function Tx(t,e,r,n){if(!Su(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Df(t){let e;for(e=0;t>wy;t>>=my,e+=1);return e}var yo=t=>(my<<BigInt(t))-my;function _x(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),i=p=>Uint8Array.of(p),o=n(t),s=n(t),c=0,a=()=>{o.fill(1),s.fill(0),c=0},u=(...p)=>r(s,o,...p),d=(p=n(0))=>{s=u(i(0),p),o=u(),p.length!==0&&(s=u(i(1),p),o=u())},f=()=>{if(c++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,g=[];for(;p<e;){o=u();let y=o.slice();g.push(y),p+=o.length}return ut(...g)};return(p,g)=>{a(),d(p);let y;for(;!(y=g(f()));)d();return a(),y}}function Au(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(i,o,s){let c=t[i];if(s&&c===void 0)return;let a=typeof c;if(a!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${a}`)}Object.entries(e).forEach(([i,o])=>n(i,o,!1)),Object.entries(r).forEach(([i,o])=>n(i,o,!0))}function Ey(t){let e=new WeakMap;return(r,...n)=>{let i=e.get(r);if(i!==void 0)return i;let o=t(r,...n);return e.set(r,o),o}}l();l();var er=BigInt(0),qt=BigInt(1),bs=BigInt(2),Rx=BigInt(3),Ux=BigInt(4),Ox=BigInt(5),FI=BigInt(7),Dx=BigInt(8),jI=BigInt(9),kx=BigInt(16);function _r(t,e){let r=t%e;return r>=er?r:e+r}function Br(t,e,r){let n=t;for(;e-- >er;)n*=n,n%=r;return n}function Bx(t,e){if(t===er)throw new Error("invert: expected non-zero number");if(e<=er)throw new Error("invert: expected positive modulus, got "+e);let r=_r(t,e),n=e,i=er,o=qt,s=qt,c=er;for(;r!==er;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==qt)throw new Error("invert: does not exist");return _r(i,e)}function vy(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Nx(t,e){let r=(t.ORDER+qt)/Ux,n=t.pow(e,r);return vy(t,n,e),n}function WI(t,e){let r=(t.ORDER-Ox)/Dx,n=t.mul(e,bs),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,bs),i),c=t.mul(o,t.sub(s,t.ONE));return vy(t,c,e),c}function GI(t){let e=go(t),r=Cx(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+FI)/kx;return(c,a)=>{let u=c.pow(a,s),d=c.mul(u,n),f=c.mul(u,i),h=c.mul(u,o),p=c.eql(c.sqr(d),a),g=c.eql(c.sqr(f),a);u=c.cmov(u,d,p),d=c.cmov(h,f,g);let y=c.eql(c.sqr(d),a),E=c.cmov(u,d,y);return vy(c,E,a),E}}function Cx(t){if(t<Rx)throw new Error("sqrt is not defined for small field");let e=t-qt,r=0;for(;e%bs===er;)e/=bs,r++;let n=bs,i=go(t);for(;Ix(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Nx;let o=i.pow(n,e),s=(e+qt)/bs;return function(a,u){if(a.is0(u))return u;if(Ix(a,u)!==1)throw new Error("Cannot find square root");let d=r,f=a.mul(a.ONE,o),h=a.pow(u,e),p=a.pow(u,s);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let g=1,y=a.sqr(h);for(;!a.eql(y,a.ONE);)if(g++,y=a.sqr(y),g===d)throw new Error("Cannot find square root");let E=qt<<BigInt(d-g-1),S=a.pow(f,E);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function zI(t){return t%Ux===Rx?Nx:t%Dx===Ox?WI:t%kx===jI?GI(t):Cx(t)}var YI=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Sy(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=YI.reduce((n,i)=>(n[i]="function",n),e);return Au(t,r),t}function JI(t,e,r){if(r<er)throw new Error("invalid exponent, negatives unsupported");if(r===er)return t.ONE;if(r===qt)return e;let n=t.ONE,i=e;for(;r>er;)r&qt&&(n=t.mul(n,i)),i=t.sqr(i),r>>=qt;return n}function kf(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((s,c,a)=>t.is0(c)?s:(n[a]=s,t.mul(s,c)),t.ONE),o=t.inv(i);return e.reduceRight((s,c,a)=>t.is0(c)?s:(n[a]=t.mul(s,n[a]),t.mul(s,c)),o),n}function Ix(t,e){let r=(t.ORDER-qt)/bs,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),s=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Nf(t,e){e!==void 0&&mu(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function go(t,e,r=!1,n={}){if(t<=er)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,o,s=!1,c;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let h=e;h.BITS&&(i=h.BITS),h.sqrt&&(o=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(s=h.modFromBytes),c=h.allowedLengths}else typeof e=="number"&&(i=e),n.sqrt&&(o=n.sqrt);let{nBitLength:a,nByteLength:u}=Nf(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:t,isLE:r,BITS:a,BYTES:u,MASK:yo(a),ZERO:er,ONE:qt,allowedLengths:c,create:h=>_r(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return er<=h&&h<t},is0:h=>h===er,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&qt)===qt,neg:h=>_r(-h,t),eql:(h,p)=>h===p,sqr:h=>_r(h*h,t),add:(h,p)=>_r(h+p,t),sub:(h,p)=>_r(h-p,t),mul:(h,p)=>_r(h*p,t),pow:(h,p)=>JI(f,h,p),div:(h,p)=>_r(h*Bx(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Bx(h,t),sqrt:o||(h=>(d||(d=zI(t)),d(f,h))),toBytes:h=>r?xy(h,u):kc(h,u),fromBytes:(h,p=!0)=>{if(c){if(!c.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+h.length);let y=new Uint8Array(u);y.set(h,r?0:y.length-h.length),h=y}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let g=r?by(h):Ai(h);if(s&&(g=_r(g,t)),!p&&!f.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>kf(f,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(f)}function Lx(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Ay(t){let e=Lx(t);return e+Math.ceil(e/2)}function Cf(t,e,r=!1){let n=t.length,i=Lx(e),o=Ay(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?by(t):Ai(t),c=_r(s,e-qt)+qt;return r?xy(c,i):kc(c,i)}var Nc=BigInt(0),xs=BigInt(1);function Tu(t,e){let r=e.negate();return t?r:e}function Pf(t,e){let r=kf(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function $x(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ty(t,e){$x(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=yo(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function Px(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,c=Number(t&i),a=t>>s;c>n&&(c-=o,a+=xs);let u=e*n,d=u+Math.abs(c)-1,f=c===0,h=c<0,p=e%2!==0;return{nextN:a,offset:d,isZero:f,isNeg:h,isNegF:p,offsetF:u}}function ZI(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function XI(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}var _y=new WeakMap,Hx=new WeakMap;function By(t){return Hx.get(t)||1}function Mx(t){if(t!==Nc)throw new Error("invalid wNAF")}var Lf=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>Nc;)r&xs&&(n=n.add(i)),i=i.double(),r>>=xs;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Ty(r,this.bits),o=[],s=e,c=s;for(let a=0;a<n;a++){c=s,o.push(c);for(let u=1;u<i;u++)c=c.add(s),o.push(c);s=c.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=Ty(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=Px(n,c,s);n=a,d?o=o.add(Tu(h,r[p])):i=i.add(Tu(f,r[u]))}return Mx(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Ty(e,this.bits);for(let s=0;s<o.windows&&n!==Nc;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=Px(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return Mx(n),i}getPrecomputes(e,r,n){let i=_y.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),_y.set(r,i))),i}cached(e,r,n){let i=By(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=By(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){$x(r,this.bits),Hx.set(e,r),_y.delete(e)}hasCache(e){return By(e)!==1}};function Vx(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>Nc||n>Nc;)r&xs&&(o=o.add(i)),n&xs&&(s=s.add(i)),i=i.double(),r>>=xs,n>>=xs;return{p1:o,p2:s}}function qx(t,e,r,n){ZI(r,t),XI(n,e);let i=r.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=t.ZERO,c=Df(BigInt(i)),a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);let u=yo(a),d=new Array(Number(u)+1).fill(s),f=Math.floor((e.BITS-1)/a)*a,h=s;for(let p=f;p>=0;p-=a){d.fill(s);for(let y=0;y<o;y++){let E=n[y],S=Number(E>>BigInt(p)&u);d[S]=d[S].add(r[y])}let g=s;for(let y=d.length-1,E=s;y>0;y--)E=E.add(d[y]),g=g.add(E);if(h=h.add(g),p!==0)for(let y=0;y<a;y++)h=h.double()}return h}function Kx(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Sy(e),e}else return go(t,{isLE:r})}function Fx(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>Nc))throw new Error(`CURVE.${a} must be positive bigint`)}let i=Kx(e.p,r.Fp,n),o=Kx(e.n,r.Fn,n),c=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of c)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}var jx=(t,e)=>(t+(t>=0?e:-e)/Wx)/e;function QI(t,e,r){let[[n,i],[o,s]]=e,c=jx(s*t,r),a=jx(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<_i,h=d<_i;f&&(u=-u),h&&(d=-d);let p=yo(Math.ceil(Df(r)/2))+Cc;if(u<_i||u>=p||d<_i||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Ry(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Iy(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return xu(r.lowS,"lowS"),xu(r.prehash,"prehash"),r.format!==void 0&&Ry(r.format),r}var Uy=class extends Error{constructor(e=""){super(e)}},Ti={Err:Uy,_tlv:{encode:(t,e)=>{let{Err:r}=Ti;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=Eu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Eu(i.length/2|128):"";return Eu(t)+o+i+e},decode(t,e){let{Err:r}=Ti,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=a,s<128)throw new r("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+s);if(c.length!==s)throw new r("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=Ti;if(t<_i)throw new e("integer: negative integers are not allowed");let r=Eu(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Ti;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ai(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ti,i=ot("signature",t),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:c,l:a}=n.decode(2,o),{v:u,l:d}=n.decode(2,a);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=Ti,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},_i=BigInt(0),Cc=BigInt(1),Wx=BigInt(2),Mf=BigInt(3),e8=BigInt(4);function mo(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let i=ot("private key",e);try{n=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function t8(t,e={}){let r=Fx("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Au(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:a}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=zx(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(G,_,D){let{x,y:U}=_.toAffine(),L=n.toBytes(x);if(xu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return ut(Gx(N),L)}else return ut(Uint8Array.of(4),L,n.toBytes(U))}function h(G){po(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,x=G.length,U=G[0],L=G.subarray(1);if(x===_&&(U===2||U===3)){let N=n.fromBytes(L);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let R=y(N),C;try{C=n.sqrt(R)}catch(J){let z=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(C);return(U&1)===1!==P&&(C=n.neg(C)),{x:N,y:C}}else if(x===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!E(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${x}, expected compressed=${_} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let _=n.sqr(G),D=n.mul(_,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function E(G,_){let D=n.sqr(_),x=y(G);return n.eql(D,x)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,Mf),e8),I=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,I)))throw new Error("bad curve params: a or b");function A(G,_,D=!1){if(!n.isValid(_)||D&&n.is0(_))throw new Error(`bad point coordinate ${G}`);return _}function O(G){if(!(G instanceof $))throw new Error("ProjectivePoint expected")}function T(G){if(!a||!a.basises)throw new Error("no endo");return QI(G,a.basises,i.ORDER)}let M=Ey((G,_)=>{let{X:D,Y:x,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:x};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(x,_),C=n.mul(U,_);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x:N,y:R}}),q=Ey(G=>{if(G.is0()){if(e.allowInfinityPoint&&!n.is0(G.Y))return;throw new Error("bad point: ZERO")}let{x:_,y:D}=G.toAffine();if(!n.isValid(_)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(_,D))throw new Error("bad point: equation left != right");if(!G.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(G,_,D,x,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=Tu(x,_),D=Tu(U,D),_.add(D)}class ${constructor(_,D,x){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:x}=_||{};if(!_||!n.isValid(D)||!n.isValid(x))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(x)?$.ZERO:new $(D,x,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(po(_,void 0,"point")));return D.assertValidity(),D}static fromHex(_){return $.fromBytes(ot("pointHex",_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,D=!0){return Q.createCache(this,_),D||this.multiply(Mf),this}assertValidity(){q(this)}hasEvenY(){let{y:_}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(_)}equals(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(x,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:_,b:D}=o,x=n.mul(D,Mf),{X:U,Y:L,Z:N}=this,R=n.ZERO,C=n.ZERO,P=n.ZERO,V=n.mul(U,U),J=n.mul(L,L),z=n.mul(N,N),W=n.mul(U,L);return W=n.add(W,W),P=n.mul(U,N),P=n.add(P,P),R=n.mul(_,P),C=n.mul(x,z),C=n.add(R,C),R=n.sub(J,C),C=n.add(J,C),C=n.mul(R,C),R=n.mul(W,R),P=n.mul(x,P),z=n.mul(_,z),W=n.sub(V,z),W=n.mul(_,W),W=n.add(W,P),P=n.add(V,V),V=n.add(P,V),V=n.add(V,z),V=n.mul(V,W),C=n.add(C,V),z=n.mul(L,N),z=n.add(z,z),V=n.mul(z,W),R=n.sub(R,V),P=n.mul(z,J),P=n.add(P,P),P=n.add(P,P),new $(R,C,P)}add(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,Mf),W=n.mul(D,L),Y=n.mul(x,N),Z=n.mul(U,R),ue=n.add(D,x),ee=n.add(L,N);ue=n.mul(ue,ee),ee=n.add(W,Y),ue=n.sub(ue,ee),ee=n.add(D,U);let ce=n.add(L,R);return ee=n.mul(ee,ce),ce=n.add(W,Z),ee=n.sub(ee,ce),ce=n.add(x,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,Z),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,Z),V=n.add(C,V),C=n.sub(Y,V),V=n.add(Y,V),P=n.mul(C,V),Y=n.add(W,W),Y=n.add(Y,W),Z=n.mul(J,Z),ee=n.mul(z,ee),Y=n.add(Y,Z),Z=n.sub(W,Z),Z=n.mul(J,Z),ee=n.add(ee,Z),W=n.mul(Y,ee),P=n.add(P,W),W=n.mul(ce,ee),C=n.mul(ue,C),C=n.sub(C,W),W=n.mul(ue,Y),V=n.mul(ce,V),V=n.add(V,W),new $(C,P,V)}subtract(_){return this.add(_.negate())}is0(){return this.equals($.ZERO)}multiply(_){let{endo:D}=e;if(!i.isValidNot0(_))throw new Error("invalid scalar: out of range");let x,U,L=N=>Q.cached(this,N,R=>Pf($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(_),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),x=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);x=N,U=R}return Pf($,[x,U])[0]}multiplyUnsafe(_){let{endo:D}=e,x=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===_i||x.is0())return $.ZERO;if(_===Cc)return x;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=Vx($,x,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(x,_)}multiplyAndAddUnsafe(_,D,x){let U=this.multiplyUnsafe(D).add(_.multiplyUnsafe(x));return U.is0()?void 0:U}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===Cc?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===Cc?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return xu(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Ct(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(_=!0){return this.toBytes(_)}_setWindowSize(_){this.precompute(_)}static normalizeZ(_){return Pf($,_)}static msm(_,D){return qx($,i,_,D)}static fromPrivateKey(_){return $.BASE.multiply(mo(i,_))}}$.BASE=new $(o.Gx,o.Gy,n.ONE),$.ZERO=new $(n.ZERO,n.ONE,n.ZERO),$.Fp=n,$.Fn=i;let X=i.BITS,Q=new Lf($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function Gx(t){return Uint8Array.of(t?2:3)}function zx(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function r8(t,e={}){let{Fn:r}=t,n=e.randomBytes||Tr,i=Object.assign(zx(t.Fp,r),{seed:Ay(r.ORDER)});function o(p){try{return!!mo(r,p)}catch{return!1}}function s(p,g){let{publicKey:y,publicKeyUncompressed:E}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==E?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return Cf(po(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(mo(r,p)).toBytes(g)}function u(p){let g=c(p);return{secretKey:g,publicKey:a(g)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;let{secretKey:g,publicKey:y,publicKeyUncompressed:E}=i;if(r.allowedLengths||g===y)return;let S=ot("key",p).length;return S===y||S===E}function f(p,g,y=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");let E=mo(r,p);return t.fromHex(g).multiply(E).toBytes(y)}return Object.freeze({getPublicKey:a,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:c,isValidPrivateKey:o,randomPrivateKey:c,normPrivateKeyToScalar:p=>mo(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function n8(t,e,r={}){If(e),Au(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||Tr,i=r.hmac||((D,...x)=>yy(e,D,ut(...x))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=r8(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},y="compact";function E(D){let x=c>>Cc;return D>x}function S(D,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return x}function I(D,x){Ry(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return po(D,L,`${x} signature`)}class A{constructor(x,U,L){this.r=S("r",x),this.s=S("s",U),L!=null&&(this.recovery=L),Object.freeze(this)}static fromBytes(x,U=y){I(x,U);let L;if(U==="der"){let{r:P,s:V}=Ti.toSig(po(x));return new A(P,V)}U==="recovered"&&(L=x[0],U="compact",x=x.subarray(1));let N=s.BYTES,R=x.subarray(0,N),C=x.subarray(N,N*2);return new A(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(x,U){return this.fromBytes(Ar(x),U)}addRecoveryBit(x){return new A(this.r,this.s,x)}recoverPublicKey(x){let U=o.ORDER,{r:L,s:N,recovery:R}=this;if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");if(c*Wx<U&&R>1)throw new Error("recovery id is ambiguous for h>1 curve");let P=R===2||R===3?L+c:L;if(!o.isValid(P))throw new Error("recovery id 2 or 3 invalid");let V=o.toBytes(P),J=t.fromBytes(ut(Gx((R&1)===0),V)),z=s.inv(P),W=T(ot("msgHash",x)),Y=s.create(-W*z),Z=s.create(N*z),ue=t.BASE.multiplyUnsafe(Y).add(J.multiplyUnsafe(Z));if(ue.is0())throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return E(this.s)}toBytes(x=y){if(Ry(x),x==="der")return Ar(Ti.hexFromSig(this));let U=s.toBytes(this.r),L=s.toBytes(this.s);if(x==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ut(Uint8Array.of(this.recovery),U,L)}return ut(U,L)}toHex(x){return Ct(this.toBytes(x))}assertValidity(){}static fromCompact(x){return A.fromBytes(ot("sig",x),"compact")}static fromDER(x){return A.fromBytes(ot("sig",x),"der")}normalizeS(){return this.hasHighS()?new A(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ct(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ct(this.toBytes("compact"))}}let O=r.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let U=Ai(x),L=x.length*8-a;return L>0?U>>BigInt(L):U},T=r.bits2int_modN||function(x){return s.create(O(x))},M=yo(a);function q(D){return Tx("num < 2^"+a,D,_i,M),s.toBytes(D)}function j(D,x){return po(D,void 0,"message"),x?po(e(D),void 0,"prehashed message"):D}function $(D,x,U){if(["recovered","canonical"].some(Y=>Y in U))throw new Error("sign() legacy options not supported");let{lowS:L,prehash:N,extraEntropy:R}=Iy(U,g);D=j(D,N);let C=T(D),P=mo(s,x),V=[q(P),q(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(ot("extraEntropy",Y))}let J=ut(...V),z=C;function W(Y){let Z=O(Y);if(!s.isValidNot0(Z))return;let ue=s.inv(Z),ee=t.BASE.multiply(Z).toAffine(),ce=s.create(ee.x);if(ce===_i)return;let Ie=s.create(ue*s.create(z+ce*P));if(Ie===_i)return;let Pe=(ee.x===ce?0:2)|Number(ee.y&Cc),Ge=Ie;return L&&E(Ie)&&(Ge=s.neg(Ie),Pe^=1),new A(ce,Ge,Pe)}return{seed:J,k2sig:W}}function X(D,x,U={}){D=ot("message",D);let{seed:L,k2sig:N}=$(D,x,U);return _x(e.outputLen,s.BYTES,i)(L,N)}function Q(D){let x,U=typeof D=="string"||ms(D),L=!U&&D!==null&&typeof D=="object"&&typeof D.r=="bigint"&&typeof D.s=="bigint";if(!U&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(L)x=new A(D.r,D.s);else if(U){try{x=A.fromBytes(ot("sig",D),"der")}catch(N){if(!(N instanceof Ti.Err))throw N}if(!x)try{x=A.fromBytes(ot("sig",D),"compact")}catch{return!1}}return x||!1}function G(D,x,U,L={}){let{lowS:N,prehash:R,format:C}=Iy(L,g);if(U=ot("publicKey",U),x=j(ot("message",x),R),"strict"in L)throw new Error("options.strict was renamed to lowS");let P=C===void 0?Q(D):A.fromBytes(ot("sig",D),C);if(P===!1)return!1;try{let V=t.fromBytes(U);if(N&&P.hasHighS())return!1;let{r:J,s:z}=P,W=T(x),Y=s.inv(z),Z=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(Z).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,x,U={}){let{prehash:L}=Iy(U,g);return x=j(x,L),A.fromBytes(D,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:X,verify:G,recoverPublicKey:_,Signature:A,hash:e})}function i8(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,i=go(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),o={Fp:r,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:o}}function o8(t){let{CURVE:e,curveOpts:r}=i8(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function s8(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Nf(r.Fn.ORDER,r.Fn.BITS))})}function Yx(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=o8(t),o=t8(e,r),s=n8(o,n,i);return s8(t,s)}function Jx(t,e){let r=n=>Yx({...t,hash:n});return{...r(e),create:r}}var Lc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},c8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},a8=BigInt(0),Zx=BigInt(1),Oy=BigInt(2);function u8(t){let e=Lc.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=Br(d,r,e)*d%e,h=Br(f,r,e)*d%e,p=Br(h,Oy,e)*u%e,g=Br(p,i,e)*p%e,y=Br(g,o,e)*g%e,E=Br(y,c,e)*y%e,S=Br(E,a,e)*E%e,I=Br(S,c,e)*y%e,A=Br(I,r,e)*d%e,O=Br(A,s,e)*g%e,T=Br(O,n,e)*u%e,M=Br(T,Oy,e);if(!Kf.eql(Kf.sqr(M),t))throw new Error("Cannot find square root");return M}var Kf=go(Lc.p,{sqrt:u8}),wo=Jx({...Lc,Fp:Kf,lowS:!0,endo:c8},Oe),Xx={};function $f(t,...e){let r=Xx[t];if(r===void 0){let n=Oe(ws(t));r=ut(n,n),Xx[t]=r}return Oe(ut(r,...e))}var ky=t=>t.toBytes(!0).slice(1),Pc=wo.Point,Ny=t=>t%Oy===a8;function Dy(t){let{Fn:e,BASE:r}=Pc,n=mo(e,t),i=r.multiply(n);return{scalar:Ny(i.y)?n:e.neg(n),bytes:ky(i)}}function eE(t){let e=Kf;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),i=e.sqrt(n);Ny(i)||(i=e.neg(i));let o=Pc.fromAffine({x:t,y:i});return o.assertValidity(),o}var _u=Ai;function tE(...t){return Pc.Fn.create(_u($f("BIP0340/challenge",...t)))}function Qx(t){return Dy(t).bytes}function d8(t,e,r=Tr(32)){let{Fn:n}=Pc,i=ot("message",t),{bytes:o,scalar:s}=Dy(e),c=ot("auxRand",r,32),a=n.toBytes(s^_u($f("BIP0340/aux",c))),u=$f("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Dy(u),h=tE(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!rE(p,i,o))throw new Error("sign: Invalid signature produced");return p}function rE(t,e,r){let{Fn:n,BASE:i}=Pc,o=ot("signature",t,64),s=ot("message",e),c=ot("publicKey",r,32);try{let a=eE(_u(c)),u=_u(o.subarray(0,32));if(!Su(u,Zx,Lc.p))return!1;let d=_u(o.subarray(32,64));if(!Su(d,Zx,Lc.n))return!1;let f=tE(n.toBytes(u),ky(a),s),h=i.multiplyUnsafe(d).add(a.multiplyUnsafe(n.neg(f))),{x:p,y:g}=h.toAffine();return!(h.is0()||!Ny(g)||p!==u)}catch{return!1}}var Ir=(()=>{let r=(i=Tr(48))=>Cf(i,Lc.n);wo.utils.randomSecretKey;function n(i){let o=r(i);return{secretKey:o,publicKey:Qx(o)}}return{keygen:n,getPublicKey:Qx,sign:d8,verify:rE,Point:Pc,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:$f,lift_x:eE,pointToBytes:ky,numberToBytesBE:kc,bytesToNumberBE:Ai,mod:_r},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var f8=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),iE=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),l8=iE.map(t=>(9*t+5)%16),oE=(()=>{let r=[[iE],[l8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>f8[o]));return r})(),sE=oE[0],cE=oE[1],aE=[[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(t=>Uint8Array.from(t)),h8=sE.map((t,e)=>t.map(r=>aE[e][r])),p8=cE.map((t,e)=>t.map(r=>aE[e][r])),y8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),g8=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function nE(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}var Hf=new Uint32Array(16),Cy=class extends Dc{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:r,h2:n,h3:i,h4:o}=this;return[e,r,n,i,o]}set(e,r,n,i,o){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=o|0}process(e,r){for(let p=0;p<16;p++,r+=4)Hf[p]=e.getUint32(r,!0);let n=this.h0|0,i=n,o=this.h1|0,s=o,c=this.h2|0,a=c,u=this.h3|0,d=u,f=this.h4|0,h=f;for(let p=0;p<5;p++){let g=4-p,y=y8[p],E=g8[p],S=sE[p],I=cE[p],A=h8[p],O=p8[p];for(let T=0;T<16;T++){let M=wu(n+nE(p,o,c,u)+Hf[S[T]]+y,A[T])+f|0;n=f,f=u,u=wu(c,10)|0,c=o,o=M}for(let T=0;T<16;T++){let M=wu(i+nE(g,s,a,d)+Hf[I[T]]+E,O[T])+h|0;i=h,h=d,d=wu(a,10)|0,a=s,s=M}}this.set(this.h1+c+d|0,this.h2+u+h|0,this.h3+f+i|0,this.h4+n+s|0,this.h0+o+a|0)}roundClean(){Vn(Hf)}destroy(){this.destroyed=!0,Vn(this.buffer),this.set(0,0,0,0,0)}},uE=Uf(()=>new Cy);l();l();function Mc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function m8(t,...e){if(!Mc(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function pE(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function My(t){if(typeof t!="function")throw new Error("function expected");return!0}function Kc(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Iu(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function qf(t){if(!Array.isArray(t))throw new Error("array expected")}function yE(t,e){if(!pE(!0,e))throw new Error(`${t}: array of strings expected`)}function Ky(t,e){if(!pE(!1,e))throw new Error(`${t}: array of numbers expected`)}function Ru(...t){let e=o=>o,r=(o,s)=>c=>o(s(c)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function jf(t){let e=typeof t=="string"?t.split(""):t,r=e.length;yE("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(qf(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${t}`);return e[o]})),decode:i=>(qf(i),i.map(o=>{Kc("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function Wf(t=""){return Kc("join",t),{encode:e=>(yE("join.decode",e),e.join(t)),decode:e=>(Kc("join.decode",e),e.split(t))}}function w8(t){return My(t),{encode:e=>e,decode:e=>t(e)}}function dE(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(qf(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(Iu(c),c<0||c>=e)throw new Error(`invalid integer: ${c}`);return c}),s=o.length;for(;;){let c=0,a=!0;for(let u=n;u<s;u++){let d=o[u],f=e*c,h=f+d;if(!Number.isSafeInteger(h)||f/e!==c||h-d!==f)throw new Error("convertRadix: carry overflow");let p=h/r;c=h%r;let g=Math.floor(p);if(o[u]=g,!Number.isSafeInteger(g)||g*r+c!==h)throw new Error("convertRadix: carry overflow");if(a)g?a=!1:n=u;else continue}if(i.push(c),a)break}for(let c=0;c<t.length-1&&t[c]===0;c++)i.push(0);return i.reverse()}var gE=(t,e)=>e===0?t:gE(e,t%e),Ff=(t,e)=>t+(e-gE(t,e)),Vf=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Ly(t,e,r,n){if(qf(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(Ff(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Ff(e,r)}`);let i=0,o=0,s=Vf[e],c=Vf[r]-1,a=[];for(let u of t){if(Iu(u),u>=s)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=r;o-=r)a.push((i>>o-r&c)>>>0);let d=Vf[o];if(d===void 0)throw new Error("invalid carry");i&=d-1}if(i=i<<r-o&c,!n&&o>=e)throw new Error("Excess padding");if(!n&&i>0)throw new Error(`Non-zero padding: ${i}`);return n&&o>0&&a.push(i>>>0),a}function b8(t){Iu(t);let e=2**8;return{encode:r=>{if(!Mc(r))throw new Error("radix.encode input should be Uint8Array");return dE(Array.from(r),e,t)},decode:r=>(Ky("radix.decode",r),Uint8Array.from(dE(r,t,e)))}}function $y(t,e=!1){if(Iu(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ff(8,t)>32||Ff(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Mc(r))throw new Error("radix2.encode input should be Uint8Array");return Ly(Array.from(r),8,t,!e)},decode:r=>(Ky("radix2.decode",r),Uint8Array.from(Ly(r,t,8,e)))}}function fE(t){return My(t),function(...e){try{return t.apply(null,e)}catch{}}}function x8(t,e){return Iu(t),My(e),{encode(r){if(!Mc(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!Mc(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=r.slice(-t),o=e(n).slice(0,t);for(let s=0;s<t;s++)if(o[s]!==i[s])throw new Error("Invalid checksum");return n}}}var $c=Ru($y(6),jf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Wf("")),E8=t=>Ru(b8(58),jf(t),Wf("")),Gf=E8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var mE=t=>Ru(x8(4,e=>t(t(e))),Gf);var Py=Ru(jf("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Wf("")),lE=[996825010,642813549,513874426,1027748829,705979059];function Bu(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<lE.length;n++)(e>>n&1)===1&&(r^=lE[n]);return r}function hE(t,e,r=1){let n=t.length,i=1;for(let o=0;o<n;o++){let s=t.charCodeAt(o);if(s<33||s>126)throw new Error(`Invalid prefix (${t})`);i=Bu(i)^s>>5}i=Bu(i);for(let o=0;o<n;o++)i=Bu(i)^t.charCodeAt(o)&31;for(let o of e)i=Bu(i)^o;for(let o=0;o<6;o++)i=Bu(i);return i^=r,Py.encode(Ly([i%Vf[30]],30,5,!1))}function wE(t){let e=t==="bech32"?1:734539939,r=$y(5),n=r.decode,i=r.encode,o=fE(n);function s(f,h,p=90){Kc("bech32.encode prefix",f),Mc(h)&&(h=Array.from(h)),Ky("bech32.encode",h);let g=f.length;if(g===0)throw new TypeError(`Invalid prefix length ${g}`);let y=g+7+h.length;if(p!==!1&&y>p)throw new TypeError(`Length ${y} exceeds limit ${p}`);let E=f.toLowerCase(),S=hE(E,h,e);return`${E}1${Py.encode(h)}${S}`}function c(f,h=90){Kc("bech32.decode input",f);let p=f.length;if(p<8||h!==!1&&p>h)throw new TypeError(`invalid string length: ${p} (${f}). Expected (8..${h})`);let g=f.toLowerCase();if(f!==g&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");let y=g.lastIndexOf("1");if(y===0||y===-1)throw new Error('Letter "1" must be present between prefix and data only');let E=g.slice(0,y),S=g.slice(y+1);if(S.length<6)throw new Error("Data must be at least 6 characters long");let I=Py.decode(S).slice(0,-6),A=hE(E,I,e);if(!S.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:E,words:I}}let a=fE(c);function u(f){let{prefix:h,words:p}=c(f,!1);return{prefix:h,words:p,bytes:n(p)}}function d(f,h){return s(f,i(h))}return{encode:s,decode:c,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:a,fromWords:n,fromWordsUnsafe:o,toWords:i}}var zf=wE("bech32"),Hc=wE("bech32m"),bE={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},v8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S8={encode(t){return m8(t),t.toHex()},decode(t){return Kc("hex",t),Uint8Array.fromHex(t)}},Ae=v8?S8:Ru($y(4),jf("0123456789abcdef"),Wf(""),w8(t=>{if(typeof t!="string"||t.length%2!==0)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}));var $e=new Uint8Array,Fy=new Uint8Array([0]);function Vc(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function Gr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function A8(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!Gr(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var jy=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function qc(t){return Object.prototype.toString.call(t)==="[object Object]"}function qn(t){return Number.isSafeInteger(t)}var Yf={equalBytes:Vc,isBytes:Gr,isCoder:Rr,checkBounds:EE,concatBytes:A8,createView:jy,isPlainObject:qc},xE=t=>{if(t!==null&&typeof t!="string"&&!Rr(t)&&!Gr(t)&&!qn(t))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${t} (${typeof t})`);return{encodeStream(e,r){if(t===null)return;if(Rr(t))return t.encodeStream(e,r);let n;if(typeof t=="number"?n=t:typeof t=="string"&&(n=Bi.resolve(e.stack,t)),typeof n=="bigint"&&(n=Number(n)),n===void 0||n!==r)throw e.err(`Wrong length: ${n} len=${t} exp=${r} (${typeof r})`)},decodeStream(e){let r;if(Rr(t)?r=Number(t.decodeStream(e)):typeof t=="number"?r=t:typeof t=="string"&&(r=Bi.resolve(e.stack,t)),typeof r=="bigint"&&(r=Number(r)),typeof r!="number")throw e.err(`Wrong length: ${r}`);return r}}},Ut={BITS:32,FULL_MASK:-1>>>0,len:t=>Math.ceil(t/32),create:t=>new Uint32Array(Ut.len(t)),clean:t=>t.fill(0),debug:t=>Array.from(t).map(e=>(e>>>0).toString(2).padStart(32,"0")),checkLen:(t,e)=>{if(Ut.len(e)!==t.length)throw new Error(`wrong length=${t.length}. Expected: ${Ut.len(e)}`)},chunkLen:(t,e,r)=>{if(e<0)throw new Error(`wrong pos=${e}`);if(e+r>t)throw new Error(`wrong range=${e}/${r} of ${t}`)},set:(t,e,r,n=!0)=>!n&&t[e]&r?!1:(t[e]|=r,!0),pos:(t,e)=>({chunk:Math.floor((t+e)/32),mask:1<<32-(t+e)%32-1}),indices:(t,e,r=!1)=>{Ut.checkLen(t,e);let{FULL_MASK:n,BITS:i}=Ut,o=i-e%i,s=o?n>>>o<<o:n,c=[];for(let a=0;a<t.length;a++){let u=t[a];if(r&&(u=~u),a===t.length-1&&(u&=s),u!==0)for(let d=0;d<i;d++){let f=1<<i-d-1;u&f&&c.push(a*i+d)}}return c},range:t=>{let e=[],r;for(let n of t)r===void 0||n!==r.pos+r.length?e.push(r={pos:n,length:1}):r.length+=1;return e},rangeDebug:(t,e,r=!1)=>`[${Ut.range(Ut.indices(t,e,r)).map(n=>`(${n.pos}/${n.length})`).join(", ")}]`,setRange:(t,e,r,n,i=!0)=>{Ut.chunkLen(e,r,n);let{FULL_MASK:o,BITS:s}=Ut,c=r%s?Math.floor(r/s):void 0,a=r+n,u=a%s?Math.floor(a/s):void 0;if(c!==void 0&&c===u)return Ut.set(t,c,o>>>s-n<<s-n-r,i);if(c!==void 0&&!Ut.set(t,c,o>>>r%s,i))return!1;let d=c!==void 0?c+1:r/s,f=u!==void 0?u:a/s;for(let h=d;h<f;h++)if(!Ut.set(t,h,o,i))return!1;return!(u!==void 0&&c!==u&&!Ut.set(t,u,o<<s-a%s,i))}},Bi={pushObj:(t,e,r)=>{let n={obj:e};t.push(n),r((i,o)=>{n.field=i,o(),n.field=void 0}),t.pop()},path:t=>{let e=[];for(let r of t)r.field!==void 0&&e.push(r.field);return e.join("/")},err:(t,e,r)=>{let n=new Error(`${t}(${Bi.path(e)}): ${typeof r=="string"?r:r.message}`);return r instanceof Error&&r.stack&&(n.stack=r.stack),n},resolve:(t,e)=>{let r=e.split("/"),n=t.map(s=>s.obj),i=0;for(;i<r.length&&r[i]==="..";i++)n.pop();let o=n.pop();for(;i<r.length;i++){if(!o||o[r[i]]===void 0)return;o=o[r[i]]}return o}},Hy=class t{constructor(e,r={},n=[],i=void 0,o=0){this.pos=0,this.bitBuf=0,this.bitPos=0,this.data=e,this.opts=r,this.stack=n,this.parent=i,this.parentOffset=o,this.view=jy(e)}_enablePointers(){if(this.parent)return this.parent._enablePointers();this.bs||(this.bs=Ut.create(this.data.length),Ut.setRange(this.bs,this.data.length,0,this.pos,this.opts.allowMultipleReads))}markBytesBS(e,r){return this.parent?this.parent.markBytesBS(this.parentOffset+e,r):!r||!this.bs?!0:Ut.setRange(this.bs,this.data.length,e,r,!1)}markBytes(e){let r=this.pos;this.pos+=e;let n=this.markBytesBS(r,e);if(!this.opts.allowMultipleReads&&!n)throw this.err(`multiple read pos=${this.pos} len=${e}`);return n}pushObj(e,r){return Bi.pushObj(this.stack,e,r)}readView(e,r){if(!Number.isFinite(e))throw this.err(`readView: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readView: Unexpected end of buffer");let n=r(this.view,this.pos);return this.markBytes(e),n}absBytes(e){if(e>this.data.length)throw new Error("Unexpected end of buffer");return this.data.subarray(e)}finish(){if(!this.opts.allowUnreadBytes){if(this.bitPos)throw this.err(`${this.bitPos} bits left after unpack: ${Ae.encode(this.data.slice(this.pos))}`);if(this.bs&&!this.parent){let e=Ut.indices(this.bs,this.data.length,!0);if(e.length){let r=Ut.range(e).map(({pos:n,length:i})=>`(${n}/${i})[${Ae.encode(this.data.subarray(n,n+i))}]`).join(", ");throw this.err(`unread byte ranges: ${r} (total=${this.data.length})`)}else return}if(!this.isEnd())throw this.err(`${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${Ae.encode(this.data.slice(this.pos))}`)}}err(e){return Bi.err("Reader",this.stack,e)}offsetReader(e){if(e>this.data.length)throw this.err("offsetReader: Unexpected end of buffer");return new t(this.absBytes(e),this.opts,this.stack,this,e)}bytes(e,r=!1){if(this.bitPos)throw this.err("readBytes: bitPos not empty");if(!Number.isFinite(e))throw this.err(`readBytes: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readBytes: Unexpected end of buffer");let n=this.data.subarray(this.pos,this.pos+e);return r||this.markBytes(e),n}byte(e=!1){if(this.bitPos)throw this.err("readByte: bitPos not empty");if(this.pos+1>this.data.length)throw this.err("readBytes: Unexpected end of buffer");let r=this.data[this.pos];return e||this.markBytes(1),r}get leftBytes(){return this.data.length-this.pos}get totalBytes(){return this.data.length}isEnd(){return this.pos>=this.data.length&&!this.bitPos}bits(e){if(e>32)throw this.err("BitReader: cannot read more than 32 bits in single call");let r=0;for(;e;){this.bitPos||(this.bitBuf=this.byte(),this.bitPos=8);let n=Math.min(e,this.bitPos);this.bitPos-=n,r=r<<n|this.bitBuf>>this.bitPos&2**n-1,this.bitBuf&=2**this.bitPos-1,e-=n}return r>>>0}find(e,r=this.pos){if(!Gr(e))throw this.err(`find: needle is not bytes! ${e}`);if(this.bitPos)throw this.err("findByte: bitPos not empty");if(!e.length)throw this.err("find: needle is empty");for(let n=r;(n=this.data.indexOf(e[0],n))!==-1;n++){if(n===-1||this.data.length-n<e.length)return;if(Vc(e,this.data.subarray(n,n+e.length)))return n}}},Vy=class{constructor(e=[]){this.pos=0,this.buffers=[],this.ptrs=[],this.bitBuf=0,this.bitPos=0,this.viewBuf=new Uint8Array(8),this.finished=!1,this.stack=e,this.view=jy(this.viewBuf)}pushObj(e,r){return Bi.pushObj(this.stack,e,r)}writeView(e,r){if(this.finished)throw this.err("buffer: finished");if(!qn(e)||e>8)throw new Error(`wrong writeView length=${e}`);r(this.view),this.bytes(this.viewBuf.slice(0,e)),this.viewBuf.fill(0)}err(e){if(this.finished)throw this.err("buffer: finished");return Bi.err("Reader",this.stack,e)}bytes(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");this.buffers.push(e),this.pos+=e.length}byte(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeByte: ends with non-empty bit buffer");this.buffers.push(new Uint8Array([e])),this.pos++}finish(e=!0){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("buffer: ends with non-empty bit buffer");let r=this.buffers.concat(this.ptrs.map(o=>o.buffer)),n=r.map(o=>o.length).reduce((o,s)=>o+s,0),i=new Uint8Array(n);for(let o=0,s=0;o<r.length;o++){let c=r[o];i.set(c,s),s+=c.length}for(let o=this.pos,s=0;s<this.ptrs.length;s++){let c=this.ptrs[s];i.set(c.ptr.encode(o),c.pos),o+=c.buffer.length}if(e){this.buffers=[];for(let o of this.ptrs)o.buffer.fill(0);this.ptrs=[],this.finished=!0,this.bitBuf=0}return i}bits(e,r){if(r>32)throw this.err("writeBits: cannot write more than 32 bits in single call");if(e>=2**r)throw this.err(`writeBits: value (${e}) >= 2**bits (${r})`);for(;r;){let n=Math.min(r,8-this.bitPos);this.bitBuf=this.bitBuf<<n|e>>r-n,this.bitPos+=n,r-=n,e&=2**r-1,this.bitPos===8&&(this.bitPos=0,this.buffers.push(new Uint8Array([this.bitBuf])),this.pos++)}}},qy=t=>Uint8Array.from(t).reverse();function EE(t,e,r){if(r){let n=2n**(e-1n);if(t<-n||t>=n)throw new Error(`value out of signed bounds. Expected ${-n} <= ${t} < ${n}`)}else if(0n>t||t>=2n**e)throw new Error(`value out of unsigned bounds. Expected 0 <= ${t} < ${2n**e}`)}function vE(t){return{encodeStream:t.encodeStream,decodeStream:t.decodeStream,size:t.size,encode:e=>{let r=new Vy;return t.encodeStream(r,e),r.finish()},decode:(e,r={})=>{let n=new Hy(e,r),i=t.decodeStream(n);return n.finish(),i}}}function Ft(t,e){if(!Rr(t))throw new Error(`validate: invalid inner value ${t}`);if(typeof e!="function")throw new Error("validate: fn should be function");return vE({size:t.size,encodeStream:(r,n)=>{let i;try{i=e(n)}catch(o){throw r.err(o)}t.encodeStream(r,i)},decodeStream:r=>{let n=t.decodeStream(r);try{return e(n)}catch(i){throw r.err(i)}}})}var jt=t=>{let e=vE(t);return t.validate?Ft(e,t.validate):e},Jf=t=>qc(t)&&typeof t.decode=="function"&&typeof t.encode=="function";function Rr(t){return qc(t)&&Jf(t)&&typeof t.encodeStream=="function"&&typeof t.decodeStream=="function"&&(t.size===void 0||qn(t.size))}function T8(){return{encode:t=>{if(!Array.isArray(t))throw new Error("array expected");let e={};for(let r of t){if(!Array.isArray(r)||r.length!==2)throw new Error("array of two elements expected");let n=r[0],i=r[1];if(e[n]!==void 0)throw new Error(`key(${n}) appears twice in struct`);e[n]=i}return e},decode:t=>{if(!qc(t))throw new Error(`expected plain object, got ${t}`);return Object.entries(t)}}}var _8={encode:t=>{if(typeof t!="bigint")throw new Error(`expected bigint, got ${typeof t}`);if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`element bigger than MAX_SAFE_INTEGER=${t}`);return Number(t)},decode:t=>{if(!qn(t))throw new Error("element is not a safe integer");return BigInt(t)}};function B8(t){if(!qc(t))throw new Error("plain object expected");return{encode:e=>{if(!qn(e)||!(e in t))throw new Error(`wrong value ${e}`);return t[e]},decode:e=>{if(typeof e!="string")throw new Error(`wrong value ${typeof e}`);return t[e]}}}function I8(t,e=!1){if(!qn(t))throw new Error(`decimal/precision: wrong value ${t}`);if(typeof e!="boolean")throw new Error(`decimal/round: expected boolean, got ${typeof e}`);let r=10n**BigInt(t);return{encode:n=>{if(typeof n!="bigint")throw new Error(`expected bigint, got ${typeof n}`);let i=(n<0n?-n:n).toString(10),o=i.length-t;o<0&&(i=i.padStart(i.length-o,"0"),o=0);let s=i.length-1;for(;s>=o&&i[s]==="0";s--);let c=i.slice(0,o),a=i.slice(o,s+1);return c||(c="0"),n<0n&&(c="-"+c),a?`${c}.${a}`:c},decode:n=>{if(typeof n!="string")throw new Error(`expected string, got ${typeof n}`);if(n==="-0")throw new Error("negative zero is not allowed");let i=!1;if(n.startsWith("-")&&(i=!0,n=n.slice(1)),!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))throw new Error(`wrong string value=${n}`);let o=n.indexOf(".");o=o===-1?n.length:o;let s=n.slice(0,o),c=n.slice(o+1).replace(/0+$/,""),a=BigInt(s)*r;if(!e&&c.length>t)throw new Error(`fractional part cannot be represented with this precision (num=${n}, prec=${t})`);let u=Math.min(c.length,t),d=BigInt(c.slice(0,u))*10n**BigInt(t-u),f=a+d;return i?-f:f}}}function R8(t){if(!Array.isArray(t))throw new Error(`expected array, got ${typeof t}`);for(let e of t)if(!Jf(e))throw new Error(`wrong base coder ${e}`);return{encode:e=>{for(let r of t){let n=r.encode(e);if(n!==void 0)return n}throw new Error(`match/encode: cannot find match in ${e}`)},decode:e=>{for(let r of t){let n=r.decode(e);if(n!==void 0)return n}throw new Error(`match/decode: cannot find match in ${e}`)}}}var SE=t=>{if(!Jf(t))throw new Error("BaseCoder expected");return{encode:t.decode,decode:t.encode}},Ii={dict:T8,numberBigint:_8,tsEnum:B8,decimal:I8,match:R8,reverse:SE};var Wy=(t,e=!1,r=!1,n=!0)=>{if(!qn(t))throw new Error(`bigint/size: wrong value ${t}`);if(typeof e!="boolean")throw new Error(`bigint/le: expected boolean, got ${typeof e}`);if(typeof r!="boolean")throw new Error(`bigint/signed: expected boolean, got ${typeof r}`);if(typeof n!="boolean")throw new Error(`bigint/sized: expected boolean, got ${typeof n}`);let i=BigInt(t),o=2n**(8n*i-1n);return jt({size:n?t:void 0,encodeStream:(s,c)=>{r&&c<0&&(c=c|o);let a=[];for(let d=0;d<t;d++)a.push(Number(c&255n)),c>>=8n;let u=new Uint8Array(a).reverse();if(!n){let d=0;for(d=0;d<u.length&&u[d]===0;d++);u=u.subarray(d)}s.bytes(e?u.reverse():u)},decodeStream:s=>{let c=s.bytes(n?t:Math.min(t,s.leftBytes)),a=e?c:qy(c),u=0n;for(let d=0;d<a.length;d++)u|=BigInt(a[d])<<8n*BigInt(d);return r&&u&o&&(u=(u^o)-o),u},validate:s=>{if(typeof s!="bigint")throw new Error(`bigint: invalid value: ${s}`);return EE(s,8n*i,!!r),s}})};var AE=Wy(32,!1);var Fc=Wy(8,!0);var TE=Wy(8,!0,!0);var U8=(t,e)=>jt({size:t,encodeStream:(r,n)=>r.writeView(t,i=>e.write(i,n)),decodeStream:r=>r.readView(t,e.read),validate:r=>{if(typeof r!="number")throw new Error(`viewCoder: expected number, got ${typeof r}`);return e.validate&&e.validate(r),r}}),Uu=(t,e,r)=>{let n=t*8,i=2**(n-1),o=a=>{if(!qn(a))throw new Error(`sintView: value is not safe integer: ${a}`);if(a<-i||a>=i)throw new Error(`sintView: value out of bounds. Expected ${-i} <= ${a} < ${i}`)},s=2**n,c=a=>{if(!qn(a))throw new Error(`uintView: value is not safe integer: ${a}`);if(0>a||a>=s)throw new Error(`uintView: value out of bounds. Expected 0 <= ${a} < ${s}`)};return U8(t,{write:r.write,read:r.read,validate:e?o:c})},Te=Uu(4,!1,{read:(t,e)=>t.getUint32(e,!0),write:(t,e)=>t.setUint32(0,e,!0)}),_E=Uu(4,!1,{read:(t,e)=>t.getUint32(e,!1),write:(t,e)=>t.setUint32(0,e,!1)}),bo=Uu(4,!0,{read:(t,e)=>t.getInt32(e,!0),write:(t,e)=>t.setInt32(0,e,!0)});var Gy=Uu(2,!1,{read:(t,e)=>t.getUint16(e,!0),write:(t,e)=>t.setUint16(0,e,!0)});var mn=Uu(1,!1,{read:(t,e)=>t.getUint8(e),write:(t,e)=>t.setUint8(0,e)});var He=(t,e=!1)=>{if(typeof e!="boolean")throw new Error(`bytes/le: expected boolean, got ${typeof e}`);let r=xE(t),n=Gr(t);return jt({size:typeof t=="number"?t:void 0,encodeStream:(i,o)=>{n||r.encodeStream(i,o.length),i.bytes(e?qy(o):o),n&&i.bytes(t)},decodeStream:i=>{let o;if(n){let s=i.find(t);if(!s)throw i.err("bytes: cannot find terminator");o=i.bytes(s-i.pos),i.bytes(t.length)}else o=i.bytes(t===null?i.leftBytes:r.decodeStream(i));return e?qy(o):o},validate:i=>{if(!Gr(i))throw new Error(`bytes: invalid value ${i}`);return i}})};function BE(t,e){if(!Rr(e))throw new Error(`prefix: invalid inner value ${e}`);return gn(He(t),SE(e))}var Zf=(t,e=!1)=>Ft(gn(He(t,e),bE),r=>{if(typeof r!="string")throw new Error(`expected string, got ${typeof r}`);return r});var IE=(t,e={isLE:!1,with0x:!1})=>{let r=gn(He(t,e.isLE),Ae),n=e.with0x;if(typeof n!="boolean")throw new Error(`hex/with0x: expected boolean, got ${typeof n}`);return n&&(r=gn(r,{encode:i=>`0x${i}`,decode:i=>{if(!i.startsWith("0x"))throw new Error("hex(with0x=true).encode input should start with 0x");return i.slice(2)}})),r};function gn(t,e){if(!Rr(t))throw new Error(`apply: invalid inner value ${t}`);if(!Jf(e))throw new Error(`apply: invalid base value ${t}`);return jt({size:t.size,encodeStream:(r,n)=>{let i;try{i=e.decode(n)}catch(o){throw r.err(""+o)}return t.encodeStream(r,i)},decodeStream:r=>{let n=t.decodeStream(r);try{return e.encode(n)}catch(i){throw r.err(""+i)}}})}var RE=(t,e=!1)=>{if(!Gr(t))throw new Error(`flag/flagValue: expected Uint8Array, got ${typeof t}`);if(typeof e!="boolean")throw new Error(`flag/xor: expected boolean, got ${typeof e}`);return jt({size:t.length,encodeStream:(r,n)=>{!!n!==e&&r.bytes(t)},decodeStream:r=>{let n=r.leftBytes>=t.length;return n&&(n=Vc(r.bytes(t.length,!0),t),n&&r.bytes(t.length)),n!==e},validate:r=>{if(r!==void 0&&typeof r!="boolean")throw new Error(`flag: expected boolean value or undefined, got ${typeof r}`);return r}})};function UE(t,e,r){if(!Rr(e))throw new Error(`flagged: invalid inner value ${e}`);if(typeof t!="string"&&!Rr(e))throw new Error(`flagged: wrong path=${t}`);return jt({encodeStream:(n,i)=>{typeof t=="string"?Bi.resolve(n.stack,t)?e.encodeStream(n,i):r&&e.encodeStream(n,r):(t.encodeStream(n,!!i),i?e.encodeStream(n,i):r&&e.encodeStream(n,r))},decodeStream:n=>{let i=!1;if(typeof t=="string"?i=!!Bi.resolve(n.stack,t):i=t.decodeStream(n),i)return e.decodeStream(n);r&&e.decodeStream(n)}})}function Xf(t,e,r=!0){if(!Rr(t))throw new Error(`magic: invalid inner value ${t}`);if(typeof r!="boolean")throw new Error(`magic: expected boolean, got ${typeof r}`);return jt({size:t.size,encodeStream:(n,i)=>t.encodeStream(n,e),decodeStream:n=>{let i=t.decodeStream(n);if(r&&typeof i!="object"&&i!==e||Gr(e)&&!Vc(e,i))throw n.err(`magic: invalid value: ${i} !== ${e}`)},validate:n=>{if(n!==void 0)throw new Error(`magic: wrong value=${typeof n}`);return n}})}function OE(t){let e=0;for(let r of t){if(r.size===void 0)return;if(!qn(r.size))throw new Error(`sizeof: wrong element size=${e}`);e+=r.size}return e}function bt(t){if(!qc(t))throw new Error(`struct: expected plain object, got ${t}`);for(let e in t)if(!Rr(t[e]))throw new Error(`struct: field ${e} is not CoderType`);return jt({size:OE(Object.values(t)),encodeStream:(e,r)=>{e.pushObj(r,n=>{for(let i in t)n(i,()=>t[i].encodeStream(e,r[i]))})},decodeStream:e=>{let r={};return e.pushObj(r,n=>{for(let i in t)n(i,()=>r[i]=t[i].decodeStream(e))}),r},validate:e=>{if(typeof e!="object"||e===null)throw new Error(`struct: invalid value ${e}`);return e}})}function DE(t){if(!Array.isArray(t))throw new Error(`Packed.Tuple: got ${typeof t} instead of array`);for(let e=0;e<t.length;e++)if(!Rr(t[e]))throw new Error(`tuple: field ${e} is not CoderType`);return jt({size:OE(t),encodeStream:(e,r)=>{if(!Array.isArray(r))throw e.err(`tuple: invalid value ${r}`);e.pushObj(r,n=>{for(let i=0;i<t.length;i++)n(`${i}`,()=>t[i].encodeStream(e,r[i]))})},decodeStream:e=>{let r=[];return e.pushObj(r,n=>{for(let i=0;i<t.length;i++)n(`${i}`,()=>r.push(t[i].decodeStream(e)))}),r},validate:e=>{if(!Array.isArray(e))throw new Error(`tuple: invalid value ${e}`);if(e.length!==t.length)throw new Error(`tuple: wrong length=${e.length}, expected ${t.length}`);return e}})}function Wt(t,e){if(!Rr(e))throw new Error(`array: invalid inner value ${e}`);let r=xE(typeof t=="string"?`../${t}`:t);return jt({size:typeof t=="number"&&e.size?t*e.size:void 0,encodeStream:(n,i)=>{let o=n;o.pushObj(i,s=>{Gr(t)||r.encodeStream(n,i.length);for(let c=0;c<i.length;c++)s(`${c}`,()=>{let a=i[c],u=n.pos;if(e.encodeStream(n,a),Gr(t)){if(t.length>o.pos-u)return;let d=o.finish(!1).subarray(u,o.pos);if(Vc(d.subarray(0,t.length),t))throw o.err(`array: inner element encoding same as separator. elm=${a} data=${d}`)}})}),Gr(t)&&n.bytes(t)},decodeStream:n=>{let i=[];return n.pushObj(i,o=>{if(t===null)for(let s=0;!n.isEnd()&&(o(`${s}`,()=>i.push(e.decodeStream(n))),!(e.size&&n.leftBytes<e.size));s++);else if(Gr(t))for(let s=0;;s++){if(Vc(n.bytes(t.length,!0),t)){n.bytes(t.length);break}o(`${s}`,()=>i.push(e.decodeStream(n)))}else{let s;o("arrayLen",()=>s=r.decodeStream(n));for(let c=0;c<s;c++)o(`${c}`,()=>i.push(e.decodeStream(n)))}}),i},validate:n=>{if(!Array.isArray(n))throw new Error(`array: invalid value ${n}`);return n}})}var tl=wo.ProjectivePoint,el=wo.CURVE.n,ke=Yf.isBytes,Fn=Yf.concatBytes,st=Yf.equalBytes;var jc=t=>uE(Oe(t)),Ri=(...t)=>Oe(Oe(Fn(...t))),YP=Ir.utils.randomPrivateKey,rl=Ir.getPublicKey,zy=wo.getPublicKey,kE=t=>t.r<el/2n;function NE(t,e,r=!1){let n=wo.sign(t,e);if(r&&!kE(n)){let i=new Uint8Array(32),o=0;for(;!kE(n);)if(i.set(Te.encode(o++)),n=wo.sign(t,e,{extraEntropy:i}),o>4294967295)throw new Error("lowR counter overflow: report the error")}return n.toDERRawBytes()}var Yy=Ir.sign,Ou=Ir.utils.taggedHash,xt;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(xt||(xt={}));function xo(t,e){let r=t.length;if(e===xt.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return tl.fromHex(t),t}else if(e===xt.schnorr){if(r!==32)throw new Error("Expected 32-byte Schnorr key");return Ir.utils.lift_x(Ir.utils.bytesToNumberBE(t)),t}else throw new Error("Unknown key type")}function CE(t,e){let r=Ir.utils,n=r.taggedHash("TapTweak",t,e),i=r.bytesToNumberBE(n);if(i>=el)throw new Error("tweak higher than curve order");return i}function LE(t,e=Uint8Array.of()){let r=Ir.utils,n=r.bytesToNumberBE(t),i=tl.fromPrivateKey(n),o=i.hasEvenY()?n:r.mod(-n,el),s=r.pointToBytes(i),c=CE(s,e);return r.numberToBytesBE(r.mod(o+c,el),32)}function Du(t,e){let r=Ir.utils,n=CE(t,e),o=r.lift_x(r.bytesToNumberBE(t)).add(tl.fromPrivateKey(n)),s=o.hasEvenY()?0:1;return[r.pointToBytes(o),s]}var nl=Oe(tl.BASE.toRawBytes(!1)),zr={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},Jy={bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239};function ku(t,e){if(!ke(t)||!ke(e))throw new Error(`cmp: wrong type a=${typeof t} b=${typeof e}`);let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!=e[n])return Math.sign(t[n]-e[n]);return Math.sign(t.length-e.length)}l();l();l();var gt;(function(t){t[t.OP_0=0]="OP_0",t[t.PUSHDATA1=76]="PUSHDATA1",t[t.PUSHDATA2=77]="PUSHDATA2",t[t.PUSHDATA4=78]="PUSHDATA4",t[t["1NEGATE"]=79]="1NEGATE",t[t.RESERVED=80]="RESERVED",t[t.OP_1=81]="OP_1",t[t.OP_2=82]="OP_2",t[t.OP_3=83]="OP_3",t[t.OP_4=84]="OP_4",t[t.OP_5=85]="OP_5",t[t.OP_6=86]="OP_6",t[t.OP_7=87]="OP_7",t[t.OP_8=88]="OP_8",t[t.OP_9=89]="OP_9",t[t.OP_10=90]="OP_10",t[t.OP_11=91]="OP_11",t[t.OP_12=92]="OP_12",t[t.OP_13=93]="OP_13",t[t.OP_14=94]="OP_14",t[t.OP_15=95]="OP_15",t[t.OP_16=96]="OP_16",t[t.NOP=97]="NOP",t[t.VER=98]="VER",t[t.IF=99]="IF",t[t.NOTIF=100]="NOTIF",t[t.VERIF=101]="VERIF",t[t.VERNOTIF=102]="VERNOTIF",t[t.ELSE=103]="ELSE",t[t.ENDIF=104]="ENDIF",t[t.VERIFY=105]="VERIFY",t[t.RETURN=106]="RETURN",t[t.TOALTSTACK=107]="TOALTSTACK",t[t.FROMALTSTACK=108]="FROMALTSTACK",t[t["2DROP"]=109]="2DROP",t[t["2DUP"]=110]="2DUP",t[t["3DUP"]=111]="3DUP",t[t["2OVER"]=112]="2OVER",t[t["2ROT"]=113]="2ROT",t[t["2SWAP"]=114]="2SWAP",t[t.IFDUP=115]="IFDUP",t[t.DEPTH=116]="DEPTH",t[t.DROP=117]="DROP",t[t.DUP=118]="DUP",t[t.NIP=119]="NIP",t[t.OVER=120]="OVER",t[t.PICK=121]="PICK",t[t.ROLL=122]="ROLL",t[t.ROT=123]="ROT",t[t.SWAP=124]="SWAP",t[t.TUCK=125]="TUCK",t[t.CAT=126]="CAT",t[t.SUBSTR=127]="SUBSTR",t[t.LEFT=128]="LEFT",t[t.RIGHT=129]="RIGHT",t[t.SIZE=130]="SIZE",t[t.INVERT=131]="INVERT",t[t.AND=132]="AND",t[t.OR=133]="OR",t[t.XOR=134]="XOR",t[t.EQUAL=135]="EQUAL",t[t.EQUALVERIFY=136]="EQUALVERIFY",t[t.RESERVED1=137]="RESERVED1",t[t.RESERVED2=138]="RESERVED2",t[t["1ADD"]=139]="1ADD",t[t["1SUB"]=140]="1SUB",t[t["2MUL"]=141]="2MUL",t[t["2DIV"]=142]="2DIV",t[t.NEGATE=143]="NEGATE",t[t.ABS=144]="ABS",t[t.NOT=145]="NOT",t[t["0NOTEQUAL"]=146]="0NOTEQUAL",t[t.ADD=147]="ADD",t[t.SUB=148]="SUB",t[t.MUL=149]="MUL",t[t.DIV=150]="DIV",t[t.MOD=151]="MOD",t[t.LSHIFT=152]="LSHIFT",t[t.RSHIFT=153]="RSHIFT",t[t.BOOLAND=154]="BOOLAND",t[t.BOOLOR=155]="BOOLOR",t[t.NUMEQUAL=156]="NUMEQUAL",t[t.NUMEQUALVERIFY=157]="NUMEQUALVERIFY",t[t.NUMNOTEQUAL=158]="NUMNOTEQUAL",t[t.LESSTHAN=159]="LESSTHAN",t[t.GREATERTHAN=160]="GREATERTHAN",t[t.LESSTHANOREQUAL=161]="LESSTHANOREQUAL",t[t.GREATERTHANOREQUAL=162]="GREATERTHANOREQUAL",t[t.MIN=163]="MIN",t[t.MAX=164]="MAX",t[t.WITHIN=165]="WITHIN",t[t.RIPEMD160=166]="RIPEMD160",t[t.SHA1=167]="SHA1",t[t.SHA256=168]="SHA256",t[t.HASH160=169]="HASH160",t[t.HASH256=170]="HASH256",t[t.CODESEPARATOR=171]="CODESEPARATOR",t[t.CHECKSIG=172]="CHECKSIG",t[t.CHECKSIGVERIFY=173]="CHECKSIGVERIFY",t[t.CHECKMULTISIG=174]="CHECKMULTISIG",t[t.CHECKMULTISIGVERIFY=175]="CHECKMULTISIGVERIFY",t[t.NOP1=176]="NOP1",t[t.CHECKLOCKTIMEVERIFY=177]="CHECKLOCKTIMEVERIFY",t[t.CHECKSEQUENCEVERIFY=178]="CHECKSEQUENCEVERIFY",t[t.NOP4=179]="NOP4",t[t.NOP5=180]="NOP5",t[t.NOP6=181]="NOP6",t[t.NOP7=182]="NOP7",t[t.NOP8=183]="NOP8",t[t.NOP9=184]="NOP9",t[t.NOP10=185]="NOP10",t[t.CHECKSIGADD=186]="CHECKSIGADD",t[t.INVALID=255]="INVALID"})(gt||(gt={}));function Zy(t=6,e=!1){return jt({encodeStream:(r,n)=>{if(n===0n)return;let i=n<0,o=BigInt(n),s=[];for(let c=i?-o:o;c;c>>=8n)s.push(Number(c&0xffn));s[s.length-1]>=128?s.push(i?128:0):i&&(s[s.length-1]|=128),r.bytes(new Uint8Array(s))},decodeStream:r=>{let n=r.leftBytes;if(n>t)throw new Error(`ScriptNum: number (${n}) bigger than limit=${t}`);if(n===0)return 0n;if(e){let s=r.bytes(n,!0);if(!(s[s.length-1]&127)&&(n<=1||!(s[s.length-2]&128)))throw new Error("Non-minimally encoded ScriptNum")}let i=0,o=0n;for(let s=0;s<n;++s)i=r.byte(),o|=BigInt(i)<<8n*BigInt(s);return i>=128&&(o&=2n**BigInt(n*8)-1n>>1n,o=-o),o}})}function KE(t,e=4,r=!0){if(typeof t=="number")return t;if(ke(t))try{let n=Zy(e,r).decode(t);return n>Number.MAX_SAFE_INTEGER?void 0:Number(n)}catch{return}}var Ye=jt({encodeStream:(t,e)=>{for(let r of e){if(typeof r=="string"){if(gt[r]===void 0)throw new Error(`Unknown opcode=${r}`);t.byte(gt[r]);continue}else if(typeof r=="number"){if(r===0){t.byte(0);continue}else if(1<=r&&r<=16){t.byte(gt.OP_1-1+r);continue}}if(typeof r=="number"&&(r=Zy().encode(BigInt(r))),!ke(r))throw new Error(`Wrong Script OP=${r} (${typeof r})`);let n=r.length;n<gt.PUSHDATA1?t.byte(n):n<=255?(t.byte(gt.PUSHDATA1),t.byte(n)):n<=65535?(t.byte(gt.PUSHDATA2),t.bytes(Gy.encode(n))):(t.byte(gt.PUSHDATA4),t.bytes(Te.encode(n))),t.bytes(r)}},decodeStream:t=>{let e=[];for(;!t.isEnd();){let r=t.byte();if(gt.OP_0<r&&r<=gt.PUSHDATA4){let n;if(r<gt.PUSHDATA1)n=r;else if(r===gt.PUSHDATA1)n=mn.decodeStream(t);else if(r===gt.PUSHDATA2)n=Gy.decodeStream(t);else if(r===gt.PUSHDATA4)n=Te.decodeStream(t);else throw new Error("Should be not possible");e.push(t.bytes(n))}else if(r===0)e.push(0);else if(gt.OP_1<=r&&r<=gt.OP_16)e.push(r-(gt.OP_1-1));else{let n=gt[r];if(n===void 0)throw new Error(`Unknown opcode=${r.toString(16)}`);e.push(n)}}return e}}),ME={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},Wc=jt({encodeStream:(t,e)=>{if(typeof e=="number"&&(e=BigInt(e)),0n<=e&&e<=252n)return t.byte(Number(e));for(let[r,n,i,o]of Object.values(ME))if(!(i>e||e>o)){t.byte(r);for(let s=0;s<n;s++)t.byte(Number(e>>8n*BigInt(s)&0xffn));return}throw t.err(`VarInt too big: ${e}`)},decodeStream:t=>{let e=t.byte();if(e<=252)return BigInt(e);let[r,n,i]=ME[e],o=0n;for(let s=0;s<n;s++)o|=BigInt(t.byte())<<8n*BigInt(s);if(o<i)throw t.err(`Wrong CompactSize(${8*n})`);return o}}),Ur=gn(Wc,Ii.numberBigint),dr=He(Wc),Gc=Wt(Ur,dr),il=t=>Wt(Wc,t),$E=bt({txid:He(32,!0),index:Te,finalScriptSig:dr,sequence:Te}),Ui=bt({amount:Fc,script:dr}),O8=bt({version:bo,segwitFlag:RE(new Uint8Array([0,1])),inputs:il($E),outputs:il(Ui),witnesses:UE("segwitFlag",Wt("inputs/length",Gc)),lockTime:Te});function D8(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Oi=Ft(O8,D8),Es=bt({version:bo,inputs:il($E),outputs:il(Ui),lockTime:Te});var Qy=Ft(He(null),t=>xo(t,xt.ecdsa)),ol=Ft(He(32),t=>xo(t,xt.schnorr)),HE=Ft(He(null),t=>{if(t.length!==64&&t.length!==65)throw new Error("Schnorr signature should be 64 or 65 bytes long");return t}),sl=bt({fingerprint:_E,path:Wt(null,Te)}),FE=bt({hashes:Wt(Ur,He(32)),der:sl}),k8=He(78),N8=bt({pubKey:ol,leafHash:He(32)}),C8=bt({version:mn,internalKey:He(32),merklePath:Wt(null,He(32))}),Di=Ft(C8,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),L8=Wt(null,bt({depth:mn,version:mn,script:dr})),Et=He(null),VE=He(20),Nu=He(32),cl={unsignedTx:[0,!1,Es,[0],[0],!1],xpub:[1,k8,sl,[],[0,2],!1],txVersion:[2,!1,Te,[2],[2],!1],fallbackLocktime:[3,!1,Te,[],[2],!1],inputCount:[4,!1,Ur,[2],[2],!1],outputCount:[5,!1,Ur,[2],[2],!1],txModifiable:[6,!1,mn,[],[2],!1],version:[251,!1,Te,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},Cu={nonWitnessUtxo:[0,!1,Oi,[],[0,2],!1],witnessUtxo:[1,!1,Ui,[],[0,2],!1],partialSig:[2,Qy,Et,[],[0,2],!1],sighashType:[3,!1,Te,[],[0,2],!1],redeemScript:[4,!1,Et,[],[0,2],!1],witnessScript:[5,!1,Et,[],[0,2],!1],bip32Derivation:[6,Qy,sl,[],[0,2],!1],finalScriptSig:[7,!1,Et,[],[0,2],!1],finalScriptWitness:[8,!1,Gc,[],[0,2],!1],porCommitment:[9,!1,Et,[],[0,2],!1],ripemd160:[10,VE,Et,[],[0,2],!1],sha256:[11,Nu,Et,[],[0,2],!1],hash160:[12,VE,Et,[],[0,2],!1],hash256:[13,Nu,Et,[],[0,2],!1],txid:[14,!1,Nu,[2],[2],!0],index:[15,!1,Te,[2],[2],!0],sequence:[16,!1,Te,[],[2],!0],requiredTimeLocktime:[17,!1,Te,[],[2],!1],requiredHeightLocktime:[18,!1,Te,[],[2],!1],tapKeySig:[19,!1,HE,[],[0,2],!1],tapScriptSig:[20,N8,HE,[],[0,2],!1],tapLeafScript:[21,Di,Et,[],[0,2],!1],tapBip32Derivation:[22,Nu,FE,[],[0,2],!1],tapInternalKey:[23,!1,ol,[],[0,2],!1],tapMerkleRoot:[24,!1,Nu,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},jE=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],WE=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Lu={redeemScript:[0,!1,Et,[],[0,2],!1],witnessScript:[1,!1,Et,[],[0,2],!1],bip32Derivation:[2,Qy,sl,[],[0,2],!1],amount:[3,!1,TE,[2],[2],!0],script:[4,!1,Et,[2],[2],!0],tapInternalKey:[5,!1,ol,[],[0,2],!1],tapTree:[6,!1,L8,[],[0,2],!1],tapBip32Derivation:[7,ol,FE,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},GE=[],qE=Wt(Fy,bt({key:BE(Ur,bt({type:Ur,key:He(null)})),value:He(Ur)}));function e0(t){let[e,r,n,i,o,s]=t;return{type:e,kc:r,vc:n,reqInc:i,allowInc:o,silentIgnore:s}}var nM=bt({type:Ur,key:He(null)});function t0(t){let e={};for(let r in t){let[n,i,o]=t[r];e[n]=[r,i,o]}return jt({encodeStream:(r,n)=>{let i=[];for(let o in t){let s=n[o];if(s===void 0)continue;let[c,a,u]=t[o];if(!a)i.push({key:{type:c,key:$e},value:u.encode(s)});else{let d=s.map(([f,h])=>[a.encode(f),u.encode(h)]);d.sort((f,h)=>ku(f[0],h[0]));for(let[f,h]of d)i.push({key:{key:f,type:c},value:h})}}if(n.unknown){n.unknown.sort((o,s)=>ku(o[0].key,s[0].key));for(let[o,s]of n.unknown)i.push({key:o,value:s})}qE.encodeStream(r,i)},decodeStream:r=>{let n=qE.decodeStream(r),i={},o={};for(let s of n){let c="unknown",a=s.key.key,u=s.value;if(e[s.key.type]){let[d,f,h]=e[s.key.type];if(c=d,!f&&a.length)throw new Error(`PSBT: Non-empty key for ${c} (key=${Ae.encode(a)} value=${Ae.encode(u)}`);if(a=f?f.decode(a):void 0,u=h.decode(u),!f){if(i[c])throw new Error(`PSBT: Same keys: ${c} (key=${a} value=${u})`);i[c]=u,o[c]=!0;continue}}else a={type:s.key.type,key:s.key.key};if(o[c])throw new Error(`PSBT: Key type with empty key and no key=${c} val=${u}`);i[c]||(i[c]=[]),i[c].push([a,u])}return i}})}var al=Ft(t0(Cu),t=>{if(t.finalScriptWitness&&!t.finalScriptWitness.length)throw new Error("validateInput: empty finalScriptWitness");if(t.partialSig&&!t.partialSig.length)throw new Error("Empty partialSig");if(t.partialSig)for(let[e]of t.partialSig)xo(e,xt.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)xo(e,xt.ecdsa);if(t.requiredTimeLocktime!==void 0&&t.requiredTimeLocktime<5e8)throw new Error(`validateInput: wrong timeLocktime=${t.requiredTimeLocktime}`);if(t.requiredHeightLocktime!==void 0&&(t.requiredHeightLocktime<=0||t.requiredHeightLocktime>=5e8))throw new Error(`validateInput: wrong heighLocktime=${t.requiredHeightLocktime}`);if(t.tapLeafScript)for(let[e,r]of t.tapLeafScript){if((e.version&254)!==r[r.length-1])throw new Error("validateInput: tapLeafScript version mimatch");if(r[r.length-1]&1)throw new Error("validateInput: tapLeafScript version has parity bit!")}return t}),ul=Ft(t0(Lu),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)xo(e,xt.ecdsa);return t}),zE=Ft(t0(cl),t=>{if((t.version||0)===0){if(!t.unsignedTx)throw new Error("PSBTv0: missing unsignedTx");for(let r of t.unsignedTx.inputs)if(r.finalScriptSig&&r.finalScriptSig.length)throw new Error("PSBTv0: input scriptSig found in unsignedTx")}return t}),P8=bt({magic:Xf(Zf(new Uint8Array([255])),"psbt"),global:zE,inputs:Wt("global/unsignedTx/inputs/length",al),outputs:Wt(null,ul)}),M8=bt({magic:Xf(Zf(new Uint8Array([255])),"psbt"),global:zE,inputs:Wt("global/inputCount",al),outputs:Wt("global/outputCount",ul)}),iM=bt({magic:Xf(Zf(new Uint8Array([255])),"psbt"),items:Wt(null,gn(Wt(Fy,DE([IE(Ur),He(Wc)])),Ii.dict()))});function Xy(t,e,r){for(let n in r){if(n==="unknown"||!e[n])continue;let{allowInc:i}=e0(e[n]);if(!i.includes(t))throw new Error(`PSBTv${t}: field ${n} is not allowed`)}for(let n in e){let{reqInc:i}=e0(e[n]);if(i.includes(t)&&r[n]===void 0)throw new Error(`PSBTv${t}: missing required field ${n}`)}}function r0(t,e,r){let n={};for(let i in r){let o=i;if(o!=="unknown"){if(!e[o])continue;let{allowInc:s,silentIgnore:c}=e0(e[o]);if(!s.includes(t)){if(c)continue;throw new Error(`Failed to serialize in PSBTv${t}: ${o} but versions allows inclusion=${s}`)}}n[o]=r[o]}return n}function YE(t){let e=t&&t.global&&t.global.version||0;Xy(e,cl,t.global);for(let s of t.inputs)Xy(e,Cu,s);for(let s of t.outputs)Xy(e,Lu,s);let r=e?t.global.inputCount:t.global.unsignedTx.inputs.length;if(t.inputs.length<r)throw new Error("Not enough inputs");let n=t.inputs.slice(r);if(n.length>1||n.length&&Object.keys(n[0]).length)throw new Error(`Unexpected inputs left in tx=${n}`);let i=e?t.global.outputCount:t.global.unsignedTx.outputs.length;if(t.outputs.length<i)throw new Error("Not outputs inputs");let o=t.outputs.slice(i);if(o.length>1||o.length&&Object.keys(o[0]).length)throw new Error(`Unexpected outputs left in tx=${o}`);return t}function dl(t,e,r,n,i){let o={...r,...e};for(let s in t){let c=s,[a,u,d]=t[c],f=n&&!n.includes(s);if(e[s]===void 0&&s in e){if(f)throw new Error(`Cannot remove signed field=${s}`);delete o[s]}else if(u){let h=r&&r[s]?r[s]:[],p=e[c];if(p){if(!Array.isArray(p))throw new Error(`keyMap(${s}): KV pairs should be [k, v][]`);p=p.map(E=>{if(E.length!==2)throw new Error(`keyMap(${s}): KV pairs should be [k, v][]`);return[typeof E[0]=="string"?u.decode(Ae.decode(E[0])):E[0],typeof E[1]=="string"?d.decode(Ae.decode(E[1])):E[1]]});let g={},y=(E,S,I)=>{if(g[E]===void 0){g[E]=[S,I];return}let A=Ae.encode(d.encode(g[E][1])),O=Ae.encode(d.encode(I));if(A!==O)throw new Error(`keyMap(${c}): same key=${E} oldVal=${A} newVal=${O}`)};for(let[E,S]of h){let I=Ae.encode(u.encode(E));y(I,E,S)}for(let[E,S]of p){let I=Ae.encode(u.encode(E));if(S===void 0){if(f)throw new Error(`Cannot remove signed field=${c}/${E}`);delete g[I]}else y(I,E,S)}o[c]=Object.values(g)}}else if(typeof o[s]=="string")o[s]=d.decode(Ae.decode(o[s]));else if(f&&s in e&&r&&r[s]!==void 0&&!st(d.encode(e[s]),d.encode(r[s])))throw new Error(`Cannot change signed field=${s}`)}for(let s in o)if(!t[s]){if(i&&s==="unknown")continue;delete o[s]}return o}var n0=Ft(P8,YE),i0=Ft(M8,YE);var $8={encode(t){if(!(t.length!==2||t[0]!==1||!ke(t[1])||Ae.encode(t[1])!=="4e73"))return{type:"p2a",script:Ye.encode(t)}},decode:t=>{if(t.type==="p2a")return[1,Ae.decode("4e73")]}};function Eo(t,e){try{return xo(t,e),!0}catch{return!1}}var H8={encode(t){if(!(t.length!==2||!ke(t[0])||!Eo(t[0],xt.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},V8={encode(t){if(!(t.length!==5||t[0]!=="DUP"||t[1]!=="HASH160"||!ke(t[2]))&&!(t[3]!=="EQUALVERIFY"||t[4]!=="CHECKSIG"))return{type:"pkh",hash:t[2]}},decode:t=>t.type==="pkh"?["DUP","HASH160",t.hash,"EQUALVERIFY","CHECKSIG"]:void 0},q8={encode(t){if(!(t.length!==3||t[0]!=="HASH160"||!ke(t[1])||t[2]!=="EQUAL"))return{type:"sh",hash:t[1]}},decode:t=>t.type==="sh"?["HASH160",t.hash,"EQUAL"]:void 0},F8={encode(t){if(!(t.length!==2||t[0]!==0||!ke(t[1]))&&t[1].length===32)return{type:"wsh",hash:t[1]}},decode:t=>t.type==="wsh"?[0,t.hash]:void 0},j8={encode(t){if(!(t.length!==2||t[0]!==0||!ke(t[1]))&&t[1].length===20)return{type:"wpkh",hash:t[1]}},decode:t=>t.type==="wpkh"?[0,t.hash]:void 0},W8={encode(t){let e=t.length-1;if(t[e]!=="CHECKMULTISIG")return;let r=t[0],n=t[e-1];if(typeof r!="number"||typeof n!="number")return;let i=t.slice(1,-2);if(n===i.length){for(let o of i)if(!ke(o))return;return{type:"ms",m:r,pubkeys:i}}},decode:t=>t.type==="ms"?[t.m,...t.pubkeys,t.pubkeys.length,"CHECKMULTISIG"]:void 0},G8={encode(t){if(!(t.length!==2||t[0]!==1||!ke(t[1])))return{type:"tr",pubkey:t[1]}},decode:t=>t.type==="tr"?[1,t.pubkey]:void 0},z8={encode(t){let e=t.length-1;if(t[e]!=="CHECKSIG")return;let r=[];for(let n=0;n<e;n++){let i=t[n];if(n&1){if(i!=="CHECKSIGVERIFY"||n===e-1)return;continue}if(!ke(i))return;r.push(i)}return{type:"tr_ns",pubkeys:r}},decode:t=>{if(t.type!=="tr_ns")return;let e=[];for(let r=0;r<t.pubkeys.length-1;r++)e.push(t.pubkeys[r],"CHECKSIGVERIFY");return e.push(t.pubkeys[t.pubkeys.length-1],"CHECKSIG"),e}},Y8={encode(t){let e=t.length-1;if(t[e]!=="NUMEQUAL"||t[1]!=="CHECKSIG")return;let r=[],n=KE(t[e-1]);if(typeof n=="number"){for(let i=0;i<e-1;i++){let o=t[i];if(i&1){if(o!==(i===1?"CHECKSIG":"CHECKSIGADD"))throw new Error("OutScript.encode/tr_ms: wrong element");continue}if(!ke(o))throw new Error("OutScript.encode/tr_ms: wrong key element");r.push(o)}return{type:"tr_ms",pubkeys:r,m:n}}},decode:t=>{if(t.type!=="tr_ms")return;let e=[t.pubkeys[0],"CHECKSIG"];for(let r=1;r<t.pubkeys.length;r++)e.push(t.pubkeys[r],"CHECKSIGADD");return e.push(t.m,"NUMEQUAL"),e}},J8={encode(t){return{type:"unknown",script:Ye.encode(t)}},decode:t=>t.type==="unknown"?Ye.decode(t.script):void 0},Z8=[$8,H8,V8,q8,F8,j8,W8,G8,z8,Y8,J8],X8=gn(Ye,Ii.match(Z8)),Je=Ft(X8,t=>{if(t.type==="pk"&&!Eo(t.pubkey,xt.ecdsa))throw new Error("OutScript/pk: wrong key");if((t.type==="pkh"||t.type==="sh"||t.type==="wpkh")&&(!ke(t.hash)||t.hash.length!==20))throw new Error(`OutScript/${t.type}: wrong hash`);if(t.type==="wsh"&&(!ke(t.hash)||t.hash.length!==32))throw new Error("OutScript/wsh: wrong hash");if(t.type==="tr"&&(!ke(t.pubkey)||!Eo(t.pubkey,xt.schnorr)))throw new Error("OutScript/tr: wrong taproot public key");if((t.type==="ms"||t.type==="tr_ns"||t.type==="tr_ms")&&!Array.isArray(t.pubkeys))throw new Error("OutScript/multisig: wrong pubkeys array");if(t.type==="ms"){let e=t.pubkeys.length;for(let r of t.pubkeys)if(!Eo(r,xt.ecdsa))throw new Error("OutScript/multisig: wrong pubkey");if(t.m<=0||e>16||t.m>e)throw new Error("OutScript/multisig: invalid params")}if(t.type==="tr_ns"||t.type==="tr_ms"){for(let e of t.pubkeys)if(!Eo(e,xt.schnorr))throw new Error(`OutScript/${t.type}: wrong pubkey`)}if(t.type==="tr_ms"){let e=t.pubkeys.length;if(t.m<=0||e>999||t.m>e)throw new Error("OutScript/tr_ms: invalid params")}return t});function JE(t,e){if(!st(t.hash,Oe(e)))throw new Error("checkScript: wsh wrong witnessScript hash");let r=Je.decode(e);if(r.type==="tr"||r.type==="tr_ns"||r.type==="tr_ms")throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2SH`);if(r.type==="wpkh"||r.type==="sh")throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2WSH`)}function d0(t,e,r){if(t){let n=Je.decode(t);if(n.type==="tr_ns"||n.type==="tr_ms"||n.type==="ms"||n.type=="pk")throw new Error(`checkScript: non-wrapped ${n.type}`);if(n.type==="sh"&&e){if(!st(n.hash,jc(e)))throw new Error("checkScript: sh wrong redeemScript hash");let i=Je.decode(e);if(i.type==="tr"||i.type==="tr_ns"||i.type==="tr_ms")throw new Error(`checkScript: P2${i.type} cannot be wrapped in P2SH`);if(i.type==="sh")throw new Error("checkScript: P2SH cannot be wrapped in P2SH")}n.type==="wsh"&&r&&JE(n,r)}if(e){let n=Je.decode(e);n.type==="wsh"&&r&&JE(n,r)}}var ki=(t,e=zr)=>{if(!Eo(t,xt.ecdsa))throw new Error("P2PKH: invalid publicKey");let r=jc(t);return{type:"pkh",script:Je.encode({type:"pkh",hash:r}),address:Yr(e).encode({type:"pkh",hash:r}),hash:r}};var vs=(t,e=zr)=>{if(!Eo(t,xt.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(t.length===65)throw new Error("P2WPKH: uncompressed public key");let r=jc(t);return{type:"wpkh",script:Je.encode({type:"wpkh",hash:r}),address:Yr(e).encode({type:"wpkh",hash:r}),hash:r}};function Q8(t,e,r=!1,n){let i=Je.decode(t);if(i.type==="unknown"){if(n){let c=gn(Ye,Ii.match(n)).decode(t);if(c!==void 0){if(typeof c.type!="string"||!c.type.startsWith("tr_"))throw new Error(`P2TR: invalid custom type=${c.type}`);return}}if(r)return}if(!["tr_ns","tr_ms"].includes(i.type))throw new Error(`P2TR: invalid leaf script=${i.type}`);let o=i;if(!r&&o.pubkeys)for(let s of o.pubkeys){if(st(s,nl))throw new Error("Unspendable taproot key in leaf script");if(st(s,e))throw new Error("Using P2TR with leaf script with same key as internal key is not supported")}}function XE(t){let e=Array.from(t);for(;e.length>=2;){e.sort((s,c)=>(c.weight||1)-(s.weight||1));let n=e.pop(),i=e.pop(),o=(i?.weight||1)+(n?.weight||1);e.push({weight:o,childs:[i?.childs||i,n?.childs||n]})}let r=e[0];return r?.childs||r}function s0(t,e=[]){if(!t)throw new Error("taprootAddPath: empty tree");if(t.type==="leaf")return{...t,path:e};if(t.type!=="branch")throw new Error(`taprootAddPath: wrong type=${t}`);return{...t,path:e,left:s0(t.left,[t.right.hash,...e]),right:s0(t.right,[t.left.hash,...e])}}function c0(t){if(!t)throw new Error("taprootAddPath: empty tree");if(t.type==="leaf")return[t];if(t.type!=="branch")throw new Error(`taprootWalkTree: wrong type=${t}`);return[...c0(t.left),...c0(t.right)]}function a0(t,e,r=!1,n){if(!t)throw new Error("taprootHashTree: empty tree");if(Array.isArray(t)&&t.length===1&&(t=t[0]),!Array.isArray(t)){let{leafVersion:a,script:u}=t;if(t.tapLeafScript||t.tapMerkleRoot&&!st(t.tapMerkleRoot,$e))throw new Error("P2TR: tapRoot leafScript cannot have tree");let d=typeof u=="string"?Ae.decode(u):u;if(!ke(d))throw new Error(`checkScript: wrong script type=${d}`);return Q8(d,e,r,n),{type:"leaf",version:a,script:d,hash:Pu(d,a)}}if(t.length!==2&&(t=XE(t)),t.length!==2)throw new Error("hashTree: non binary tree!");let i=a0(t[0],e,r,n),o=a0(t[1],e,r,n),[s,c]=[i.hash,o.hash];return ku(c,s)===-1&&([s,c]=[c,s]),{type:"branch",left:i,right:o,hash:Ou("TapBranch",s,c)}}var u0=192,Pu=(t,e=u0)=>Ou("TapLeaf",new Uint8Array([e]),dr.encode(t));function Ss(t,e,r=zr,n=!1,i){if(!t&&!e)throw new Error("p2tr: should have pubKey or scriptTree (or both)");let o=typeof t=="string"?Ae.decode(t):t||nl;if(!Eo(o,xt.schnorr))throw new Error("p2tr: non-schnorr pubkey");if(e){let s=s0(a0(e,o,n,i)),c=s.hash,[a,u]=Du(o,c),d=c0(s).map(f=>({...f,controlBlock:Di.encode({version:(f.version||u0)+u,internalKey:o,merklePath:f.path})}));return{type:"tr",script:Je.encode({type:"tr",pubkey:a}),address:Yr(r).encode({type:"tr",pubkey:a}),tweakedPubkey:a,tapInternalKey:o,leaves:d,tapLeafScript:d.map(f=>[Di.decode(f.controlBlock),Fn(f.script,new Uint8Array([f.version||u0]))]),tapMerkleRoot:c}}else{let s=Du(o,$e)[0];return{type:"tr",script:Je.encode({type:"tr",pubkey:s}),address:Yr(r).encode({type:"tr",pubkey:s}),tweakedPubkey:s,tapInternalKey:o}}}var QE=mE(Oe);function ev(t,e){if(e.length<2||e.length>40)throw new Error("Witness: invalid length");if(t>16)throw new Error("Witness: invalid version");if(t===0&&!(e.length===20||e.length===32))throw new Error("Witness: invalid length for version")}function o0(t,e,r=zr){ev(t,e);let n=t===0?zf:Hc;return n.encode(r.bech32,[t].concat(n.toWords(e)))}function ZE(t,e){return QE.encode(Fn(Uint8Array.from(e),t))}function Yr(t=zr){return{encode(e){let{type:r}=e;if(r==="wpkh")return o0(0,e.hash,t);if(r==="wsh")return o0(0,e.hash,t);if(r==="tr")return o0(1,e.pubkey,t);if(r==="pkh")return ZE(e.hash,[t.pubKeyHash]);if(r==="sh")return ZE(e.hash,[t.scriptHash]);throw new Error(`Unknown address type=${r}`)},decode(e){if(e.length<14||e.length>74)throw new Error("Invalid address length");if(t.bech32&&e.toLowerCase().startsWith(`${t.bech32}1`)){let n;try{if(n=zf.decode(e),n.words[0]!==0)throw new Error(`bech32: wrong version=${n.words[0]}`)}catch{if(n=Hc.decode(e),n.words[0]===0)throw new Error(`bech32m: wrong version=${n.words[0]}`)}if(n.prefix!==t.bech32)throw new Error(`wrong bech32 prefix=${n.prefix}`);let[i,...o]=n.words,s=zf.fromWords(o);if(ev(i,s),i===0&&s.length===32)return{type:"wsh",hash:s};if(i===0&&s.length===20)return{type:"wpkh",hash:s};if(i===1&&s.length===32)return{type:"tr",pubkey:s};throw new Error("Unknown witness program")}let r=QE.decode(e);if(r.length!==21)throw new Error("Invalid base58 address");if(r[0]===t.pubKeyHash)return{type:"pkh",hash:r.slice(1)};if(r[0]===t.scriptHash)return{type:"sh",hash:r.slice(1)};throw new Error(`Invalid address prefix=${r[0]}`)}}}l();var fl=new Uint8Array(32),eR={amount:0xffffffffffffffffn,script:$e},tR=t=>Math.ceil(t/4),rR=8,nR=2,As=0,p0=4294967295,iR=Ii.decimal(rR),Ku=(t,e)=>t===void 0?e:t;function hl(t){if(Array.isArray(t))return t.map(e=>hl(e));if(ke(t))return Uint8Array.from(t);if(["number","bigint","boolean","string","undefined"].includes(typeof t))return t;if(t===null)return t;if(typeof t=="object")return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,hl(r)]));throw new Error(`cloneDeep: unknown type=${t} (${typeof t})`)}var Ve;(function(t){t[t.DEFAULT=0]="DEFAULT",t[t.ALL=1]="ALL",t[t.NONE=2]="NONE",t[t.SINGLE=3]="SINGLE",t[t.ANYONECANPAY=128]="ANYONECANPAY"})(Ve||(Ve={}));var vo;(function(t){t[t.DEFAULT=0]="DEFAULT",t[t.ALL=1]="ALL",t[t.NONE=2]="NONE",t[t.SINGLE=3]="SINGLE",t[t.DEFAULT_ANYONECANPAY=128]="DEFAULT_ANYONECANPAY",t[t.ALL_ANYONECANPAY=129]="ALL_ANYONECANPAY",t[t.NONE_ANYONECANPAY=130]="NONE_ANYONECANPAY",t[t.SINGLE_ANYONECANPAY=131]="SINGLE_ANYONECANPAY"})(vo||(vo={}));function oR(t,e,r,n=$e){return st(r,e)&&(t=LE(t,n),e=rl(t)),{privKey:t,pubKey:e}}function Ts(t){if(t.script===void 0||t.amount===void 0)throw new Error("Transaction/output: script and amount required");return{script:t.script,amount:t.amount}}function Mu(t){if(t.txid===void 0||t.index===void 0)throw new Error("Transaction/input: txid and index required");return{txid:t.txid,index:t.index,sequence:Ku(t.sequence,p0),finalScriptSig:Ku(t.finalScriptSig,$e)}}function f0(t){for(let e in t){let r=e;jE.includes(r)||delete t[r]}}var l0=bt({txid:He(32,!0),index:Te});function sR(t){if(typeof t!="number"||typeof vo[t]!="string")throw new Error(`Invalid SigHash=${t}`);return t}function tv(t){let e=t&31;return{isAny:!!(t&Ve.ANYONECANPAY),isNone:e===Ve.NONE,isSingle:e===Ve.SINGLE}}function cR(t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error(`Wrong object type for transaction options: ${t}`);let e={...t,version:Ku(t.version,nR),lockTime:Ku(t.lockTime,0),PSBTVersion:Ku(t.PSBTVersion,0)};if(typeof e.allowUnknowInput<"u"&&(t.allowUnknownInputs=e.allowUnknowInput),typeof e.allowUnknowOutput<"u"&&(t.allowUnknownOutputs=e.allowUnknowOutput),typeof e.lockTime!="number")throw new Error("Transaction lock time should be number");if(Te.encode(e.lockTime),e.PSBTVersion!==0&&e.PSBTVersion!==2)throw new Error(`Unknown PSBT version ${e.PSBTVersion}`);for(let r of["allowUnknownVersion","allowUnknownOutputs","allowUnknownInputs","disableScriptCheck","bip174jsCompat","allowLegacyWitnessUtxo","lowR"]){let n=e[r];if(n!==void 0&&typeof n!="boolean")throw new Error(`Transation options wrong type: ${r}=${n} (${typeof n})`)}if(e.allowUnknownVersion?typeof e.version=="number":![-1,0,1,2,3].includes(e.version))throw new Error(`Unknown version: ${e.version}`);if(e.customScripts!==void 0){let r=e.customScripts;if(!Array.isArray(r))throw new Error(`wrong custom scripts type (expected array): customScripts=${r} (${typeof r})`);for(let n of r){if(typeof n.encode!="function"||typeof n.decode!="function")throw new Error(`wrong script=${n} (${typeof n})`);if(n.finalizeTaproot!==void 0&&typeof n.finalizeTaproot!="function")throw new Error(`wrong script=${n} (${typeof n})`)}}return Object.freeze(e)}function rv(t){if(t.nonWitnessUtxo&&t.index!==void 0){let e=t.nonWitnessUtxo.outputs.length-1;if(t.index>e)throw new Error(`validateInput: index(${t.index}) not in nonWitnessUtxo`);let r=t.nonWitnessUtxo.outputs[t.index];if(t.witnessUtxo&&(!st(t.witnessUtxo.script,r.script)||t.witnessUtxo.amount!==r.amount))throw new Error("validateInput: witnessUtxo different from nonWitnessUtxo");if(t.txid){if(t.nonWitnessUtxo.outputs.length-1<t.index)throw new Error("nonWitnessUtxo: incorect output index");let i=_s.fromRaw(Oi.encode(t.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),o=Ae.encode(t.txid);if(i.isFinal&&i.id!==o)throw new Error(`nonWitnessUtxo: wrong txid, exp=${o} got=${i.id}`)}}return t}function ll(t){if(t.nonWitnessUtxo){if(t.index===void 0)throw new Error("Unknown input index");return t.nonWitnessUtxo.outputs[t.index]}else{if(t.witnessUtxo)return t.witnessUtxo;throw new Error("Cannot find previous output info")}}function nv(t,e,r,n=!1,i=!1){let{nonWitnessUtxo:o,txid:s}=t;typeof o=="string"&&(o=Ae.decode(o)),ke(o)&&(o=Oi.decode(o)),!("nonWitnessUtxo"in t)&&o===void 0&&(o=e?.nonWitnessUtxo),typeof s=="string"&&(s=Ae.decode(s)),s===void 0&&(s=e?.txid);let c={...e,...t,nonWitnessUtxo:o,txid:s};!("nonWitnessUtxo"in t)&&c.nonWitnessUtxo===void 0&&delete c.nonWitnessUtxo,c.sequence===void 0&&(c.sequence=p0),c.tapMerkleRoot===null&&delete c.tapMerkleRoot,c=dl(Cu,c,e,r,i),al.encode(c);let a;return c.nonWitnessUtxo&&c.index!==void 0?a=c.nonWitnessUtxo.outputs[c.index]:c.witnessUtxo&&(a=c.witnessUtxo),a&&!n&&d0(a&&a.script,c.redeemScript,c.witnessScript),c}function h0(t,e=!1){let r="legacy",n=Ve.ALL,i=ll(t),o=Je.decode(i.script),s=o.type,c=o,a=[o];if(o.type==="tr")return n=Ve.DEFAULT,{txType:"taproot",type:"tr",last:o,lastScript:i.script,defaultSighash:n,sighash:t.sighashType||n};{if((o.type==="wpkh"||o.type==="wsh")&&(r="segwit"),o.type==="sh"){if(!t.redeemScript)throw new Error("inputType: sh without redeemScript");let h=Je.decode(t.redeemScript);(h.type==="wpkh"||h.type==="wsh")&&(r="segwit"),a.push(h),c=h,s+=`-${h.type}`}if(c.type==="wsh"){if(!t.witnessScript)throw new Error("inputType: wsh without witnessScript");let h=Je.decode(t.witnessScript);h.type==="wsh"&&(r="segwit"),a.push(h),c=h,s+=`-${h.type}`}let u=a[a.length-1];if(u.type==="sh"||u.type==="wsh")throw new Error("inputType: sh/wsh cannot be terminal type");let d=Je.encode(u),f={type:s,txType:r,last:u,lastScript:d,defaultSighash:n,sighash:t.sighashType||n};if(r==="legacy"&&!e&&!t.nonWitnessUtxo)throw new Error("Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure");return f}}var _s=class t{constructor(e={}){this.global={},this.inputs=[],this.outputs=[];let r=this.opts=cR(e);r.lockTime!==As&&(this.global.fallbackLocktime=r.lockTime),this.global.txVersion=r.version}static fromRaw(e,r={}){let n=Oi.decode(e),i=new t({...r,version:n.version,lockTime:n.lockTime});for(let o of n.outputs)i.addOutput(o);if(i.outputs=n.outputs,i.inputs=n.inputs,n.witnesses)for(let o=0;o<n.witnesses.length;o++)i.inputs[o].finalScriptWitness=n.witnesses[o];return i}static fromPSBT(e,r={}){let n;try{n=n0.decode(e)}catch(f){try{n=i0.decode(e)}catch{throw f}}let i=n.global.version||0;if(i!==0&&i!==2)throw new Error(`Wrong PSBT version=${i}`);let o=n.global.unsignedTx,s=i===0?o?.version:n.global.txVersion,c=i===0?o?.lockTime:n.global.fallbackLocktime,a=new t({...r,version:s,lockTime:c,PSBTVersion:i}),u=i===0?o?.inputs.length:n.global.inputCount;a.inputs=n.inputs.slice(0,u).map((f,h)=>rv({finalScriptSig:$e,...n.global.unsignedTx?.inputs[h],...f}));let d=i===0?o?.outputs.length:n.global.outputCount;return a.outputs=n.outputs.slice(0,d).map((f,h)=>({...f,...n.global.unsignedTx?.outputs[h]})),a.global={...n.global,txVersion:s},c!==As&&(a.global.fallbackLocktime=c),a}toPSBT(e=this.opts.PSBTVersion){if(e!==0&&e!==2)throw new Error(`Wrong PSBT version=${e}`);let r=this.inputs.map(o=>rv(r0(e,Cu,o)));for(let o of r)o.partialSig&&!o.partialSig.length&&delete o.partialSig,o.finalScriptSig&&!o.finalScriptSig.length&&delete o.finalScriptSig,o.finalScriptWitness&&!o.finalScriptWitness.length&&delete o.finalScriptWitness;let n=this.outputs.map(o=>r0(e,Lu,o)),i={...this.global};return e===0?(i.unsignedTx=Es.decode(Es.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Mu).map(o=>({...o,finalScriptSig:$e})),outputs:this.outputs.map(Ts)})),delete i.fallbackLocktime,delete i.txVersion):(i.version=e,i.txVersion=this.version,i.inputCount=this.inputs.length,i.outputCount=this.outputs.length,i.fallbackLocktime&&i.fallbackLocktime===As&&delete i.fallbackLocktime),this.opts.bip174jsCompat&&(r.length||r.push({}),n.length||n.push({})),(e===0?n0:i0).encode({global:i,inputs:r,outputs:n})}get lockTime(){let e=As,r=0,n=As,i=0;for(let o of this.inputs)o.requiredHeightLocktime&&(e=Math.max(e,o.requiredHeightLocktime),r++),o.requiredTimeLocktime&&(n=Math.max(n,o.requiredTimeLocktime),i++);return r&&r>=i?e:n!==As?n:this.global.fallbackLocktime||As}get version(){if(this.global.txVersion===void 0)throw new Error("No global.txVersion");return this.global.txVersion}inputStatus(e){this.checkInputIdx(e);let r=this.inputs[e];return r.finalScriptSig&&r.finalScriptSig.length||r.finalScriptWitness&&r.finalScriptWitness.length?"finalized":r.tapKeySig||r.tapScriptSig&&r.tapScriptSig.length||r.partialSig&&r.partialSig.length?"signed":"unsigned"}inputSighash(e){this.checkInputIdx(e);let r=this.inputs[e].sighashType,n=r===void 0?Ve.DEFAULT:r,i=n===Ve.DEFAULT?Ve.ALL:n&3;return{sigInputs:n&Ve.ANYONECANPAY,sigOutputs:i}}signStatus(){let e=!0,r=!0,n=[],i=[];for(let o=0;o<this.inputs.length;o++){if(this.inputStatus(o)==="unsigned")continue;let{sigInputs:c,sigOutputs:a}=this.inputSighash(o);if(c===Ve.ANYONECANPAY?n.push(o):e=!1,a===Ve.ALL)r=!1;else if(a===Ve.SINGLE)i.push(o);else if(a!==Ve.NONE)throw new Error(`Wrong signature hash output type: ${a}`)}return{addInput:e,addOutput:r,inputs:n,outputs:i}}get isFinal(){for(let e=0;e<this.inputs.length;e++)if(this.inputStatus(e)!=="finalized")return!1;return!0}get hasWitnesses(){let e=!1;for(let r of this.inputs)r.finalScriptWitness&&r.finalScriptWitness.length&&(e=!0);return e}get weight(){if(!this.isFinal)throw new Error("Transaction is not finalized");let e=32,r=this.outputs.map(Ts);e+=4*Ur.encode(this.outputs.length).length;for(let n of r)e+=32+4*dr.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*Ur.encode(this.inputs.length).length;for(let n of this.inputs)e+=160+4*dr.encode(n.finalScriptSig||$e).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=Gc.encode(n.finalScriptWitness).length);return e}get vsize(){return tR(this.weight)}toBytes(e=!1,r=!1){return Oi.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Mu).map(n=>({...n,finalScriptSig:e&&n.finalScriptSig||$e})),outputs:this.outputs.map(Ts),witnesses:this.inputs.map(n=>n.finalScriptWitness||[]),segwitFlag:r&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return Ae.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Ae.encode(Ri(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Ae.encode(Ri(this.toBytes(!0)).reverse())}checkInputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.inputs.length)throw new Error(`Wrong input index=${e}`)}getInput(e){return this.checkInputIdx(e),hl(this.inputs[e])}get inputsLength(){return this.inputs.length}addInput(e,r=!1){if(!r&&!this.signStatus().addInput)throw new Error("Tx has signed inputs, cannot add new one");return this.inputs.push(nv(e,void 0,void 0,this.opts.disableScriptCheck)),this.inputs.length-1}updateInput(e,r,n=!1){this.checkInputIdx(e);let i;if(!n){let o=this.signStatus();(!o.addInput||o.inputs.includes(e))&&(i=WE)}this.inputs[e]=nv(r,this.inputs[e],i,this.opts.disableScriptCheck,this.opts.allowUnknown)}checkOutputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.outputs.length)throw new Error(`Wrong output index=${e}`)}getOutput(e){return this.checkOutputIdx(e),hl(this.outputs[e])}getOutputAddress(e,r=zr){let n=this.getOutput(e);if(n.script)return Yr(r).encode(Je.decode(n.script))}get outputsLength(){return this.outputs.length}normalizeOutput(e,r,n){let{amount:i,script:o}=e;if(i===void 0&&(i=r?.amount),typeof i!="bigint")throw new Error(`Wrong amount type, should be of type bigint in sats, but got ${i} of type ${typeof i}`);typeof o=="string"&&(o=Ae.decode(o)),o===void 0&&(o=r?.script);let s={...r,...e,amount:i,script:o};if(s.amount===void 0&&delete s.amount,s=dl(Lu,s,r,n,this.opts.allowUnknown),ul.encode(s),s.script&&!this.opts.allowUnknownOutputs&&Je.decode(s.script).type==="unknown")throw new Error("Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure");return this.opts.disableScriptCheck||d0(s.script,s.redeemScript,s.witnessScript),s}addOutput(e,r=!1){if(!r&&!this.signStatus().addOutput)throw new Error("Tx has signed outputs, cannot add new one");return this.outputs.push(this.normalizeOutput(e)),this.outputs.length-1}updateOutput(e,r,n=!1){this.checkOutputIdx(e);let i;if(!n){let o=this.signStatus();(!o.addOutput||o.outputs.includes(e))&&(i=GE)}this.outputs[e]=this.normalizeOutput(r,this.outputs[e],i)}addOutputAddress(e,r,n=zr){return this.addOutput({script:Je.encode(Yr(n).decode(e)),amount:r})}get fee(){let e=0n;for(let n of this.inputs){let i=ll(n);if(!i)throw new Error("Empty input amount");e+=i.amount}let r=this.outputs.map(Ts);for(let n of r)e-=n.amount;return e}preimageLegacy(e,r,n){let{isAny:i,isNone:o,isSingle:s}=tv(n);if(e<0||!Number.isSafeInteger(e))throw new Error(`Invalid input idx=${e}`);if(s&&e>=this.outputs.length||e>=this.inputs.length)return AE.encode(1n);r=Ye.encode(Ye.decode(r).filter(d=>d!=="CODESEPARATOR"));let c=this.inputs.map(Mu).map((d,f)=>({...d,finalScriptSig:f===e?r:$e}));i?c=[c[e]]:(o||s)&&(c=c.map((d,f)=>({...d,sequence:f===e?d.sequence:0})));let a=this.outputs.map(Ts);o?a=[]:s&&(a=a.slice(0,e).fill(eR).concat([a[e]]));let u=Oi.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Ri(u,bo.encode(n))}preimageWitnessV0(e,r,n,i){let{isAny:o,isNone:s,isSingle:c}=tv(n),a=fl,u=fl,d=fl,f=this.inputs.map(Mu),h=this.outputs.map(Ts);o||(a=Ri(...f.map(l0.encode))),!o&&!c&&!s&&(u=Ri(...f.map(g=>Te.encode(g.sequence)))),!c&&!s?d=Ri(...h.map(Ui.encode)):c&&e<h.length&&(d=Ri(Ui.encode(h[e])));let p=f[e];return Ri(bo.encode(this.version),a,u,He(32,!0).encode(p.txid),Te.encode(p.index),dr.encode(r),Fc.encode(i),Te.encode(p.sequence),d,Te.encode(this.lockTime),Te.encode(n))}preimageWitnessV1(e,r,n,i,o=-1,s,c=192,a){if(!Array.isArray(i)||this.inputs.length!==i.length)throw new Error(`Invalid amounts array=${i}`);if(!Array.isArray(r)||this.inputs.length!==r.length)throw new Error(`Invalid prevOutScript array=${r}`);let u=[mn.encode(0),mn.encode(n),bo.encode(this.version),Te.encode(this.lockTime)],d=n===Ve.DEFAULT?Ve.ALL:n&3,f=n&Ve.ANYONECANPAY,h=this.inputs.map(Mu),p=this.outputs.map(Ts);f!==Ve.ANYONECANPAY&&u.push(...[h.map(l0.encode),i.map(Fc.encode),r.map(dr.encode),h.map(y=>Te.encode(y.sequence))].map(y=>Oe(Fn(...y)))),d===Ve.ALL&&u.push(Oe(Fn(...p.map(Ui.encode))));let g=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([g])),f===Ve.ANYONECANPAY){let y=h[e];u.push(l0.encode(y),Fc.encode(i[e]),dr.encode(r[e]),Te.encode(y.sequence))}else u.push(Te.encode(e));return g&1&&u.push(Oe(dr.encode(a||$e))),d===Ve.SINGLE&&u.push(e<p.length?Oe(Ui.encode(p[e])):fl),s&&u.push(Pu(s,c),mn.encode(0),bo.encode(o)),Ou("TapSighash",...u)}signIdx(e,r,n,i){this.checkInputIdx(r);let o=this.inputs[r],s=h0(o,this.opts.allowLegacyWitnessUtxo);if(!ke(e)){if(!o.bip32Derivation||!o.bip32Derivation.length)throw new Error("bip32Derivation: empty");let d=o.bip32Derivation.filter(h=>h[1].fingerprint==e.fingerprint).map(([h,{path:p}])=>{let g=e;for(let y of p)g=g.deriveChild(y);if(!st(g.publicKey,h))throw new Error("bip32Derivation: wrong pubKey");if(!g.privateKey)throw new Error("bip32Derivation: no privateKey");return g});if(!d.length)throw new Error(`bip32Derivation: no items with fingerprint=${e.fingerprint}`);let f=!1;for(let h of d)this.signIdx(h.privateKey,r)&&(f=!0);return f}n?n.forEach(sR):n=[s.defaultSighash];let c=s.sighash;if(!n.includes(c))throw new Error(`Input with not allowed sigHash=${c}. Allowed: ${n.join(", ")}`);let{sigOutputs:a}=this.inputSighash(r);if(a===Ve.SINGLE&&r>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${r}`);let u=ll(o);if(s.txType==="taproot"){let d=this.inputs.map(ll),f=d.map(E=>E.script),h=d.map(E=>E.amount),p=!1,g=rl(e),y=o.tapMerkleRoot||$e;if(o.tapInternalKey){let{pubKey:E,privKey:S}=oR(e,g,o.tapInternalKey,y),[I,A]=Du(o.tapInternalKey,y);if(st(I,E)){let O=this.preimageWitnessV1(r,f,c,h),T=Fn(Yy(O,S,i),c!==Ve.DEFAULT?new Uint8Array([c]):$e);this.updateInput(r,{tapKeySig:T},!0),p=!0}}if(o.tapLeafScript){o.tapScriptSig=o.tapScriptSig||[];for(let[E,S]of o.tapLeafScript){let I=S.subarray(0,-1),A=Ye.decode(I),O=S[S.length-1],T=Pu(I,O);if(A.findIndex($=>ke($)&&st($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,I,O),j=Fn(Yy(q,e,i),c!==Ve.DEFAULT?new Uint8Array([c]):$e);this.updateInput(r,{tapScriptSig:[[{pubKey:g,leafHash:T},j]]},!0),p=!0}}if(!p)throw new Error("No taproot scripts signed");return!0}else{let d=zy(e),f=!1,h=jc(d);for(let y of Ye.decode(s.lastScript))ke(y)&&(st(y,d)||st(y,h))&&(f=!0);if(!f)throw new Error(`Input script doesn't have pubKey: ${s.lastScript}`);let p;if(s.txType==="legacy")p=this.preimageLegacy(r,s.lastScript,c);else if(s.txType==="segwit"){let y=s.lastScript;s.last.type==="wpkh"&&(y=Je.encode({type:"pkh",hash:s.last.hash})),p=this.preimageWitnessV0(r,y,c,u.amount)}else throw new Error(`Transaction/sign: unknown tx type: ${s.txType}`);let g=NE(p,e,this.opts.lowR);this.updateInput(r,{partialSig:[[d,Fn(g,new Uint8Array([c]))]]},!0)}return!0}sign(e,r,n){let i=0;for(let o=0;o<this.inputs.length;o++)try{this.signIdx(e,o,r,n)&&i++}catch{}if(!i)throw new Error("No inputs signed");return i}finalizeIdx(e){if(this.checkInputIdx(e),this.fee<0n)throw new Error("Outputs spends more than inputs amount");let r=this.inputs[e],n=h0(r,this.opts.allowLegacyWitnessUtxo);if(n.txType==="taproot"){if(r.tapKeySig)r.finalScriptWitness=[r.tapKeySig];else if(r.tapLeafScript&&r.tapScriptSig){let a=r.tapLeafScript.sort((u,d)=>Di.encode(u[0]).length-Di.encode(d[0]).length);for(let[u,d]of a){let f=d.slice(0,-1),h=d[d.length-1],p=Je.decode(f),g=Pu(f,h),y=r.tapScriptSig.filter(S=>st(S[0].leafHash,g)),E=[];if(p.type==="tr_ms"){let S=p.m,I=p.pubkeys,A=0;for(let O of I){let T=y.findIndex(M=>st(M[0].pubKey,O));if(A===S||T===-1){E.push($e);continue}E.push(y[T][1]),A++}if(A!==S)continue}else if(p.type==="tr_ns"){for(let S of p.pubkeys){let I=y.findIndex(A=>st(A[0].pubKey,S));I!==-1&&E.push(y[I][1])}if(E.length!==p.pubkeys.length)continue}else if(p.type==="unknown"&&this.opts.allowUnknownInputs){let S=Ye.decode(f);if(E=y.map(([{pubKey:I},A])=>{let O=S.findIndex(T=>ke(T)&&st(T,I));if(O===-1)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:A,pos:O}}).sort((I,A)=>I.pos-A.pos).map(I=>I.signature),!E.length)continue}else{let S=this.opts.customScripts;if(S)for(let I of S){if(!I.finalizeTaproot)continue;let A=Ye.decode(f),O=I.encode(A);if(O===void 0)continue;let T=I.finalizeTaproot(f,O,y);if(T){r.finalScriptWitness=T.concat(Di.encode(u)),r.finalScriptSig=$e,f0(r);return}}throw new Error("Finalize: Unknown tapLeafScript")}r.finalScriptWitness=E.reverse().concat([f,Di.encode(u)]);break}if(!r.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}else throw new Error("finalize/taproot: unknown input");r.finalScriptSig=$e,f0(r);return}if(!r.partialSig||!r.partialSig.length)throw new Error("Not enough partial sign");let i=$e,o=[];if(n.last.type==="ms"){let a=n.last.m,u=n.last.pubkeys,d=[];for(let f of u){let h=r.partialSig.find(p=>st(f,p[0]));h&&d.push(h[1])}if(d=d.slice(0,a),d.length!==a)throw new Error(`Multisig: wrong signatures count, m=${a} n=${u.length} signatures=${d.length}`);i=Ye.encode([0,...d])}else if(n.last.type==="pk")i=Ye.encode([r.partialSig[0][1]]);else if(n.last.type==="pkh")i=Ye.encode([r.partialSig[0][1],r.partialSig[0][0]]);else if(n.last.type==="wpkh")i=$e,o=[r.partialSig[0][1],r.partialSig[0][0]];else if(n.last.type==="unknown"&&!this.opts.allowUnknownInputs)throw new Error("Unknown inputs not allowed");let s,c;if(n.type.includes("wsh-")&&(i.length&&n.lastScript.length&&(o=Ye.decode(i).map(a=>{if(a===0)return $e;if(ke(a))return a;throw new Error(`Wrong witness op=${a}`)})),o=o.concat(n.lastScript)),n.txType==="segwit"&&(c=o),n.type.startsWith("sh-wsh-")?s=Ye.encode([Ye.encode([0,Oe(n.lastScript)])]):n.type.startsWith("sh-")?s=Ye.encode([...Ye.decode(i),n.lastScript]):n.type.startsWith("wsh-")||n.txType!=="segwit"&&(s=i),!s&&!c)throw new Error("Unknown error finalizing input");s&&(r.finalScriptSig=s),c&&(r.finalScriptWitness=c),f0(r)}finalize(){for(let e=0;e<this.inputs.length;e++)this.finalizeIdx(e)}extract(){if(!this.isFinal)throw new Error("Transaction has unfinalized inputs");if(!this.outputs.length)throw new Error("Transaction has no outputs");if(this.fee<0n)throw new Error("Outputs spends more than inputs amount");return this.toBytes(!0,!0)}combine(e){for(let i of["PSBTVersion","version","lockTime"])if(this.opts[i]!==e.opts[i])throw new Error(`Transaction/combine: different ${i} this=${this.opts[i]} other=${e.opts[i]}`);for(let i of["inputs","outputs"])if(this[i].length!==e[i].length)throw new Error(`Transaction/combine: different ${i} length this=${this[i].length} other=${e[i].length}`);let r=this.global.unsignedTx?Es.encode(this.global.unsignedTx):$e,n=e.global.unsignedTx?Es.encode(e.global.unsignedTx):$e;if(!st(r,n))throw new Error("Transaction/combine: different unsigned tx");this.global=dl(cl,this.global,e.global,void 0,this.opts.allowUnknown);for(let i=0;i<this.inputs.length;i++)this.updateInput(i,e.inputs[i],!0);for(let i=0;i<this.outputs.length;i++)this.updateOutput(i,e.outputs[i],!0);return this}clone(){return t.fromPSBT(this.toPSBT(this.opts.PSBTVersion),this.opts)}};l();l();l();l();l();function iv(t,e){var r="",n=e&&e.include,i=e&&e.exclude;i&&typeof i=="string"&&(i=[i]),n&&n.sort();var o=new WeakMap,s=e&&e.allowCircular,c=e&&e.filterUndefined,a=e&&e.undefinedInArrayToNull;return u(t,""),r;function u(d,f){if(d===null||typeof d!="object"||d.toJSON!=null)r+=JSON.stringify(d);else if(Array.isArray(d)){var h=o.get(d);if(h!==void 0&&f.startsWith(h)){if(!s)throw new Error("Circular reference detected");r+='"[Circular]"';return}o.set(d,f),r+="[";var p=!1;d.forEach(function(S,I){p&&(r+=","),p=!0,a&&S===void 0&&(S=null),u(S,f+"["+I+"]")}),r+="]"}else{var h=o.get(d);if(h!==void 0&&f.startsWith(h)){if(!s)throw new Error("Circular reference detected");r+='"[Circular]"';return}o.set(d,f),r+="{";var g=!1,y=function(I){i&&i.includes(I)||(g&&(r+=","),g=!0,r+=JSON.stringify(I),r+=":",u(d[I],f+"."+I))};if(f===""&&n)n.forEach(function(I){d.hasOwnProperty(I)&&y(I)});else{var E=Object.keys(d);c&&(E=E.filter(function(I){return d[I]!==void 0})),E.sort(),E.forEach(function(I){y(I)})}r+="}"}}}function ov(t,e){return iv(t,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}l();var y0;(function(t){t.INVALID_DID="INVALID_DID",t.METHOD_NOT_SUPPORTED="METHOD_NOT_SUPPORTED",t.INTERNAL_ERROR="INTERNAL_ERROR",t.INVALID_DID_DOCUMENT="INVALID_DID_DOCUMENT",t.INVALID_DID_UPDATE="INVALID_DID_UPDATE",t.INVALID_DID_DOCUMENT_LENGTH="INVALID_DID_DOCUMENT_LENGTH",t.INVALID_DID_URL="INVALID_DID_URL",t.INVALID_PREVIOUS_DID_PROOF="INVALID_PREVIOUS_DID_PROOF",t.INVALID_PUBLIC_KEY="INVALID_PUBLIC_KEY",t.INVALID_PUBLIC_KEY_MULTIBASE="INVALID_PUBLIC_KEY_MULTIBASE",t.INVALID_PUBLIC_KEY_LENGTH="INVALID_PUBLIC_KEY_LENGTH",t.INVALID_PUBLIC_KEY_TYPE="INVALID_PUBLIC_KEY_TYPE",t.INVALID_SIGNATURE="INVALID_SIGNATURE",t.NOT_FOUND="NOT_FOUND",t.REPRESENTATION_NOT_SUPPORTED="REPRESENTATION_NOT_SUPPORTED",t.UNSUPPORTED_PUBLIC_KEY_TYPE="UNSUPPORTED_PUBLIC_KEY_TYPE",t.PROOF_VERIFICATION_ERROR="PROOF_VERIFICATION_ERROR",t.PROOF_GENERATION_ERROR="PROOF_GENERATION_ERROR",t.PROOF_SERIALIZATION_ERROR="PROOF_SERIALIZATION_ERROR",t.PROOF_PARSING_ERROR="PROOF_PARSING_ERROR",t.VERIFICATION_METHOD_ERROR="VERIFICATION_METHOD_ERROR",t.LATE_PUBLISHING_ERROR="LATE_PUBLISHING_ERROR",t.INVALID_SIDECAR_DATA="INVALID_SIDECAR_DATA",t.MISSING_UPDATE_DATA="MISSING_UPDATE_DATA",t.INVALID_UPDATE="INVALID_UPDATE",t.INVALID_DOMAIN_ERROR="INVALID_DOMAIN_ERROR",t.MISSING_RESOLUTION_OPTIONS="MISSING_RESOLUTION_OPTIONS"})(y0||(y0={}));var{INVALID_DID:Lt,METHOD_NOT_SUPPORTED:pl,INTERNAL_ERROR:sv,INVALID_DID_DOCUMENT:Ue,INVALID_DID_UPDATE:Ne,INVALID_DID_URL:GM,INVALID_PREVIOUS_DID_PROOF:zM,INVALID_PUBLIC_KEY:YM,INVALID_PUBLIC_KEY_MULTIBASE:JM,INVALID_PUBLIC_KEY_LENGTH:ZM,INVALID_PUBLIC_KEY_TYPE:XM,INVALID_SIGNATURE:QM,PROOF_VERIFICATION_ERROR:Wn,PROOF_GENERATION_ERROR:Ao,PROOF_SERIALIZATION_ERROR:cv,PROOF_PARSING_ERROR:eK,VERIFICATION_METHOD_ERROR:yl,LATE_PUBLISHING_ERROR:av,INVALID_SIDECAR_DATA:tK,MISSING_UPDATE_DATA:rK,MISSING_RESOLUTION_OPTIONS:nK}=y0;var Gt=class t extends Error{name="DidMethodError";type="DidMethodError";data;constructor(e,r={}){super(e),this.type=r.type??this.type,this.name=r.name??this.name,this.data=r.data,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?.(this,t)}},tt=class extends Gt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}},mt=class extends Gt{constructor(e,r="IdentifierError",n){super(e,{type:r,name:r,data:n})}},vt=class extends Gt{constructor(e,r="UpdateError",n){super(e,{type:r,name:r,data:n})}},rt=class extends Gt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var Ze=class extends Gt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},So=class extends Gt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},Jr=class extends Gt{constructor(e,r="DataIntegrityProofError",n){super(e,{type:r,name:r,data:n})}},wn=class extends Gt{constructor(e,r="KeyPairError",n){super(e,{type:r,name:r,data:n})}},jn=class extends Gt{constructor(e,r="SecretKeyError",n){super(e,{type:r,name:r,data:n})}},Bs=class extends Gt{constructor(e,r="PublicKeyError",n){super(e,{type:r,name:r,data:n})}},bn=class extends Gt{constructor(e,r="MultikeyError",n){super(e,{type:r,name:r,data:n})}};var zc=class extends Gt{constructor(e,r="CanonicalizationError",n){super(e,{type:r,name:r,data:n})}};var aR=new Set(["jcs"]),uR=new Set(["hex","base58","base64urlnopad"]);function g0(t){let e=t.toLowerCase();if(!aR.has(e))throw new zc(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function m0(t){let e=t.toLowerCase();if(!uR.has(e))throw new zc(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function tr(t,e="jcs"){switch(g0(e)){case"jcs":{let n=JSON.parse(JSON.stringify(t));return ov(n)}default:throw new zc(`Unsupported algorithm: ${e}`,"ALGORITHM_ERROR")}}function To(t){return Oe(t)}function Zr(t,e="base64urlnopad"){switch(m0(e)){case"hex":return Ae.encode(t);case"base58":return Gf.encode(t);case"base64urlnopad":return $c.encode(t)}}function Is(t,e="base64urlnopad"){switch(m0(e)){case"hex":return Ae.decode(t);case"base58":return Gf.decode(t);case"base64urlnopad":return $c.decode(t)}}function Yc(t,e="jcs"){return To(tr(t,g0(e)))}function Gn(t,e){let r=g0(e?.algorithm??"jcs"),n=m0(e?.encoding??"base64urlnopad");return Zr(To(tr(t,r)),n)}l();l();var w0={};Sf(w0,{JsonPatchError:()=>ct,_areEquals:()=>Vu,applyOperation:()=>Rs,applyPatch:()=>vl,applyReducer:()=>pR,deepClone:()=>lR,getValueByPointer:()=>xl,validate:()=>dv,validator:()=>El});l();l();var dR=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)i.hasOwnProperty(o)&&(n[o]=i[o])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),fR=Object.prototype.hasOwnProperty;function ml(t,e){return fR.call(t,e)}function wl(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var i in t)ml(t,i)&&n.push(i);return n}function Pt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function bl(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function zn(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function $u(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function gl(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(gl(t[e]))return!0}else if(typeof t=="object"){for(var n=wl(t),i=n.length,o=0;o<i;o++)if(gl(t[n[o]]))return!0}}return!1}function uv(t,e){var r=[t];for(var n in e){var i=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof i<"u"&&r.push(n+": "+i)}return r.join(`
3
- `)}var Hu=function(t){dR(e,t);function e(r,n,i,o,s){var c=this.constructor,a=t.call(this,uv(r,{name:n,index:i,operation:o,tree:s}))||this;return a.name=n,a.index=i,a.operation=o,a.tree=s,Object.setPrototypeOf(a,c.prototype),a.message=uv(r,{name:n,index:i,operation:o,tree:s}),a}return e}(Error);var ct=Hu,lR=Pt,Jc={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=xl(r,this.path);n&&(n=Pt(n));var i=Rs(r,{op:"remove",path:this.from}).removed;return Rs(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=xl(r,this.from);return Rs(r,{op:"add",path:this.path,value:Pt(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Vu(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},hR={add:function(t,e,r){return bl(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:Jc.move,copy:Jc.copy,test:Jc.test,_get:Jc._get};function xl(t,e){if(e=="")return t;var r={op:"_get",path:e};return Rs(t,r),r.value}function Rs(t,e,r,n,i,o){if(r===void 0&&(r=!1),n===void 0&&(n=!0),i===void 0&&(i=!0),o===void 0&&(o=0),r&&(typeof r=="function"?r(e,0,t,e.path):El(e,0)),e.path===""){var s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=xl(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Vu(t,e.value),s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(r)throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return s}}else{n||(t=Pt(t));var c=e.path||"",a=c.split("/"),u=t,d=1,f=a.length,h=void 0,p=void 0,g=void 0;for(typeof r=="function"?g=r:g=El;;){if(p=a[d],p&&p.indexOf("~")!=-1&&(p=$u(p)),i&&(p=="__proto__"||p=="prototype"&&d>0&&a[d-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&h===void 0&&(u[p]===void 0?h=a.slice(0,d).join("/"):d==f-1&&(h=e.path),h!==void 0&&g(e,0,t,h)),d++,Array.isArray(u)){if(p==="-")p=u.length;else{if(r&&!bl(p))throw new ct("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,e,t);bl(p)&&(p=~~p)}if(d>=f){if(r&&e.op==="add"&&p>u.length)throw new ct("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,t);var s=hR[e.op].call(e,u,p,t);if(s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}}else if(d>=f){var s=Jc[e.op].call(e,u,p,t);if(s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(u=u[p],r&&d<f&&(!u||typeof u!="object"))throw new ct("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function vl(t,e,r,n,i){if(n===void 0&&(n=!0),i===void 0&&(i=!0),r&&!Array.isArray(e))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Pt(t));for(var o=new Array(e.length),s=0,c=e.length;s<c;s++)o[s]=Rs(t,e[s],r,!0,i,s),t=o[s].newDocument;return o.newDocument=t,o}function pR(t,e,r){var n=Rs(t,e);if(n.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function El(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ct("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Jc[t.op]){if(typeof t.path!="string")throw new ct("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ct('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ct("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&gl(t.value))throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var i=t.path.split("/").length,o=n.split("/").length;if(i!==o+1&&i!==o)throw new ct("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new ct("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var s={op:"_get",path:t.from,value:void 0},c=dv([s],r);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new ct("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function dv(t,e,r){try{if(!Array.isArray(t))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)vl(Pt(e),Pt(t),r||!0);else{r=r||El;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof ct)return i;throw i}}function Vu(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),i,o,s;if(r&&n){if(o=t.length,o!=e.length)return!1;for(i=o;i--!==0;)if(!Vu(t[i],e[i]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(o=c.length,o!==Object.keys(e).length)return!1;for(i=o;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=o;i--!==0;)if(s=c[i],!Vu(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var v0={};Sf(v0,{compare:()=>vR,generate:()=>b0,observe:()=>ER,unobserve:()=>xR});l();var x0=new WeakMap,yR=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),gR=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function mR(t){return x0.get(t)}function wR(t,e){return t.observers.get(e)}function bR(t,e){t.observers.delete(e.callback)}function xR(t,e){e.unobserve()}function ER(t,e){var r=[],n,i=mR(t);if(!i)i=new yR(t),x0.set(t,i);else{var o=wR(i,e);n=o&&o.observer}if(n)return n;if(n={},i.value=Pt(t),e){n.callback=e,n.next=null;var s=function(){b0(n)},c=function(){clearTimeout(n.next),n.next=setTimeout(s)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return n.patches=r,n.object=t,n.unobserve=function(){b0(n),clearTimeout(n.next),bR(i,n),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new gR(e,n)),n}function b0(t,e){e===void 0&&(e=!1);var r=x0.get(t.object);E0(r.value,t.object,t.patches,"",e),t.patches.length&&vl(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function E0(t,e,r,n,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=wl(e),s=wl(t),c=!1,a=!1,u=s.length-1;u>=0;u--){var d=s[u],f=t[d];if(ml(e,d)&&!(e[d]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var h=e[d];typeof f=="object"&&f!=null&&typeof h=="object"&&h!=null&&Array.isArray(f)===Array.isArray(h)?E0(f,h,r,n+"/"+zn(d),i):f!==h&&(c=!0,i&&r.push({op:"test",path:n+"/"+zn(d),value:Pt(f)}),r.push({op:"replace",path:n+"/"+zn(d),value:Pt(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+zn(d),value:Pt(f)}),r.push({op:"remove",path:n+"/"+zn(d)}),a=!0):(i&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),c=!0)}if(!(!a&&o.length==s.length))for(var u=0;u<o.length;u++){var d=o[u];!ml(t,d)&&e[d]!==void 0&&r.push({op:"add",path:n+"/"+zn(d),value:Pt(e[d])})}}}function vR(t,e,r){r===void 0&&(r=!1);var n=[];return E0(t,e,n,"",r),n}var fv=Object.assign({},w0,v0,{JsonPatchError:Hu,deepClone:Pt,escapePathComponent:zn,unescapePathComponent:$u});var{applyPatch:SR,compare:AR,deepClone:TR}=fv,Zc=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.clone??TR,s=i?e:o(e),c=this.validateOperations(r);if(c)throw new tt("Invalid JSON Patch operations","JSON_PATCH_APPLY_ERROR",{error:c});try{let a=SR(s,r,!1,i);if(a.newDocument===void 0)throw new tt("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{result:a});return a.newDocument}catch(a){throw new tt("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{error:a})}}static diff(e,r,n=""){let i=AR(e??{},r??{});if(!n)return i;let o=n.endsWith("/")?n.slice(0,-1):n;return i.map(s=>({...s,path:this.joinPointer(o,s.path)}))}static joinPointer(e,r){if(!e)return r;let n=e.startsWith("/")?e:`/${e}`;return`${this.escapeSegmentPath(n)}${r}`}static escapeSegmentPath(e){return e.split("/").map((r,n)=>n===0?r:r.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}static validateOperations(e){if(!Array.isArray(e))return new Error("Operations must be an array");for(let r of e){if(!r||typeof r!="object")return new Error("Operation must be an object");if(typeof r.op!="string")return new Error("Operation.op must be a string");if(typeof r.path!="string")return new Error("Operation.path must be a string");if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")return new Error(`Operation.from must be a string for op=${r.op}`)}return null}};l();var _o;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(_o||(_o={}));var Sl;(function(t){t.k="k",t.x="x"})(Sl||(Sl={}));var qu;(function(t){t[t.bitcoin=0]="bitcoin",t[t.signet=1]="signet",t[t.regtest=2]="regtest",t[t.testnet3=3]="testnet3",t[t.testnet4=4]="testnet4",t[t.mutinynet=5]="mutinynet"})(qu||(qu={}));l();var Bo=class{static toISOStringNonFractional(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new Error(`Invalid date: ${e}`);return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toUnixSeconds(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new Error(`Invalid date: ${e}`);return Math.floor(e.getTime()/1e3)}static dateStringToTimestamp(e){let r=new Date(e);return Number.isNaN(r.getTime())?new Date(0):r}static blocktimeToTimestamp(e){return new Date(e*1e3)}static isValidXsdDateTime(e){if(!e)return!1;let r=/^-?(\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,n=e.match(r);if(!n)return!1;let[,i,o,s,c,a,u,,d]=n,f=parseInt(i,10),h=parseInt(o,10),p=parseInt(s,10),g=parseInt(c,10),y=parseInt(a,10),E=parseInt(u,10);if(f===0||h<1||h>12)return!1;let S=[31,28,31,30,31,30,31,31,30,31,30,31],I=f%4===0&&f%100!==0||f%400===0,A=h===2&&I?29:S[h-1];if(p<1||p>A)return!1;if(g===24){if(y!==0||E!==0)return!1}else if(g>23)return!1;if(y>59||E>59)return!1;if(d&&d!=="Z"){let O=d.match(/^[+-](\d{2}):(\d{2})$/);if(O){let T=parseInt(O[1],10),M=parseInt(O[2],10);if(T>14||T===14&&M!==0||M>59)return!1}}return!0}};l();var Us=class{static isObject(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}static isParsable(e){if(typeof e!="string")return!1;try{return JSON.parse(e),!0}catch{return!1}}static isUnprototyped(e){return e===null||typeof e!="object"?!1:Object.getPrototypeOf(e)===null}static normalize(e){return this.cloneInternal(e,{stripPrototypes:!0})}static copy(e){return{...e}}static clone(e){return typeof structuredClone=="function"?structuredClone(e):this.cloneInternal(e)}static cloneReplace(e,r,n){return this.cloneInternal(e,{transform:i=>typeof i=="string"?i.replace(r,n):i})}static deepEqual(e,r,n=new WeakMap,i=0){if(i>1024)throw new Error("Maximum comparison depth exceeded");if(Object.is(e,r))return!0;if(typeof e!=typeof r||e===null||r===null||typeof e!="object")return!1;if(n.get(e)===r)return!0;if(n.set(e,r),ArrayBuffer.isView(e)&&ArrayBuffer.isView(r)){let c=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(c.byteLength!==a.byteLength)return!1;for(let u=0;u<c.byteLength;u++)if(c[u]!==a[u])return!1;return!0}if(e instanceof Date&&r instanceof Date)return e.getTime()===r.getTime();if(e instanceof Set&&r instanceof Set){if(e.size!==r.size)return!1;for(let c of e){let a=!1;for(let u of r)if(this.deepEqual(c,u,n,i+1)){a=!0;break}if(!a)return!1}return!0}if(e instanceof Map&&r instanceof Map){if(e.size!==r.size)return!1;for(let[c,a]of e){let u=!1;if(r.has(c))u=this.deepEqual(a,r.get(c),n,i+1);else for(let[d,f]of r)if(this.deepEqual(c,d,n,i+1)&&this.deepEqual(a,f,n,i+1)){u=!0;break}if(!u)return!1}return!0}if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return!1;for(let c=0;c<e.length;c++)if(!this.deepEqual(e[c],r[c],n,i+1))return!1;return!0}let o=Object.keys(e),s=Object.keys(r);if(o.length!==s.length)return!1;for(let c of o)if(!Object.prototype.hasOwnProperty.call(r,c)||!this.deepEqual(e[c],r[c],n,i+1))return!1;return!0}static deleteKeys(e,r){let n=new Set(r.map(o=>typeof o=="number"?o.toString():o)),i=o=>{if(Array.isArray(o))return o.map(s=>i(s));if(o&&typeof o=="object"){let s={};for(let c of Object.keys(o))n.has(c)||(s[c]=i(o[c]));return s}return o};return i(e)}static sanitize(e){let r=n=>{if(Array.isArray(n))return n.filter(i=>i!==void 0).map(i=>r(i));if(n&&typeof n=="object"){let i={};for(let[o,s]of Object.entries(n)){let c=r(s);c!==void 0&&(i[o]=c)}return i}return n};return r(e)}static cloneInternal(e,r={},n=new WeakMap,i=0){if(i>1024)throw new Error("Maximum clone depth exceeded");let o=r.transform?r.transform(e):e;if(o!==e||typeof e!="object"||e===null)return o;if(n.has(e))throw new Error("Cannot clone circular structure");if(Array.isArray(e)){let c=[];n.set(e,c);for(let a of e)c.push(this.cloneInternal(a,r,n,i+1));return c}if(ArrayBuffer.isView(e)){if(e instanceof DataView)return new DataView(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(typeof e.slice=="function")return e.slice()}if(e instanceof Date)return new Date(e.getTime());let s=r.stripPrototypes?{}:Object.create(Object.getPrototypeOf(e));n.set(e,s);for(let c of Object.keys(e))s[c]=this.cloneInternal(e[c],r,n,i+1);return s}};l();var rr=class extends tt{constructor(e,r="BeaconError",n){super(e,r,n)}},lv=class extends tt{constructor(e,r="SingletonBeaconError",n){super(e,r,n)}},hv=class extends tt{constructor(e,r="AggregateBeaconError",n){super(e,r,n)}},pv=class extends tt{constructor(e,r="CASBeaconError",n){super(e,r,n)}},Fu=class extends tt{constructor(e,r="SMTBeaconError",n){super(e,r,n)}};l();l();l();l();l();l();l();l();l();l();l();l();l();l();l();var CR={bech32:"bcrt",pubKeyHash:111,scriptHash:196,wif:239};function Io(t){switch(t){case"bitcoin":return zr;case"testnet3":case"testnet4":case"signet":case"mutinynet":return Jy;case"regtest":return CR;default:throw new Error(`Unknown network "${t}"`)}}l();var ju=class{satsPerVbyte;constructor(e=5){if(e<0||!Number.isFinite(e))throw new Error(`Invalid satsPerVbyte: ${e}`);this.satsPerVbyte=e}async estimateFee(e){if(e<0||!Number.isFinite(e))throw new Error(`Invalid vsize: ${e}`);return BigInt(Math.ceil(e*this.satsPerVbyte))}};l();var A0="0000000000000000000000000000000000000000000000000000000000000000",T0="4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b";l();var _0;(function(t){t[t.hex=0]="hex",t[t.json=1]="json",t[t.jsonext=2]="jsonext",t[t.jsonextprev=3]="jsonextprev"})(_0||(_0={}));var B0=new ju(5);var MR=160,KR=155,$R=240,HR={p2pkh:$R,p2wpkh:KR,p2tr:MR},gv={p2pkh:34,p2wpkh:31,p2tr:43},mv={p2pkh:546,p2wpkh:294,p2tr:330};function wv(t,e){return HR[t]-gv[t]+gv[e]}function bv(t,e){let r=Yr(e).decode(t);if(r.type==="pkh")return"p2pkh";if(r.type==="wpkh")return"p2wpkh";if(r.type==="tr")return"p2tr";throw new rr(`Unsupported singleton beacon address type "${r.type}". Expected P2PKH, P2WPKH, or P2TR (taproot key-path).`,"UNSUPPORTED_BEACON_ADDRESS_TYPE",{address:t,kind:r.type})}function VR(t,e,r){return t==="p2pkh"?ki(e,r).address:t==="p2wpkh"?vs(e,r).address:Ss(e.slice(1,33),void 0,r).address}function xv(t,e,r){if(!r||r===t)return t;try{Yr(e).decode(r)}catch{throw new rr(`Invalid change address "${r}" for network "${e}".`,"INVALID_CHANGE_ADDRESS",{changeAddress:r,network:e})}return r}function Ev(t,e){try{return bv(t,e)}catch{return"p2tr"}}function vv(t){return Ye.encode(["RETURN",t])}var I0=546;function qR(t,e){if(t.status.block_height!==e.status.block_height)return t.status.block_height-e.status.block_height;let r=t.txid.localeCompare(e.txid);return r!==0?r:t.vout-e.vout}function FR(t,e){if(!t.length)throw new rr("No UTXOs found, please fund address!","UNFUNDED_BEACON_ADDRESS",{address:e});let r=t.filter(i=>i.status.confirmed===!0),n=r.filter(i=>i.value>I0);if(!n.length){let i=r.length===0?`all ${t.length} UTXO(s) are unconfirmed`:`all ${r.length} confirmed UTXO(s) are at or below the ${I0}-sat dust limit`;throw new rr(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:I0})}return[...n].sort(qR)[0]}async function Sv(t,e){let r=await e.rest.address.getUtxos(t),n=FR(r,t),i=await e.rest.transaction.getHex(n.txid);return{utxo:n,prevTxBytes:Ar(i)}}async function T7(t){let e=t.feeEstimator??B0,{utxo:r,prevTxBytes:n}=await Sv(t.beaconAddress,t.bitcoin),i=xv(t.beaconAddress,t.network,t.changeAddress),o=Je.encode(Yr(t.network).decode(t.beaconAddress)),s=Ev(i,t.network),c=await e.estimateFee(wv("p2tr",s));if(BigInt(r.value)<=c)throw new rr(`UTXO value (${r.value}) insufficient to cover fee (${c}).`,"INSUFFICIENT_FUNDS",{address:t.beaconAddress,valueSats:r.value,feeSats:c});let a=new _s({allowUnknownOutputs:!0});a.addInput({txid:r.txid,index:r.vout,nonWitnessUtxo:n,witnessUtxo:{amount:BigInt(r.value),script:o},tapInternalKey:t.internalPubkey});let u=BigInt(r.value)-c;return u>=BigInt(mv[s])&&a.addOutputAddress(i,u,t.network),a.addOutput({script:vv(t.signalBytes),amount:0n}),{tx:a,prevOutScripts:[o],prevOutValues:[BigInt(r.value)],beaconAddress:t.beaconAddress,changeAddress:i,utxo:r,feeSats:c,scriptKind:"p2tr"}}async function jR(t,e,r,n,i,o){let s=n.publicKey;if(r==="p2pkh"){let u=vo.ALL,d=t.preimageLegacy(e,i,u),f=n.sign(d,"ecdsa"),h=ut(f,new Uint8Array([u]));return t.updateInput(e,{partialSig:[[s,h]]},!0),t.finalize(),t.hex}if(r==="p2wpkh"){let u=Je.decode(i);if(u.type!=="wpkh")throw new rr(`Expected P2WPKH prev-output script, got "${u.type}".`,"PREVOUT_SCRIPT_MISMATCH",{kind:r,observedScriptType:u.type});let d=Je.encode({type:"pkh",hash:u.hash}),f=vo.ALL,h=t.preimageWitnessV0(e,d,f,o),p=n.sign(h,"ecdsa"),g=ut(p,new Uint8Array([f]));return t.updateInput(e,{partialSig:[[s,g]]},!0),t.finalize(),t.hex}let c=t.preimageWitnessV1(e,[i],vo.DEFAULT,[o]),a=n.sign(c,"bip341");return t.updateInput(e,{tapKeySig:a}),t.finalize(),t.hex}var Ro=class{service;constructor(e){this.service=e}async buildSignAndBroadcast(e,r,n,i){let o=i?.feeEstimator??B0,s=this.service.serviceEndpoint.replace("bitcoin:",""),{utxo:c,prevTxBytes:a}=await Sv(s,n),u=await this.buildSinglePartyTx({signalBytes:e,beaconAddress:s,utxo:c,prevTxBytes:a,signer:r,bitcoin:n,feeEstimator:o,changeAddress:i?.changeAddress}),d=await this.signSinglePartyTx(u,r);return this.broadcastRawTx(n,d)}async buildSinglePartyTx(e){let r=e.bitcoin.data,n=e.signer.publicKey,i=bv(e.beaconAddress,r),o=xv(e.beaconAddress,r,e.changeAddress),s=VR(i,n,r);if(s!==e.beaconAddress)throw new rr(`Signer pubkey produces ${i.toUpperCase()} address "${s}", but beacon address is "${e.beaconAddress}".`,"SIGNER_KEY_MISMATCH",{kind:i,address:e.beaconAddress,derivedAddress:s});let c=Ev(o,r),a=await e.feeEstimator.estimateFee(wv(i,c)),u=BigInt(e.utxo.value);if(u<=a)throw new rr(`UTXO value (${e.utxo.value}) insufficient to cover fee (${a}).`,"INSUFFICIENT_FUNDS",{address:e.beaconAddress,valueSats:e.utxo.value,feeSats:a});let d=new _s({allowUnknownOutputs:!0}),f;if(i==="p2pkh")f=ki(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes});else if(i==="p2wpkh")f=vs(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes,witnessUtxo:{amount:u,script:f}});else{let p=n.slice(1,33);f=Ss(p,void 0,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes,witnessUtxo:{amount:u,script:f},tapInternalKey:p})}let h=u-a;return h>=BigInt(mv[c])&&d.addOutputAddress(o,h,r),d.addOutput({script:vv(e.signalBytes),amount:0n}),{tx:d,prevOutScripts:[f],prevOutValues:[u],beaconAddress:e.beaconAddress,changeAddress:o,utxo:e.utxo,feeSats:a,scriptKind:i}}async signSinglePartyTx(e,r){return jR(e.tx,0,e.scriptKind,r,e.prevOutScripts[0],e.prevOutValues[0])}async broadcastRawTx(e,r){return e.rest.transaction.send(r)}};l();var Al=class extends Ro{constructor(e){super({...e,type:"CASBeacon"})}processSignals(e,r){let n=new Array,i=new Array,o=this.service.id.split("#")[0];for(let s of e){let c=s.signalBytes,a=r.casMap.get(c);if(!a){i.push({kind:"NeedCASAnnouncement",announcementHash:c,beaconServiceId:this.service.id});continue}let u=a[o];if(!u)continue;let d=Zr(Is(u,"base64urlnopad"),"hex"),f=r.updateMap.get(d);if(!f){i.push({kind:"NeedSignedUpdate",updateHash:d,beaconServiceId:this.service.id});continue}n.push([f,s.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=this.service.id.split("#")[0],s=Gn(e),c={[o]:s},a=To(tr(c));return await this.buildSignAndBroadcast(a,r,n,i),i?.casPublish&&await i.casPublish(c),e}};l();l();var Tl=class extends Ro{constructor(e){super({...e,type:"SingletonBeacon"})}processSignals(e,r){let n=new Array,i=new Array;for(let o of e){let s=o.signalBytes,c=r.updateMap.get(s);if(!c){i.push({kind:"NeedSignedUpdate",updateHash:s,beaconServiceId:this.service.id});continue}n.push([c,o.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=To(tr(e));return await this.buildSignAndBroadcast(o,r,n,i),e}};l();l();l();var WR=new Uint8Array(32),R0=1n<<BigInt(256),Av=(()=>{let t=new Array(257),e=R0>>1n;for(let r=0;r<256;r++)t[r]=e,e>>=1n;return t[256]=0n,t})();l();l();l();function Wu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Yn(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function ve(t,e,r=""){let n=Wu(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let s=r&&`"${r}" `,c=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+c+", got "+a)}return t}function _l(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Yn(t.outputLen),Yn(t.blockLen)}function Xc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function _v(t,e){ve(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Os(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Bl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function xn(t,e){return t<<32-e|t>>>e}var Bv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",GR=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ds(t){if(ve(t),Bv)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=GR[t[r]];return e}var Ni={_0:48,_9:57,A:65,F:70,a:97,f:102};function Tv(t){if(t>=Ni._0&&t<=Ni._9)return t-Ni._0;if(t>=Ni.A&&t<=Ni.F)return t-(Ni.A-10);if(t>=Ni.a&&t<=Ni.f)return t-(Ni.a-10)}function ks(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Bv)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=Tv(t.charCodeAt(o)),c=Tv(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function fr(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];ve(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}function Iv(t,e={}){let r=(i,o)=>t(o).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}function Ns(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var Rv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var O0=BigInt(0),U0=BigInt(1);function Gu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Uv(t){if(typeof t=="bigint"){if(!Il(t))throw new Error("positive bigint expected, got "+t)}else Yn(t);return t}function zu(t){let e=Uv(t).toString(16);return e.length&1?"0"+e:e}function Ov(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?O0:BigInt("0x"+t)}function Uo(t){return Ov(Ds(t))}function D0(t){return Ov(Ds(zR(ve(t)).reverse()))}function Rl(t,e){Yn(e),t=Uv(t);let r=ks(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function k0(t,e){return Rl(t,e).reverse()}function Qc(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function zR(t){return Uint8Array.from(t)}function Dv(t){return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new Error(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var Il=t=>typeof t=="bigint"&&O0<=t;function YR(t,e,r){return Il(t)&&Il(e)&&Il(r)&&e<=t&&t<r}function kv(t,e,r,n){if(!YR(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function N0(t){let e;for(e=0;t>O0;t>>=U0,e+=1);return e}var Yu=t=>(U0<<BigInt(t))-U0;function Nv(t,e,r){if(Yn(t,"hashLen"),Yn(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=E=>new Uint8Array(E),i=Uint8Array.of(),o=Uint8Array.of(0),s=Uint8Array.of(1),c=1e3,a=n(t),u=n(t),d=0,f=()=>{a.fill(1),u.fill(0),d=0},h=(...E)=>r(u,fr(a,...E)),p=(E=i)=>{u=h(o,E),a=h(),E.length!==0&&(u=h(s,E),a=h())},g=()=>{if(d++>=c)throw new Error("drbg: tried max amount of iterations");let E=0,S=[];for(;E<e;){a=h();let I=a.slice();S.push(I),E+=a.length}return fr(...S)};return(E,S)=>{f(),p(E);let I;for(;!(I=S(g()));)p();return f(),I}}function Ju(t,e={},r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(o,s,c){let a=t[o];if(c&&a===void 0)return;let u=typeof a;if(u!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${u}`)}let i=(o,s)=>Object.entries(o).forEach(([c,a])=>n(c,a,s));i(e,!1),i(r,!0)}function C0(t){let e=new WeakMap;return(r,...n)=>{let i=e.get(r);if(i!==void 0)return i;let o=t(r,...n);return e.set(r,o),o}}function L0(t){return t.length===32}function Ul(t){if(!L0(t))throw new RangeError(`Invalid hash: expected ${32} bytes, got ${t.length}`)}function dt(...t){return Oe(ut(...t))}function Zu(t){Ul(t);let e=0n;for(let r of t)e=e<<8n|BigInt(r);return e}function P0(t){let e=new Uint8Array(32),r=t;for(let n=31;n>=0;n--)e[n]=Number(r&0xffn),r>>=8n;if(r!==0n)throw new RangeError("Value exceeds 256 bits");return e}function M0(t){Ul(t);let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function K0(t,e){return!L0(t)||!L0(e)?!1:Qc(t,e)}function ea(t){return Ul(t),$c.encode(t)}function Jn(t){let e=$c.decode(t);if(e.length!==32)throw new RangeError(`Invalid base64url hash: expected ${32} decoded bytes, got ${e.length}`);return e}l();l();var Cv;(function(t){t[t.Pending=0]="Pending",t[t.Valid=1]="Valid",t[t.Invalid=2]="Invalid"})(Cv||(Cv={}));l();l();var Oo=256;function ta(t,e){return Number(t>>BigInt(e)&1n)}var Lv=(()=>{let t=new Array(Oo+1),e=new Uint8Array(32);for(let r=0;r<=Oo;r++)e=dt(e,e),t[r]=e;return t})();function Ol(t,e){if(t.length===0)return Lv[e];if(e===0)return t[0].leaf;let r=Oo-e,n=[],i=[];for(let o of t)(ta(o.index,r)===0?n:i).push(o);return dt(Ol(n,e-1),Ol(i,e-1))}function Pv(t){return Ol(t,Oo)}function Mv(t,e){let r=0n,n=[];for(let i=1;i<=Oo;i++){let o=Oo-i,s=[];for(let c of t){if(c.index===e)continue;let a=!0;for(let u=0;u<o;u++)if(ta(c.index,u)!==ta(e,u)){a=!1;break}a&&ta(c.index,o)!==ta(e,o)&&s.push(c)}s.length===0?r|=1n<<BigInt(o):n.push(Ol(s,i-1))}return{collapsed:r,hashes:n}}function Kv(t,e,r,n,i){let o=n,s=0;for(let c=0;c<Oo;c++){let a=Oo-1-c,u;if((t>>BigInt(a)&1n)===1n)u=Lv[c];else{if(s>=e.length)return!1;u=e[s++]}o=ta(r,a)===1?dt(u,o):dt(o,u)}return s===e.length&&K0(o,i)}l();var JR=new TextEncoder;function Dl(t){return Zu(dt(JR.encode(t)))}function $v(t,e){return dt(dt(t),dt(e))}function Hv(t){return dt(dt(t))}l();function Vv(t,e,r){let n={id:ea(t),collapsed:ea(P0(e.collapsed)),hashes:e.hashes.map(i=>ea(i))};return r?.nonce&&(n.nonce=ea(r.nonce)),r?.updateId&&(n.updateId=ea(r.updateId)),n}function ZR(t){let e={rootHash:Jn(t.id),collapsed:Zu(Jn(t.collapsed)),hashes:t.hashes.map(r=>Jn(r))};return t.nonce&&(e.nonce=Jn(t.nonce)),t.updateId&&(e.updateId=Jn(t.updateId)),e}function qv(t,e,r){let{rootHash:n,collapsed:i,hashes:o}=ZR(t);return Kv(i,o,e,r,n)}l();var kl=class{#e=new Map;#t=new Map;#n=null;#r=null;constructor(e=!0){}addEntries(e){for(let r of e){let n=Dl(r.did);if(this.#e.has(n))throw new RangeError(`Duplicate DID index for: ${r.did}`);this.#e.set(n,r),this.#t.set(r.did,n)}this.#n=null,this.#r=null}finalize(){let e=[];for(let[r,n]of this.#e){let i=n.signedUpdate!==void 0?$v(n.nonce,n.signedUpdate):Hv(n.nonce);e.push({index:r,leaf:i})}this.#n=e,this.#r=Pv(e)}get rootHash(){if(this.#r===null)throw new Error("Tree not finalized: call finalize() first");return this.#r}proof(e){let r=this.#t.get(e);if(r===void 0)throw new RangeError(`DID not in tree: ${e}`);if(this.#n===null||this.#r===null)throw new Error("Tree not finalized: call finalize() first");let n=this.#e.get(r),i=Mv(this.#n,r),o=n.signedUpdate!==void 0?dt(n.signedUpdate):void 0;return Vv(this.#r,i,{nonce:n.nonce,updateId:o})}reset(){this.#n=null,this.#r=null}};var Nl=class extends Ro{constructor(e){super({...e,type:"SMTBeacon"})}processSignals(e,r){let n=new Array,i=new Array,o=this.service.id.split("#")[0];for(let s of e){let c=r.smtMap.get(s.signalBytes);if(!c){i.push({kind:"NeedSMTProof",smtRootHash:s.signalBytes,beaconServiceId:this.service.id});continue}if(!c.nonce)throw new Fu("SMT proof missing required nonce field.","INVALID_SMT_PROOF",{smtProof:c,did:o});let a=Dl(o),u=Jn(c.nonce),d=c.updateId?dt(dt(u),Jn(c.updateId)):dt(dt(u));if(!qv(c,a,d))throw new Fu("SMT proof verification failed.","INVALID_SMT_PROOF",{smtProof:c,did:o});if(!c.updateId)continue;let h=M0(Jn(c.updateId)),p=r.updateMap.get(h);if(!p){i.push({kind:"NeedSignedUpdate",updateHash:h,beaconServiceId:this.service.id});continue}n.push([p,s.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=this.service.id.split("#")[0],s=new TextEncoder().encode(tr(e)),c=Tr(32),a=new kl;return a.addEntries([{did:o,nonce:c,signedUpdate:s}]),a.finalize(),await this.buildSignAndBroadcast(a.rootHash,r,n,i),e}};var ra=class{static establish(e){switch(e.type){case"SingletonBeacon":return new Tl(e);case"CASBeacon":return new Al(e);case"SMTBeacon":return new Nl(e);default:throw new tt("Invalid Beacon Type","INVALID_BEACON_ERROR",e)}}};l();l();l();l();l();l();var Li;(function(t){t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation"})(Li||(Li={}));l();var ft={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};l();var me=class t{constructor({method:e,id:r,path:n,query:i,fragment:o,params:s}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=i,this.fragment=o,this.params=s}static parse(e){if(!e)return null;let r=t.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:i,path:o,query:s,fragment:c}=r.groups,a={uri:`did:${n}:${i}`,method:n,id:i};if(o&&(a.path=o),s&&(a.query=s.slice(1)),c&&(a.fragment=c.slice(1)),s){let u={},d=s.slice(1).split("&");for(let f of d){let[h,p]=f.split("=");u[h]=p}a.params=u}return a}};me.METHOD_PATTERN="([a-z0-9]+)";me.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})";me.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${me.PCT_ENCODED_PATTERN})`;me.METHOD_ID_PATTERN=`((?:${me.ID_CHAR_PATTERN}*:)*(${me.ID_CHAR_PATTERN}+))`;me.PATH_PATTERN="(/[^#?]*)?";me.QUERY_PATTERN="([?][^#]*)?";me.FRAGMENT_PATTERN="(#.*)?";me.DID_URI_PATTERN=new RegExp(`^did:(?<method>${me.METHOD_PATTERN}):(?<id>${me.METHOD_ID_PATTERN})(?<path>${me.PATH_PATTERN})(?<query>${me.QUERY_PATTERN})(?<fragment>${me.FRAGMENT_PATTERN})$`);l();var re=class t extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,t)}},ie;(function(t){t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidPreviousDidProof="invalidPreviousDidProof",t.InvalidPublicKey="invalidPublicKey",t.InvalidPublicKeyLength="invalidPublicKeyLength",t.InvalidPublicKeyType="invalidPublicKeyType",t.InvalidSignature="invalidSignature",t.NotFound="notFound",t.RepresentationNotSupported="representationNotSupported",t.UnsupportedPublicKeyType="unsupportedPublicKeyType"})(ie||(ie={}));l();l();l();l();l();var e6=Pn(jv(),1);l();l();l();l();var EH=new Uint8Array(0);function Wv(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function na(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}l();function r6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,E=0,S=0,I=g.length;S!==I&&g[S]===0;)S++,y++;for(var A=(I-S)*d+1>>>0,O=new Uint8Array(A);S!==I;){for(var T=g[S],M=0,q=A-1;(T!==0||M<E)&&q!==-1;q--,M++)T+=256*O[q]>>>0,O[q]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");E=M,S++}for(var j=A-E;j!==A&&O[j]===0;)j++;for(var $=a.repeat(y);j<A;++j)$+=t.charAt(O[j]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var E=0,S=0;g[y]===a;)E++,y++;for(var I=(g.length-y)*u+1>>>0,A=new Uint8Array(I);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=I-1;(O!==0||T<S)&&M!==-1;M--,T++)O+=c*A[M]>>>0,A[M]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=T,y++}if(g[y]!==" "){for(var q=I-S;q!==I&&A[q]===0;)q++;for(var j=new Uint8Array(E+(I-q)),$=E;q!==I;)j[$++]=A[q++];return j}}}function p(g){var y=h(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var n6=r6,i6=n6,Gv=i6;var q0=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},F0=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return zv(this,e)}},j0=class{decoders;constructor(e){this.decoders=e}or(e){return zv(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function zv(t,e){return new j0({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var W0=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new q0(e,r,n),this.decoder=new F0(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Yv({name:t,prefix:e,encode:r,decode:n}){return new W0(t,e,r,n)}function G0({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=Gv(r,t);return Yv({prefix:e,name:t,encode:n,decode:o=>na(i(o))})}function o6(t,e,r,n){let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),c=0,a=0,u=0;for(let d=0;d<o;++d){let f=i[t[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s}function s6(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,o+=e[i&c>>s];if(s!==0&&(o+=e[i&c<<r-s]),n)for(;o.length*r&7;)o+="=";return o}function nr({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return Yv({prefix:e,name:t,encode(i){return s6(i,n,r)},decode(i){return o6(i,n,r,t)}})}var Xu=nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),UH=nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),OH=nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),DH=nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),kH=nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),NH=nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),CH=nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),LH=nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),z0=nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var lr=G0({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$H=G0({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var FH=nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jH=nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zn=nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),WH=nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});l();function Jv(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function Zv(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function ia(t){let r=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[n,i]=r;return i}var Qu=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Xv=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(s){return new Promise(function(c,a){s=t[o](s),i(c,a,s.done,s.value)})}}function i(o,s,c,a){Promise.resolve(a).then(function(u){o({value:u,done:c})},s)}},Ll=new TextEncoder,Cs=new TextDecoder,ne=class t{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new t(e,"ArrayBuffer")}static asyncIterable(e){if(!Zv(e))throw new TypeError("Input must be of type AsyncIterable.");return new t(e,"AsyncIterable")}static base32Z(e){return new t(e,"Base32Z")}static base58Btc(e){return new t(e,"Base58Btc")}static base64Url(e){return new t(e,"Base64Url")}static bufferSource(e){return new t(e,"BufferSource")}static hex(e){if(typeof e!="string")throw new TypeError("Hex input must be a string.");if(e.length%2!==0)throw new TypeError("Hex input must have an even number of characters.");return new t(e,"Hex")}static multibase(e){return new t(e,"Multibase")}static object(e){return new t(e,"Object")}static string(e){return new t(e,"String")}static uint8Array(e){return new t(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return lr.baseDecode(this.data).buffer;case"Base64Url":return Zn.baseDecode(this.data).buffer;case"BufferSource":{if(ia(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Jv(this.data)?this.data.buffer.slice(this.data.byteOffset,this.data.byteOffset+this.data.byteLength):this.data.buffer;throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":return this.toUint8Array().buffer;case"String":return this.toUint8Array().buffer;case"Uint8Array":return this.data.buffer;default:throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`)}}toArrayBufferAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":return yield(yield this.toBlobAsync()).arrayBuffer();default:throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`)}})}toBase32Z(){switch(this.format){case"Uint8Array":return z0.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`)}}toBase58Btc(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return lr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return lr.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`)}}toBase64Url(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return Zn.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return Zn.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=Ll.encode(e);return Zn.baseEncode(r)}case"String":{let e=Ll.encode(this.data);return Zn.baseEncode(e)}case"Uint8Array":return Zn.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Qu(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a=[];try{for(var o=!0,s=Xv(this.data),c;c=yield s.next(),e=c.done,!e;o=!0){i=c.value,o=!1;let d=i;a.push(d)}}catch(d){r={error:d}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return new Blob(a)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return t.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return t.uint8Array(r).toHex()}case"Uint8Array":{let r="";for(let n=0;n<this.data.length;n++)r+=e[this.data[n]];return r}default:throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`)}}toMultibase(){switch(this.format){case"Base58Btc":return`z${this.data}`;default:throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`)}}toObject(){switch(this.format){case"Base64Url":{let e=Zn.baseDecode(this.data),r=Cs.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Cs.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toStringAsync();return JSON.parse(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`)}})}toString(){switch(this.format){case"ArrayBuffer":return Cs.decode(this.data);case"Base64Url":{let e=Zn.baseDecode(this.data);return Cs.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Cs.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Qu(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a="";try{for(var o=!0,s=Xv(this.data),c;c=yield s.next(),e=c.done,!e;o=!0){i=c.value,o=!1;let u=i;typeof u=="string"?a+=u:a+=Cs.decode(u,{stream:!0})}}catch(u){r={error:u}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return a+=Cs.decode(void 0,{stream:!1}),a}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return z0.baseDecode(this.data);case"Base58Btc":return lr.baseDecode(this.data);case"Base64Url":return Zn.baseDecode(this.data);case"BufferSource":{let e=ia(this.data);if(e==="Uint8Array")return this.data;if(e==="ArrayBuffer")return new Uint8Array(this.data);if(ArrayBuffer.isView(this.data))return new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":{let e=new Uint8Array(this.data.length/2);for(let r=0;r<this.data.length;r+=2){let n=parseInt(this.data.substring(r,r+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[r/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return Ll.encode(e)}case"String":return Ll.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toArrayBufferAsync();return new Uint8Array(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`)}})}};l();var ed;(function(t){t.Debug="debug",t.Silent="silent"})(ed||(ed={}));var Y0=class{constructor(){this.logLevel=ed.Silent}setLogLevel(e){this.logLevel=e}log(e){this.info(e)}info(e){this.logLevel!==ed.Silent&&console.info(e)}error(e){this.logLevel!==ed.Silent&&console.error(e)}},c6=new Y0;typeof window<"u"&&(window.web5logger=c6);l();l();l();l();var Pi={};Sf(Pi,{decode:()=>oa,encodeTo:()=>Ls,encodingLength:()=>Ps});l();l();var a6=t1,Qv=128,u6=127,d6=~u6,f6=Math.pow(2,31);function t1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=f6;)e[r++]=t&255|Qv,t/=128;for(;t&d6;)e[r++]=t&255|Qv,t>>>=7;return e[r]=t|0,t1.bytes=r-n+1,e}var l6=J0,h6=128,e1=127;function J0(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw J0.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&e1)<<i:(s&e1)*Math.pow(2,i),i+=7}while(s>=h6);return J0.bytes=o-n,r}var p6=Math.pow(2,7),y6=Math.pow(2,14),g6=Math.pow(2,21),m6=Math.pow(2,28),w6=Math.pow(2,35),b6=Math.pow(2,42),x6=Math.pow(2,49),E6=Math.pow(2,56),v6=Math.pow(2,63),S6=function(t){return t<p6?1:t<y6?2:t<g6?3:t<m6?4:t<w6?5:t<b6?6:t<x6?7:t<E6?8:t<v6?9:10},A6={encode:a6,decode:l6,encodingLength:S6},T6=A6,td=T6;function oa(t,e=0){return[td.decode(t,e),td.decode.bytes]}function Ls(t,e,r=0){return td.encode(t,e,r),e}function Ps(t){return td.encodingLength(t)}function Z0(t,e){let r=e.byteLength,n=Ps(t),i=n+Ps(r),o=new Uint8Array(i+r);return Ls(t,o,0),Ls(r,o,n),o.set(e,i),new sa(t,r,e,o)}function r1(t){let e=na(t),[r,n]=oa(e),[i,o]=oa(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new sa(r,i,s,e)}function n1(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Wv(t.bytes,r.bytes)}}var sa=class{code;size;digest;bytes;constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();function i1(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return B6(r,Q0(t),e??lr.encoder);default:return I6(r,Q0(t),e??Xu.encoder)}}var o1=new WeakMap;function Q0(t){let e=o1.get(t);if(e==null){let r=new Map;return o1.set(t,r),r}return e}var eg=class t{code;version;multihash;bytes;"/";constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==rd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==R6)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=Z0(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&n1(e.multihash,n.multihash)}toString(e){return i1(this,e)}toJSON(){return{"/":i1(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:s}=r;return new t(n,i,o,s??s1(n,i,o.bytes))}else if(r[U6]===!0){let{version:n,multihash:i,code:o}=r,s=r1(i);return t.create(n,o,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==rd)throw new Error(`Version 0 CID must use dag-pb (code: ${rd}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=s1(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,rd,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=na(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new sa(r.multihashCode,r.digestSize,o,i);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,h]=oa(e.subarray(r));return r+=h,f},i=n(),o=rd;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,c=n(),a=n(),u=r+a,d=u-s;return{version:i,codec:o,multihashCode:c,digestSize:a,multihashSize:d,size:u}}static parse(e,r){let[n,i]=_6(e,r),o=t.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Q0(o).set(n,e),o}};function _6(t,e){switch(t[0]){case"Q":{let r=e??lr;return[lr.prefix,r.decode(`${lr.prefix}${t}`)]}case lr.prefix:{let r=e??lr;return[lr.prefix,r.decode(t)]}case Xu.prefix:{let r=e??Xu;return[Xu.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function B6(t,e,r){let{prefix:n}=r;if(n!==lr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let o=r.encode(t).slice(1);return e.set(n,o),o}else return i}function I6(t,e,r){let{prefix:n}=r,i=e.get(n);if(i==null){let o=r.encode(t);return e.set(n,o),o}else return i}var rd=112,R6=18;function s1(t,e,r){let n=Ps(t),i=n+Ps(e),o=new Uint8Array(i+r.byteLength);return Ls(t,o,0),Ls(e,o,n),o.set(r,i),o}var U6=Symbol.for("@ipld/js-cid/CID");l();l();l();l();l();l();var zt=class t{static addPrefix(e){var r;let{code:n,data:i,name:o}=e;if(!(o?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=t.codeToName.has(n)?n:t.nameToCode.get(o),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let s=Pi.encodingLength(n),c=new Uint8Array(s+i.byteLength);return c.set(i,s),Pi.encodeTo(n,c),c}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Pi.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=t.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=t.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){t.codeToName.set(e.code,e.name),t.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,i]=Pi.decode(r),o=t.codeToName.get(n);if(o===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(i),name:o}}};zt.codeToName=new Map;zt.nameToCode=new Map;zt.registerCodec({code:237,name:"ed25519-pub"});zt.registerCodec({code:4864,name:"ed25519-priv"});zt.registerCodec({code:236,name:"x25519-pub"});zt.registerCodec({code:4866,name:"x25519-priv"});zt.registerCodec({code:231,name:"secp256k1-pub"});zt.registerCodec({code:4865,name:"secp256k1-priv"});l();function tg(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&tg(t[e])})}l();var PU=Pn(Gg(),1),Xs=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})};var dh=class{constructor(){this.store=new Map}clear(){return Xs(this,void 0,void 0,function*(){this.store.clear()})}close(){return Xs(this,void 0,void 0,function*(){})}delete(e){return Xs(this,void 0,void 0,function*(){return this.store.delete(e)})}get(e){return Xs(this,void 0,void 0,function*(){return this.store.get(e)})}has(e){return Xs(this,void 0,void 0,function*(){return this.store.has(e)})}list(){return Xs(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(e,r){return Xs(this,void 0,void 0,function*(){this.store.set(e,r)})}};l();l();var ek=Pn(ow(),1);var tk=Pn(ow(),1);l();l();l();l();l();function rk(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function sw(t,...e){if(!rk(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function cw(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function hT(t,e){sw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var Da=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var qh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),_n=(t,e)=>t<<32-e|t>>>e;var wj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function nk(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function aw(t){return typeof t=="string"&&(t=nk(t)),sw(t),t}var Vh=class{clone(){return this._cloneInto()}},bj={}.toString;function pT(t){let e=n=>t().update(aw(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function yT(t=32){if(Da&&typeof Da.getRandomValues=="function")return Da.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function ik(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}var gT=(t,e,r)=>t&e^~t&r,mT=(t,e,r)=>t&e^t&r^e&r,Fh=class extends Vh{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=qh(this.buffer)}update(e){cw(this);let{view:r,buffer:n,blockLen:i}=this;e=aw(e);let o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=qh(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){cw(this),hT(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;ik(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=qh(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.length=i,e.pos=c,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var ok=new Uint32Array([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]),Fo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),jo=new Uint32Array(64),uw=class extends Fh{constructor(){super(64,32,8,!1),this.A=Fo[0]|0,this.B=Fo[1]|0,this.C=Fo[2]|0,this.D=Fo[3]|0,this.E=Fo[4]|0,this.F=Fo[5]|0,this.G=Fo[6]|0,this.H=Fo[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)jo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=jo[f-15],p=jo[f-2],g=_n(h,7)^_n(h,18)^h>>>3,y=_n(p,17)^_n(p,19)^p>>>10;jo[f]=y+jo[f-7]+g+jo[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=_n(c,6)^_n(c,11)^_n(c,25),p=d+h+gT(c,a,u)+ok[f]+jo[f]|0,y=(_n(n,2)^_n(n,13)^_n(n,22))+mT(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){jo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Wo=pT(()=>new uw);var sk=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},ka=class{static digest(e){return sk(this,arguments,void 0,function*({data:r}){return Wo(r)})}};l();var ci=class{};var ck=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},jh=class extends ci{digest(e){return ck(this,arguments,void 0,function*({algorithm:r,data:n}){switch(r){case"SHA-256":return yield ka.digest({data:n})}})}};l();l();l();l();l();l();function wT(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function ak(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function dw(t,...e){if(!ak(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function bT(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");wT(t.outputLen),wT(t.blockLen)}function Na(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function xT(t,e){dw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var Wh=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ET(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Gh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Bn=(t,e)=>t<<32-e|t>>>e,uk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!uk)throw new Error("Non little-endian hardware is not supported");function fw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Cd(t){if(typeof t=="string"&&(t=fw(t)),!ET(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function zh(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!ET(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var Ca=class{clone(){return this._cloneInto()}},Fj={}.toString;function Yh(t){let e=n=>t().update(Cd(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ld(t=32){if(Wh&&typeof Wh.getRandomValues=="function")return Wh.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function dk(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}var La=class extends Ca{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Gh(this.buffer)}update(e){Na(this);let{view:r,buffer:n,blockLen:i}=this;e=Cd(e);let o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Gh(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Na(this),xT(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;dk(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Gh(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.length=i,e.pos=c,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var fk=(t,e,r)=>t&e^~t&r,lk=(t,e,r)=>t&e^t&r^e&r,hk=new Uint32Array([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]),Go=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zo=new Uint32Array(64),lw=class extends La{constructor(){super(64,32,8,!1),this.A=Go[0]|0,this.B=Go[1]|0,this.C=Go[2]|0,this.D=Go[3]|0,this.E=Go[4]|0,this.F=Go[5]|0,this.G=Go[6]|0,this.H=Go[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)zo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=zo[f-15],p=zo[f-2],g=Bn(h,7)^Bn(h,18)^h>>>3,y=Bn(p,17)^Bn(p,19)^p>>>10;zo[f]=y+zo[f-7]+g+zo[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=Bn(c,6)^Bn(c,11)^Bn(c,25),p=d+h+fk(c,a,u)+hk[f]+zo[f]|0,y=(Bn(n,2)^Bn(n,13)^Bn(n,22))+lk(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){zo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Jh=Yh(()=>new lw);l();var Xh={};Sf(Xh,{bitGet:()=>xk,bitLen:()=>bk,bitMask:()=>Pd,bitSet:()=>Ek,bytesToHex:()=>Ji,bytesToNumberBE:()=>Zi,bytesToNumberLE:()=>Rn,concatBytes:()=>Qi,createHmacDrbg:()=>yw,ensureBytes:()=>Fe,equalBytes:()=>mk,hexToBytes:()=>dc,hexToNumber:()=>pw,isBytes:()=>In,numberToBytesBE:()=>pr,numberToBytesLE:()=>Xi,numberToHexUnpadded:()=>TT,numberToVarBytesBE:()=>gk,utf8ToBytes:()=>wk,validateObject:()=>rn});l();var AT=BigInt(0),Zh=BigInt(1),pk=BigInt(2);function In(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var yk=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ji(t){if(!In(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=yk[t[r]];return e}function TT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function pw(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var Yi={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function vT(t){if(t>=Yi._0&&t<=Yi._9)return t-Yi._0;if(t>=Yi._A&&t<=Yi._F)return t-(Yi._A-10);if(t>=Yi._a&&t<=Yi._f)return t-(Yi._a-10)}function dc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,r=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=vT(t.charCodeAt(o)),c=vT(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function Zi(t){return pw(Ji(t))}function Rn(t){if(!In(t))throw new Error("Uint8Array expected");return pw(Ji(Uint8Array.from(t).reverse()))}function pr(t,e){return dc(t.toString(16).padStart(e*2,"0"))}function Xi(t,e){return pr(t,e).reverse()}function gk(t){return dc(TT(t))}function Fe(t,e,r){let n;if(typeof e=="string")try{n=dc(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(In(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${t} expected ${r} bytes, got ${i}`);return n}function Qi(...t){let e=0;for(let i=0;i<t.length;i++){let o=t[i];if(!In(o))throw new Error("Uint8Array expected");e+=o.length}let r=new Uint8Array(e),n=0;for(let i=0;i<t.length;i++){let o=t[i];r.set(o,n),n+=o.length}return r}function mk(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function wk(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function bk(t){let e;for(e=0;t>AT;t>>=Zh,e+=1);return e}function xk(t,e){return t>>BigInt(e)&Zh}var Ek=(t,e,r)=>t|(r?Zh:AT)<<BigInt(e),Pd=t=>(pk<<BigInt(t-1))-Zh,hw=t=>new Uint8Array(t),ST=t=>Uint8Array.from(t);function yw(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=hw(t),i=hw(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},c=(...f)=>r(i,n,...f),a=(f=hw())=>{i=c(ST([0]),f),n=c(),f.length!==0&&(i=c(ST([1]),f),n=c())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f<e;){n=c();let p=n.slice();h.push(p),f+=n.length}return Qi(...h)};return(f,h)=>{s(),a(f);let p;for(;!(p=h(u()));)a();return s(),p}}var vk={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||In(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function rn(t,e,r={}){let n=(i,o,s)=>{let c=vk[o];if(typeof c!="function")throw new Error(`Invalid validator "${o}", expected function`);let a=t[i];if(!(s&&a===void 0)&&!c(a,t))throw new Error(`Invalid param ${String(i)}=${a} (${typeof a}), expected ${o}`)};for(let[i,o]of Object.entries(e))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return t}var Tt=BigInt(0),Xe=BigInt(1),fc=BigInt(2),Sk=BigInt(3),gw=BigInt(4),_T=BigInt(5),BT=BigInt(8),Ak=BigInt(9),Tk=BigInt(16);function _e(t,e){let r=t%e;return r>=Tt?r:e+r}function mw(t,e,r){if(r<=Tt||e<Tt)throw new Error("Expected power/modulo > 0");if(r===Xe)return Tt;let n=Xe;for(;e>Tt;)e&Xe&&(n=n*t%r),t=t*t%r,e>>=Xe;return n}function je(t,e,r){let n=t;for(;e-- >Tt;)n*=n,n%=r;return n}function Qh(t,e){if(t===Tt||e<=Tt)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=_e(t,e),n=e,i=Tt,o=Xe,s=Xe,c=Tt;for(;r!==Tt;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==Xe)throw new Error("invert: does not exist");return _e(i,e)}function _k(t){let e=(t-Xe)/fc,r,n,i;for(r=t-Xe,n=0;r%fc===Tt;r/=fc,n++);for(i=fc;i<t&&mw(i,e,t)!==t-Xe;i++);if(n===1){let s=(t+Xe)/gw;return function(a,u){let d=a.pow(u,s);if(!a.eql(a.sqr(d),u))throw new Error("Cannot find square root");return d}}let o=(r+Xe)/fc;return function(c,a){if(c.pow(a,e)===c.neg(c.ONE))throw new Error("Cannot find square root");let u=n,d=c.pow(c.mul(c.ONE,i),r),f=c.pow(a,o),h=c.pow(a,r);for(;!c.eql(h,c.ONE);){if(c.eql(h,c.ZERO))return c.ZERO;let p=1;for(let y=c.sqr(h);p<u&&!c.eql(y,c.ONE);p++)y=c.sqr(y);let g=c.pow(d,Xe<<BigInt(u-p-1));d=c.sqr(g),f=c.mul(f,g),h=c.mul(h,d),u=p}return f}}function Bk(t){if(t%gw===Sk){let e=(t+Xe)/gw;return function(n,i){let o=n.pow(i,e);if(!n.eql(n.sqr(o),i))throw new Error("Cannot find square root");return o}}if(t%BT===_T){let e=(t-_T)/BT;return function(n,i){let o=n.mul(i,fc),s=n.pow(o,e),c=n.mul(i,s),a=n.mul(n.mul(c,fc),s),u=n.mul(c,n.sub(a,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return t%Tk,_k(t)}var IT=(t,e)=>(_e(t,e)&Xe)===Xe,Ik=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ww(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Ik.reduce((n,i)=>(n[i]="function",n),e);return rn(t,r)}function Rk(t,e,r){if(r<Tt)throw new Error("Expected power > 0");if(r===Tt)return t.ONE;if(r===Xe)return e;let n=t.ONE,i=e;for(;r>Tt;)r&Xe&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Xe;return n}function Uk(t,e){let r=new Array(e.length),n=e.reduce((o,s,c)=>t.is0(s)?o:(r[c]=o,t.mul(o,s)),t.ONE),i=t.inv(n);return e.reduceRight((o,s,c)=>t.is0(s)?o:(r[c]=t.mul(o,r[c]),t.mul(o,s)),i),r}function bw(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Pa(t,e,r=!1,n={}){if(t<=Tt)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=bw(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Bk(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Pd(i),ZERO:Tt,ONE:Xe,create:a=>_e(a,t),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return Tt<=a&&a<t},is0:a=>a===Tt,isOdd:a=>(a&Xe)===Xe,neg:a=>_e(-a,t),eql:(a,u)=>a===u,sqr:a=>_e(a*a,t),add:(a,u)=>_e(a+u,t),sub:(a,u)=>_e(a-u,t),mul:(a,u)=>_e(a*u,t),pow:(a,u)=>Rk(c,a,u),div:(a,u)=>_e(a*Qh(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>Qh(a,t),sqrt:n.sqrt||(a=>s(c,a)),invertBatch:a=>Uk(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?Xi(a,o):pr(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return r?Rn(a):Zi(a)}});return Object.freeze(c)}function RT(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function UT(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function xw(t){let e=UT(t);return e+Math.ceil(e/2)}function OT(t,e,r=!1){let n=t.length,i=UT(e),o=xw(e);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?Zi(t):Rn(t),c=_e(s,e-Xe)+Xe;return r?Xi(c,i):pr(c,i)}l();l();var Dk=BigInt(0),Ew=BigInt(1);function ep(t,e){let r=(i,o)=>{let s=o.negate();return i?s:o},n=i=>{let o=Math.ceil(e/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:r,unsafeLadder(i,o){let s=t.ZERO,c=i;for(;o>Dk;)o&Ew&&(s=s.add(c)),c=c.double(),o>>=Ew;return s},precomputeWindow(i,o){let{windows:s,windowSize:c}=n(o),a=[],u=i,d=u;for(let f=0;f<s;f++){d=u,a.push(d);for(let h=1;h<c;h++)d=d.add(u),a.push(d);u=d.double()}return a},wNAF(i,o,s){let{windows:c,windowSize:a}=n(i),u=t.ZERO,d=t.BASE,f=BigInt(2**i-1),h=2**i,p=BigInt(i);for(let g=0;g<c;g++){let y=g*a,E=Number(s&f);s>>=p,E>a&&(E-=h,s+=Ew);let S=y,I=y+Math.abs(E)-1,A=g%2!==0,O=E<0;E===0?d=d.add(r(A,o[S])):u=u.add(r(O,o[I]))}return{p:u,f:d}},wNAFCached(i,o,s,c){let a=i._WINDOW_SIZE||1,u=o.get(i);return u||(u=this.precomputeWindow(i,a),a!==1&&o.set(i,c(u))),this.wNAF(a,u,s)}}}function Md(t){return ww(t.Fp),rn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...bw(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function kk(t){let e=Md(t);rn(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:Nk,hexToBytes:Ck}=Xh,lc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=lc;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)throw new e("Invalid signature integer: wrong length");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{d:Nk(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=lc,r=typeof t=="string"?Ck(t):t;if(!In(r))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:o}=lc._parseInt(r.subarray(2)),{d:s,l:c}=lc._parseInt(o);if(c.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let d=u.toString(16);return d.length&1?`0${d}`:d},n=e(r(t.s)),i=e(r(t.r)),o=n.length/2,s=i.length/2,c=r(o),a=r(s);return`30${r(s+o+4)}02${a}${i}02${c}${n}`}},eo=BigInt(0),nn=BigInt(1),fW=BigInt(2),DT=BigInt(3),lW=BigInt(4);function Lk(t){let e=kk(t),{Fp:r}=e,n=e.toBytes||((g,y,E)=>{let S=y.toAffine();return Qi(Uint8Array.from([4]),r.toBytes(S.x),r.toBytes(S.y))}),i=e.fromBytes||(g=>{let y=g.subarray(1),E=r.fromBytes(y.subarray(0,r.BYTES)),S=r.fromBytes(y.subarray(r.BYTES,2*r.BYTES));return{x:E,y:S}});function o(g){let{a:y,b:E}=e,S=r.sqr(g),I=r.mul(S,g);return r.add(r.add(I,r.mul(g,y)),E)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function s(g){return typeof g=="bigint"&&eo<g&&g<e.n}function c(g){if(!s(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(g){let{allowedPrivateKeyLengths:y,nByteLength:E,wrapPrivateKey:S,n:I}=e;if(y&&typeof g!="bigint"){if(In(g)&&(g=Ji(g)),typeof g!="string"||!y.includes(g.length))throw new Error("Invalid key");g=g.padStart(E*2,"0")}let A;try{A=typeof g=="bigint"?g:Zi(Fe("private key",g,E))}catch{throw new Error(`private key must be ${E} bytes, hex or bigint, not ${typeof g}`)}return S&&(A=_e(A,I)),c(A),A}let u=new Map;function d(g){if(!(g instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(y,E,S){if(this.px=y,this.py=E,this.pz=S,y==null||!r.isValid(y))throw new Error("x required");if(E==null||!r.isValid(E))throw new Error("y required");if(S==null||!r.isValid(S))throw new Error("z required")}static fromAffine(y){let{x:E,y:S}=y||{};if(!y||!r.isValid(E)||!r.isValid(S))throw new Error("invalid affine point");if(y instanceof f)throw new Error("projective point not allowed");let I=A=>r.eql(A,r.ZERO);return I(E)&&I(S)?f.ZERO:new f(E,S,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let E=r.invertBatch(y.map(S=>S.pz));return y.map((S,I)=>S.toAffine(E[I])).map(f.fromAffine)}static fromHex(y){let E=f.fromAffine(i(Fe("pointHex",y)));return E.assertValidity(),E}static fromPrivateKey(y){return f.BASE.multiply(a(y))}_setWindowSize(y){this._WINDOW_SIZE=y,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:y,y:E}=this.toAffine();if(!r.isValid(y)||!r.isValid(E))throw new Error("bad point: x or y not FE");let S=r.sqr(E),I=o(y);if(!r.eql(S,I))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y}=this.toAffine();if(r.isOdd)return!r.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){d(y);let{px:E,py:S,pz:I}=this,{px:A,py:O,pz:T}=y,M=r.eql(r.mul(E,T),r.mul(A,I)),q=r.eql(r.mul(S,T),r.mul(O,I));return M&&q}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){let{a:y,b:E}=e,S=r.mul(E,DT),{px:I,py:A,pz:O}=this,T=r.ZERO,M=r.ZERO,q=r.ZERO,j=r.mul(I,I),$=r.mul(A,A),X=r.mul(O,O),Q=r.mul(I,A);return Q=r.add(Q,Q),q=r.mul(I,O),q=r.add(q,q),T=r.mul(y,q),M=r.mul(S,X),M=r.add(T,M),T=r.sub($,M),M=r.add($,M),M=r.mul(T,M),T=r.mul(Q,T),q=r.mul(S,q),X=r.mul(y,X),Q=r.sub(j,X),Q=r.mul(y,Q),Q=r.add(Q,q),q=r.add(j,j),j=r.add(q,j),j=r.add(j,X),j=r.mul(j,Q),M=r.add(M,j),X=r.mul(A,O),X=r.add(X,X),j=r.mul(X,Q),T=r.sub(T,j),q=r.mul(X,$),q=r.add(q,q),q=r.add(q,q),new f(T,M,q)}add(y){d(y);let{px:E,py:S,pz:I}=this,{px:A,py:O,pz:T}=y,M=r.ZERO,q=r.ZERO,j=r.ZERO,$=e.a,X=r.mul(e.b,DT),Q=r.mul(E,A),G=r.mul(S,O),_=r.mul(I,T),D=r.add(E,S),x=r.add(A,O);D=r.mul(D,x),x=r.add(Q,G),D=r.sub(D,x),x=r.add(E,I);let U=r.add(A,T);return x=r.mul(x,U),U=r.add(Q,_),x=r.sub(x,U),U=r.add(S,I),M=r.add(O,T),U=r.mul(U,M),M=r.add(G,_),U=r.sub(U,M),j=r.mul($,x),M=r.mul(X,_),j=r.add(M,j),M=r.sub(G,j),j=r.add(G,j),q=r.mul(M,j),G=r.add(Q,Q),G=r.add(G,Q),_=r.mul($,_),x=r.mul(X,x),G=r.add(G,_),_=r.sub(Q,_),_=r.mul($,_),x=r.add(x,_),Q=r.mul(G,x),q=r.add(q,Q),Q=r.mul(U,x),M=r.mul(D,M),M=r.sub(M,Q),Q=r.mul(D,G),j=r.mul(U,j),j=r.add(j,Q),new f(M,q,j)}subtract(y){return this.add(y.negate())}is0(){return this.equals(f.ZERO)}wNAF(y){return p.wNAFCached(this,u,y,E=>{let S=r.invertBatch(E.map(I=>I.pz));return E.map((I,A)=>I.toAffine(S[A])).map(f.fromAffine)})}multiplyUnsafe(y){let E=f.ZERO;if(y===eo)return E;if(c(y),y===nn)return this;let{endo:S}=e;if(!S)return p.unsafeLadder(this,y);let{k1neg:I,k1:A,k2neg:O,k2:T}=S.splitScalar(y),M=E,q=E,j=this;for(;A>eo||T>eo;)A&nn&&(M=M.add(j)),T&nn&&(q=q.add(j)),j=j.double(),A>>=nn,T>>=nn;return I&&(M=M.negate()),O&&(q=q.negate()),q=new f(r.mul(q.px,S.beta),q.py,q.pz),M.add(q)}multiply(y){c(y);let E=y,S,I,{endo:A}=e;if(A){let{k1neg:O,k1:T,k2neg:M,k2:q}=A.splitScalar(E),{p:j,f:$}=this.wNAF(T),{p:X,f:Q}=this.wNAF(q);j=p.constTimeNegate(O,j),X=p.constTimeNegate(M,X),X=new f(r.mul(X.px,A.beta),X.py,X.pz),S=j.add(X),I=$.add(Q)}else{let{p:O,f:T}=this.wNAF(E);S=O,I=T}return f.normalizeZ([S,I])[0]}multiplyAndAddUnsafe(y,E,S){let I=f.BASE,A=(T,M)=>M===eo||M===nn||!T.equals(I)?T.multiplyUnsafe(M):T.multiply(M),O=A(this,E).add(A(y,S));return O.is0()?void 0:O}toAffine(y){let{px:E,py:S,pz:I}=this,A=this.is0();y==null&&(y=A?r.ONE:r.inv(I));let O=r.mul(E,y),T=r.mul(S,y),M=r.mul(I,y);if(A)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:O,y:T}}isTorsionFree(){let{h:y,isTorsionFree:E}=e;if(y===nn)return!0;if(E)return E(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:E}=e;return y===nn?this:E?E(f,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return this.assertValidity(),n(f,this,y)}toHex(y=!0){return Ji(this.toRawBytes(y))}}f.BASE=new f(e.Gx,e.Gy,r.ONE),f.ZERO=new f(r.ZERO,r.ONE,r.ZERO);let h=e.nBitLength,p=ep(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:s}}function Pk(t){let e=Md(t);return rn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function kT(t){let e=Pk(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(x){return eo<x&&x<r.ORDER}function c(x){return _e(x,n)}function a(x){return Qh(x,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=Lk({...e,toBytes(x,U,L){let N=U.toAffine(),R=r.toBytes(N.x),C=Qi;return L?C(Uint8Array.from([U.hasEvenY()?2:3]),R):C(Uint8Array.from([4]),R,r.toBytes(N.y))},fromBytes(x){let U=x.length,L=x[0],N=x.subarray(1);if(U===i&&(L===2||L===3)){let R=Zi(N);if(!s(R))throw new Error("Point is not on curve");let C=f(R),P=r.sqrt(C),V=(P&nn)===nn;return(L&1)===1!==V&&(P=r.neg(P)),{x:R,y:P}}else if(U===o&&L===4){let R=r.fromBytes(N.subarray(0,r.BYTES)),C=r.fromBytes(N.subarray(r.BYTES,2*r.BYTES));return{x:R,y:C}}else throw new Error(`Point of length ${U} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),p=x=>Ji(pr(x,e.nByteLength));function g(x){let U=n>>nn;return x>U}function y(x){return g(x)?c(-x):x}let E=(x,U,L)=>Zi(x.slice(U,L));class S{constructor(U,L,N){this.r=U,this.s=L,this.recovery=N,this.assertValidity()}static fromCompact(U){let L=e.nByteLength;return U=Fe("compactSignature",U,L*2),new S(E(U,0,L),E(U,L,2*L))}static fromDER(U){let{r:L,s:N}=lc.toSig(Fe("DER",U));return new S(L,N)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(U){return new S(this.r,this.s,U)}recoverPublicKey(U){let{r:L,s:N,recovery:R}=this,C=q(Fe("msgHash",U));if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");let P=R===2||R===3?L+e.n:L;if(P>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let V=R&1?"03":"02",J=u.fromHex(V+p(P)),z=a(P),W=c(-C*z),Y=c(N*z),Z=u.BASE.multiplyAndAddUnsafe(J,W,Y);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return dc(this.toDERHex())}toDERHex(){return lc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return dc(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let I={isValidPrivateKey(x){try{return d(x),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let x=xw(e.n);return OT(e.randomBytes(x),e.n)},precompute(x=8,U=u.BASE){return U._setWindowSize(x),U.multiply(BigInt(3)),U}};function A(x,U=!0){return u.fromPrivateKey(x).toRawBytes(U)}function O(x){let U=In(x),L=typeof x=="string",N=(U||L)&&x.length;return U?N===i||N===o:L?N===2*i||N===2*o:x instanceof u}function T(x,U,L=!0){if(O(x))throw new Error("first arg must be private key");if(!O(U))throw new Error("second arg must be public key");return u.fromHex(U).multiply(d(x)).toRawBytes(L)}let M=e.bits2int||function(x){let U=Zi(x),L=x.length*8-e.nBitLength;return L>0?U>>BigInt(L):U},q=e.bits2int_modN||function(x){return c(M(x))},j=Pd(e.nBitLength);function $(x){if(typeof x!="bigint")throw new Error("bigint expected");if(!(eo<=x&&x<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return pr(x,e.nByteLength)}function X(x,U,L=Q){if(["recovered","canonical"].some(ee=>ee in L))throw new Error("sign() legacy options not supported");let{hash:N,randomBytes:R}=e,{lowS:C,prehash:P,extraEntropy:V}=L;C==null&&(C=!0),x=Fe("msgHash",x),P&&(x=Fe("prehashed msgHash",N(x)));let J=q(x),z=d(U),W=[$(z),$(J)];if(V!=null){let ee=V===!0?R(r.BYTES):V;W.push(Fe("extraEntropy",ee))}let Y=Qi(...W),Z=J;function ue(ee){let ce=M(ee);if(!h(ce))return;let Ie=a(ce),Pe=u.BASE.multiply(ce).toAffine(),Ge=c(Pe.x);if(Ge===eo)return;let wt=c(Ie*c(Z+Ge*z));if(wt===eo)return;let pi=(Pe.x===Ge?0:2)|Number(Pe.y&nn),uo=wt;return C&&g(wt)&&(uo=y(wt),pi^=1),new S(Ge,uo,pi)}return{seed:Y,k2sig:ue}}let Q={lowS:e.lowS,prehash:!1},G={lowS:e.lowS,prehash:!1};function _(x,U,L=Q){let{seed:N,k2sig:R}=X(x,U,L),C=e;return yw(C.hash.outputLen,C.nByteLength,C.hmac)(N,R)}u.BASE._setWindowSize(8);function D(x,U,L,N=G){let R=x;if(U=Fe("msgHash",U),L=Fe("publicKey",L),"strict"in N)throw new Error("options.strict was renamed to lowS");let{lowS:C,prehash:P}=N,V,J;try{if(typeof R=="string"||In(R))try{V=S.fromDER(R)}catch(Pe){if(!(Pe instanceof lc.Err))throw Pe;V=S.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:Pe,s:Ge}=R;V=new S(Pe,Ge)}else throw new Error("PARSE");J=u.fromHex(L)}catch(Pe){if(Pe.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(C&&V.hasHighS())return!1;P&&(U=e.hash(U));let{r:z,s:W}=V,Y=q(U),Z=a(W),ue=c(Y*Z),ee=c(z*Z),ce=u.BASE.multiplyAndAddUnsafe(J,ue,ee)?.toAffine();return ce?c(ce.x)===z:!1}return{CURVE:e,getPublicKey:A,getSharedSecret:T,sign:_,verify:D,ProjectivePoint:u,Signature:S,utils:I}}l();l();var tp=class extends Ca{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,bT(e);let n=Cd(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);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),o.fill(0)}update(e){return Na(this),this.iHash.update(e),this}digestInto(e){Na(this),dw(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},vw=(t,e,r)=>new tp(t,e).update(r).digest();vw.create=(t,e)=>new tp(t,e);function Mk(t){return{hash:t,hmac:(e,...r)=>vw(t,e,zh(...r)),randomBytes:Ld}}function rp(t,e){let r=n=>kT({...t,...Mk(n)});return Object.freeze({...r(e),create:r})}var LT=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),NT=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Kk=BigInt(1),Sw=BigInt(2),CT=(t,e)=>(t+e/Sw)/e;function $k(t){let e=LT,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=je(d,r,e)*d%e,h=je(f,r,e)*d%e,p=je(h,Sw,e)*u%e,g=je(p,i,e)*p%e,y=je(g,o,e)*g%e,E=je(y,c,e)*y%e,S=je(E,a,e)*E%e,I=je(S,c,e)*y%e,A=je(I,r,e)*d%e,O=je(A,s,e)*g%e,T=je(O,n,e)*u%e,M=je(T,Sw,e);if(!Aw.eql(Aw.sqr(M),t))throw new Error("Cannot find square root");return M}var Aw=Pa(LT,void 0,void 0,{sqrt:$k}),yr=rp({a:BigInt(0),b:BigInt(7),Fp:Aw,n:NT,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=NT,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Kk*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=CT(o*t,e),a=CT(-n*t,e),u=_e(t-c*r-a*i,e),d=_e(-c*n-a*o,e),f=u>s,h=d>s;if(f&&(u=e-u),h&&(d=e-d),u>s||d>s)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}}},Jh),BW=BigInt(0);var IW=yr.ProjectivePoint;l();l();function PT(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort(),o={};for(let s of i)o[s]=e(n[s]);return o}return n},r=e(t);return JSON.stringify(r)}var Hk=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Tw="urn:jwk:";function ge(t){return Hk(this,arguments,void 0,function*({jwk:e}){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);tg(n);let i=PT(n),o=ne.string(i).toUint8Array(),s=yield ka.digest({data:o});return ne.uint8Array(s).toBase64Url()})}function ai(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="EC"||typeof t.d!="string"||typeof t.x!="string")}function Ma(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t)||"d"in t||t.kty!=="EC"||typeof t.x!="string")}function ui(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="OKP"||typeof t.d!="string"||typeof t.x!="string")}function Ka(t){return!(!t||typeof t!="object"||"d"in t||!("kty"in t&&"crv"in t&&"x"in t)||t.kty!=="OKP"||typeof t.x!="string")}function MT(t){if(!t||typeof t!="object")return!1;switch(t.kty){case"EC":case"OKP":case"RSA":return"d"in t;case"oct":return"k"in t;default:return!1}}var Kt=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Vk=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Ot=class t{static adjustSignatureToLowS(e){return Kt(this,arguments,void 0,function*({signature:r}){let n=yr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Kt(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static compressPublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){return yr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Kt(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=yield t.getCurvePoint({keyBytes:n}),o={kty:"EC",crv:"secp256k1",x:ne.uint8Array(i.x).toBase64Url(),y:ne.uint8Array(i.y).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertDerToCompactSignature(e){return Kt(this,arguments,void 0,function*({derSignature:r}){return yr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){return yr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Kt(this,void 0,void 0,function*(){let e=yr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Kt(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,o=Vk(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Kt(this,arguments,void 0,function*({privateKey:r}){if(!ai(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Kt(this,arguments,void 0,function*({publicKey:r}){if(!(Ma(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ne.base64Url(r.x).toUint8Array(),o=ne.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...o])})}static sharedSecret(e){return Kt(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return yr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return Kt(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=Wo(r);return yr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return Kt(this,arguments,void 0,function*({privateKeyBytes:r}){return yr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){try{yr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Kt(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=Wo(i);return yr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return Kt(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=yr.getPublicKey(r));let n=yr.ProjectivePoint.fromHex(r),i=pr(n.x,32),o=pr(n.y,32);return{x:i,y:o}})}};l();l();var KT=Pa(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),qk=KT.create(BigInt("-3")),Fk=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),jk=rp({a:qk,b:Fk,Fp:KT,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Jh),Nr=jk;var $t=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Wk=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Ht=class t{static adjustSignatureToLowS(e){return $t(this,arguments,void 0,function*({signature:r}){let n=Nr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static compressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return Nr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return $t(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=yield t.getCurvePoint({keyBytes:n}),o={kty:"EC",crv:"P-256",x:ne.uint8Array(i.x).toBase64Url(),y:ne.uint8Array(i.y).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertDerToCompactSignature(e){return $t(this,arguments,void 0,function*({derSignature:r}){return Nr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return Nr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return $t(this,void 0,void 0,function*(){let e=Nr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return $t(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=r,o=Wk(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return $t(this,arguments,void 0,function*({privateKey:r}){if(!ai(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return $t(this,arguments,void 0,function*({publicKey:r}){if(!(Ma(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ne.base64Url(r.x).toUint8Array(),o=ne.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...o])})}static sharedSecret(e){return $t(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return Nr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return $t(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=Wo(r);return Nr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){return Nr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){try{Nr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return $t(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=Wo(i);return Nr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return $t(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Nr.getPublicKey(r));let n=Nr.ProjectivePoint.fromHex(r),i=pr(n.x,32),o=pr(n.y,32);return{x:i,y:o}})}};var Kd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},$d=class extends ci{computePublicKey(e){return Kd(this,arguments,void 0,function*({key:r}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield Ot.computePublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Ht.computePublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Kd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"ES256K":case"secp256k1":{let n=yield Ot.generateKey();return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Ht.generateKey();return n.alg="ES256",n}}})}getPublicKey(e){return Kd(this,arguments,void 0,function*({key:r}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield Ot.getPublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Ht.getPublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Kd(this,arguments,void 0,function*({key:r,data:n}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":return yield Ot.sign({key:r,data:n});case"P-256":return yield Ht.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Kd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Ma(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(r.crv){case"secp256k1":return yield Ot.verify({key:r,signature:n,data:i});case"P-256":return yield Ht.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};l();l();l();l();l();var np=BigInt(4294967295),_w=BigInt(32);function $T(t,e=!1){return e?{h:Number(t&np),l:Number(t>>_w&np)}:{h:Number(t>>_w&np)|0,l:Number(t&np)|0}}function Gk(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){let{h:o,l:s}=$T(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var zk=(t,e)=>BigInt(t>>>0)<<_w|BigInt(e>>>0),Yk=(t,e,r)=>t>>>r,Jk=(t,e,r)=>t<<32-r|e>>>r,Zk=(t,e,r)=>t>>>r|e<<32-r,Xk=(t,e,r)=>t<<32-r|e>>>r,Qk=(t,e,r)=>t<<64-r|e>>>r-32,eN=(t,e,r)=>t>>>r-32|e<<64-r,tN=(t,e)=>e,rN=(t,e)=>t,nN=(t,e,r)=>t<<r|e>>>32-r,iN=(t,e,r)=>e<<r|t>>>32-r,oN=(t,e,r)=>e<<r-32|t>>>64-r,sN=(t,e,r)=>t<<r-32|e>>>64-r;function cN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var aN=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),uN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,dN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),fN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,lN=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),hN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var pN={fromBig:$T,split:Gk,toBig:zk,shrSH:Yk,shrSL:Jk,rotrSH:Zk,rotrSL:Xk,rotrBH:Qk,rotrBL:eN,rotr32H:tN,rotr32L:rN,rotlSH:nN,rotlSL:iN,rotlBH:oN,rotlBL:sN,add:cN,add3L:aN,add3H:uN,add4L:dN,add4H:fN,add5H:hN,add5L:lN},le=pN;var[yN,gN]=le.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Yo=new Uint32Array(80),Jo=new Uint32Array(80),Bw=class extends La{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:c,Dl:a,Eh:u,El:d,Fh:f,Fl:h,Gh:p,Gl:g,Hh:y,Hl:E}=this;return[e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,E]}set(e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,E){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=c|0,this.Dl=a|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=h|0,this.Gh=p|0,this.Gl=g|0,this.Hh=y|0,this.Hl=E|0}process(e,r){for(let A=0;A<16;A++,r+=4)Yo[A]=e.getUint32(r),Jo[A]=e.getUint32(r+=4);for(let A=16;A<80;A++){let O=Yo[A-15]|0,T=Jo[A-15]|0,M=le.rotrSH(O,T,1)^le.rotrSH(O,T,8)^le.shrSH(O,T,7),q=le.rotrSL(O,T,1)^le.rotrSL(O,T,8)^le.shrSL(O,T,7),j=Yo[A-2]|0,$=Jo[A-2]|0,X=le.rotrSH(j,$,19)^le.rotrBH(j,$,61)^le.shrSH(j,$,6),Q=le.rotrSL(j,$,19)^le.rotrBL(j,$,61)^le.shrSL(j,$,6),G=le.add4L(q,Q,Jo[A-7],Jo[A-16]),_=le.add4H(G,M,X,Yo[A-7],Yo[A-16]);Yo[A]=_|0,Jo[A]=G|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:c,Cl:a,Dh:u,Dl:d,Eh:f,El:h,Fh:p,Fl:g,Gh:y,Gl:E,Hh:S,Hl:I}=this;for(let A=0;A<80;A++){let O=le.rotrSH(f,h,14)^le.rotrSH(f,h,18)^le.rotrBH(f,h,41),T=le.rotrSL(f,h,14)^le.rotrSL(f,h,18)^le.rotrBL(f,h,41),M=f&p^~f&y,q=h&g^~h&E,j=le.add5L(I,T,q,gN[A],Jo[A]),$=le.add5H(j,S,O,M,yN[A],Yo[A]),X=j|0,Q=le.rotrSH(n,i,28)^le.rotrBH(n,i,34)^le.rotrBH(n,i,39),G=le.rotrSL(n,i,28)^le.rotrBL(n,i,34)^le.rotrBL(n,i,39),_=n&o^n&c^o&c,D=i&s^i&a^s&a;S=y|0,I=E|0,y=p|0,E=g|0,p=f|0,g=h|0,{h:f,l:h}=le.add(u|0,d|0,$|0,X|0),u=c|0,d=a|0,c=o|0,a=s|0,o=n|0,s=i|0;let x=le.add3L(X,G,D);n=le.add3H(x,$,Q,_),i=x|0}({h:n,l:i}=le.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=le.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:c,l:a}=le.add(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:d}=le.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:h}=le.add(this.Eh|0,this.El|0,f|0,h|0),{h:p,l:g}=le.add(this.Fh|0,this.Fl|0,p|0,g|0),{h:y,l:E}=le.add(this.Gh|0,this.Gl|0,y|0,E|0),{h:S,l:I}=le.add(this.Hh|0,this.Hl|0,S|0,I|0),this.set(n,i,o,s,c,a,u,d,f,h,p,g,y,E,S,I)}roundClean(){Yo.fill(0),Jo.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Iw=Yh(()=>new Bw);l();var Un=BigInt(0),Cr=BigInt(1),ip=BigInt(2),mN=BigInt(8),wN={zip215:!0};function bN(t){let e=Md(t);return rn(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function op(t){let e=bN(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:c,h:a}=e,u=ip<<BigInt(c*8)-Cr,d=r.create,f=e.uvRatio||((N,R)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(R))}}catch{return{isValid:!1,value:Un}}}),h=e.adjustScalarBytes||(N=>N),p=e.domain||((N,R,C)=>{if(R.length||C)throw new Error("Contexts/pre-hash are not supported");return N}),g=N=>typeof N=="bigint"&&Un<N,y=(N,R)=>g(N)&&g(R)&&N<R,E=N=>N===Un||y(N,u);function S(N,R){if(y(N,R))return N;throw new Error(`Expected valid scalar < ${R}, got ${typeof N} ${N}`)}function I(N){return N===Un?N:S(N,n)}let A=new Map;function O(N){if(!(N instanceof T))throw new Error("ExtendedPoint expected")}class T{constructor(R,C,P,V){if(this.ex=R,this.ey=C,this.ez=P,this.et=V,!E(R))throw new Error("x required");if(!E(C))throw new Error("y required");if(!E(P))throw new Error("z required");if(!E(V))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(R){if(R instanceof T)throw new Error("extended point not allowed");let{x:C,y:P}=R||{};if(!E(C)||!E(P))throw new Error("invalid affine point");return new T(C,P,Cr,d(C*P))}static normalizeZ(R){let C=r.invertBatch(R.map(P=>P.ez));return R.map((P,V)=>P.toAffine(C[V])).map(T.fromAffine)}_setWindowSize(R){this._WINDOW_SIZE=R,A.delete(this)}assertValidity(){let{a:R,d:C}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:P,ey:V,ez:J,et:z}=this,W=d(P*P),Y=d(V*V),Z=d(J*J),ue=d(Z*Z),ee=d(W*R),ce=d(Z*d(ee+Y)),Ie=d(ue+d(C*d(W*Y)));if(ce!==Ie)throw new Error("bad point: equation left != right (1)");let Pe=d(P*V),Ge=d(J*z);if(Pe!==Ge)throw new Error("bad point: equation left != right (2)")}equals(R){O(R);let{ex:C,ey:P,ez:V}=this,{ex:J,ey:z,ez:W}=R,Y=d(C*W),Z=d(J*V),ue=d(P*W),ee=d(z*V);return Y===Z&&ue===ee}is0(){return this.equals(T.ZERO)}negate(){return new T(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:R}=e,{ex:C,ey:P,ez:V}=this,J=d(C*C),z=d(P*P),W=d(ip*d(V*V)),Y=d(R*J),Z=C+P,ue=d(d(Z*Z)-J-z),ee=Y+z,ce=ee-W,Ie=Y-z,Pe=d(ue*ce),Ge=d(ee*Ie),wt=d(ue*Ie),pi=d(ce*ee);return new T(Pe,Ge,pi,wt)}add(R){O(R);let{a:C,d:P}=e,{ex:V,ey:J,ez:z,et:W}=this,{ex:Y,ey:Z,ez:ue,et:ee}=R;if(C===BigInt(-1)){let uu=d((J-V)*(Z+Y)),yf=d((J+V)*(Z-Y)),du=d(yf-uu);if(du===Un)return this.double();let gf=d(z*ip*ee),mf=d(W*ip*ue),qr=mf+gf,lo=yf+uu,fu=mf-gf,wf=d(qr*du),us=d(lo*fu),bf=d(qr*fu),Jp=d(du*lo);return new T(wf,us,Jp,bf)}let ce=d(V*Y),Ie=d(J*Z),Pe=d(W*P*ee),Ge=d(z*ue),wt=d((V+J)*(Y+Z)-ce-Ie),pi=Ge-Pe,uo=Ge+Pe,au=d(Ie-C*ce),pf=d(wt*pi),Yp=d(uo*au),fo=d(wt*au),Vr=d(pi*uo);return new T(pf,Yp,Vr,fo)}subtract(R){return this.add(R.negate())}wNAF(R){return j.wNAFCached(this,A,R,T.normalizeZ)}multiply(R){let{p:C,f:P}=this.wNAF(S(R,n));return T.normalizeZ([C,P])[0]}multiplyUnsafe(R){let C=I(R);return C===Un?q:this.equals(q)||C===Cr?this:this.equals(M)?this.wNAF(C).p:j.unsafeLadder(this,C)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return j.unsafeLadder(this,n).is0()}toAffine(R){let{ex:C,ey:P,ez:V}=this,J=this.is0();R==null&&(R=J?mN:r.inv(V));let z=d(C*R),W=d(P*R),Y=d(V*R);if(J)return{x:Un,y:Cr};if(Y!==Cr)throw new Error("invZ was invalid");return{x:z,y:W}}clearCofactor(){let{h:R}=e;return R===Cr?this:this.multiplyUnsafe(R)}static fromHex(R,C=!1){let{d:P,a:V}=e,J=r.BYTES;R=Fe("pointHex",R,J);let z=R.slice(),W=R[J-1];z[J-1]=W&-129;let Y=Rn(z);Y===Un||(C?S(Y,u):S(Y,r.ORDER));let Z=d(Y*Y),ue=d(Z-Cr),ee=d(P*Z-V),{isValid:ce,value:Ie}=f(ue,ee);if(!ce)throw new Error("Point.fromHex: invalid y coordinate");let Pe=(Ie&Cr)===Cr,Ge=(W&128)!==0;if(!C&&Ie===Un&&Ge)throw new Error("Point.fromHex: x=0 and x_0=1");return Ge!==Pe&&(Ie=d(-Ie)),T.fromAffine({x:Ie,y:Y})}static fromPrivateKey(R){return Q(R).point}toRawBytes(){let{x:R,y:C}=this.toAffine(),P=Xi(C,r.BYTES);return P[P.length-1]|=R&Cr?128:0,P}toHex(){return Ji(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,Cr,d(e.Gx*e.Gy)),T.ZERO=new T(Un,Cr,Cr,Un);let{BASE:M,ZERO:q}=T,j=ep(T,c*8);function $(N){return _e(N,n)}function X(N){return $(Rn(N))}function Q(N){let R=c;N=Fe("private key",N,R);let C=Fe("hashed private key",o(N),2*R),P=h(C.slice(0,R)),V=C.slice(R,2*R),J=X(P),z=M.multiply(J),W=z.toRawBytes();return{head:P,prefix:V,scalar:J,point:z,pointBytes:W}}function G(N){return Q(N).pointBytes}function _(N=new Uint8Array,...R){let C=Qi(...R);return X(o(p(C,Fe("context",N),!!i)))}function D(N,R,C={}){N=Fe("message",N),i&&(N=i(N));let{prefix:P,scalar:V,pointBytes:J}=Q(R),z=_(C.context,P,N),W=M.multiply(z).toRawBytes(),Y=_(C.context,W,J,N),Z=$(z+Y*V);I(Z);let ue=Qi(W,Xi(Z,r.BYTES));return Fe("result",ue,c*2)}let x=wN;function U(N,R,C,P=x){let{context:V,zip215:J}=P,z=r.BYTES;N=Fe("signature",N,2*z),R=Fe("message",R),i&&(R=i(R));let W=Rn(N.slice(z,2*z)),Y,Z,ue;try{Y=T.fromHex(C,J),Z=T.fromHex(N.slice(0,z),J),ue=M.multiplyUnsafe(W)}catch{return!1}if(!J&&Y.isSmallOrder())return!1;let ee=_(V,Z.toRawBytes(),Y.toRawBytes(),R);return Z.add(Y.multiplyUnsafe(ee)).subtract(ue).clearCofactor().equals(T.ZERO)}return M._setWindowSize(8),{CURVE:e,getPublicKey:G,sign:D,verify:U,ExtendedPoint:T,utils:{getExtendedPublicKey:Q,randomPrivateKey:()=>s(r.BYTES),precompute(N=8,R=T.BASE){return R._setWindowSize(N),R.multiply(BigInt(3)),R}}}}l();var Hd=BigInt(0),Rw=BigInt(1);function xN(t){return rn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function HT(t){let e=xN(t),{P:r}=e,n=A=>_e(A,r),i=e.montgomeryBits,o=Math.ceil(i/8),s=e.nByteLength,c=e.adjustScalarBytes||(A=>A),a=e.powPminus2||(A=>mw(A,r-BigInt(2),r));function u(A,O,T){let M=n(A*(O-T));return O=n(O-M),T=n(T+M),[O,T]}function d(A){if(typeof A=="bigint"&&Hd<=A&&A<r)return A;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let f=(e.a-BigInt(2))/BigInt(4);function h(A,O){let T=d(A),M=d(O),q=T,j=Rw,$=Hd,X=T,Q=Rw,G=Hd,_;for(let x=BigInt(i-1);x>=Hd;x--){let U=M>>x&Rw;G^=U,_=u(G,j,X),j=_[0],X=_[1],_=u(G,$,Q),$=_[0],Q=_[1],G=U;let L=j+$,N=n(L*L),R=j-$,C=n(R*R),P=N-C,V=X+Q,J=X-Q,z=n(J*L),W=n(V*R),Y=z+W,Z=z-W;X=n(Y*Y),Q=n(q*n(Z*Z)),j=n(N*C),$=n(P*(N+n(f*P)))}_=u(G,j,X),j=_[0],X=_[1],_=u(G,$,Q),$=_[0],Q=_[1];let D=a($);return n(j*D)}function p(A){return Xi(n(A),o)}function g(A){let O=Fe("u coordinate",A,o);return s===32&&(O[31]&=127),Rn(O)}function y(A){let O=Fe("scalar",A),T=O.length;if(T!==o&&T!==s)throw new Error(`Expected ${o} or ${s} bytes, got ${T}`);return Rn(c(O))}function E(A,O){let T=g(O),M=y(A),q=h(T,M);if(q===Hd)throw new Error("Invalid private or public key received");return p(q)}let S=p(e.Gu);function I(A){return E(A,S)}return{scalarMult:E,scalarMultBase:I,getSharedSecret:(A,O)=>E(A,O),getPublicKey:A=>I(A),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Vd=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),VT=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),UG=BigInt(0),EN=BigInt(1),Uw=BigInt(2),vN=BigInt(5),qT=BigInt(10),SN=BigInt(20),AN=BigInt(40),FT=BigInt(80);function jT(t){let e=Vd,n=t*t%e*t%e,i=je(n,Uw,e)*n%e,o=je(i,EN,e)*t%e,s=je(o,vN,e)*o%e,c=je(s,qT,e)*s%e,a=je(c,SN,e)*c%e,u=je(a,AN,e)*a%e,d=je(u,FT,e)*u%e,f=je(d,FT,e)*u%e,h=je(f,qT,e)*s%e;return{pow_p_5_8:je(h,Uw,e)*t%e,b2:n}}function WT(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function TN(t,e){let r=Vd,n=_e(e*e*e,r),i=_e(n*n*e,r),o=jT(t*i).pow_p_5_8,s=_e(t*n*o,r),c=_e(e*s*s,r),a=s,u=_e(s*VT,r),d=c===t,f=c===_e(-t,r),h=c===_e(-t*VT,r);return d&&(s=a),(f||h)&&(s=u),IT(s,r)&&(s=_e(-s,r)),{isValid:d||f,value:s}}var on=Pa(Vd,void 0,!0),qd={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:on,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Iw,randomBytes:Ld,adjustScalarBytes:WT,uvRatio:TN},Zo=op(qd);function GT(t,e,r){if(e.length>255)throw new Error("Context is too big");return zh(fw("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var OG=op({...qd,domain:GT}),DG=op({...qd,domain:GT,prehash:Iw}),hc=HT({P:Vd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Vd,{pow_p_5_8:r,b2:n}=jT(t);return _e(je(r,BigInt(3),e)*n,e)},adjustScalarBytes:WT,randomBytes:Ld});function zT(t){let{y:e}=Zo.ExtendedPoint.fromHex(t),r=BigInt(1);return on.toBytes(on.create((r+e)*on.inv(r-e)))}function YT(t){let e=qd.hash(t.subarray(0,32));return qd.adjustScalarBytes(e).subarray(0,32)}var _N=(on.ORDER+BigInt(3))/BigInt(8),kG=on.pow(Uw,_N),NG=on.sqrt(on.neg(on.ONE)),CG=(on.ORDER-BigInt(5))/BigInt(8),LG=BigInt(486662);var PG=RT(on,on.neg(BigInt(486664)));var MG=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),KG=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),$G=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),HG=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var VG=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var sn=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},BN=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},_t=class t{static bytesToPrivateKey(e){return sn(this,arguments,void 0,function*({privateKeyBytes:r}){let n=Zo.getPublicKey(r),i={crv:"Ed25519",d:ne.uint8Array(r).toBase64Url(),kty:"OKP",x:ne.uint8Array(n).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return sn(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield ge({jwk:n}),n})}static computePublicKey(e){return sn(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=Zo.getPublicKey(n),o={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertPrivateKeyToX25519(e){return sn(this,arguments,void 0,function*({privateKey:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=YT(n),o=hc.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:ne.uint8Array(i).toBase64Url(),x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static convertPublicKeyToX25519(e){return sn(this,arguments,void 0,function*({publicKey:r}){let n=yield t.publicKeyToBytes({publicKey:r});if(!(yield t.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let o=zT(n),s={kty:"OKP",crv:"X25519",x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static generateKey(){return sn(this,void 0,void 0,function*(){let e=Zo.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return sn(this,arguments,void 0,function*({key:r}){var n;if(!(ui(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=r,o=BN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return sn(this,arguments,void 0,function*({privateKey:r}){if(!ui(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return sn(this,arguments,void 0,function*({publicKey:r}){if(!Ka(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return ne.base64Url(r.x).toUint8Array()})}static sign(e){return sn(this,arguments,void 0,function*({key:r,data:n}){let i=yield t.privateKeyToBytes({privateKey:r});return Zo.sign(n,i)})}static validatePublicKey(e){return sn(this,arguments,void 0,function*({publicKeyBytes:r}){try{Zo.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return sn(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r});return Zo.verify(n,i,o)})}};var Fd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},sp=class extends ci{computePublicKey(e){return Fd(this,arguments,void 0,function*({key:r}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield _t.computePublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Fd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"Ed25519":{let n=yield _t.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return Fd(this,arguments,void 0,function*({key:r}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield _t.getPublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Fd(this,arguments,void 0,function*({key:r,data:n}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":return yield _t.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Fd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Ka(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(r.crv){case"Ed25519":return yield _t.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};var to=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Ow={Ed25519:{implementation:sp,names:["Ed25519"]},secp256k1:{implementation:$d,names:["ES256K","secp256k1"]},secp256r1:{implementation:$d,names:["ES256","secp256r1"]},"SHA-256":{implementation:jh,names:["SHA-256"]}},Xt=class{constructor(e){var r;this._algorithmInstances=new Map,this._keyStore=(r=e?.keyStore)!==null&&r!==void 0?r:new dh}digest(e){return to(this,arguments,void 0,function*({algorithm:r,data:n}){return yield this.getAlgorithm({algorithm:r}).digest({algorithm:r,data:n})})}exportKey(e){return to(this,arguments,void 0,function*({keyUri:r}){return yield this.getPrivateKey({keyUri:r})})}generateKey(e){return to(this,arguments,void 0,function*({algorithm:r}){let i=yield this.getAlgorithm({algorithm:r}).generateKey({algorithm:r});if(i?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let o=`${Tw}${i.kid}`;return yield this._keyStore.set(o,i),o})}getKeyUri(e){return to(this,arguments,void 0,function*({key:r}){let n=yield ge({jwk:r});return`${Tw}${n}`})}getPublicKey(e){return to(this,arguments,void 0,function*({keyUri:r}){let n=yield this.getPrivateKey({keyUri:r}),i=this.getAlgorithmName({key:n});return yield this.getAlgorithm({algorithm:i}).getPublicKey({key:n})})}importKey(e){return to(this,arguments,void 0,function*({key:r}){var n;if(!MT(r))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let i=structuredClone(r);(n=i.kid)!==null&&n!==void 0||(i.kid=yield ge({jwk:i}));let o=yield this.getKeyUri({key:i});return yield this._keyStore.set(o,i),o})}sign(e){return to(this,arguments,void 0,function*({keyUri:r,data:n}){let i=yield this.getPrivateKey({keyUri:r}),o=this.getAlgorithmName({key:i});return this.getAlgorithm({algorithm:o}).sign({data:n,key:i})})}verify(e){return to(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=this.getAlgorithmName({key:r});return this.getAlgorithm({algorithm:o}).verify({key:r,signature:n,data:i})})}getAlgorithm({algorithm:e}){var r;let n=(r=Ow[e])===null||r===void 0?void 0:r.implementation;if(!n)throw new Error(`Algorithm not supported: ${e}`);return this._algorithmInstances.has(n)||this._algorithmInstances.set(n,new n),this._algorithmInstances.get(n)}getAlgorithmName({key:e}){let r=e.alg,n=e.crv;for(let i in Ow){let o=Ow[i];if(r&&o.names.includes(r))return i;if(n&&o.names.includes(n))return i}throw new Error(`Unable to determine algorithm based on provided input: alg=${r}, crv=${n}`)}getPrivateKey(e){return to(this,arguments,void 0,function*({keyUri:r}){let n=yield this._keyStore.get(r);if(!n)throw new Error(`Key not found: ${r}`);return n})}};l();var cp=class t{static getJoseSignatureAlgorithmFromPublicKey(e){let r={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(r).includes(e.alg))return e.alg;if(e.crv&&Object.keys(r).includes(e.crv))return r[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(r).join(", ")}. Supported 'crv' values: ${Object.keys(r).join(", ")}.`)}static randomBytes(e){return yT(e)}static randomUuid(){return Da.randomUUID()}static randomPin({length:e}){if(3>e||e>10)throw new Error("randomPin() can securely generate a PIN between 3 to 10 digits.");let r=Math.pow(10,e)-1,n;if(e<=6){let i=Math.pow(10,e);do{let o=t.randomBytes(Math.ceil(e/2));n=new DataView(o.buffer).getUint16(0,!1)%i}while(n>r)}else{let i=Math.pow(10,10);do{let o=t.randomBytes(4);n=new DataView(o.buffer).getUint32(0,!1)%i}while(n>r)}return n.toString().padStart(e,"0")}};l();l();l();l();l();l();l();l();l();l();var Xo=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},IN=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},$a=class t{static bytesToPrivateKey(e){return Xo(this,arguments,void 0,function*({privateKeyBytes:r}){let n=hc.getPublicKey(r),i={kty:"OKP",crv:"X25519",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return Xo(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield ge({jwk:n}),n})}static computePublicKey(e){return Xo(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=hc.getPublicKey(n),o={kty:"OKP",crv:"X25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static generateKey(){return Xo(this,void 0,void 0,function*(){let e=hc.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Xo(this,arguments,void 0,function*({key:r}){var n;if(!(ui(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=r,o=IN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Xo(this,arguments,void 0,function*({privateKey:r}){if(!ui(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Xo(this,arguments,void 0,function*({publicKey:r}){if(!Ka(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return ne.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return Xo(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return hc.getSharedSecret(i,o)})}};l();l();l();function Lr(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Nw({didDocument:t}){var e,r;if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let n=[];return n.push(...(r=(e=t.verificationMethod)===null||e===void 0?void 0:e.filter(kw))!==null&&r!==void 0?r:[]),Object.keys(Li).forEach(i=>{var o,s;n.push(...(s=(o=t[i])===null||o===void 0?void 0:o.filter(kw))!==null&&s!==void 0?s:[])}),n}function JT({didDocument:t}){let r=Nw({didDocument:t}).map(n=>n.type);return[...new Set(r)]}function ZT({didDocument:t,methodId:e}){let r=[];return Object.keys(Li).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],o=Lr(e);i.some(c=>{let a=Lr(c)===o,u=kw(c)&&Lr(c.id)===o;return a||u})&&r.push(n)}}),r}function XT(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function kw(t){return!(!t||typeof t!="object"||t===null||!("id"in t&&"type"in t&&"controller"in t)||typeof t.id!="string"||typeof t.type!="string"||typeof t.controller!="string")}function Cw({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=zt.addPrefix({code:e,data:t,name:r}),i=ne.uint8Array(n).toBase58Btc();return ne.base58Btc(i).toMultibase()}function Lw({multibaseKeyId:t}){try{let e=ne.multibase(t).toBase58Btc(),r=ne.base58Btc(e).toUint8Array(),{code:n,data:i,name:o}=zt.removePrefix({prefixedData:r});return{keyBytes:i,multicodecCode:n,multicodecName:o}}catch{throw new re(ie.InvalidDid,`Invalid multibase identifier: ${t}`)}}var jd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},gr=class t{constructor({uri:e,document:r,metadata:n,keyManager:i}){this.uri=e,this.document=r,this.metadata=n,this.keyManager=i}export(){return jd(this,void 0,void 0,function*(){if(!(Array.isArray(this.document.verificationMethod)&&this.document.verificationMethod.length>0))throw new Error(`DID document for '${this.uri}' is missing verification methods`);let e=JSON.parse(JSON.stringify({uri:this.uri,document:this.document,metadata:this.metadata}));if("exportKey"in this.keyManager&&typeof this.keyManager.exportKey=="function"){let r=[];for(let n of this.document.verificationMethod){if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=yield this.keyManager.getKeyUri({key:n.publicKeyJwk}),o=yield this.keyManager.exportKey({keyUri:i});r.push(Object.assign({},o))}e.privateKeys=r}return e})}getSigner(e){return jd(this,void 0,void 0,function*(){var r;let n=(r=this.document.verificationMethod)===null||r===void 0?void 0:r.find(a=>{var u,d;return Lr(a.id)===((u=Lr(e?.methodId))!==null&&u!==void 0?u:Lr((d=this.document.assertionMethod)===null||d===void 0?void 0:d[0]))});if(!(n&&n.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");let i=yield this.keyManager.getKeyUri({key:n.publicKeyJwk}),o=yield this.keyManager.getPublicKey({keyUri:i}),s=this.keyManager;return{algorithm:cp.getJoseSignatureAlgorithmFromPublicKey(o),keyId:n.id,sign(a){return jd(this,arguments,void 0,function*({data:u}){return yield s.sign({data:u,keyUri:i})})},verify(a){return jd(this,arguments,void 0,function*({data:u,signature:d}){return yield s.verify({data:u,key:o,signature:d})})}}})}static import(e){return jd(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){var i;let o=Nw({didDocument:r.document});if(o.length===0)throw new re(ie.InvalidDidDocument,"At least one verification method is required but 0 were given");for(let c of(i=r.privateKeys)!==null&&i!==void 0?i:[]){let a=yield n.getKeyUri({key:c});(yield n.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1))||(yield n.importKey({key:c}))}for(let c of o){if(!c.publicKeyJwk)throw new Error(`Verification method '${c.id}' does not contain a public key in JWK format`);let a=yield n.getKeyUri({key:c.publicKeyJwk});yield n.getPublicKey({keyUri:a})}return new t({uri:r.uri,document:r.document,metadata:r.metadata,keyManager:n})})}};l();l();l();l();l();var Pw="0123456789abcdef",e_=[],QT=[];for(let t=0;t<256;t++)e_[t]=Pw[t>>4&15]+Pw[t&15],t<16&&(t<10?QT[48+t]=t:QT[87+t]=t);var Mw=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=e_[t[n++]];return r};var t_=(t,e=0)=>{let r=t.length||0;if(!e){let s=r;for(;s--;)e+=t[s].length}let n=new Uint8Array(e),i=e,o=r;for(;o--;)i-=t[o].length,n.set(t[o],i);return n};l();var r_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",UN=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Wd=0;Wd<r_.length;Wd++)UN[r_.charCodeAt(Wd)]=Wd;var Wd;var ON=new TextDecoder,Kw=(t,e)=>e?new TextDecoder(e).decode(t):ON.decode(t),DN=new TextEncoder,cn=t=>DN.encode(t);var n_=typeof window<"u"?window:self,i_=n_.crypto||n_.msCrypto||{},VY=i_.subtle||i_.webkitSubtle;l();function Ha(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function ap(t){return ArrayBuffer.isView(t)?"arraybufferview":Array.isArray(t)?"array":t instanceof Number?"number":t instanceof Boolean?"boolean":t instanceof Set?"set":t instanceof Map?"map":t instanceof String?"string":t instanceof ArrayBuffer?"arraybuffer":typeof t}function Be(t,e,r){let n=[],i=null;return Be._encode(n,t),i=t_(n),Be.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Be.bytes=-1;Be._floatConversionDetected=!1;Be._encode=function(t,e){if(e!=null)switch(ap(e)){case"object":Be.dict(t,e);break;case"map":Be.dictMap(t,e);break;case"array":Be.list(t,e);break;case"set":Be.listSet(t,e);break;case"string":Be.string(t,e);break;case"number":Be.number(t,e);break;case"boolean":Be.number(t,e);break;case"arraybufferview":Be.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Be.buffer(t,new Uint8Array(e));break}};var up=new Uint8Array([101]),o_=new Uint8Array([100]),s_=new Uint8Array([108]);Be.buffer=function(t,e){t.push(cn(e.length+":"),e)};Be.string=function(t,e){t.push(cn(cn(e).byteLength+":"+e))};Be.number=function(t,e){if(Number.isInteger(e))return t.push(cn("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,o=n*r+i;t.push(cn("i"+o+"e")),o!==e&&!Be._floatConversionDetected&&(Be._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+o+'"'),console.trace())};Be.dict=function(t,e){t.push(o_);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Be.string(t,n),Be._encode(t,e[n]));t.push(up)};Be.dictMap=function(t,e){t.push(o_);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?Be._encode(t,n):Be.string(t,String(n)),Be._encode(t,e.get(n)));t.push(up)};Be.list=function(t,e){let r=0,n=e.length;for(t.push(s_);r<n;r++)e[r]!=null&&Be._encode(t,e[r]);t.push(up)};Be.listSet=function(t,e){t.push(s_);for(let r of e)r!=null&&Be._encode(t,r);t.push(up)};var c_=Be;l();var kN=105,NN=58,CN=100,LN=108,$w=101;function a_(t,e,r){let n=0,i=1;for(let o=e;o<r;o++){let s=t[o];if(s<58&&s>=48){n=n*10+(s-48);continue}if(!(o===e&&s===43)){if(o===e&&s===45){i=-1;continue}if(s===46)break;throw new Error("not a number: buffer["+o+"] = "+s)}}return n*i}function de(t,e,r,n){return t==null||t.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof r!="number"&&n==null&&(n=r,r=void 0),de.position=0,de.encoding=n||null,de.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):cn(t),de.bytes=de.data.length,de.next())}de.bytes=0;de.position=0;de.data=null;de.encoding=null;de.next=function(){switch(de.data[de.position]){case CN:return de.dictionary();case LN:return de.list();case kN:return de.integer();default:return de.buffer()}};de.find=function(t){let e=de.position,r=de.data.length,n=de.data;for(;e<r;){if(n[e]===t)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(t)+'" [0x'+t.toString(16)+"]")};de.dictionary=function(){de.position++;let t={};for(;de.data[de.position]!==$w;){let e=de.buffer(),r=Kw(e);r.includes("\uFFFD")&&(r=Mw(e)),t[r]=de.next()}return de.position++,t};de.list=function(){de.position++;let t=[];for(;de.data[de.position]!==$w;)t.push(de.next());return de.position++,t};de.integer=function(){let t=de.find($w),e=a_(de.data,de.position+1,t);return de.position+=t+1-de.position,e};de.buffer=function(){let t=de.find(NN),e=a_(de.data,de.position,t),r=++t+e;return de.position=r,de.encoding?Kw(de.data.slice(t,r)):de.data.slice(t,r)};var u_=de;l();function PN(t){let e=2;for(let r of t)e+=dp(r);return e}function MN(t){let e=2;for(let[r,n]of t){let i=cn(r).byteLength;e+=Ha(i)+1+i,e+=dp(n)}return e}function KN(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=cn(r[n]).byteLength;e+=Ha(i)+1+i,e+=dp(t[r[n]])}return e}function $N(t){let e=cn(t).byteLength;return Ha(e)+1+e}function HN(t){let e=t.byteLength-t.byteOffset;return Ha(e)+1+e}function dp(t){if(t==null)return 0;let r=ap(t);switch(r){case"arraybufferview":return HN(t);case"string":return $N(t);case"array":case"set":return PN(t);case"number":return 1+Ha(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return KN(t);case"map":return MN(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var Hw=dp;var VN=Hw,Vw={encode:c_,decode:u_,byteLength:Hw,encodingLength:VN};l();l();var qN=/^(\d{1,3}\.){3,3}\d{1,3}$/;var FN=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;var On={name:"v4",size:4,isFormat:t=>qN.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,i=0;for(let o=0;o<n;){let s=t.charCodeAt(o++);s===46?(e[r++]=i,i=0):i=i*10+(s-48)}return e[r]=i,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},ro={name:"v6",size:16,isFormat:t=>t.length>0&&FN.test(t),encode(t,e,r){r=~~r;let n=r+16,i=-1,o=0,s=0,c=!0,a=!1;e=e||new Uint8Array(r+16);for(let u=0;u<t.length;u++){let d=t.charCodeAt(u);d===58?(c?i!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(i=r):(a===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2),o=0,s=0),c=!0,a=!1):d===46?(r<n&&(e[r]=s),r++,s=0,o=0,c=!1,a=!0):(c=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,s=s*10+d),o=(o<<4)+d)}if(c===!1)a===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2);else if(i===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(i!==-1){r+=2;for(let u=Math.min(r-1,n-1);u>=i+2;u--)e[u]=e[u-2];e[i]=0,e[i+1]=0,i=r}if(i!==r&&i!==-1)for(r>n-2&&(r=n-2);n>i;)e[--n]=r<n&&r>i?e[--r]:0;else for(;r<n;)e[r++]=0;return e},decode(t,e){e=~~e;let r="";for(let n=0;n<16;n+=2)n!==0&&(r+=":"),r+=(t[e+n]<<8|t[e+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};function d_(t){if(On.isFormat(t))return On.size;if(ro.isFormat(t))return ro.size;throw Error(`Invalid ip address: ${t}`)}function f_(t){return d_(t)===On.size?1:2}function l_(t,e,r){r=~~r;let n=d_(t);return typeof e=="function"&&(e=e(r+n)),n===On.size?On.encode(t,e,r):ro.encode(t,e,r)}function h_(t,e,r){if(e=~~e,r=r||t.length-e,r===On.size)return On.decode(t,e,r);if(r===ro.size)return ro.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${On.size} for v4 or ${ro.size} for v6.`)}l();function Gd(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t}function Va(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}l();function p_(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t}l();function y_(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t}l();function qw(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t}function Fw(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}l();function g_(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`}function jw(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}l();l();function Ww(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let i=t.charCodeAt(n);if(i<=127)e+=1;else if(i<=2047)e+=2;else if((i&63488)!==55296)e+=3;else{let o=n+1;o===r||i>=56320||(t.charCodeAt(o)&64512)!==56320?e+=3:(n=o,e+=4)}}return e}function qa(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(Ww(t)+r));let i=r;for(let o=0;o<n;o+=1){let s=t.charCodeAt(o);if(s<=127)e[i++]=s;else if(s<=2047)e[i++]=192|(s&1984)>>6,e[i++]=128|s&63;else if((s&63488)!==55296)e[i++]=224|(s&61440)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63;else{let c=o+1;if(c===n||s>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let a=t.charCodeAt(c);(a&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(o=c,s=65536|(s&1023)<<10|a&1023,e[i++]=240|(s&1835008)>>18,e[i++]=128|(s&258048)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63)}}}return qa.bytes=i-r,e}qa.bytes=0;function Fa(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let i=e;i<r;){let o=t[i++],s;if(o<=128)s=o;else if(o>191&&o<224)s=(o&31)<<6|t[i++]&63;else if(o>239&&o<365){s=((o&7)<<18|(t[i++]&63)<<12|(t[i++]&63)<<6|t[i++]&63)-65536;let c=55296|s>>10&1023;n+=String.fromCharCode(c),s=56320|s&1023}else s=(o&15)<<12|(t[i++]&63)<<6|t[i++]&63;n+=String.fromCharCode(s)}return Fa.bytes=r-e,n}Fa.bytes=0;var Qo=t=>t instanceof Uint8Array;function no(t){return typeof t=="string"?Ww(t):t.byteLength}function fp(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):qa(t)}function lp(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return qa(e,t,r),qa.bytes}var zd={},m_=new Array(255);for(let t=0;t<=15;t+=1){let e=t.toString(16),r=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),o=i.toUpperCase(),s=t<<4|n,c=`${e}${i}`;m_[s]=c,zd[c]=s,zd[`${r}${i}`]=s,zd[`${e}${o}`]=s,zd[`${r}${o}`]=s}}function w_(t,e,r){let n="";for(let i=e;i<r;){let o=t[i++];n+=m_[o]}return n}function Gw(t){return t.length>>>1}function b_(t,e,r,n){let i=0;for(;r<n;){let o=e.substr(i,2),s=zd[o];if(s===void 0)return;t[r++]=s,i+=2}return t}var XN=Math.pow(2,24),QN=Math.pow(2,16),eC=Math.pow(2,8),di=(t,e)=>t[e]*XN+t[e+1]*QN+t[e+2]*eC+t[e+3],he=(t,e)=>t[e]<<8|t[e+1],fi=(t,e,r)=>(e=+e,t[r+3]=e,e=e>>>8,t[r+2]=e,e=e>>>8,t[r+1]=e,e=e>>>8,t[r]=e,r+4),ae=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function mr(t,e,r,n,i){return r<0&&(n-=r,r=0),n<0&&(n=0),i<0?new Uint8Array(0):r>=e.length||n>=i?0:tC(t,e,r,n,i)}function tC(t,e,r,n,i){i-n>e.length-r&&(i=n+e.length-r);let o=i-n,s=t.length-n;return o>s&&(o=s),(n!==0||i<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,o)),e.set(t,r),o}var nC=0,x_=32768,Yw=32768,iC=~Yw,v_=32768,oC=~v_;function Ke({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var se=Ke({encode(t,e,r){e||(e=new Uint8Array(se.encodingLength(t))),r||(r=0);let n=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let o=i.split(".");for(let s=0;s<o.length;s++){let c=lp(e,o[s],r+1);e[r]=c,r+=c+1}}return e[r++]=0,se.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,i=0,o=0,s=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(o+=s?0:1,c===0)break;if(c&192)if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let a=he(t,e-1)-49152;if(a>=n)throw new Error("Cannot decode name (bad pointer)");e=a,n=a,o+=s?0:1,s=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");r.push(Fa(t,e,e+c)),e+=c,o+=s?0:c}}return se.decode.bytes=o,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:no(t.replace(/^\.|\.$/gm,""))+2}}),Bt=Ke({encode(t,e,r){e||(e=new Uint8Array(Bt.encodingLength(t))),r||(r=0);let n=lp(e,t,r+1);return e[r]=n,Bt.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=Fa(t,e+1,e+1+r);return Bt.decode.bytes=r+1,n},encodingLength(t){return no(t)+1}}),ja=Ke({bytes:12,encode(t,e,r){e||(e=new Uint8Array(ja.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?x_:nC;return ae(e,t.id||0,r),ae(e,n|i,r+2),ae(e,t.questions.length,r+4),ae(e,t.answers.length,r+6),ae(e,t.authorities.length,r+8),ae(e,t.additionals.length,r+10),e},decode(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=he(t,e+2);return{id:he(t,e),type:r&x_?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:y_(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:p_(r&15),questions:new Array(he(t,e+4)),answers:new Array(he(t,e+6)),authorities:new Array(he(t,e+8)),additionals:new Array(he(t,e+10))}},encodingLength(){return 12}}),pp=Ke({encode(t,e,r){e||(e=new Uint8Array(pp.encodingLength(t))),r||(r=0);let n=t.length;return ae(e,n,r),mr(t,e,r+2,0,n),pp.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=he(t,e),n=t.slice(e+2,e+2+r);return pp.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),yp=Ke({encode(t,e,r){return e||(e=new Uint8Array(yp.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),yp.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=he(t,e),n=se.decode(t,e+2);return yp.decode.bytes=r+2,n},encodingLength(t){return se.encodingLength(t)+2}}),gp=Ke({encode(t,e,r){e||(e=new Uint8Array(gp.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.mname,e,r),r+=se.encode.bytes,se.encode(t.rname,e,r),r+=se.encode.bytes,fi(e,t.serial||0,r),r+=4,fi(e,t.refresh||0,r),r+=4,fi(e,t.retry||0,r),r+=4,fi(e,t.expire||0,r),r+=4,fi(e,t.minimum||0,r),r+=4,ae(e,r-n-2,n),gp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=se.decode(t,e),e+=se.decode.bytes,n.rname=se.decode(t,e),e+=se.decode.bytes,n.serial=di(t,e),e+=4,n.refresh=di(t,e),e+=4,n.retry=di(t,e),e+=4,n.expire=di(t,e),e+=4,n.minimum=di(t,e),e+=4,gp.decode.bytes=e-r,n},encodingLength(t){return 22+se.encodingLength(t.mname)+se.encodingLength(t.rname)}}),mp=Ke({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=fp(t[i])),!Qo(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(mp.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,mr(i,e,r,0,i.length),r+=i.length}),ae(e,r-n-2,n),mp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=he(t,e);e+=2;let i=[];for(;n>0;){let o=t[e++];if(--n,n<o)throw new Error("Buffer overflow");i.push(t.slice(e,e+o)),e+=o,n-=o}return mp.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=no(r)+1:e+=r.length+1}),e}}),wp=Ke({encode(t,e,r){e||(e=new Uint8Array(wp.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=fp(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return mr(t,e,r,0,i),r+=i,ae(e,r-n-2,n),wp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=he(t,e);e+=2;let i=t.slice(e,e+n);return e+=n,wp.decode.bytes=e-r,i},encodingLength(t){return t?(Qo(t)?t.length:no(t))+2:2}}),bp=Ke({encode(t,e,r){e||(e=new Uint8Array(bp.encodingLength(t))),r||(r=0);let n=r;return r+=2,Bt.encode(t.cpu,e,r),r+=Bt.encode.bytes,Bt.encode(t.os,e,r),r+=Bt.encode.bytes,ae(e,r-n-2,n),bp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Bt.decode(t,e),e+=Bt.decode.bytes,n.os=Bt.decode(t,e),e+=Bt.decode.bytes,bp.decode.bytes=e-r,n},encodingLength(t){return Bt.encodingLength(t.cpu)+Bt.encodingLength(t.os)+2}}),za=Ke({encode(t,e,r){return e||(e=new Uint8Array(za.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),za.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=se.decode(t,e+2);return za.decode.bytes=se.decode.bytes+2,r},encodingLength(t){return se.encodingLength(t)+2}}),xp=Ke({encode(t,e,r){e||(e=new Uint8Array(xp.encodingLength(t))),r||(r=0),ae(e,t.priority||0,r+2),ae(e,t.weight||0,r+4),ae(e,t.port||0,r+6),se.encode(t.target,e,r+8);let n=se.encode.bytes+6;return ae(e,n,r),xp.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=he(t,e),n={};return n.priority=he(t,e+2),n.weight=he(t,e+4),n.port=he(t,e+6),n.target=se.decode(t,e+8),xp.decode.bytes=r+2,n},encodingLength(t){return 8+se.encodingLength(t.target)}}),es=Ke({encode(t,e,r){let n=es.encodingLength(t);return e||(e=new Uint8Array(es.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=es.ISSUER_CRITICAL),ae(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Bt.encode(t.tag,e,r),r+=Bt.encode.bytes,lp(e,t.value,r),r+=no(t.value),es.encode.bytes=n,e},decode(t,e){e||(e=0);let r=he(t,e);e+=2;let n=e,i={};return i.flags=t[e],e+=1,i.tag=Bt.decode(t,e),e+=Bt.decode.bytes,i.value=Fa(t,e,n+r),i.issuerCritical=!!(i.flags&es.ISSUER_CRITICAL),es.decode.bytes=r+2,i},encodingLength(t){return Bt.encodingLength(t.tag)+Bt.encodingLength(t.value)+2}});es.ISSUER_CRITICAL=128;var Ep=Ke({encode(t,e,r){e||(e=new Uint8Array(Ep.encodingLength(t))),r||(r=0);let n=r;return r+=2,ae(e,t.preference||0,r),r+=2,se.encode(t.exchange,e,r),r+=se.encode.bytes,ae(e,r-n-2,n),Ep.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=he(t,e),e+=2,n.exchange=se.decode(t,e),e+=se.decode.bytes,Ep.decode.bytes=e-r,n},encodingLength(t){return 4+se.encodingLength(t.exchange)}}),S_=Ke({encode(t,e,r){return e||(e=new Uint8Array(S_.encodingLength(t))),r||(r=0),ae(e,4,r),r+=2,On.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,On.decode(t,e)},bytes:6}),vp=Ke({encode(t,e,r){return e||(e=new Uint8Array(vp.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,ro.encode(t,e,r),vp.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=ro.decode(t,e);return vp.decode.bytes=18,r},bytes:18}),E_=t=>new Uint8Array(t),io=Ke({encode(t,e,r){e||(e=new Uint8Array(io.encodingLength(t))),r||(r=0);let n=r,i=jw(t.code);if(ae(e,i,r),r+=2,t.data)ae(e,t.data.length,r),r+=2,mr(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let o=t.sourcePrefixLength||0,s=t.family||f_(t.ip,E_),c=l_(t.ip,E_),a=Math.ceil(o/8);ae(e,a+4,r),r+=2,ae(e,s,r),r+=2,e[r++]=o,e[r++]=t.scopePrefixLength||0,mr(c,e,r,0,a),r+=a}break;case 11:t.timeout?(ae(e,2,r),r+=2,ae(e,t.timeout,r),r+=2):(ae(e,0,r),r+=2);break;case 12:{let o=t.length||0;ae(e,o,r),r+=2,e.fill(0,r,r+o),r+=o}break;case 14:{let o=t.tags.length*2;ae(e,o,r),r+=2;for(let s of t.tags)ae(e,s,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return io.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=he(t,e),r.type=g_(r.code),e+=2;let n=he(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=he(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let i=new Uint8Array(r.family===1?4:16);mr(t,i,0,e,e+n-4),r.ip=h_(i)}break;case 11:n>0&&(r.timeout=he(t,e),e+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(he(t,e)),e+=2}return io.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(jw(t.code)){case 8:{let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8}case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)}}),ts=Ke({encode(t,e,r){e||(e=new Uint8Array(ts.encodingLength(t))),r||(r=0);let n=r,i=Ga(t,io);return ae(e,i,r),r=ef(t,io,e,r+2),ts.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],i=he(t,e);e+=2;let o=0;for(;i>0;)n[o++]=io.decode(t,e),e+=io.decode.bytes,i-=io.decode.bytes;return ts.decode.bytes=e-r,n},encodingLength(t){return 2+Ga(t||[],io)}}),li=Ke({encode(t,e,r){e||(e=new Uint8Array(li.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!Qo(i))throw new Error("Key must be a Buffer");return r+=2,ae(e,t.flags,r),r+=2,e[r]=li.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,mr(i,e,r,0,i.length),r+=i.length,li.encode.bytes=r-n,ae(e,li.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);if(e+=2,n.flags=he(t,e),e+=2,t[e]!==li.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+i+2),e+=n.key.length,li.decode.bytes=e-r,n},encodingLength(t){return 6+no(t.key)}});li.PROTOCOL_DNSSEC=3;li.ZONE_KEY=128;li.SECURE_ENTRYPOINT=32768;var Yd=Ke({encode(t,e,r){e||(e=new Uint8Array(Yd.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!Qo(i))throw new Error("Signature must be a Buffer");return r+=2,ae(e,Va(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,fi(e,t.originalTTL,r),r+=4,fi(e,t.expiration,r),r+=4,fi(e,t.inception,r),r+=4,ae(e,t.keyTag,r),r+=2,se.encode(t.signersName,e,r),r+=se.encode.bytes,mr(i,e,r,0,i.length),r+=i.length,Yd.encode.bytes=r-n,ae(e,Yd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.typeCovered=Gd(he(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=di(t,e),e+=4,n.expiration=di(t,e),e+=4,n.inception=di(t,e),e+=4,n.keyTag=he(t,e),e+=2,n.signersName=se.decode(t,e),e+=se.decode.bytes,n.signature=t.slice(e,r+i+2),e+=n.signature.length,Yd.decode.bytes=e-r,n},encodingLength(t){return 20+se.encodingLength(t.signersName)+no(t.signature)}}),Jd=Ke({encode(t,e,r){e||(e=new Uint8Array(Jd.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.mbox||".",e,r),r+=se.encode.bytes,se.encode(t.txt||".",e,r),r+=se.encode.bytes,Jd.encode.bytes=r-n,ae(e,Jd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=se.decode(t,e)||".",e+=se.decode.bytes,n.txt=se.decode(t,e)||".",e+=se.decode.bytes,Jd.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.mbox||".")+se.encodingLength(t.txt||".")}}),Pr=Ke({encode(t,e,r){e||(e=new Uint8Array(Pr.encodingLength(t))),r||(r=0);let n=r,i=[];for(let o=0;o<t.length;o++){let s=Va(t[o]);i[s>>8]===void 0&&(i[s>>8]=[]),i[s>>8][s>>3&31]|=1<<7-(s&7)}for(let o=0;o<i.length;o++)if(i[o]!==void 0){let s=fp(i[o]);e[r]=o,r+=1,e[r]=s.length,r+=1,mr(s,e,r,0,s.length),r+=s.length}return Pr.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,i=[];for(;e-n<r;){let o=t[e];e+=1;let s=t[e];e+=1;for(let c=0;c<s;c++){let a=t[e+c];for(let u=0;u<8;u++)if(a&1<<7-u){let d=Gd(o<<8|c<<3|u);i.push(d)}}e+=s}return Pr.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Va(t[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let r=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(r+=2+Math.ceil((e[n]+1)/8));return r}}),Zd=Ke({encode(t,e,r){e||(e=new Uint8Array(Zd.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.nextDomain,e,r),r+=se.encode.bytes,Pr.encode(t.rrtypes,e,r),r+=Pr.encode.bytes,Zd.encode.bytes=r-n,ae(e,Zd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.nextDomain=se.decode(t,e),e+=se.decode.bytes,n.rrtypes=Pr.decode(t,e,i-(e-r)),e+=Pr.decode.bytes,Zd.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.nextDomain)+Pr.encodingLength(t.rrtypes)}}),Xd=Ke({encode(t,e,r){e||(e=new Uint8Array(Xd.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!Qo(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!Qo(o))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,ae(e,t.iterations,r),r+=2,e[r]=i.length,r+=1,mr(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,mr(o,e,r,0,o.length),r+=o.length,Pr.encode(t.rrtypes,e,r),r+=Pr.encode.bytes,Xd.encode.bytes=r-n,ae(e,Xd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=he(t,e),e+=2;let o=t[e];e+=1,n.salt=t.slice(e,e+o),e+=o;let s=t[e];return e+=1,n.nextDomain=t.slice(e,e+s),e+=s,n.rrtypes=Pr.decode(t,e,i-(e-r)),e+=Pr.decode.bytes,Xd.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Pr.encodingLength(t.rrtypes)}}),Qd=Ke({encode(t,e,r){e||(e=new Uint8Array(Qd.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!Qo(i))throw new Error("Digest must be a Buffer");return r+=2,ae(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,mr(i,e,r,0,i.length),r+=i.length,Qd.encode.bytes=r-n,ae(e,Qd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.keyTag=he(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+i+2),e+=n.digest.length,Qd.decode.bytes=e-r,n},encodingLength(t){return 6+no(t.digest)}}),Wa=Ke({encode(t,e,r){e||(e=new Uint8Array(Wa.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=Gw(t.fingerprint),o=Jw(t.hash);if(i!==o)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${o}`);return b_(e,t.fingerprint,r,r+=i),Wa.encode.bytes=r-n,ae(e,Wa.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};e+=2,n.algorithm=t[e],e+=1,n.hash=t[e],e+=1;let i=Jw(n.hash);return n.fingerprint=w_(t,e,e+i),e+=i,Wa.decode.bytes=e-r,n},encodingLength(t){return 4+Gw(t.fingerprint)}});function Jw(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Wa.getFingerprintLengthForHashType=Jw;function zw(t){switch(t.toUpperCase()){case"A":return S_;case"PTR":return za;case"CNAME":return za;case"DNAME":return za;case"TXT":return mp;case"NULL":return wp;case"AAAA":return vp;case"SRV":return xp;case"HINFO":return bp;case"CAA":return es;case"NS":return yp;case"SOA":return gp;case"MX":return Ep;case"OPT":return ts;case"DNSKEY":return li;case"RRSIG":return Yd;case"RP":return Jd;case"NSEC":return Zd;case"NSEC3":return Xd;case"SSHFP":return Wa;case"DS":return Qd}return pp}var an=Ke({encode(t,e,r){e||(e=new Uint8Array(an.encodingLength(t))),r||(r=0);let n=r;if(se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Va(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");ae(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,ae(e,t.flags||0,r+6),r+=8,ts.encode(t.options||[],e,r),r+=ts.encode.bytes}else{let i=Fw(t.class===void 0?"IN":t.class);t.flush&&(i|=Yw),ae(e,i,r+2),fi(e,t.ttl||0,r+4),r+=8;let o=zw(t.type);o.encode(t.data,e,r),r+=o.encode.bytes}return an.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=se.decode(t,e),e+=se.decode.bytes,r.type=Gd(he(t,e)),r.type==="OPT")r.udpPayloadSize=he(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=he(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=ts.decode(t,e+8),e+=8+ts.decode.bytes;else{let i=he(t,e+2);r.ttl=di(t,e+4),r.class=qw(i&iC),r.flush=!!(i&Yw);let o=zw(r.type);r.data=o.decode(t,e+8),e+=8+o.decode.bytes}return an.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return se.encodingLength(t.name)+8+zw(t.type).encodingLength(e)}}),Ya=Ke({encode(t,e,r){e||(e=new Uint8Array(Ya.encodingLength(t))),r||(r=0);let n=r;return se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Va(t.type),r),r+=2,ae(e,Fw(t.class===void 0?"IN":t.class),r),r+=2,Ya.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=se.decode(t,e),e+=se.decode.bytes,n.type=Gd(he(t,e)),e+=2,n.class=qw(he(t,e)),e+=2,!!(n.class&v_)&&(n.class&=oC),Ya.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var A_=1024;var Vt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(sC(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),ja.encode(t,e,r),r+=ja.encode.bytes,r=ef(t.questions,Ya,e,r),r=ef(t.answers,an,e,r),r=ef(t.authorities,an,e,r),r=ef(t.additionals,an,e,r),Vt.encode.bytes=r-i,n&&tf.bytes!==e.length?e.slice(0,tf.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=ja.decode(t,e);return e+=ja.decode.bytes,e=hp(n.questions,Ya,t,e),e=hp(n.answers,an,t,e),e=hp(n.authorities,an,t,e),e=hp(n.additionals,an,t,e),Vt.decode.bytes=e-r,n},encodingLength:function(t){return ja.encodingLength(t)+Ga(t.questions||[],Ya)+Ga(t.answers||[],an)+Ga(t.authorities||[],an)+Ga(t.additionals||[],an)}};Vt.encode.bytes=0;Vt.decode.bytes=0;function Sp(t,e){if(t.questions)throw new Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:e},t);return r.question&&(r.questions=[r.question],delete r.question),r}var Ap={encode:function(t,e,r){return e=Vt.encode(Sp(t,"query"),e,r),Ap.encode.bytes=Vt.encode.bytes,e},decode:function(t,e){let r=Vt.decode(t,e);return Ap.decode.bytes=Vt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Vt.encodingLength(Sp(t,"query"))}};Ap.encode.bytes=0;Ap.decode.bytes=0;var Tp={encode:function(t,e,r){return e=Vt.encode(Sp(t,"response"),e,r),Tp.encode.bytes=Vt.encode.bytes,e},decode:function(t,e){let r=Vt.decode(t,e);return Tp.decode.bytes=Vt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Vt.encodingLength(Sp(t,"response"))}};Tp.encode.bytes=0;Tp.decode.bytes=0;var tf=Vt.encode,_p=Vt.decode,sC=Vt.encodingLength;function T_(t){let e=tf(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),mr(e,r,2,0,e.length),T_.bytes=r.byteLength,r}T_.bytes=0;function __(t){let e=he(t,0);if(t.byteLength<e+2)return null;let r=_p(t.slice(2));return __.bytes=_p.bytes,r}__.bytes=0;function Ga(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function ef(t,e,r,n){for(let i=0;i<t.length;i++)e.encode(t[i],r,n),n+=e.encode.bytes;return n}function hp(t,e,r,n){for(let i=0;i<t.length;i++)t[i]=e.decode(r,n),n+=e.decode.bytes;return n}l();var B_=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},un=class{static getSigningMethod(e){return B_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")})}static resolve(e,r){return B_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")})}};var kt=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},I_=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},R_="https://diddht.tbddev.org",cC=0,rs=7200,Bp=";",or=",",Zw;(function(t){t[t.Discoverable=0]="Discoverable",t[t.Organization=1]="Organization",t[t.Government=2]="Government",t[t.Corporation=3]="Corporation",t[t.LocalBusiness=4]="LocalBusiness",t[t.SoftwarePackage=5]="SoftwarePackage",t[t.WebApp=6]="WebApp",t[t.FinancialInstitution=7]="FinancialInstitution"})(Zw||(Zw={}));var sr;(function(t){t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519"})(sr||(sr={}));var Xw;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(Xw||(Xw={}));var O_={Ed25519:sr.Ed25519,ES256K:sr.secp256k1,ES256:sr.secp256r1,"P-256":sr.secp256r1,secp256k1:sr.secp256k1,secp256r1:sr.secp256r1,X25519:sr.X25519},U_={[sr.Ed25519]:"EdDSA",[sr.secp256k1]:"ES256K",[sr.secp256r1]:"ES256",[sr.X25519]:"ECDH-ES+A256KW"},rf=class t extends un{static create(){return kt(this,arguments,void 0,function*({keyManager:e=new Xt,options:r={}}={}){var n,i,o,s,c,a,u,d,f,h,p;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in O_)))throw new Error("One or more verification method algorithms are not supported");let g=(i=r.verificationMethods)===null||i===void 0?void 0:i.filter(T=>"id"in T).map(T=>T.id);if(g&&g.length!==new Set(g).size)throw new Error("One or more verification method IDs are not unique");if(!((o=r.services)===null||o===void 0)&&o.some(T=>!T.id||!T.type||!T.serviceEndpoint))throw new Error("One or more services are missing required properties");let y=yield e.generateKey({algorithm:"Ed25519"}),E=yield e.getPublicKey({keyUri:y}),S=yield Dt.identityKeyToIdentifier({identityKey:E}),I=Object.assign(Object.assign({id:S},r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs}),r.controllers&&{controller:r.controllers}),A=[...(s=r.verificationMethods)!==null&&s!==void 0?s:[]];A?.some(T=>{var M;return((M=T.id)===null||M===void 0?void 0:M.split("#").pop())==="0"})||A.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let T of A){let M=T.id&&T.id.split("#").pop()==="0"?y:yield e.generateKey({algorithm:T.algorithm}),q=yield e.getPublicKey({keyUri:M}),j=(a=(c=T.id)!==null&&c!==void 0?c:q.kid)!==null&&a!==void 0?a:yield ge({jwk:q});j=`${S}#${Lr(j)}`,(u=I.verificationMethod)!==null&&u!==void 0||(I.verificationMethod=[]),I.verificationMethod.push({id:j,type:"JsonWebKey",controller:(d=T.controller)!==null&&d!==void 0?d:S,publicKeyJwk:q});for(let $ of(f=T.purposes)!==null&&f!==void 0?f:[])I[$]||(I[$]=[]),I[$].push(j)}(h=r.services)===null||h===void 0||h.forEach(T=>{var M;(M=I.service)!==null&&M!==void 0||(I.service=[]),T.id=`${S}#${T.id.split("#").pop()}`,I.service.push(T)});let O=new gr({uri:S,document:I,metadata:Object.assign({published:!1},r.types&&{types:r.types}),keyManager:e});if(!((p=r.publish)!==null&&p!==void 0)||p){let T=yield t.publish({did:O,gatewayUri:r.gatewayUri});O.metadata=T.didDocumentMetadata}return O})}static import(e){return kt(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){var i;let o=me.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield gr.import({portableDid:r,keyManager:n});if(!(!((i=s.document.verificationMethod)===null||i===void 0)&&i.some(c=>{var a;return((a=c.id)===null||a===void 0?void 0:a.split("#").pop())==="0"})))throw new re(ie.InvalidDidDocument,"DID document must contain an Identity Key");return s})}static getSigningMethod(e){return kt(this,arguments,void 0,function*({didDocument:r,methodId:n="#0"}){var i;let o=me.parse(r.id);if(o&&o.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${o.method}`);let s=(i=r.verificationMethod)===null||i===void 0?void 0:i.find(c=>{var a,u;return Lr(c.id)===((a=Lr(n))!==null&&a!==void 0?a:Lr((u=r.assertionMethod)===null||u===void 0?void 0:u[0]))});if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static publish(e){return kt(this,arguments,void 0,function*({did:r,gatewayUri:n=R_}){return yield Ip.put({did:r,gatewayUri:n})})}static resolve(e){return kt(this,arguments,void 0,function*(r,n={}){var i;let o=(i=n?.gatewayUri)!==null&&i!==void 0?i:R_;try{yield Dt.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Ip.get({didUri:r,gatewayUri:o});return Object.assign(Object.assign({},ft),{didDocument:s,didDocumentMetadata:c})}catch(s){if(!(s instanceof re))throw new Error(s);return Object.assign(Object.assign({},ft),{didResolutionMetadata:Object.assign({error:s.code},s.message&&{errorMessage:s.message})})}})}};rf.methodName="dht";var Ip=class t{static get(e){return kt(this,arguments,void 0,function*({didUri:r,gatewayUri:n}){let i=Dt.identifierToIdentityKeyBytes({didUri:r}),o=yield t.pkarrGet({gatewayUri:n,publicKeyBytes:i}),s=yield Dt.parseBep44GetMessage({bep44Message:o}),c=yield t.fromDnsPacket({didUri:r,dnsPacket:s});return c.didDocumentMetadata.versionId=o.seq.toString(),c})}static put(e){return kt(this,arguments,void 0,function*({did:r,gatewayUri:n}){let i=yield t.toDnsPacket({didDocument:r.document,didMetadata:r.metadata,authoritativeGatewayUris:[n]}),o=yield Dt.createBep44PutMessage({dnsPacket:i,publicKeyBytes:Dt.identifierToIdentityKeyBytes({didUri:r.uri}),signer:yield r.getSigner({methodId:"0"})}),s=yield t.pkarrPut({gatewayUri:n,bep44Message:o});return{didDocument:r.document,didDocumentMetadata:Object.assign(Object.assign({},r.metadata),{published:s,versionId:o.seq.toString()}),didRegistrationMetadata:{}}})}static pkarrGet(e){return kt(this,arguments,void 0,function*({gatewayUri:r,publicKeyBytes:n}){let i=ne.uint8Array(n).toBase32Z(),o=new URL(i,r).href,s;try{if(s=yield fetch(o,{method:"GET"}),!s.ok)throw new re(ie.NotFound,`Pkarr record not found for: ${i}`)}catch(u){throw u instanceof re?u:new re(ie.InternalError,`Failed to fetch Pkarr record: ${u.message}`)}let c=yield s.arrayBuffer();if(!c)throw new re(ie.NotFound,`Pkarr record not found for: ${i}`);if(c.byteLength<72)throw new re(ie.InvalidDidDocumentLength,`Pkarr response must be at least 72 bytes but got: ${c.byteLength}`);if(c.byteLength>1072)throw new re(ie.InvalidDidDocumentLength,`Pkarr response exceeds 1000 byte limit: ${c.byteLength}`);return{k:n,seq:Number(new DataView(c).getBigUint64(64)),sig:new Uint8Array(c,0,64),v:new Uint8Array(c,72)}})}static pkarrPut(e){return kt(this,arguments,void 0,function*({gatewayUri:r,bep44Message:n}){let i=ne.uint8Array(n.k).toBase32Z(),o=new URL(i,r).href,s=new Uint8Array(n.v.length+72);s.set(n.sig,0),new DataView(s.buffer).setBigUint64(n.sig.length,BigInt(n.seq)),s.set(n.v,n.sig.length+8);let c;try{c=yield fetch(o,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s})}catch(a){throw new re(ie.InternalError,`Failed to put Pkarr record for identifier ${i}: ${a.message}`)}return c.ok})}static fromDnsPacket(e){return kt(this,arguments,void 0,function*({didUri:r,dnsPacket:n}){var i,o,s;let c={id:r},a={published:!0},u=new Map;for(let d of(i=n?.answers)!==null&&i!==void 0?i:[]){if(d.type!=="TXT")continue;let f=d.name.split(".")[0].substring(1);switch(!0){case f.startsWith("aka"):{let h=Dt.parseTxtDataToString(d.data);c.alsoKnownAs=h.split(or);break}case f.startsWith("cnt"):{let h=Dt.parseTxtDataToString(d.data);c.controller=h.includes(or)?h.split(or):h;break}case f.startsWith("k"):{let{id:h,t:p,k:g,c:y,a:E}=Dt.parseTxtDataToObject(d.data),S=ne.base64Url(g).toUint8Array(),I=sr[Number(p)],A=yield Dt.keyConverter(I).bytesToPublicKey({publicKeyBytes:S});A.alg=E||U_[Number(p)];let O=f==="k0"?"0":h!==void 0?h:yield ge({jwk:A});(o=c.verificationMethod)!==null&&o!==void 0||(c.verificationMethod=[]);let T=`${r}#${O}`;c.verificationMethod.push({id:T,type:"JsonWebKey",controller:y??r,publicKeyJwk:A}),u.set(f,T);break}case f.startsWith("s"):{let h=Dt.parseTxtDataToObject(d.data),{id:p,t:g,se:y}=h,E=I_(h,["id","t","se"]),S=y.includes(or)?y.split(or):[y],I=Object.fromEntries(Object.entries(E).map(([A,O])=>[A,O.includes(or)?O.split(or):O]));(s=c.service)!==null&&s!==void 0||(c.service=[]),c.service.push(Object.assign(Object.assign({},I),{id:`${r}#${p}`,type:g,serviceEndpoint:S}));break}case f.startsWith("typ"):{let{id:h}=Dt.parseTxtDataToObject(d.data);a.types=h.split(or).map(p=>Number(p));break}case f.startsWith("did"):{let h=I=>I.split(or).map(A=>u.get(A)).filter(A=>typeof A=="string"),{auth:p,asm:g,del:y,inv:E,agm:S}=Dt.parseTxtDataToObject(d.data);p&&(c.authentication=h(p)),g&&(c.assertionMethod=h(g)),y&&(c.capabilityDelegation=h(y)),E&&(c.capabilityInvocation=h(E)),S&&(c.keyAgreement=h(S));break}}}return{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{}}})}static toDnsPacket(e){return kt(this,arguments,void 0,function*({didDocument:r,didMetadata:n,authoritativeGatewayUris:i,previousDidProof:o}){var s,c,a,u,d;let f=[],h=[],p=new Map,g=[],y=[];if(o!==void 0){let{signature:I,previousDid:A}=o;yield Dt.validatePreviousDidProof({newDid:r.id,previousDidProof:o}),f.push({type:"TXT",name:"_prv._did.",ttl:rs,data:`id=${A};s=${I}`})}if(r.alsoKnownAs&&f.push({type:"TXT",name:"_aka._did.",ttl:rs,data:r.alsoKnownAs.join(or)}),r.controller){let I=Array.isArray(r.controller)?r.controller.join(or):r.controller;f.push({type:"TXT",name:"_cnt._did.",ttl:rs,data:I})}for(let[I,A]of(c=(s=r.verificationMethod)===null||s===void 0?void 0:s.entries())!==null&&c!==void 0?c:[]){let O=`k${I}`;y.push(O);let T=A.id.split("#").pop();p.set(T,O);let M=A.publicKeyJwk;if(!(M?.crv&&M.crv in O_))throw new re(ie.InvalidPublicKeyType,`Verification method '${A.id}' contains an unsupported key type: ${(a=M?.crv)!==null&&a!==void 0?a:"undefined"}`);let q=sr[M.crv],j=yield Dt.keyConverter(M.crv).publicKeyToBytes({publicKey:M}),$=ne.uint8Array(j).toBase64Url(),X=[`t=${q}`,`k=${$}`];T!=="0"&&(yield ge({jwk:M}))!==T&&X.unshift(`id=${T}`),M.alg!==U_[q]&&X.push(`a=${M.alg}`),A.controller!==r.id&&X.push(`c=${A.controller}`),f.push({type:"TXT",name:`_${O}._did.`,ttl:rs,data:X.join(Bp)})}(u=r.service)===null||u===void 0||u.forEach((I,A)=>{let O=`s${A}`;g.push(O);let{id:T,type:M,serviceEndpoint:q}=I,j=I_(I,["id","type","serviceEndpoint"]);T=Lr(T),q=Array.isArray(q)?q.join(","):q;let X=Object.entries(Object.assign({id:T,t:M,se:q},j)).map(([G,_])=>`${G}=${_}`).join(Bp),Q=Dt.chunkDataIfNeeded(X);f.push({type:"TXT",name:`_${O}._did.`,ttl:rs,data:Q})});let E=[`v=${cC}`];if(y.length&&E.push(`vm=${y.join(or)}`),Object.keys(Li).forEach(I=>{var A;let O=(A=r[I])===null||A===void 0?void 0:A.map(T=>p.get(T.split("#").pop()));if(O){let T=Xw[I];E.push(`${T}=${O.join(or)}`)}}),g.length&&E.push(`svc=${g.join(or)}`),!((d=n.types)===null||d===void 0)&&d.length){let A=n.types.map(O=>typeof O=="string"?Zw[O]:O);f.push({type:"TXT",name:"_typ._did.",ttl:rs,data:`id=${A.join(or)}`})}f.push({type:"TXT",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:rs,data:E.join(Bp)});for(let I of i||[])h.push({type:"NS",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:rs,data:I+"."});return{id:0,type:"response",flags:A_,answers:[...f,...h]}})}static getUniqueDidSuffix(e){return e.split(":")[2]}},Dt=class t{static createBep44PutMessage(e){return kt(this,arguments,void 0,function*({dnsPacket:r,publicKeyBytes:n,signer:i}){let o=Math.ceil(Date.now()/1e3),s=tf(r),c=Vw.encode({seq:o,v:s}).subarray(1,-1);if(c.length>1e3)throw new re(ie.InvalidDidDocumentLength,`DNS packet exceeds the 1000 byte maximum size: ${c.length} bytes`);let a=yield i.sign({data:c});return{k:n,seq:o,sig:a,v:s}})}static identifierToIdentityKey(e){return kt(this,arguments,void 0,function*({didUri:r}){let n=t.identifierToIdentityKeyBytes({didUri:r});return yield _t.bytesToPublicKey({publicKeyBytes:n})})}static identifierToIdentityKeyBytes({didUri:e}){let r=me.parse(e);if(!r)throw new re(ie.InvalidDid,`Invalid DID URI: ${e}`);if(r.method!==rf.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${r.method}`);let n;try{n=ne.base32Z(r.id).toUint8Array()}catch{throw new re(ie.InvalidPublicKey,"Failed to decode method-specific identifier")}if(n.length!==32)throw new re(ie.InvalidPublicKeyLength,`Invalid public key length: ${n.length}`);return n}static identityKeyToIdentifier(e){return kt(this,arguments,void 0,function*({identityKey:r}){let n=yield _t.publicKeyToBytes({publicKey:r}),i=ne.uint8Array(n).toBase32Z();return`did:${rf.methodName}:${i}`})}static keyConverter(e){let n={Ed25519:_t,"P-256":{publicKeyToBytes:i=>kt(this,[i],void 0,function*({publicKey:o}){let s=yield Ht.publicKeyToBytes({publicKey:o});return yield Ht.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Ht.bytesToPublicKey,privateKeyToBytes:Ht.privateKeyToBytes,bytesToPrivateKey:Ht.bytesToPrivateKey},secp256k1:{publicKeyToBytes:i=>kt(this,[i],void 0,function*({publicKey:o}){let s=yield Ot.publicKeyToBytes({publicKey:o});return yield Ot.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Ot.bytesToPublicKey,privateKeyToBytes:Ot.privateKeyToBytes,bytesToPrivateKey:Ot.bytesToPrivateKey},X25519:$a}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static parseBep44GetMessage(e){return kt(this,arguments,void 0,function*({bep44Message:r}){let n=yield _t.bytesToPublicKey({publicKeyBytes:r.k}),i=Vw.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!(yield _t.verify({key:n,signature:r.sig,data:i})))throw new re(ie.InvalidSignature,"Invalid signature for DHT BEP44 message");return _p(r.v)})}static parseTxtDataToObject(e){return this.parseTxtDataToString(e).split(Bp).reduce((r,n)=>{let[i,o]=n.split("=");return r[i]=o,r},{})}static parseTxtDataToString(e){if(typeof e=="string")return e;if(e instanceof Uint8Array)return ne.uint8Array(e).toString();if(Array.isArray(e))return e.map(r=>this.parseTxtDataToString(r)).join("");throw new re(ie.InternalError,"Pkarr returned DNS TXT record with invalid data type")}static validatePreviousDidProof(e){return kt(this,arguments,void 0,function*({newDid:r,previousDidProof:n}){let i=yield t.identifierToIdentityKey({didUri:n.previousDid}),o=t.identifierToIdentityKeyBytes({didUri:r}),s=ne.base64Url(n.signature).toUint8Array();if(!(yield _t.verify({key:i,data:o,signature:s})))throw new re(ie.InvalidPreviousDidProof,"The previous DID proof is invalid.")})}static chunkDataIfNeeded(e){if(e.length<=255)return e;let r=[];for(let n=0;n<e.length;n+=255)r.push(e.slice(n,n+255));return r}};l();l();l();l();l();var We={DeltaExceedsMaximumSize:"DeltaExceedsMaximumSize",DidDocumentPublicKeyIdDuplicated:"DidDocumentPublicKeyIdDuplicated",DidDocumentPublicKeyMissingOrIncorrectType:"DidDocumentPublicKeyMissingOrIncorrectType",DidDocumentServiceIdDuplicated:"DidDocumentServiceIdDuplicated",DidSuffixIncorrectLength:"DidSuffixIncorrectLength",EncodedStringIncorrectEncoding:"EncodedStringIncorrectEncoding",IdNotUsingBase64UrlCharacterSet:"IdNotUsingBase64UrlCharacterSet",IdTooLong:"IdTooLong",JwkEs256kMissingOrInvalidCrv:"JwkEs256kMissingOrInvalidCrv",JwkEs256kMissingOrInvalidKty:"JwkEs256kMissingOrInvalidKty",JwkEs256kHasIncorrectLengthOfX:"JwkEs256kHasIncorrectLengthOfX",JwkEs256kHasIncorrectLengthOfY:"JwkEs256kHasIncorrectLengthOfY",JwkEs256kHasIncorrectLengthOfD:"JwkEs256kHasIncorrectLengthOfD",MultihashStringNotAMultihash:"MultihashStringNotAMultihash",MultihashUnsupportedHashAlgorithm:"MultihashUnsupportedHashAlgorithm",PublicKeyJwkEs256kHasUnexpectedProperty:"PublicKeyJwkEs256kHasUnexpectedProperty",PublicKeyPurposeDuplicated:"PublicKeyPurposeDuplicated",ServiceEndpointCannotBeAnArray:"ServiceEndpointCannotBeAnArray",ServiceEndpointStringNotValidUri:"ServiceEndpointStringNotValidUri",ServiceTypeTooLong:"ServiceTypeTooLong"};l();var Le=class extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};l();l();l();l();var VJ=new Uint8Array(0);var Qw=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};l();var eb=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},tb=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return D_(this,e)}},rb=class{constructor(e){this.decoders=e}or(e){return D_(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},D_=(t,e)=>new rb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),nb=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new eb(e,r,n),this.decoder=new tb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},aC=({name:t,prefix:e,encode:r,decode:n})=>new nb(t,e,r,n);var uC=(t,e,r,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),c=0,a=0,u=0;for(let d=0;d<o;++d){let f=i[t[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s},dC=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,o+=e[i&c>>s];if(s&&(o+=e[i&c<<r-s]),n)for(;o.length*r&7;)o+="=";return o},nf=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>aC({prefix:e,name:t,encode(i){return dC(i,n,r)},decode(i){return uC(i,n,r,t)}});var QJ=nf({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),eZ=nf({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),of=nf({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),tZ=nf({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var wr=class t{static encode(e){return of.baseEncode(e)}static decodeAsBytes(e,r){if(!t.isBase64UrlString(e))throw new Le(We.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return of.baseDecode(e)}static decodeAsString(e,r){let n=t.decodeAsBytes(e,r);return t.bytesToString(n)}static isBase64UrlString(e){return/^[A-Za-z0-9_-]+$/.test(e)}static stringToBytes(e){return new TextEncoder().encode(e)}static bytesToString(e){return new TextDecoder().decode(e)}};l();var q_=Pn(N_(),1);l();l();var ib;(function(t){t.Public="public",t.Private="private"})(ib||(ib={}));var Mr=ib;var It=class{static validateEs256kOperationKey(e,r){let n=new Set(["kty","crv","x","y"]);r===Mr.Private&&n.add("d");for(let i in e)if(!n.has(i))throw new Le(We.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${i}'.`);if(e.crv!=="secp256k1")throw new Le(We.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${e.crv}.'`);if(e.kty!=="EC")throw new Le(We.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${e.kty}.'`);if(e.x.length!==43)throw new Le(We.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(e.y.length!==43)throw new Le(We.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(r===Mr.Private&&(e.d===void 0||e.d.length!==43))throw new Le(We.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(e){if(e.length>50)throw new Le(We.IdTooLong,`Key ID length ${e.length} exceed max allowed length of 50.`);if(!wr.isBase64UrlString(e))throw new Le(We.IdNotUsingBase64UrlCharacterSet,`Key ID '${e}' is not a Base64URL string.`)}static validatePublicKeyPurposes(e){if(e===void 0)return;let r=new Set;for(let n of e){if(r.has(n))throw new Le(We.PublicKeyPurposeDuplicated,`Public key purpose '${n}' already specified.`);r.add(n)}}};l();var sf=class{};sf.hashAlgorithmInMultihashCode=18;sf.maxCanonicalizedDeltaSizeInBytes=1e3;var cr=sf;l();var P_=Pn(L_(),1);var Dn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=P_.default(r);return wr.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?t.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}};l();l();l();l();var fC=$_,M_=128,lC=127,hC=~lC,pC=Math.pow(2,31);function $_(t,e,r){e=e||[],r=r||0;for(var n=r;t>=pC;)e[r++]=t&255|M_,t/=128;for(;t&hC;)e[r++]=t&255|M_,t>>>=7;return e[r]=t|0,$_.bytes=r-n+1,e}var yC=ob,gC=128,K_=127;function ob(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw ob.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&K_)<<i:(s&K_)*Math.pow(2,i),i+=7}while(s>=gC);return ob.bytes=o-n,r}var mC=Math.pow(2,7),wC=Math.pow(2,14),bC=Math.pow(2,21),xC=Math.pow(2,28),EC=Math.pow(2,35),vC=Math.pow(2,42),SC=Math.pow(2,49),AC=Math.pow(2,56),TC=Math.pow(2,63),_C=function(t){return t<mC?1:t<wC?2:t<bC?3:t<xC?4:t<EC?5:t<vC?6:t<SC?7:t<AC?8:t<TC?9:10},BC={encode:fC,decode:yC,encodingLength:_C},IC=BC,cf=IC;var sb=(t,e=0)=>[cf.decode(t,e),cf.decode.bytes],cb=(t,e,r=0)=>(cf.encode(t,e,r),e),ab=t=>cf.encodingLength(t);var ub=(t,e)=>{let r=e.byteLength,n=ab(t),i=n+ab(r),o=new Uint8Array(i+r);return cb(t,o,0),cb(r,o,n),o.set(e,i),new Up(t,r,e,o)},H_=t=>{let e=Qw(t),[r,n]=sb(e),[i,o]=sb(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Up(r,i,s,e)};var Up=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();l();var fb=({name:t,code:e,encode:r})=>new db(t,e,r),db=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?ub(this.code,r):r.then(n=>ub(this.code,n))}else throw Error("Unknown type, must be binary type")}};var V_=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Op=fb({name:"sha2-256",code:18,encode:V_("SHA-256")}),CZ=fb({name:"sha2-512",code:19,encode:V_("SHA-512")});var af=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Nt=class t{static hash(e,r){return af(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield Op.digest(e)).bytes;break;default:throw new Le(We.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return af(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield Op.encode(e);break;default:throw new Le(We.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=Dn.canonicalizeAsBytes(e);return yield t.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=Dn.canonicalizeAsBytes(e),i=yield t.hashAsNonMultihashBytes(n,r);return yield t.hashThenEncode(i,r)})}static hashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=yield t.hash(e,r);return wr.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=wr.decodeAsBytes(e,r);try{n=H_(i)}catch{throw new Le(We.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let o=cr.hashAlgorithmInMultihashCode;if(o!==n.code)throw new Le(We.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${o} or change IonSdkConfig to desired hashing algorithm.`)}};l();var lb;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(lb||(lb={}));var uf=lb;l();var hb;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(hb||(hb={}));var pc=hb;var Dp=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},ns=class t{static createCreateRequest(e){return Dp(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,o=e.document.services;It.validateEs256kOperationKey(r,Mr.Public),It.validateEs256kOperationKey(n,Mr.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=cr.hashAlgorithmInMultihashCode,c=[{action:pc.Replace,document:e.document}],a={updateCommitment:yield Nt.canonicalizeThenDoubleHashThenEncode(n,s),patches:c};t.validateDeltaSize(a);let d={deltaHash:yield Nt.canonicalizeThenHashThenEncode(a,s),recoveryCommitment:yield Nt.canonicalizeThenDoubleHashThenEncode(r,s)};return{type:uf.Create,suffixData:d,delta:a}})}static createDeactivateRequest(e){return Dp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.recoveryPublicKey,Mr.Public);let r=cr.hashAlgorithmInMultihashCode,n=yield Nt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},o=yield e.signer.sign({alg:"ES256K"},i);return{type:uf.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:o}})}static createRecoverRequest(e){return Dp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.recoveryPublicKey,Mr.Public),It.validateEs256kOperationKey(e.nextRecoveryPublicKey,Mr.Public),It.validateEs256kOperationKey(e.nextUpdatePublicKey,Mr.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=cr.hashAlgorithmInMultihashCode,n=yield Nt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:pc.Replace,document:e.document}],o=yield Nt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),s={patches:i,updateCommitment:o},c=yield Nt.canonicalizeThenHashThenEncode(s,r),u={recoveryCommitment:yield Nt.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:c},d=yield e.signer.sign({alg:"ES256K"},u);return{type:uf.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:d}})}static createUpdateRequest(e){return Dp(this,void 0,void 0,function*(){if(t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.updatePublicKey,Mr.Public),It.validateEs256kOperationKey(e.nextUpdatePublicKey,Mr.Public),t.validateServices(e.servicesToAdd),t.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let g of e.idsOfServicesToRemove)It.validateId(g);if(e.idsOfPublicKeysToRemove!==void 0)for(let g of e.idsOfPublicKeysToRemove)It.validateId(g);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let g={action:pc.AddServices,services:n};r.push(g)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let g={action:pc.RemoveServices,ids:i};r.push(g)}let o=e.publicKeysToAdd;if(o!==void 0&&o.length>0){let g={action:pc.AddPublicKeys,publicKeys:o};r.push(g)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let g={action:pc.RemovePublicKeys,ids:s};r.push(g)}let c=cr.hashAlgorithmInMultihashCode,a=yield Nt.canonicalizeThenHashThenEncode(e.updatePublicKey,c),u=yield Nt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,c),d={patches:r,updateCommitment:u},f=yield Nt.canonicalizeThenHashThenEncode(d,c),h={updateKey:e.updatePublicKey,deltaHash:f},p=yield e.signer.sign({alg:"ES256K"},h);return{type:uf.Update,didSuffix:e.didSuffix,revealValue:a,delta:d,signedData:p}})}static validateDidSuffix(e){Nt.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let r=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Le(We.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(It.validateId(n.id),r.has(n.id))throw new Le(We.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),It.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(t.validateService(n),r.has(n.id))throw new Le(We.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){It.validateId(e.id);let r=30;if(e.type.length>r){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${r}.`;throw new Le(We.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Le(We.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&q_.parse(e.serviceEndpoint).error!==void 0)throw new Le(We.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=Dn.canonicalizeAsBytes(e);if(r.length>cr.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${cr.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Le(We.DeltaExceedsMaximumSize,n)}}};var F_=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Ja=class t{static createLongFormDid(e){return F_(this,void 0,void 0,function*(){let r=yield ns.createCreateRequest(e),n=yield t.computeDidUniqueSuffix(r.suffixData),i;cr.network===void 0||cr.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${cr.network}:${n}`;let o={suffixData:r.suffixData,delta:r.delta},s=Dn.canonicalizeAsBytes(o),c=wr.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return F_(this,void 0,void 0,function*(){let r=Dn.canonicalizeAsBytes(e),n=yield Nt.hash(r,cr.hashAlgorithmInMultihashCode);return wr.encode(n)})}};l();l();var j_;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(j_||(j_={}));l();var W_;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(W_||(W_={}));l();var is=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},hi;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(hi||(hi={}));var OC={Ed25519:hi.Ed25519,ES256K:hi.secp256k1,ES256:hi.secp256r1,"P-256":hi.secp256r1,secp256k1:hi.secp256k1,secp256r1:hi.secp256r1},G_="https://ion.tbd.engineering",pb=class t extends un{static create(){return is(this,arguments,void 0,function*({keyManager:e=new Xt,options:r={}}={}){var n,i,o,s,c,a,u;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in OC)))throw new Error("One or more verification method algorithms are not supported");let d=(i=r.verificationMethods)===null||i===void 0?void 0:i.filter(T=>"id"in T).map(T=>T.id);if(d&&d.length!==new Set(d).size)throw new Error("One or more verification method IDs are not unique");if(!((o=r.services)===null||o===void 0)&&o.some(T=>!T.id||!T.type||!T.serviceEndpoint))throw new Error("One or more services are missing required properties");let f={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},h=[];for(let T of(s=r.verificationMethods)!==null&&s!==void 0?s:[f]){let M=yield e.generateKey({algorithm:T.algorithm}),q=yield e.getPublicKey({keyUri:M});h.push({id:T.id,publicKeyJwk:q,purposes:(c=T.purposes)!==null&&c!==void 0?c:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let p=yield e.generateKey({algorithm:hi.secp256k1}),g=yield e.getPublicKey({keyUri:p}),y=yield e.generateKey({algorithm:hi.secp256k1}),E=yield e.getPublicKey({keyUri:y}),S=yield yc.computeLongFormDidUri({recoveryKey:g,updateKey:E,services:(a=r.services)!==null&&a!==void 0?a:[],verificationMethods:h}),{didDocument:I,didResolutionMetadata:A}=yield t.resolve(S,{gatewayUri:r.gatewayUri});if(I===null)throw new Error(`Unable to resolve DID during creation: ${A?.error}`);let O=new gr({uri:S,document:I,metadata:{published:!1,canonicalId:S.split(":",3).join(":"),recoveryKey:g,updateKey:E},keyManager:e});if(!((u=r.publish)!==null&&u!==void 0)||u){let T=yield t.publish({did:O,gatewayUri:r.gatewayUri});O.metadata=T.didDocumentMetadata}return O})}static getSigningMethod(e){return is(this,arguments,void 0,function*({didDocument:r,methodId:n}){var i;let o=me.parse(r.id);if(o&&o.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${o.method}`);let s=(i=r.verificationMethod)===null||i===void 0?void 0:i.find(c=>{var a;return c.id===(n??((a=r.assertionMethod)===null||a===void 0?void 0:a[0]))});if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static import(e){return is(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield gr.import({portableDid:r,keyManager:n})})}static publish(e){return is(this,arguments,void 0,function*({did:r,gatewayUri:n=G_}){var i,o,s;let c=(o=(i=r.document.verificationMethod)===null||i===void 0?void 0:i.map(d=>({id:d.id,publicKeyJwk:d.publicKeyJwk,purposes:ZT({didDocument:r.document,methodId:d.id})})))!==null&&o!==void 0?o:[],a=yield yc.createIonDocument({services:(s=r.document.service)!==null&&s!==void 0?s:[],verificationMethods:c}),u=yield yc.constructCreateRequest({ionDocument:a,recoveryKey:r.metadata.recoveryKey,updateKey:r.metadata.updateKey});try{let d=yc.appendPathToUrl({baseUrl:n,path:"/operations"}),f=yield fetch(d,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return{didDocument:r.document,didDocumentMetadata:Object.assign(Object.assign({},r.metadata),{published:f.ok}),didRegistrationMetadata:{}}}catch{return{didDocument:null,didDocumentMetadata:{published:!1},didRegistrationMetadata:{error:ie.InternalError,errorMessage:`Failed to publish DID document for: ${r.uri}`}}}})}static resolve(e){return is(this,arguments,void 0,function*(r,n={}){var i,o;let s=me.parse(r);if(!s)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"invalidDid"}});if(s.method!==t.methodName)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"methodNotSupported"}});let c=(i=n?.gatewayUri)!==null&&i!==void 0?i:G_;try{let a=yc.appendPathToUrl({baseUrl:c,path:`/identifiers/${r}`}),u=yield fetch(a);if(!u.ok)throw new re(ie.NotFound,`Unable to find DID document for: ${r}`);let{didDocument:d,didDocumentMetadata:f}=yield u.json();return Object.assign(Object.assign(Object.assign({},ft),d&&{didDocument:d}),{didDocumentMetadata:Object.assign({published:(o=f?.method)===null||o===void 0?void 0:o.published},f)})}catch(a){if(!(a instanceof re))throw new Error(a);return Object.assign(Object.assign({},ft),{didResolutionMetadata:Object.assign({error:a.code},a.message&&{errorMessage:a.message})})}})}};pb.methodName="ion";var yc=class t{static appendPathToUrl({baseUrl:e,path:r}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=r.startsWith("/")?r.substring(1):r,n.toString()}static computeLongFormDidUri(e){return is(this,arguments,void 0,function*({recoveryKey:r,updateKey:n,services:i,verificationMethods:o}){let s=yield t.createIonDocument({services:i,verificationMethods:o}),c=t.normalizeJwk(r),a=t.normalizeJwk(n);return yield Ja.createLongFormDid({document:s,recoveryKey:c,updateKey:a})})}static constructCreateRequest(e){return is(this,arguments,void 0,function*({ionDocument:r,recoveryKey:n,updateKey:i}){return yield ns.createCreateRequest({document:r,recoveryKey:t.normalizeJwk(n),updateKey:t.normalizeJwk(i)})})}static createIonDocument(e){return is(this,arguments,void 0,function*({services:r,verificationMethods:n}){var i,o;let s=[];for(let u of n){let d=(o=(i=u.id)!==null&&i!==void 0?i:u.publicKeyJwk.kid)!==null&&o!==void 0?o:yield ge({jwk:u.publicKeyJwk});d=`${d.split("#").pop()}`;let f={id:d,publicKeyJwk:t.normalizeJwk(u.publicKeyJwk),purposes:u.purposes,type:"JsonWebKey2020"};s.push(f)}let c=r.map(u=>Object.assign(Object.assign({},u),{id:`${u.id.split("#").pop()}`}));return{publicKeys:s,services:c}})}static normalizeJwk(e){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);return n}};l();var kp=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},yb=class t extends un{static create(){return kp(this,arguments,void 0,function*({keyManager:e=new Xt,options:r={}}={}){var n,i,o,s;if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let c=(s=(n=r.algorithm)!==null&&n!==void 0?n:(o=(i=r.verificationMethods)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.algorithm)!==null&&s!==void 0?s:"Ed25519",a=yield e.generateKey({algorithm:c}),u=yield e.getPublicKey({keyUri:a}),d=ne.object(u).toBase64Url(),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f)).didDocument;return new gr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return kp(this,arguments,void 0,function*({didDocument:r}){var n;let i=me.parse(r.id);if(i&&i.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${i.method}`);let[o]=(n=r.verificationMethod)!==null&&n!==void 0?n:[];if(!(o&&o.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return o})}static import(e){return kp(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield gr.import({portableDid:r,keyManager:n});if(o.document.verificationMethod.length!==1)throw new re(ie.InvalidDidDocument,"DID document must contain exactly one verification method");return o})}static resolve(e,r){return kp(this,void 0,void 0,function*(){let n=me.parse(e),i;try{i=ne.base64Url(n.id).toObject()}catch{}if(!n||!i)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"methodNotSupported"}});let o={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},s=`${o.id}#0`;switch(o.verificationMethod=[{id:s,type:"JsonWebKey",controller:o.id,publicKeyJwk:i}],o.authentication=[s],o.assertionMethod=[s],o.capabilityInvocation=[s],o.capabilityDelegation=[s],o.keyAgreement=[s],i.use){case"sig":{delete o.keyAgreement;break}case"enc":{delete o.authentication,delete o.assertionMethod,delete o.capabilityInvocation,delete o.capabilityDelegation;break}}return Object.assign(Object.assign({},ft),{didDocument:o})})}};yb.methodName="jwk";l();var kn=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},oo;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(oo||(oo={}));var gb={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1",X25519KeyAgreementKey2020:"https://w3id.org/security/suites/x25519-2020/v1"},DC={Ed25519:oo.Ed25519,ES256K:oo.secp256k1,ES256:oo.secp256r1,"P-256":oo.secp256r1,secp256k1:oo.secp256k1,secp256r1:oo.secp256r1,X25519:oo.X25519},mb=class t extends un{static create(){return kn(this,arguments,void 0,function*({keyManager:e=new Xt,options:r={}}={}){var n,i,o,s;if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let c=(s=(n=r.algorithm)!==null&&n!==void 0?n:(o=(i=r.verificationMethods)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.algorithm)!==null&&s!==void 0?s:"Ed25519",a=yield e.generateKey({algorithm:c}),u=yield e.getPublicKey({keyUri:a}),d=yield br.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new gr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return kn(this,arguments,void 0,function*({didDocument:r}){var n;let i=me.parse(r.id);if(i&&i.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${i.method}`);let[o]=r.assertionMethod||[],s=(n=r.verificationMethod)===null||n===void 0?void 0:n.find(c=>c.id===o);if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static import(e){return kn(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield gr.import({portableDid:r,keyManager:n});if(o.document.verificationMethod.length!==1)throw new re(ie.InvalidDidDocument,"DID document must contain exactly one verification method");return o})}static resolve(e,r){return kn(this,void 0,void 0,function*(){try{let n=yield t.createDocument({didUri:e,options:r});return Object.assign(Object.assign({},ft),{didDocument:n})}catch(n){if(!(n instanceof re))throw new Error(n);return Object.assign(Object.assign({},ft),{didResolutionMetadata:Object.assign({error:n.code},n.message&&{errorMessage:n.message})})}})}static createDocument(e){return kn(this,arguments,void 0,function*({didUri:r,options:n={}}){let{defaultContext:i="https://www.w3.org/ns/did/v1",enableEncryptionKeyDerivation:o=!1,enableExperimentalPublicKeyTypes:s=!1,publicKeyFormat:c="JsonWebKey2020"}=n,a={id:""},u=me.parse(r);if(!u)throw new re(ie.InvalidDid,`Invalid DID URI: ${r}`);let d=u.id;if(u.method!==t.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${u.method}`);if(!t.validateIdentifier(u))throw new re(ie.InvalidDid,`Invalid DID URI: ${r}`);let f=yield t.createSignatureMethod({didUri:r,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:c}});if(a.id=u.uri,a.verificationMethod=[f],a.authentication=[f.id],a.assertionMethod=[f.id],a.capabilityInvocation=[f.id],a.capabilityDelegation=[f.id],o===!0){let g=c==="Ed25519VerificationKey2020"?"X25519KeyAgreementKey2020":"JsonWebKey2020",y=yield this.createEncryptionMethod({didUri:r,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:g}});a.verificationMethod.push(y),a.keyAgreement=[y.id]}let h=[i];return JT({didDocument:a}).forEach(g=>{let y=gb[g];h.push(y)}),a["@context"]=h,a})}static createEncryptionMethod(e){return kn(this,arguments,void 0,function*({didUri:r,multibaseValue:n,options:i}){let{enableExperimentalPublicKeyTypes:o,publicKeyFormat:s}=i,c={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:u}=yield t.deriveEncryptionKey({multibaseValue:n}),d=a.byteLength,f=br.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(d!==f)throw new re(ie.InvalidPublicKeyLength,`Expected ${d} bytes. Actual: ${f}`);let h=Cw({keyBytes:a,multicodecCode:u});c.id=`${r}#${h}`;try{new URL(c.id)}catch{throw new re(ie.InvalidDidUrl,"Verification Method ID is not a valid DID URL.")}if(!(s in gb))throw new re(ie.UnsupportedPublicKeyType,`Unsupported format: ${s}`);if(o===!1&&!["Multikey","JsonWebKey2020","X25519KeyAgreementKey2020"].includes(s))throw new re(ie.InvalidPublicKeyType,`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(c.type=s,c.controller=r,s==="X25519KeyAgreementKey2020"&&(c.publicKeyMultibase=h),s==="JsonWebKey2020"){let{crv:g}=yield br.multicodecToJwk({code:u});c.publicKeyJwk=yield br.keyConverter(g).bytesToPublicKey({publicKeyBytes:a})}return c})}static createSignatureMethod(e){return kn(this,arguments,void 0,function*({didUri:r,multibaseValue:n,options:i}){let{enableExperimentalPublicKeyTypes:o,publicKeyFormat:s}=i,c={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:u,multicodecName:d}=Lw({multibaseKeyId:n}),f=a.byteLength,h=br.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(f!==h)throw new re(ie.InvalidPublicKeyLength,`Expected ${f} bytes. Actual: ${h}`);let p=!1;switch(d){case"secp256k1-pub":p=yield Ot.validatePublicKey({publicKeyBytes:a});break;case"ed25519-pub":p=yield _t.validatePublicKey({publicKeyBytes:a});break;case"x25519-pub":p=!0;break}if(!p)throw new re(ie.InvalidPublicKey,"Invalid public key detected.");c.id=`${r}#${n}`;try{new URL(c.id)}catch{throw new re(ie.InvalidDidUrl,"Verification Method ID is not a valid DID URL.")}if(!(s in gb))throw new re(ie.UnsupportedPublicKeyType,`Unsupported format: ${s}`);if(o===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(s))throw new re(ie.InvalidPublicKeyType,`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(c.type=s,c.controller=r,s==="Ed25519VerificationKey2020"&&(c.publicKeyMultibase=n),s==="JsonWebKey2020"){let{crv:y}=yield br.multicodecToJwk({code:u});c.publicKeyJwk=yield br.keyConverter(y).bytesToPublicKey({publicKeyBytes:a})}return c})}static deriveEncryptionKey(e){return kn(this,arguments,void 0,function*({multibaseValue:r}){let n={keyBytes:new Uint8Array,multicodecCode:0},{keyBytes:i,multicodecCode:o}=Lw({multibaseKeyId:r});if(o===237){let s=yield br.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield _t.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield br.keyConverter("Ed25519").publicKeyToBytes({publicKey:c}),multicodecCode:236}}return n})}static validateIdentifier(e){let{method:r,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&r==="key"&&Number("1")>0&&ia(n)==="String"&&n.startsWith("z")}};mb.methodName="key";var br=class t{static jwkToMulticodec(e){return kn(this,arguments,void 0,function*({jwk:r}){let n=[];r.crv&&(n.push(r.crv),r.d?n.push("private"):n.push("public"));let i=n.join(":"),o=t.JWK_TO_MULTICODEC[i];if(o===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${i}'`);return{code:zt.getCodeFromName({name:o}),name:o}})}static keyCompressor(e){let n={"P-256":Ht.compressPublicKey,secp256k1:Ot.compressPublicKey}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static keyConverter(e){let n={Ed25519:_t,"P-256":Ht,secp256k1:Ot,X25519:$a}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static multicodecToJwk(e){return kn(this,arguments,void 0,function*({code:r,name:n}){if(!(n?!r:r))throw new Error("Either 'name' or 'code' must be defined, but not both.");n=n===void 0?zt.getNameFromCode({code:r}):n;let i=n,o=t.MULTICODEC_TO_JWK[i];if(o===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return Object.assign({},o)})}static publicKeyToMultibaseId(e){return kn(this,arguments,void 0,function*({publicKey:r}){var n;if(!(r?.crv&&r.crv in DC))throw new re(ie.InvalidPublicKeyType,`Public key contains an unsupported key type: ${(n=r?.crv)!==null&&n!==void 0?n:"undefined"}`);let i=yield t.keyConverter(r.crv).publicKeyToBytes({publicKey:r});/^(secp256k1|P-256|P-384|P-521)$/.test(r.crv)&&(i=yield t.keyCompressor(r.crv)({publicKeyBytes:i}));let{name:o}=yield t.jwkToMulticodec({jwk:r});return Cw({keyBytes:i,multicodecName:o})})}};br.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv","X25519:public":"x25519-pub","X25519:private":"x25519-priv"};br.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};br.MULTICODEC_TO_JWK={"ed25519-pub":{crv:"Ed25519",kty:"OKP",x:""},"ed25519-priv":{crv:"Ed25519",kty:"OKP",x:"",d:""},"secp256k1-pub":{crv:"secp256k1",kty:"EC",x:"",y:""},"secp256k1-priv":{crv:"secp256k1",kty:"EC",x:"",y:"",d:""},"x25519-pub":{crv:"X25519",kty:"OKP",x:""},"x25519-priv":{crv:"X25519",kty:"OKP",x:"",d:""}};l();var kC=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},wb=class t extends un{static resolve(e,r){return kC(this,void 0,void 0,function*(){let n=me.parse(e);if(!n)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"methodNotSupported"}});let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let o=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let s=yield fetch(o);if(!s.ok)throw new Error("HTTP error status code returned");let c=yield s.json();return Object.assign(Object.assign({},ft),{didDocument:c})}catch{return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"notFound"}})}})}};wb.methodName="web";l();var KC=Pn(Y_(),1),$C=Pn(Gg(),1);l();l();var Kr=class t{static extractDidFragment(e){if(typeof e=="string"&&e.length!==0)return e}static isDidVerificationMethod(e){return!(!e||typeof e!="object"||e===null||!("id"in e&&"type"in e&&"controller"in e)||typeof e.id!="string"||typeof e.type!="string"||typeof e.controller!="string")}static isDidService(e){return!(!e||typeof e!="object"||e===null||!("id"in e&&"type"in e&&"serviceEndpoint"in e)||typeof e.id!="string"||typeof e.type!="string"||typeof e.serviceEndpoint!="string")}static getVerificationMethods(e){if(!e)throw new TypeError("Required parameter missing: 'didDocument'");let r=[];return r.push(...e.verificationMethod?.filter(t.isDidVerificationMethod)??[]),Object.keys(Li).forEach(n=>{r.push(...e[n]?.filter(t.isDidVerificationMethod)??[])}),r}static deriveRootCapability(e){return{"@context":"https://w3id.org/zcap/v1",id:`urn:zcap:root:${encodeURIComponent(e)}`,controller:e,invocationTarget:e}}static dereferenceZcapId(e){let r={},[n,i,o,s]=e.split(":")??[];if([n,i,o,s].length!==4)throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!n||n!=="urn")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!i||i!=="zcap")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!o||o!=="root")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);let a=decodeURIComponent(s);return r.id=e,r.controller=a,r.invocationTarget=a,r}};l();l();l();l();l();l();l();function J_(t,e,r){return t&e^~t&r}function Z_(t,e,r){return t&e^t&r^e&r}var Cp=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Bl(this.buffer)}update(e){Xc(this),ve(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Bl(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Xc(this),_v(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Os(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let c=Bl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=c,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},so=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var HC=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]),os=new Uint32Array(64),bb=class extends Cp{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)os[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=os[f-15],p=os[f-2],g=xn(h,7)^xn(h,18)^h>>>3,y=xn(p,17)^xn(p,19)^p>>>10;os[f]=y+os[f-7]+g+os[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=xn(c,6)^xn(c,11)^xn(c,25),p=d+h+J_(c,a,u)+HC[f]+os[f]|0,y=(xn(n,2)^xn(n,13)^xn(n,22))+Z_(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Os(os)}destroy(){this.set(0,0,0,0,0,0,0,0),Os(this.buffer)}},xb=class extends bb{A=so[0]|0;B=so[1]|0;C=so[2]|0;D=so[3]|0;E=so[4]|0;F=so[5]|0;G=so[6]|0;H=so[7]|0;constructor(){super(32)}};var Lp=Iv(()=>new xb,Rv(1));l();l();var ar=BigInt(0),Qt=BigInt(1),mc=BigInt(2),eB=BigInt(3),tB=BigInt(4),rB=BigInt(5),VC=BigInt(7),nB=BigInt(8),qC=BigInt(9),iB=BigInt(16);function Nn(t,e){let r=t%e;return r>=ar?r:e+r}function $r(t,e,r){let n=t;for(;e-- >ar;)n*=n,n%=r;return n}function X_(t,e){if(t===ar)throw new Error("invert: expected non-zero number");if(e<=ar)throw new Error("invert: expected positive modulus, got "+e);let r=Nn(t,e),n=e,i=ar,o=Qt,s=Qt,c=ar;for(;r!==ar;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==Qt)throw new Error("invert: does not exist");return Nn(i,e)}function vb(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function oB(t,e){let r=(t.ORDER+Qt)/tB,n=t.pow(e,r);return vb(t,n,e),n}function FC(t,e){let r=(t.ORDER-rB)/nB,n=t.mul(e,mc),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,mc),i),c=t.mul(o,t.sub(s,t.ONE));return vb(t,c,e),c}function jC(t){let e=eu(t),r=sB(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+VC)/iB;return(c,a)=>{let u=c.pow(a,s),d=c.mul(u,n),f=c.mul(u,i),h=c.mul(u,o),p=c.eql(c.sqr(d),a),g=c.eql(c.sqr(f),a);u=c.cmov(u,d,p),d=c.cmov(h,f,g);let y=c.eql(c.sqr(d),a),E=c.cmov(u,d,y);return vb(c,E,a),E}}function sB(t){if(t<eB)throw new Error("sqrt is not defined for small field");let e=t-Qt,r=0;for(;e%mc===ar;)e/=mc,r++;let n=mc,i=eu(t);for(;Q_(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return oB;let o=i.pow(n,e),s=(e+Qt)/mc;return function(a,u){if(a.is0(u))return u;if(Q_(a,u)!==1)throw new Error("Cannot find square root");let d=r,f=a.mul(a.ONE,o),h=a.pow(u,e),p=a.pow(u,s);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let g=1,y=a.sqr(h);for(;!a.eql(y,a.ONE);)if(g++,y=a.sqr(y),g===d)throw new Error("Cannot find square root");let E=Qt<<BigInt(d-g-1),S=a.pow(f,E);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function WC(t){return t%tB===eB?oB:t%nB===rB?FC:t%iB===qC?jC(t):sB(t)}var GC=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Sb(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=GC.reduce((n,i)=>(n[i]="function",n),e);return Ju(t,r),t}function zC(t,e,r){if(r<ar)throw new Error("invalid exponent, negatives unsupported");if(r===ar)return t.ONE;if(r===Qt)return e;let n=t.ONE,i=e;for(;r>ar;)r&Qt&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Qt;return n}function Pp(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((s,c,a)=>t.is0(c)?s:(n[a]=s,t.mul(s,c)),t.ONE),o=t.inv(i);return e.reduceRight((s,c,a)=>t.is0(c)?s:(n[a]=t.mul(s,n[a]),t.mul(s,c)),o),n}function Q_(t,e){let r=(t.ORDER-Qt)/mc,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),s=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function YC(t,e){e!==void 0&&Yn(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var Eb=class{ORDER;BITS;BYTES;isLE;ZERO=ar;ONE=Qt;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=ar)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:i,nByteLength:o}=YC(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Nn(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ar<=e&&e<this.ORDER}is0(e){return e===ar}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Qt)===Qt}neg(e){return Nn(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return Nn(e*e,this.ORDER)}add(e,r){return Nn(e+r,this.ORDER)}sub(e,r){return Nn(e-r,this.ORDER)}mul(e,r){return Nn(e*r,this.ORDER)}pow(e,r){return zC(this,e,r)}div(e,r){return Nn(e*X_(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return X_(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=WC(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?k0(e,this.BYTES):Rl(e,this.BYTES)}fromBytes(e,r=!1){ve(e);let{_lengths:n,BYTES:i,isLE:o,ORDER:s,_mod:c}=this;if(n){if(!n.includes(e.length)||e.length>i)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(i);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=o?D0(e):Uo(e);if(c&&(a=Nn(a,s)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Pp(this,e)}cmov(e,r,n){return n?r:e}};function eu(t,e={}){return new Eb(t,e)}function cB(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Ab(t){let e=cB(t);return e+Math.ceil(e/2)}function Mp(t,e,r=!1){ve(t);let n=t.length,i=cB(e),o=Ab(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?D0(t):Uo(t),c=Nn(s,e-Qt)+Qt;return r?k0(c,i):Rl(c,i)}var tu=BigInt(0),wc=BigInt(1);function df(t,e){let r=e.negate();return t?r:e}function Ib(t,e){let r=Pp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function fB(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Tb(t,e){fB(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=Yu(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function aB(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,c=Number(t&i),a=t>>s;c>n&&(c-=o,a+=wc);let u=e*n,d=u+Math.abs(c)-1,f=c===0,h=c<0,p=e%2!==0;return{nextN:a,offset:d,isZero:f,isNeg:h,isNegF:p,offsetF:u}}var _b=new WeakMap,lB=new WeakMap;function Bb(t){return lB.get(t)||1}function uB(t){if(t!==tu)throw new Error("invalid wNAF")}var Kp=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>tu;)r&wc&&(n=n.add(i)),i=i.double(),r>>=wc;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Tb(r,this.bits),o=[],s=e,c=s;for(let a=0;a<n;a++){c=s,o.push(c);for(let u=1;u<i;u++)c=c.add(s),o.push(c);s=c.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=Tb(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=aB(n,c,s);n=a,d?o=o.add(df(h,r[p])):i=i.add(df(f,r[u]))}return uB(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Tb(e,this.bits);for(let s=0;s<o.windows&&n!==tu;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=aB(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return uB(n),i}getPrecomputes(e,r,n){let i=_b.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),_b.set(r,i))),i}cached(e,r,n){let i=Bb(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Bb(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){fB(r,this.bits),lB.set(e,r),_b.delete(e)}hasCache(e){return Bb(e)!==1}};function hB(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>tu||n>tu;)r&wc&&(o=o.add(i)),n&wc&&(s=s.add(i)),i=i.double(),r>>=wc,n>>=wc;return{p1:o,p2:s}}function dB(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Sb(e),e}else return eu(t,{isLE:r})}function pB(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>tu))throw new Error(`CURVE.${a} must be positive bigint`)}let i=dB(e.p,r.Fp,n),o=dB(e.n,r.Fn,n),c=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of c)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}function $p(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}l();l();var Hp=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(_l(e),ve(r,void 0,"key"),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 n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Os(i)}update(e){return Xc(this),this.iHash.update(e),this}digestInto(e){Xc(this),ve(e,this.outputLen,"output"),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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Rb=(t,e,r)=>new Hp(t,e).update(r).digest();Rb.create=(t,e)=>new Hp(t,e);var yB=(t,e)=>(t+(t>=0?e:-e)/gB)/e;function JC(t,e,r){let[[n,i],[o,s]]=e,c=yB(s*t,r),a=yB(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<co,h=d<co;f&&(u=-u),h&&(d=-d);let p=Yu(Math.ceil(N0(r)/2))+ru;if(u<co||u>=p||d<co||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Ob(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ub(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Gu(r.lowS,"lowS"),Gu(r.prehash,"prehash"),r.format!==void 0&&Ob(r.format),r}var Db=class extends Error{constructor(e=""){super(e)}},ss={Err:Db,_tlv:{encode:(t,e)=>{let{Err:r}=ss;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=zu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?zu(i.length/2|128):"";return zu(t)+o+i+e},decode(t,e){let{Err:r}=ss,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=a,s<128)throw new r("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+s);if(c.length!==s)throw new r("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=ss;if(t<co)throw new e("integer: negative integers are not allowed");let r=zu(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=ss;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Uo(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=ss,i=ve(t,void 0,"signature"),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:c,l:a}=n.decode(2,o),{v:u,l:d}=n.decode(2,a);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=ss,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},co=BigInt(0),ru=BigInt(1),gB=BigInt(2),Vp=BigInt(3),ZC=BigInt(4);function mB(t,e={}){let r=pB("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Ju(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:a}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=bB(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(G,_,D){let{x,y:U}=_.toAffine(),L=n.toBytes(x);if(Gu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return fr(wB(N),L)}else return fr(Uint8Array.of(4),L,n.toBytes(U))}function h(G){ve(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,x=G.length,U=G[0],L=G.subarray(1);if(x===_&&(U===2||U===3)){let N=n.fromBytes(L);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let R=y(N),C;try{C=n.sqrt(R)}catch(J){let z=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(C);return(U&1)===1!==P&&(C=n.neg(C)),{x:N,y:C}}else if(x===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!E(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${x}, expected compressed=${_} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let _=n.sqr(G),D=n.mul(_,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function E(G,_){let D=n.sqr(_),x=y(G);return n.eql(D,x)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,Vp),ZC),I=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,I)))throw new Error("bad curve params: a or b");function A(G,_,D=!1){if(!n.isValid(_)||D&&n.is0(_))throw new Error(`bad point coordinate ${G}`);return _}function O(G){if(!(G instanceof $))throw new Error("Weierstrass Point expected")}function T(G){if(!a||!a.basises)throw new Error("no endo");return JC(G,a.basises,i.ORDER)}let M=C0((G,_)=>{let{X:D,Y:x,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:x};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(x,_),C=n.mul(U,_);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x:N,y:R}}),q=C0(G=>{if(G.is0()){if(e.allowInfinityPoint&&!n.is0(G.Y))return;throw new Error("bad point: ZERO")}let{x:_,y:D}=G.toAffine();if(!n.isValid(_)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(_,D))throw new Error("bad point: equation left != right");if(!G.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(G,_,D,x,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=df(x,_),D=df(U,D),_.add(D)}class ${static BASE=new $(o.Gx,o.Gy,n.ONE);static ZERO=new $(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;constructor(_,D,x){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:x}=_||{};if(!_||!n.isValid(D)||!n.isValid(x))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(x)?$.ZERO:new $(D,x,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(ve(_,void 0,"point")));return D.assertValidity(),D}static fromHex(_){return $.fromBytes(ks(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,D=!0){return Q.createCache(this,_),D||this.multiply(Vp),this}assertValidity(){q(this)}hasEvenY(){let{y:_}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(_)}equals(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(x,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:_,b:D}=o,x=n.mul(D,Vp),{X:U,Y:L,Z:N}=this,R=n.ZERO,C=n.ZERO,P=n.ZERO,V=n.mul(U,U),J=n.mul(L,L),z=n.mul(N,N),W=n.mul(U,L);return W=n.add(W,W),P=n.mul(U,N),P=n.add(P,P),R=n.mul(_,P),C=n.mul(x,z),C=n.add(R,C),R=n.sub(J,C),C=n.add(J,C),C=n.mul(R,C),R=n.mul(W,R),P=n.mul(x,P),z=n.mul(_,z),W=n.sub(V,z),W=n.mul(_,W),W=n.add(W,P),P=n.add(V,V),V=n.add(P,V),V=n.add(V,z),V=n.mul(V,W),C=n.add(C,V),z=n.mul(L,N),z=n.add(z,z),V=n.mul(z,W),R=n.sub(R,V),P=n.mul(z,J),P=n.add(P,P),P=n.add(P,P),new $(R,C,P)}add(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,Vp),W=n.mul(D,L),Y=n.mul(x,N),Z=n.mul(U,R),ue=n.add(D,x),ee=n.add(L,N);ue=n.mul(ue,ee),ee=n.add(W,Y),ue=n.sub(ue,ee),ee=n.add(D,U);let ce=n.add(L,R);return ee=n.mul(ee,ce),ce=n.add(W,Z),ee=n.sub(ee,ce),ce=n.add(x,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,Z),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,Z),V=n.add(C,V),C=n.sub(Y,V),V=n.add(Y,V),P=n.mul(C,V),Y=n.add(W,W),Y=n.add(Y,W),Z=n.mul(J,Z),ee=n.mul(z,ee),Y=n.add(Y,Z),Z=n.sub(W,Z),Z=n.mul(J,Z),ee=n.add(ee,Z),W=n.mul(Y,ee),P=n.add(P,W),W=n.mul(ce,ee),C=n.mul(ue,C),C=n.sub(C,W),W=n.mul(ue,Y),V=n.mul(ce,V),V=n.add(V,W),new $(C,P,V)}subtract(_){return this.add(_.negate())}is0(){return this.equals($.ZERO)}multiply(_){let{endo:D}=e;if(!i.isValidNot0(_))throw new Error("invalid scalar: out of range");let x,U,L=N=>Q.cached(this,N,R=>Ib($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(_),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),x=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);x=N,U=R}return Ib($,[x,U])[0]}multiplyUnsafe(_){let{endo:D}=e,x=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===co||x.is0())return $.ZERO;if(_===ru)return x;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=hB($,x,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(x,_)}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===ru?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===ru?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return Gu(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Ds(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let X=i.BITS,Q=new Kp($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function wB(t){return Uint8Array.of(t?2:3)}function bB(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function XC(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ns,i=Object.assign(bB(t.Fp,r),{seed:Ab(r.ORDER)});function o(p){try{let g=r.fromBytes(p);return r.isValidNot0(g)}catch{return!1}}function s(p,g){let{publicKey:y,publicKeyUncompressed:E}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==E?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return Mp(ve(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(g)}function u(p){let{secretKey:g,publicKey:y,publicKeyUncompressed:E}=i;if(!Wu(p)||"_lengths"in r&&r._lengths||g===y)return;let S=ve(p,void 0,"key").length;return S===y||S===E}function d(p,g,y=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(g)===!1)throw new Error("second arg must be public key");let E=r.fromBytes(p);return t.fromBytes(g).multiply(E).toBytes(y)}let f={isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:c},h=$p(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:h,Point:t,utils:f,lengths:i})}function xB(t,e,r={}){_l(e),Ju(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||Ns,i=r.hmac||((D,x)=>Rb(e,D,x)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=XC(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*gB<o.ORDER;function E(D){let x=c>>ru;return D>x}function S(D,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return x}function I(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(D,x){Ob(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return ve(D,L)}class O{r;s;recovery;constructor(x,U,L){if(this.r=S("r",x),this.s=S("s",U),L!=null){if(I(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(x,U=g.format){A(x,U);let L;if(U==="der"){let{r:P,s:V}=ss.toSig(ve(x));return new O(P,V)}U==="recovered"&&(L=x[0],U="compact",x=x.subarray(1));let N=p.signature/2,R=x.subarray(0,N),C=x.subarray(N,N*2);return new O(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(x,U){return this.fromBytes(ks(x),U)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new O(this.r,this.s,x)}recoverPublicKey(x){let{r:U,s:L}=this,N=this.assertRecovery(),R=N===2||N===3?U+c:U;if(!o.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let C=o.toBytes(R),P=t.fromBytes(fr(wB((N&1)===0),C)),V=s.inv(R),J=M(ve(x,void 0,"msgHash")),z=s.create(-J*V),W=s.create(L*V),Y=t.BASE.multiplyUnsafe(z).add(P.multiplyUnsafe(W));if(Y.is0())throw new Error("invalid recovery: point at infinify");return Y.assertValidity(),Y}hasHighS(){return E(this.s)}toBytes(x=g.format){if(Ob(x),x==="der")return ks(ss.hexFromSig(this));let{r:U,s:L}=this,N=s.toBytes(U),R=s.toBytes(L);return x==="recovered"?(I(),fr(Uint8Array.of(this.assertRecovery()),N,R)):fr(N,R)}toHex(x){return Ds(this.toBytes(x))}}let T=r.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let U=Uo(x),L=x.length*8-a;return L>0?U>>BigInt(L):U},M=r.bits2int_modN||function(x){return s.create(T(x))},q=Yu(a);function j(D){return kv("num < 2^"+a,D,co,q),s.toBytes(D)}function $(D,x){return ve(D,void 0,"message"),x?ve(e(D),void 0,"prehashed message"):D}function X(D,x,U){let{lowS:L,prehash:N,extraEntropy:R}=Ub(U,g);D=$(D,N);let C=M(D),P=s.fromBytes(x);if(!s.isValidNot0(P))throw new Error("invalid private key");let V=[j(P),j(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(ve(Y,void 0,"extraEntropy"))}let J=fr(...V),z=C;function W(Y){let Z=T(Y);if(!s.isValidNot0(Z))return;let ue=s.inv(Z),ee=t.BASE.multiply(Z).toAffine(),ce=s.create(ee.x);if(ce===co)return;let Ie=s.create(ue*s.create(z+ce*P));if(Ie===co)return;let Pe=(ee.x===ce?0:2)|Number(ee.y&ru),Ge=Ie;return L&&E(Ie)&&(Ge=s.neg(Ie),Pe^=1),new O(ce,Ge,y?void 0:Pe)}return{seed:J,k2sig:W}}function Q(D,x,U={}){let{seed:L,k2sig:N}=X(D,x,U);return Nv(e.outputLen,s.BYTES,i)(L,N).toBytes(U.format)}function G(D,x,U,L={}){let{lowS:N,prehash:R,format:C}=Ub(L,g);if(U=ve(U,void 0,"publicKey"),x=$(x,R),!Wu(D)){let P=D instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}A(D,C);try{let P=O.fromBytes(D,C),V=t.fromBytes(U);if(N&&P.hasHighS())return!1;let{r:J,s:z}=P,W=M(x),Y=s.inv(z),Z=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(Z).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,x,U={}){let{prehash:L}=Ub(U,g);return x=$(x,L),O.fromBytes(D,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:Q,verify:G,recoverPublicKey:_,Signature:O,hash:e})}var jp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},QC={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},eL=BigInt(0),kb=BigInt(2);function tL(t){let e=jp.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=$r(d,r,e)*d%e,h=$r(f,r,e)*d%e,p=$r(h,kb,e)*u%e,g=$r(p,i,e)*p%e,y=$r(g,o,e)*g%e,E=$r(y,c,e)*y%e,S=$r(E,a,e)*E%e,I=$r(S,c,e)*y%e,A=$r(I,r,e)*d%e,O=$r(A,s,e)*g%e,T=$r(O,n,e)*u%e,M=$r(T,kb,e);if(!qp.eql(qp.sqr(M),t))throw new Error("Cannot find square root");return M}var qp=eu(jp.p,{sqrt:tL}),bc=mB(jp,{Fp:qp,endo:QC}),dn=xB(bc,Lp),EB={};function Fp(t,...e){let r=EB[t];if(r===void 0){let n=Lp(Dv(t));r=fr(n,n),EB[t]=r}return Lp(fr(r,...e))}var Cb=t=>t.toBytes(!0).slice(1),Lb=t=>t%kb===eL;function Nb(t){let{Fn:e,BASE:r}=bc,n=e.fromBytes(t),i=r.multiply(n);return{scalar:Lb(i.y)?n:e.neg(n),bytes:Cb(i)}}function SB(t){let e=qp;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),i=e.sqrt(n);Lb(i)||(i=e.neg(i));let o=bc.fromAffine({x:t,y:i});return o.assertValidity(),o}var ff=Uo;function AB(...t){return bc.Fn.create(ff(Fp("BIP0340/challenge",...t)))}function vB(t){return Nb(t).bytes}function rL(t,e,r=Ns(32)){let{Fn:n}=bc,i=ve(t,void 0,"message"),{bytes:o,scalar:s}=Nb(e),c=ve(r,32,"auxRand"),a=n.toBytes(s^ff(Fp("BIP0340/aux",c))),u=Fp("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Nb(u),h=AB(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!TB(p,i,o))throw new Error("sign: Invalid signature produced");return p}function TB(t,e,r){let{Fp:n,Fn:i,BASE:o}=bc,s=ve(t,64,"signature"),c=ve(e,void 0,"message"),a=ve(r,32,"publicKey");try{let u=SB(ff(a)),d=ff(s.subarray(0,32));if(!n.isValidNot0(d))return!1;let f=ff(s.subarray(32,64));if(!i.isValidNot0(f))return!1;let h=AB(i.toBytes(d),Cb(u),c),p=o.multiplyUnsafe(f).add(u.multiplyUnsafe(i.neg(h))),{x:g,y}=p.toAffine();return!(p.is0()||!Lb(y)||g!==d)}catch{return!1}}var Wp=(()=>{let r=(n=Ns(48))=>Mp(n,jp.n);return{keygen:$p(r,vB),getPublicKey:vB,sign:rL,verify:TB,Point:bc,utils:{randomSecretKey:r,taggedHash:Fp,lift_x:SB,pointToBytes:Cb},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function nL(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function BB(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function Pb(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function IB(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Mb(t){if(!Array.isArray(t))throw new Error("array expected")}function RB(t,e){if(!BB(!0,e))throw new Error(`${t}: array of strings expected`)}function iL(t,e){if(!BB(!1,e))throw new Error(`${t}: array of numbers expected`)}function oL(...t){let e=o=>o,r=(o,s)=>c=>o(s(c)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function sL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;RB("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(Mb(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${t}`);return e[o]})),decode:i=>(Mb(i),i.map(o=>{Pb("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function cL(t=""){return Pb("join",t),{encode:e=>(RB("join.decode",e),e.join(t)),decode:e=>(Pb("join.decode",e),e.split(t))}}function _B(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Mb(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(IB(c),c<0||c>=e)throw new Error(`invalid integer: ${c}`);return c}),s=o.length;for(;;){let c=0,a=!0;for(let u=n;u<s;u++){let d=o[u],f=e*c,h=f+d;if(!Number.isSafeInteger(h)||f/e!==c||h-d!==f)throw new Error("convertRadix: carry overflow");let p=h/r;c=h%r;let g=Math.floor(p);if(o[u]=g,!Number.isSafeInteger(g)||g*r+c!==h)throw new Error("convertRadix: carry overflow");if(a)g?a=!1:n=u;else continue}if(i.push(c),a)break}for(let c=0;c<t.length-1&&t[c]===0;c++)i.push(0);return i.reverse()}function aL(t){IB(t);let e=2**8;return{encode:r=>{if(!nL(r))throw new Error("radix.encode input should be Uint8Array");return _B(Array.from(r),e,t)},decode:r=>(iL("radix.decode",r),Uint8Array.from(_B(r,t,e)))}}var uL=t=>oL(aL(58),sL(t),cL("")),nu=uL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var UB=new Uint8Array([231,1]),ht=class t{#e;#t={prefix:UB,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:Ar(e);if(!r||r.length!==33)throw new Bs("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!dn.utils.isValidPublicKey(r))throw new Bs("Invalid argument: not a valid secp256k1 compressed point","CONSTRUCTOR_ERROR",{keyBytes:r});this.#e=new Uint8Array(r),this.#t.encoded=this.encode(),this.#t.key=[...this.#t.prefix,...this.compressed]}get compressed(){return new Uint8Array(this.#e)}get uncompressed(){return dn.Point.fromBytes(this.compressed).toBytes(!1)}get xOnly(){return this.compressed.slice(1)}get parity(){let e=this.compressed[0];if(![2,3].includes(e))throw new Bs("Invalid state: parity byte must be 2 or 3","PARITY_ERROR",{parity:e});return e}get isEven(){return this.parity===2}get x(){return this.compressed.slice(1,33)}get y(){return this.uncompressed.slice(33,65)}get multibase(){return{prefix:new Uint8Array(this.#t.prefix),key:[...this.#t.key],encoded:this.#t.encoded}}get hex(){return Ct(this.compressed)}get point(){return{x:this.x,y:this.y}}bip340(){return this.xOnly}decode(){return nu.decode(this.multibase.encoded.slice(1))}encode(){let e=Array.from(this.compressed),r=Array.from(UB);return r.push(...e),"z"+nu.encode(Uint8Array.from(r))}verify(e,r,n){if(n??={scheme:"schnorr"},n.scheme==="ecdsa")return dn.verify(e,r,this.compressed);if(n.scheme==="schnorr")return Wp.verify(e,r,this.x);throw new Bs(`Invalid scheme: ${n.scheme}.`,"VERIFY_SIGNATURE_ERROR",n)}equals(e){return Qc(this.compressed,e.compressed)}toJSON(){return{hex:this.hex,multibase:this.multibase,point:{x:Array.from(this.x),y:Array.from(this.y),parity:this.parity}}}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromJSON(e){return new t(Uint8Array.from([e.point.parity,...e.point.x]))}};l();var OB=new Uint8Array([129,38]),dL=Ct(Oe(OB)),Hr=class t{#e;#t;#n;constructor(e){let r=e instanceof Uint8Array,n=typeof e=="bigint";if(!r&&!n)throw new jn("Invalid entropy: must be a valid byte array (32) or bigint","CONSTRUCTOR_ERROR");if(r&&e.length===32&&(this.#e=new Uint8Array(e),this.#t=t.toSecret(this.#e)),n&&e>=1n&&e<dn.Point.Fn.ORDER&&(this.#e=t.toBytes(e),this.#t=e),!this.#e||this.#e.length!==32)throw new jn("Invalid bytes: must be a valid 32-byte secret key","CONSTRUCTOR_ERROR");if(!this.#t||this.#t<1n||this.#t>=dn.Point.Fn.ORDER)throw new jn("Invalid seed: must be valid bigint","CONSTRUCTOR_ERROR");this.#n=this.encode()}destroy(){this.#e&&this.#e.fill(0),this.#t=void 0,this.#n=""}get bytes(){return new Uint8Array(this.#e)}get seed(){return BigInt(this.#t)}get hex(){return Ct(this.bytes)}get multibase(){return this.#n}encode(){let e=Array.from(this.bytes),r=Array.from(OB);return r.push(...e),"z"+nu.encode(Uint8Array.from(r))}equals(e){return Qc(this.bytes,e.bytes)}computePublicKey(){return new ht(dn.getPublicKey(this.bytes))}toJSON(){return{type:"Secp256k1SecretKey"}}exportJSON(){return{bytes:Array.from(this.bytes),seed:this.seed.toString(),hex:this.hex}}toString(){return"[Secp256k1SecretKey]"}[Symbol.for("nodejs.util.inspect.custom")](){return"[Secp256k1SecretKey]"}isValid(){return dn.utils.isValidSecretKey(this.bytes)}hasValidPublicKey(){try{return this.computePublicKey(),!0}catch{return!1}}sign(e,r){if(r??={scheme:"schnorr"},r.scheme==="ecdsa")return dn.sign(e,this.bytes);if(r.scheme==="schnorr")return Wp.sign(e,this.bytes);throw new jn(`Invalid scheme: ${r.scheme}.`,"SIGN_ERROR",r)}static decode(e){let r=nu.decode(e.slice(1));if(r.length!==34)throw new jn("Invalid argument: must be 34 byte secretKeyMultibase","DECODE_MULTIBASE_ERROR");let n=r.slice(0,2);if(Ct(Oe(n))!==dL)throw new jn(`Invalid prefix: malformed multibase prefix ${n}`,"DECODE_MULTIBASE_ERROR");return r}static fromJSON(e){return new t(new Uint8Array(e.bytes))}static toSecret(e){return e.reduce((r,n)=>r<<8n|BigInt(n),0n)}static toBytes(e){let r=Uint8Array.from({length:32},(n,i)=>Number(e>>BigInt(8*(31-i))&BigInt(255)));if(!dn.utils.isValidSecretKey(r))throw new jn("Invalid secret key: secret out of valid range","SET_PRIVATE_KEY_ERROR");return new Uint8Array(r)}static fromBigInt(e){return new t(t.toBytes(e))}static random(){let e;do e=Tr(32);while(!dn.utils.isValidSecretKey(e));return e}static generate(){let e=this.random();return new t(e)}static getPublicKey(e){return new t(e).computePublicKey()}};var ao=class t{#e;#t;constructor(e={}){if(!e.publicKey&&!e.secretKey)throw new wn("Argument missing: must at least provide a publicKey","CONSTRUCTOR_ERROR");if(e.secretKey instanceof Uint8Array?this.#e=new Hr(e.secretKey):e.secretKey instanceof Hr&&(this.#e=e.secretKey),e.publicKey instanceof ht?this.#t=e.publicKey:e.publicKey instanceof Uint8Array?this.#t=new ht(e.publicKey):this.#t=this.#e.computePublicKey(),this.#e&&e.publicKey){let r=this.#e.computePublicKey();if(!this.#t.equals(r))throw new wn("Public key does not match secret key","CONSTRUCTOR_ERROR")}}get secretKey(){if(!this.#e)throw new wn("Secret key not available","SECRET_KEY_ERROR");if(!this.#e.isValid())throw new wn("Secret key is not valid","SECRET_KEY_ERROR");return this.#e}set publicKey(e){if(this.#e){let r=this.#e.computePublicKey();if(!e.equals(r))throw new wn("Public key does not match secret key","PUBLIC_KEY_ERROR")}this.#t=e}get publicKey(){return this.#t}get hasSecretKey(){return!!this.#e}get raw(){return{public:this.publicKey.compressed,secret:this.#e?this.#e.bytes:void 0}}get hex(){return{public:this.publicKey.hex,secret:this.#e?this.#e.hex:void 0}}get multibase(){return{publicKeyMultibase:this.#t.multibase.encoded,secretKeyMultibase:this.#e?this.#e.multibase:""}}toJSON(){return{publicKey:this.publicKey.toJSON()}}exportJSON(){if(!this.#e)throw new wn("Cannot export: secret key required. Use publicKey.toJSON() for public-key-only pairs.","SERIALIZE_ERROR");return{secretKey:this.#e.exportJSON(),publicKey:this.publicKey.toJSON()}}[Symbol.for("nodejs.util.inspect.custom")](){return`[SchnorrKeyPair ${this.publicKey.hex}]`}static fromJSON(e){return new t({secretKey:Hr.fromJSON(e.secretKey),publicKey:ht.fromJSON(e.publicKey)})}static fromSecret(e){let r=typeof e=="string"?Ar(e):e;if(r.length!==32)throw new wn("Invalid arg: must be 32 byte secret key","FROM_SECRET_KEY_ERROR");let n=new Hr(r),i=n.computePublicKey();return new t({secretKey:n,publicKey:i})}static fromBigInt(e){let r=Hr.fromBigInt(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}static toHex(e){return Ct(e)}static equals(e,r){return e.publicKey.equals(r.publicKey)}static generate(){let e=Hr.random(),r=new Hr(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}};l();l();l();var xr=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in _o))throw new mt('Expected "idType" to be "KEY" or "EXTERNAL"',Lt,{idType:n});if(i!==1)throw new mt('Expected "version" to be 1',Lt,{version:i});if(typeof o!="string")throw new mt('Expected "network" to be a known network name',Lt,{network:o});let s=qu[o];if(s===void 0)throw new mt('Invalid "network" name',Lt,{network:o});if(n==="KEY")try{new ht(e)}catch{throw new mt('Expected "genesisBytes" to be a valid compressed secp256k1 public key',Lt,{genesisBytes:e})}else if(e.length!==32)throw new mt('Expected "genesisBytes" to be a 32-byte hash for EXTERNAL identifiers',Lt,{genesisBytes:e});let c=n==="KEY"?"k":"x",a=i-1<<4|s,u=new Uint8Array([a,...e]);return`did:btcr2:${Hc.encodeFromBytes(c,u)}`}static decode(e){let r=e.split(":");if(r.length!==3)throw new mt(`Invalid did: ${e}`,Lt,{identifier:e});let[n,i,o]=r;if(n!=="did")throw new mt(`Invalid did: ${e}`,Lt,{identifier:e});if(i!=="btcr2")throw new mt(`Invalid did method: ${i}`,pl,{identifier:e});if(!o)throw new mt(`Invalid method-specific id: ${e}`,Lt,{identifier:e});let{prefix:s,bytes:c}=Hc.decodeToBytes(o);if(!["x","k"].includes(s))throw new mt(`Invalid hrp: ${s}`,Lt,{identifier:e});if(!c||c.length<1)throw new mt(`Failed to decode id: ${o}`,Lt,{identifier:e});let a=s==="k"?"KEY":"EXTERNAL",u=c[0]>>>4;if(u!==0)throw new mt(`Invalid btcr2_version (expected 0): ${u}`,Lt,{identifier:e});let d=1,f=c[0]&15,h=qu[f],p;if(typeof h=="string")p=h;else if(f>=12&&f<=14)p=f-11;else throw new mt(`Invalid network: ${f}`,Lt,{identifier:e});let g=c.slice(1);if(a==="KEY")try{new ht(g)}catch{throw new mt(`Invalid genesisBytes: ${g}`,Lt,{identifier:e})}else if(g.length!==32)throw new mt(`Invalid genesisBytes: ${g}`,Lt,{identifier:e});return{idType:a,hrp:s,version:d,network:p,genesisBytes:g}}static generate(){let e=ao.generate(),r=this.encode(e.publicKey.compressed,{idType:"KEY",version:1,network:"regtest"});return{keyPair:e.exportJSON(),did:r}}static getPublicKey(e){let{idType:r,genesisBytes:n}=t.decode(e);if(r!=="KEY")throw new mt(`Cannot extract public key from EXTERNAL DID: ${e}. EXTERNAL DIDs encode a document hash, not a public key.`,Lt,{did:e,idType:r});return new ht(n)}static isValid(e){try{return this.decode(e),!0}catch{return!1}}};var fn=class{static parseBitcoinAddress(e){if(!e.startsWith("bitcoin:"))throw new tt("Invalid Bitcoin URI format","BEACON_SERVICE_ERROR",{uri:e});return e.replace("bitcoin:","").split("?")[0]}static isBeaconService(e){return!(!Kr.isDidService(e)||!["SingletonBeacon","CASBeacon","SMTBeacon"].includes(e.type)||[e.serviceEndpoint].flat().some(r=>typeof r=="string"&&!r.startsWith("bitcoin:")))}static getBeaconServices(e){return e.service.filter(this.isBeaconService)??[]}static createBeaconServices(e,r){try{return["p2pkh","p2wpkh","p2tr"].map(i=>this.createBeaconService(e,i,r))}catch(n){throw new rr("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=xr.decode(e),o=Io(i.network),s=i.genesisBytes,c=`${e}#initial${r.toUpperCase()}`,u=`bitcoin:${r==="p2tr"?Ss(s.slice(1,33),void 0,o).address:r==="p2wpkh"?vs(s,o).address:ki(s,o).address}`;return{id:c,type:n,serviceEndpoint:u}}catch(i){throw new rr("Failed to create beacon service: "+i.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:n})}}static generateBeaconServices({id:e,publicKey:r,network:n,beaconType:i}){try{let o=ki(r,n).address,s=vs(r,n).address,c=Ss(r.slice(1,33),void 0,n).address;if(!o||!s||!c)throw new Gt("Failed to generate bitcoin addresses");return[{id:`${e}#initialP2PKH`,type:i,serviceEndpoint:`bitcoin:${o}`},{id:`${e}#initialP2WPKH`,type:i,serviceEndpoint:`bitcoin:${s}`},{id:`${e}#initialP2TR`,type:i,serviceEndpoint:`bitcoin:${c}`}]}catch(o){throw new rr("Failed to create beacon services: "+o.message,"BEACON_SERVICE_ERROR",{id:e,publicKey:r,network:n,beaconType:i})}}static parseBeaconServiceEndpoint(e){return{...e,serviceEndpoint:e.serviceEndpoint.replace("bitcoin:","")}}static getBeaconServicesMap(e){return new Map(e.map(this.parseBeaconServiceEndpoint).map(r=>[r.serviceEndpoint,r]))}static getBeaconServiceIds(e){return this.getBeaconServices(e).map(r=>r.id)}};function DB(t){if(!t)return null;let e=t.trim().split(/\s+/);if(e.length!==3||e[0]!=="OP_RETURN"||e[1]!=="OP_PUSHBYTES_32")return null;let r=e[2];return/^[0-9a-fA-F]{64}$/.test(r)?r.toLowerCase():null}var kB=class{static async indexer(e,r){let n=new Map,i=await r.rest.block.count();for(let o of e){n.set(o,[]);let s=await r.rest.address.getTxs(fn.parseBitcoinAddress(o.serviceEndpoint));if(!(!s||!s.length))for(let c of s){let a=c.vout.slice(-1)[0];if(!a)continue;let u=DB(a.scriptpubkey_asm);if(!u)continue;let d=i-c.status.block_height+1;n.get(o)?.push({tx:c,signalBytes:u,blockMetadata:{confirmations:d,height:c.status.block_height,time:c.status.block_time}})}}return n}static async fullnode(e,r){let n=new Map;for(let u of e)n.set(u,[]);let i=r.rpc;if(!i)throw new rt("RPC connection is not available","RPC_CONNECTION_ERROR",r);let o=await i.getBlockCount(),s=fn.getBeaconServicesMap(e),c=0,a=await r.rpc.getBlock({height:c});for(console.info("Searching for beacon signals, please wait ...");a.height<=o;){for(let u of a.tx)if(u.txid!==T0)for(let d of u.vin){if(d.coinbase||d.txinwitness&&d.txinwitness.length===1&&d.txinwitness[0]===A0||!d.txid||d.vout===void 0)continue;let f=await i.getRawTransaction(d.txid,2);if(!f.vout[d.vout])continue;let h=f.vout[d.vout].scriptPubKey;if(!h.address)continue;let p=s.get(h.address);if(!p)continue;let g=f.vout[d.vout].scriptPubKey.asm,y=DB(g);y&&(console.info(`Tx ${u.txid} contains beacon service address ${h.address} and OP_RETURN!`,u),n.get(p)?.push({tx:u,signalBytes:y,blockMetadata:{height:a.height,time:a.time,confirmations:a.confirmations}}))}if(c+=1,c>o){console.info(`Chain tip reached ${c}, breaking ...`);break}a=await i.getBlock({height:c})}return n}};l();l();l();l();l();l();l();var Vte=new Uint8Array(0);function NB(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}l();function fL(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,E=0,S=0,I=g.length;S!==I&&g[S]===0;)S++,y++;for(var A=(I-S)*d+1>>>0,O=new Uint8Array(A);S!==I;){for(var T=g[S],M=0,q=A-1;(T!==0||M<E)&&q!==-1;q--,M++)T+=256*O[q]>>>0,O[q]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");E=M,S++}for(var j=A-E;j!==A&&O[j]===0;)j++;for(var $=a.repeat(y);j<A;++j)$+=t.charAt(O[j]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var E=0,S=0;g[y]===a;)E++,y++;for(var I=(g.length-y)*u+1>>>0,A=new Uint8Array(I);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=I-1;(O!==0||T<S)&&M!==-1;M--,T++)O+=c*A[M]>>>0,A[M]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=T,y++}if(g[y]!==" "){for(var q=I-S;q!==I&&A[q]===0;)q++;for(var j=new Uint8Array(E+(I-q)),$=E;q!==I;)j[$++]=A[q++];return j}}}function p(g){var y=h(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var lL=fL,hL=lL,CB=hL;var Kb=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},$b=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let i=r.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return LB(this,e)}},Hb=class{decoders;constructor(e){this.decoders=e}or(e){return LB(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function LB(t,e){return new Hb({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var Vb=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Kb(e,r,n),this.decoder=new $b(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function pL({name:t,prefix:e,encode:r,decode:n}){return new Vb(t,e,r,n)}function qb({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=CB(r,t);return pL({prefix:e,name:t,encode:n,decode:o=>NB(i(o))})}var lf=qb({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Xte=qb({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var iu=class{cryptosuite;constructor(e){this.cryptosuite=e}addProof(e,r){let n=this.cryptosuite.createProof(e,r);if(!n.type||!n.verificationMethod||!n.proofPurpose)throw new Jr("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Ao,{config:r,proof:n});if(r.domain&&n.domain!==r.domain)throw new Jr("Domain mismatch: proof.domain !== config.domain",Ao,{config:r,proof:n});if(r.challenge&&n.challenge!==r.challenge)throw new Jr("Challenge mismatch options and challenge passed",Ao,{config:r,proof:n});let i=e;return i.proof=n,i}verifyProof(e,r,n,i,o){let s=JSON.parse(e),c=s.proof;if(!c.type||!c.verificationMethod||!c.proofPurpose)throw new Jr("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Wn,s);if(r&&r!==c.proofPurpose)throw new Jr("Proof purpose mismatch: proof.proofPurpose !== expectedPurpose",Wn,{proof:c,expectedPurpose:r});if(o&&o!==c.challenge)throw new Jr("Challenge mismatch: proof.challenge !== expectedChallenge","INVALID_CHALLENGE_ERROR",{proof:c,expectedChallenge:o});if(i){if(Array.isArray(i)&&i.length){if(i.length!==c.domain?.length)throw new Jr("Domain mismatch: expectedDomain length does not match proof.domain length",Wn,{proof:c,expectedDomain:i});if(i.every(u=>c.domain?.includes(u)))throw new Jr("Domain mismatch: expectedDomain and proof.domain do not match",Wn,{proof:c,expectedDomain:i})}else if(c.domain!==i)throw new Jr("Domain mismatch: proof.domain !== expectedDomain",Wn,{proof:c,expectedDomain:i})}let a=this.cryptosuite.verifyProof(s);return a.mediaType=n,a}};var ou=class{type="DataIntegrityProof";cryptosuite="bip340-jcs-2025";multikey;constructor(e){this.multikey=e}toDataIntegrityProof(){return new iu(this)}createProof(e,r){r["@context"]=e["@context"]??r["@context"];let n=this.proofConfiguration(r),i=this.transformDocument(e,r),o=this.generateHash(n,i),s=this.proofSerialization(o,r),c=r;return c.proofValue=lf.encode(s),c.cryptosuite=this.cryptosuite,c.type=this.type,c}verifyProof(e){let{proof:r,...n}=e,{proofValue:i,...o}=r,s=this.transformDocument(n,o),c=this.proofConfiguration(o),a=this.generateHash(c,s),u=lf.decode(e.proof.proofValue),d=this.proofVerification(a,u,o);return{verified:d,verifiedDocument:d?e:void 0}}transformDocument(e,r){if(r.type!==this.type)throw new tt("Type mismatch: config.type !== this.type",Wn,{config:r,this:this});if(r.cryptosuite!==this.cryptosuite)throw new tt("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Wn,{config:r,this:this});return tr(e)}generateHash(e,r){let n=Oe(ws(e)),i=Oe(ws(r)),o=ut(n,i);return Oe(o)}proofConfiguration(e){if(e.type!==this.type)throw new So("Type mismatch: config.type !== this.type",Ao,{config:e,this:this});if(e.cryptosuite!==this.cryptosuite)throw new So("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Ao,{config:e,this:this});if(e.created&&!Bo.isValidXsdDateTime(e.created))throw new So('Invalid config: "created" must be a valid XMLSchema DateTime string',Ao,e);return tr(e)}proofSerialization(e,r){if(r.verificationMethod!==this.multikey.fullId())throw new So("Id mismatch: config.verificationMethod !== this.multikey.fullId()",cv,{config:r,this:this});return this.multikey.sign(e)}proofVerification(e,r,n){if(n.verificationMethod!==this.multikey.fullId())throw new So("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Wn,{config:n,this:this});return this.multikey.verify(r,e)}};l();l();l();var cs=class t{static type="Multikey";id;controller;#e;#t;constructor({id:e,controller:r,keyPair:n,externalSigner:i}){if(!n)throw new bn('Argument missing: "keyPair" required',"CONSTRUCTOR_ERROR");if(!n.publicKey)throw new bn('Argument missing: "keyPair" must contain a "publicKey"',"CONSTRUCTOR_ERROR");if(i){let o=i.publicKey,s=n.publicKey.compressed;if(o.length!==s.length||!o.every((c,a)=>c===s[a]))throw new bn("externalSigner.publicKey does not match keyPair.publicKey.compressed","CONSTRUCTOR_ERROR")}this.id=e,this.controller=r,this.#e=n,this.#t=i}get keyPair(){return this.#e}get publicKey(){return this.#e.publicKey}get secretKey(){try{return this.#e.secretKey}catch{throw new bn("Cannot get: no secretKey","PRIVATE_KEY_ERROR")}}toCryptosuite(){return new ou(this)}sign(e){if(this.#t)return this.#t.sign(e,"bip340");if(!this.signer)throw new bn("Cannot sign: no secretKey","SIGN_ERROR");return Ir.sign(e,this.secretKey.bytes,Tr(32))}verify(e,r){return Ir.verify(e,r,this.publicKey.x)}fullId(){return this.id.startsWith("#")?`${this.controller}${this.id}`:this.id}toVerificationMethod(){return{id:this.id,type:t.type,controller:this.controller,publicKeyMultibase:this.publicKey.multibase.encoded}}get signer(){return!!this.#t||!!this.#e.secretKey}toJSON(){return{id:this.id,controller:this.controller,fullId:this.fullId(),signer:this.signer,keyPair:this.keyPair.exportJSON(),verificationMethod:this.toVerificationMethod()}}static create({id:e,controller:r,keyPair:n}){return new t({id:e,controller:r,keyPair:n})}static fromSecretKey(e,r,n){let i=new Hr(n),o=i.computePublicKey(),s=new ao({publicKey:o,secretKey:i});return new t({id:e,controller:r,keyPair:s})}static fromSigner(e,r,n){let i=new ht(n.publicKey),o=new ao({publicKey:i});return new t({id:e,controller:r,keyPair:o,externalSigner:n})}static fromPublicKey({id:e,controller:r,publicKeyBytes:n}){let i=new ht(n),o=new ao({publicKey:i});return new t({id:e,controller:r,keyPair:o})}static fromVerificationMethod({id:e,controller:r,publicKeyMultibase:n}){if(!n)throw new bn("Invalid publicKeyMultibase: cannot be undefined",yl,{publicKeyMultibase:n});let i=lf.decode(n);if(i.length!==35)throw new bn(`Invalid publicKeyMultibase length: ${i.length}`,yl,{publicKeyMultibase:n});if(i[0]!==231||i[1]!==1)throw new bn(`Invalid publicKeyMultibase prefix: expected secp256k1 multicodec [0xe7, 0x01], got [0x${i[0]?.toString(16)??"??"}, 0x${i[1]?.toString(16)??"??"}]`,yl,{publicKeyMultibase:n});let o=i.slice(2),s=new ao({publicKey:o});return new t({id:e,controller:r,keyPair:s})}};l();l();l();l();l();var yL=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],su="Multikey",cu="zQ3s",ln="did:btcr2:_",Pre="",gL=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function mL(t){if(!Kr.isDidVerificationMethod(t))return!1;let{type:e,publicKeyMultibase:r}=t;return e===su&&typeof r=="string"&&r.startsWith(cu)}var Fb=class{id;type;controller;publicKeyMultibase;secretKeyMultibase;constructor({id:e,type:r,controller:n,publicKeyMultibase:i,secretKeyMultibase:o}){if(r!==su)throw new Ze(`Invalid verification method: type must be "${su}"`,Ue,{id:e,type:r});if(typeof i!="string"||!i.startsWith(cu))throw new Ze(`Invalid verification method: publicKeyMultibase must start with "${cu}"`,Ue,{id:e,publicKeyMultibase:i});this.id=e,this.type=r,this.controller=n,this.publicKeyMultibase=i,this.secretKeyMultibase=o,o||delete this.secretKeyMultibase}},hn=class t{id;"@context"=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"];verificationMethod;authentication;assertionMethod;capabilityInvocation;capabilityDelegation;service;deactivated;constructor(e){if(!e.id)throw new Ze("DID Document must have an id",Ue,e);let r=e.id.includes("k1")?_o.KEY:_o.EXTERNAL,n=e.id===ln,{id:i,verificationMethod:o,service:s}=e;if(!n){if(!t.isValidId(i))throw new Ze(`Invalid id: ${i}`,Ue,e);if(!t.isValidVerificationMethods(o))throw new Ze("Invalid verificationMethod: "+o,Ue,e);if(!t.isValidServices(s))throw new Ze("Invalid service: "+s,Ue,e)}if(this.id=e.id,this.verificationMethod=e.verificationMethod||[],this.service=e.service||[],this["@context"]=e["@context"]||["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],r===_o.KEY){let c=`${this.id}#initialKey`;this.authentication=e.authentication||[c],this.assertionMethod=e.assertionMethod||[c],this.capabilityInvocation=e.capabilityInvocation||[c],this.capabilityDelegation=e.capabilityDelegation||[c]}else this.authentication=e.authentication,this.assertionMethod=e.assertionMethod,this.capabilityInvocation=e.capabilityInvocation,this.capabilityDelegation=e.capabilityDelegation;t.sanitize(this),n?this.validateGenesis():t.validate(this)}toJSON(){return{id:this.id,"@context":this["@context"],verificationMethod:this.verificationMethod,authentication:this.authentication,assertionMethod:this.assertionMethod,capabilityInvocation:this.capabilityInvocation,capabilityDelegation:this.capabilityDelegation,service:this.service,deactivated:this.deactivated}}static fromKeyIdentifier(e,r,n){e=e.includes("#")?e:`${e}#initialKey`;let i={id:e,verificationMethod:[new Fb({id:e,type:"Multikey",controller:e,publicKeyMultibase:r})],service:n};return new t(i)}static fromExternalIdentifier(e){return new t(e)}static sanitize(e){for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}static isValid(e){if(!this.isValidContext(e?.["@context"]))throw new Ze('Invalid "@context"',Ue,e);if(!this.isValidId(e?.id))throw new Ze('Invalid "id"',Ue,e);if(!this.isValidVerificationMethods(e?.verificationMethod))throw new Ze('Invalid "verificationMethod"',Ue,e);if(!this.isValidServices(e?.service))throw new Ze('Invalid "service"',Ue,e);if(!this.isValidVerificationRelationships(e))throw new Ze("Invalid verification relationships",Ue,e);return!0}static isValidContext(e){return!Array.isArray(e)||e.length===0?!1:yL.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return xr.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(mL)}static isValidServices(e){return Array.isArray(e)&&e.every(XT)}static isValidVerificationRelationships(e){let r=["authentication","assertionMethod","capabilityInvocation","capabilityDelegation"],n=Object.keys(e);return r.filter(o=>n.includes(o)).every(o=>{let s=e[o];return s&&Array.isArray(s)&&s.every(c=>typeof c=="string"||Kr.isDidVerificationMethod(c))})}static validate(e){return e.id===ln?e.validateGenesis():t.isValid(e),e}validateGenesis(){if(this.id!==ln)throw new Ze("Invalid GenesisDocument ID",Ue,this);if(!this.verificationMethod.every(e=>e.id.includes(ln)&&e.controller===ln))throw new Ze("Invalid GenesisDocument verificationMethod",Ue,this);if(!this.service.every(e=>e.id.includes(ln)))throw new Ze("Invalid GenesisDocument service",Ue,this);if(!t.isValidVerificationRelationships(this))throw new Ze("Invalid GenesisDocument assertionMethod",Ue,this);return!0}toIntermediate(){if(this.id.includes("k1"))throw new Ze("Cannot convert a key identifier to an intermediate document",Ue,this);return new jb(this)}},jb=class t extends hn{constructor(e){super(e)}toDidDocument(e){let r=JSON.stringify(this).replaceAll(ln,e),n=JSON.parse(r);return new hn(n)}static fromDidDocument(e){let r=Us.cloneReplace(e,gL,ln);return new t(r)}static create(e,r,n){return new t({id:ln,...r,verificationMethod:e,service:n})}static fromPublicKey(e,r){let n=new ht(e),i=ln,o=ki(n.compressed,Io(r)).address,s=[{id:`${i}#service-0`,serviceEndpoint:`bitcoin:${o}`,type:"SingletonBeacon"}],c={authentication:[`${i}#key-0`],assertionMethod:[`${i}#key-0`],capabilityInvocation:[`${i}#key-0`],capabilityDelegation:[`${i}#key-0`]},a=[{id:`${i}#key-0`,type:"Multikey",controller:i,publicKeyMultibase:n.multibase.encoded}];return t.create(a,c,s)}static fromJSON(e){return new t(e)}static toGenesisBytes(e){return To(tr(e))}};var Gp=class t{#e={phase:"Construct"};#t;#n;#r;#o;#i;constructor(e){this.#t=e.sourceDocument,this.#n=e.patches,this.#r=e.sourceVersionId,this.#o=e.verificationMethod,this.#i=e.beaconService}static construct(e,r,n){let i={"@context":["https://w3id.org/security/v2","https://w3id.org/zcap/v1","https://w3id.org/json-ld-patch/v1","https://btcr2.dev/context/v1"],patch:r,targetHash:"",targetVersionId:n+1,sourceHash:Gn(e)},o=Zc.apply(e,r);if(o.id!==e.id)throw new vt(`Patches must not change the DID document id (source "${e.id}" to target "${o.id}").`,Ne,{sourceId:e.id,targetId:o.id});try{hn.isValid(o)}catch(s){throw new vt("Error validating targetDocument: "+(s instanceof Error?s.message:String(s)),Ne,o)}return i.targetHash=Gn(o),i}static sign(e,r,n,i){if(!e.startsWith("did:btcr2:"))throw new vt(`Expected a did:btcr2 identifier for the root capability; got "${e}".`,Ne,{did:e});let o=n.controller,s=n.id.indexOf("#");if(s<0)throw new vt(`Verification method id must contain a fragment (e.g. "${n.id}#initialKey"); got "${n.id}".`,Ne,{verificationMethodId:n.id});let c=n.id.slice(s),a=cs.fromSigner(c,o,i),u=a.publicKey.multibase.encoded;if(n.publicKeyMultibase&&u!==n.publicKeyMultibase)throw new vt(`Signing key does not match verification method "${n.id}": the signer's public key differs from the method's published publicKeyMultibase.`,Ne,{verificationMethodId:n.id,expected:n.publicKeyMultibase,actual:u});let d={"@context":["https://w3id.org/security/v2","https://w3id.org/zcap/v1","https://w3id.org/json-ld-patch/v1","https://btcr2.dev/context/v1"],cryptosuite:"bip340-jcs-2025",type:"DataIntegrityProof",verificationMethod:n.id,proofPurpose:"capabilityInvocation",capability:`urn:zcap:root:${encodeURIComponent(e)}`,capabilityAction:"Write"};return a.toCryptosuite().toDataIntegrityProof().addProof(r,d)}static async announce(e,r,n,i){return ra.establish(e).broadcastSignal(r,n,i)}#s(){return t.construct(this.#t,this.#n,this.#r)}advance(){for(;;)switch(this.#e.phase){case"Construct":{let e=this.#s();this.#e={phase:"Sign",unsignedUpdate:e};continue}case"Sign":return{status:"action-required",needs:[{kind:"NeedSigningKey",verificationMethodId:this.#o.id,unsignedUpdate:this.#e.unsignedUpdate}]};case"Fund":return{status:"action-required",needs:[{kind:"NeedFunding",beaconAddress:this.#i.serviceEndpoint.replace("bitcoin:",""),beaconService:this.#i}]};case"Broadcast":return{status:"action-required",needs:[{kind:"NeedBroadcast",beaconService:this.#i,signedUpdate:this.#e.signedUpdate}]};case"Complete":return{status:"complete",result:{signedUpdate:this.#e.signedUpdate}}}}provide(e,r){switch(e.kind){case"NeedSigningKey":{if(this.#e.phase!=="Sign")throw new vt(`Cannot provide NeedSigningKey: updater phase is ${this.#e.phase}, expected Sign.`,Ne,{phase:this.#e.phase});if(!r)throw new vt("NeedSigningKey requires a Signer.",Ne);let n=this.#e.unsignedUpdate,i=t.sign(this.#t.id,n,this.#o,r);this.#e={phase:"Fund",unsignedUpdate:n,signedUpdate:i};break}case"NeedFunding":{if(this.#e.phase!=="Fund")throw new vt(`Cannot provide NeedFunding: updater phase is ${this.#e.phase}, expected Fund.`,Ne,{phase:this.#e.phase});if(r!==void 0){let n=r;if(typeof n.utxoCount!="number"||!Number.isFinite(n.utxoCount)||n.utxoCount<1)throw new vt(`NeedFunding proof must have utxoCount >= 1; got ${String(n.utxoCount)}.`,Ne,{utxoCount:n.utxoCount})}this.#e={phase:"Broadcast",unsignedUpdate:this.#e.unsignedUpdate,signedUpdate:this.#e.signedUpdate};break}case"NeedBroadcast":{if(this.#e.phase!=="Broadcast")throw new vt(`Cannot provide NeedBroadcast: updater phase is ${this.#e.phase}, expected Broadcast.`,Ne,{phase:this.#e.phase});this.#e={phase:"Complete",signedUpdate:this.#e.signedUpdate};break}}}};var zp=class{static methodName="btcr2";static create(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r||{};if(!n)throw new tt("idType is required for creating a did:btcr2 identifier",Ue,r);return xr.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=xr.decode(e),i=as.sidecarData(r.sidecar),o=n.hrp===Sl.k?as.deterministic(n):null;return new as(n,i,o,{versionId:r.versionId,versionTime:r.versionTime,genesisDocument:r.sidecar?.genesisDocument,maxDiscoveryRounds:r.maxDiscoveryRounds})}static update({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethodId:i,beaconId:o}){if(!e.capabilityInvocation?.some(a=>a===i))throw new vt("Invalid verificationMethodId: not authorized for capabilityInvocation",Ue,e);let s=this.getSigningMethod(e,i);if(!s)throw new vt("Invalid verificationMethod: not found in source document",Ue,{sourceDocument:e,verificationMethodId:i});if(s.type!==su)throw new vt(`Invalid verificationMethod: verificationMethod.type must be "${su}"`,Ue,s);if(!s.publicKeyMultibase?.startsWith(cu))throw new vt(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${cu}"`,Ue,s);let c=e.service.filter(a=>a.id===o).filter(a=>!!a).shift();if(!c)throw new vt("No beacon service found for provided beaconId",Ne,{sourceDocument:e,beaconId:o});return new Gp({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethod:s,beaconService:c})}static getSigningMethod(e,r){r??="#initialKey";let n=me.parse(e.id);if(n&&n.method!==this.methodName)throw new tt(`Method not supported: ${n.method}`,pl,{identifier:e.id});let i=e.verificationMethod?.find(o=>Kr.extractDidFragment(o.id)===(Kr.extractDidFragment(r)??Kr.extractDidFragment(e.assertionMethod?.[0])));if(!(i&&i.publicKeyMultibase))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return i}};function hf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function wL(t){return hf(t)&&Object.values(t).every(e=>typeof e=="string")}function bL(t){return hf(t)?Array.isArray(t.patch)&&typeof t.sourceHash=="string"&&typeof t.targetHash=="string"&&typeof t.targetVersionId=="number"&&hf(t.proof):!1}function xL(t){return hf(t)?typeof t.id=="string"&&typeof t.collapsed=="string"&&Array.isArray(t.hashes):!1}var as=class t{#e;#t;#n;#r;#o;#i;#s=null;#f=new Map;#l=new Set;#d=new Set;#c=[];#a=null;#h=1;#y=[];#u;#p=0;constructor(e,r,n,i){this.#e=e,this.#o=r,this.#i=n,this.#t=i?.versionId,this.#n=i?.versionTime;let o=i?.maxDiscoveryRounds;this.#u=typeof o=="number"&&o>0?o:1/0,i?.genesisDocument&&(this.#s=i.genesisDocument),this.#r=n?"BeaconDiscovery":"GenesisDocument"}static deterministic(e){let r=e.genesisBytes,n=xr.encode(r,e),{multibase:i}=new ht(r),o=fn.generateBeaconServices({id:n,publicKey:r,network:Io(e.network),beaconType:"SingletonBeacon"});return new hn({id:n,verificationMethod:[{id:`${n}#initialKey`,type:"Multikey",controller:n,publicKeyMultibase:i.encoded}],service:o})}static external(e,r){let n=Yc(r);if(!vu(e.genesisBytes,n))throw new rt("Initial document mismatch: genesisBytes !== genesisDocumentHash",Ue,{genesisBytes:Zr(e.genesisBytes,"hex"),genesisDocumentHash:Zr(n,"hex")});let i=xr.encode(e.genesisBytes,e),o=JSON.parse(JSON.stringify(r).replaceAll(ln,i));return new hn(o)}static sidecarData(e={}){let r=new Map;if(e.updates?.length)for(let o of e.updates)r.set(Gn(o,{encoding:"hex"}),o);let n=new Map;if(e.casUpdates?.length)for(let o of e.casUpdates)n.set(Gn(o,{encoding:"hex"}),o);let i=new Map;if(e.smtProofs?.length)for(let o of e.smtProofs)i.set(Zr(Is(o.id,"base64urlnopad"),"hex"),o);return{updateMap:r,casMap:n,smtMap:i}}static updates(e,r,n,i,o={currentVersionId:1,updateHashHistory:[]}){let s=o.currentVersionId,c=o.updateHashHistory,a=r.sort(([d,f],[h,p])=>d.targetVersionId-h.targetVersionId||f.height-p.height),u={didDocument:e,metadata:{versionId:`${s}`,confirmations:0,updated:"",deactivated:e.deactivated||!1}};for(let[d,f]of a){let h=Yc(u.didDocument),p=Bo.blocktimeToTimestamp(f.time);if(u.metadata.updated=Bo.toISOStringNonFractional(p),u.metadata.confirmations=f.confirmations,n&&p>Bo.dateStringToTimestamp(n))return u;if(d.targetVersionId<=s)c.push(h),this.confirmDuplicate(d,c);else if(d.targetVersionId===s+1){let y=Is(d.sourceHash,"base64urlnopad");if(!vu(y,h))throw new rt("Hash mismatch: update.sourceHash !== currentDocumentHash",Ne,{sourceHash:d.sourceHash,currentDocumentHash:Zr(h,"hex")});u.didDocument=this.applyUpdate(u.didDocument,d);let E=Us.deleteKeys(d,["proof"]);c.push(Yc(E))}else if(d.targetVersionId>s+1)throw new rt("Version Id Mismatch: targetVersionId cannot be > currentVersionId + 1","LATE_PUBLISHING_ERROR",{targetVersionId:d.targetVersionId,currentVersionId:s+1});s++,u.metadata.versionId=`${s}`;let g=Number(i);if(!isNaN(g)&&g<=s)return u;if(u.didDocument.deactivated)return u.metadata.deactivated=u.didDocument.deactivated,u}return u}static confirmDuplicate(e,r){let{proof:n,...i}=e,o=Yc(i),s=r[e.targetVersionId-2];if(!vu(s,o))throw new rt("Invalid duplicate: unsigned update hash does not match historical hash",av,{unsignedUpdateHash:Zr(o,"hex"),historicalHash:Zr(s,"hex")})}static applyUpdate(e,r){let n=r.proof?.capability;if(!n)throw new rt("No root capability found in update",Ne,r);let i=Kr.dereferenceZcapId(n),{invocationTarget:o,controller:s}=i;if(![o,s].every(S=>S===e.id))throw new rt("Invalid root capability",Ne,{rootCapability:i,currentDocument:e});let c=r.proof?.verificationMethod;if(!c)throw new rt("No verificationMethod found in update",Ne,r);let a=zp.getSigningMethod(e,c),u=cs.fromVerificationMethod(a),d=new ou(u),f=tr(r),p=new iu(d).verifyProof(f,"capabilityInvocation");if(!p.verified)throw new rt("Invalid update: proof not verified",Ne,p);let g=Zc.apply(e,r.patch);hn.validate(g);let y=Yc(g),E=Is(r.targetHash);if(!vu(E,y))throw new rt("Invalid update: update.targetHash !== currentDocumentHash",Ne,{updateTargetHash:E,currentDocumentHash:y});return g}resolve(){for(;;)switch(this.#r){case"GenesisDocument":{if(this.#s){this.#i=t.external(this.#e,this.#s),this.#s=null,this.#r="BeaconDiscovery";continue}return{status:"action-required",needs:[{kind:"NeedGenesisDocument",genesisHash:Zr(this.#e.genesisBytes,"hex")}]}}case"BeaconDiscovery":{let r=fn.getBeaconServices(this.#i).filter(n=>{let i=fn.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)});if(r.length>0){for(let n of r){let i=fn.parseBitcoinAddress(n.serviceEndpoint);this.#d.add(i)}return{status:"action-required",needs:[{kind:"NeedBeaconSignals",beaconServices:r}]}}this.#r="BeaconProcess";continue}case"BeaconProcess":{let e=[];for(let[r,n]of this.#f){if(this.#l.has(r.id)||!n.length)continue;let o=ra.establish(r).processSignals(n,this.#o);o.needs.length>0?e.push(...o.needs):(this.#c.push(...o.updates),this.#l.add(r.id))}if(e.length>0)return{status:"action-required",needs:e};this.#r="ApplyUpdates";continue}case"ApplyUpdates":{if(this.#c.length>0&&(this.#a=t.updates(this.#i,this.#c,this.#n,this.#t,{currentVersionId:this.#h,updateHashHistory:this.#y}),this.#h=Number(this.#a.metadata.versionId),this.#i=this.#a.didDocument,this.#c=[],fn.getBeaconServices(this.#i).some(n=>{let i=fn.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)}))){if(++this.#p>this.#u)throw new rt(`Exceeded the configured maximum of ${this.#u} beacon-discovery rounds. Raise or remove ResolutionOptions.maxDiscoveryRounds to resolve this DID.`,sv,{maxDiscoveryRounds:this.#u,discoveryRounds:this.#p});this.#r="BeaconDiscovery";continue}this.#r="Complete";continue}case"Complete":return{status:"resolved",result:this.#a??{didDocument:this.#i,metadata:{versionId:this.#t??"1",deactivated:this.#i.deactivated||!1}}}}}provide(e,r){switch(e.kind){case"NeedGenesisDocument":{if(!hf(r))throw new rt("Provided data for NeedGenesisDocument must be a document object.",Ne,{kind:e.kind});this.#s=r;break}case"NeedBeaconSignals":{if(!(r instanceof Map))throw new rt("Provided data for NeedBeaconSignals must be a Map of beacon services to signals.",Ne,{kind:e.kind});for(let[n,i]of r)this.#f.set(n,i);break}case"NeedCASAnnouncement":{if(!wL(r))throw new rt("Provided data for NeedCASAnnouncement is not a CAS announcement.",Ne,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.announcementHash)throw new rt(`CAS announcement hash mismatch: expected ${e.announcementHash}, got ${n}.`,Ne,{expected:e.announcementHash,actual:n});this.#o.casMap.set(n,r);break}case"NeedSignedUpdate":{if(!bL(r))throw new rt("Provided data for NeedSignedUpdate is not a signed BTCR2 update.",Ne,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.updateHash)throw new rt(`Signed update hash mismatch: expected ${e.updateHash}, got ${n}.`,Ne,{expected:e.updateHash,actual:n});this.#o.updateMap.set(n,r);break}case"NeedSMTProof":{if(!xL(r))throw new rt("Provided data for NeedSMTProof is not an SMT proof.",Ne,{kind:e.kind});let n=Zr(Is(r.id,"base64urlnopad"),"hex");if(n!==e.smtRootHash)throw new rt(`SMT proof root hash mismatch: expected ${e.smtRootHash}, got ${n}`,Ne,{expected:e.smtRootHash,actual:n});this.#o.smtMap.set(e.smtRootHash,r);break}}}};function EL(t){let e=t.capabilityInvocation?.[0];if(e===void 0)throw new Ze("Cannot derive aggregation communication key: capabilityInvocation is absent",Ue,{id:t.id});let r=typeof e=="string"?t.verificationMethod?.find(n=>n.id===e):e;if(!r)throw new Ze(`Cannot derive aggregation communication key: capabilityInvocation[0] "${e}" does not resolve to a verification method`,Ue,{id:t.id,invocation:e});return cs.fromVerificationMethod(r).publicKey}function bne(t,e){try{let r=xr.decode(t);if(r.idType==="KEY")return new ht(r.genesisBytes);if(e?.genesisDocument){let n=as.external(r,e.genesisDocument);return EL(n)}}catch{}}l();l();l();var PB=class{document={};constructor(e){if(!e.id)throw new Ze('Missing required "id" property',Ue,e);this.document.id=e.id,this.document.verificationMethod=e.verificationMethod??[],e["@context"]&&(this.document["@context"]=e["@context"])}withAuthentication(e){return e&&(this.document.authentication=e),this}withAssertionMethod(e){return e&&(this.document.assertionMethod=e),this}withCapabilityInvocation(e){return e&&(this.document.capabilityInvocation=e),this}withCapabilityDelegation(e){return e&&(this.document.capabilityDelegation=e),this}withService(e){return e&&(this.document.service=e),this}build(){let e=new hn(this.document);for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}};export{hv as AggregateBeaconError,Kr as Appendix,Pre as BECH32M_CHARS,yL as BTCR2_DID_DOCUMENT_CONTEXT,rr as BeaconError,ra as BeaconFactory,kB as BeaconSignalDiscovery,fn as BeaconUtils,Al as CASBeacon,pv as CASBeaconError,gv as CHANGE_OUTPUT_VBYTES,B0 as DEFAULT_FEE_ESTIMATOR,gL as DID_REGEX,mv as DUST_LIMIT_SATS,zp as DidBtcr2,hn as DidDocument,PB as DidDocumentBuilder,Fb as DidVerificationMethod,jb as GenesisDocument,ln as ID_PLACEHOLDER_VALUE,xr as Identifier,cu as MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX,su as MULTIKEY_VERIFICATION_METHOD_TYPE,$R as P2PKH_BEACON_TX_VSIZE,MR as P2TR_BEACON_TX_VSIZE,KR as P2WPKH_BEACON_TX_VSIZE,as as Resolver,HR as SINGLETON_BEACON_TX_VSIZE,Nl as SMTBeacon,Fu as SMTBeaconError,I0 as SPENDABLE_DUST_LIMIT_SATS,Ro as SinglePartyBeacon,Tl as SingletonBeacon,lv as SingletonBeaconError,ju as StaticFeeEstimator,Gp as Updater,wv as beaconTxVsize,T7 as buildAggregationBeaconTx,VR as deriveSingletonAddress,bv as detectSingletonScriptKind,DB as extractOpReturnSignal,EL as getAggregationCommunicationKey,mL as isMultikeyVerificationMethod,vv as opReturnScript,bne as resolveBtcr2SenderPk,xv as resolveChangeAddress,FR as selectSpendableUtxo};
1
+ var rI=Object.create;var ey=Object.defineProperty;var nI=Object.getOwnPropertyDescriptor;var iI=Object.getOwnPropertyNames;var oI=Object.getPrototypeOf,sI=Object.prototype.hasOwnProperty;var cI=(t,e)=>()=>(t&&(e=t(t=0)),e);var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Sf=(t,e)=>{for(var r in e)ey(t,r,{get:e[r],enumerable:!0})},aI=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of iI(e))!sI.call(t,i)&&i!==r&&ey(t,i,{get:()=>e[i],enumerable:!(n=nI(e,i))||n.enumerable});return t};var Pn=(t,e,r)=>(r=t!=null?rI(oI(t)):{},aI(e||!t||!t.__esModule?ey(r,"default",{value:t,enumerable:!0}):r,t));var ix=oe(Af=>{"use strict";l();Af.byteLength=dI;Af.toByteArray=lI;Af.fromByteArray=yI;var Mn=[],Wr=[],uI=typeof Uint8Array<"u"?Uint8Array:Array,ty="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(hs=0,rx=ty.length;hs<rx;++hs)Mn[hs]=ty[hs],Wr[ty.charCodeAt(hs)]=hs;var hs,rx;Wr[45]=62;Wr[95]=63;function nx(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function dI(t){var e=nx(t),r=e[0],n=e[1];return(r+n)*3/4-n}function fI(t,e,r){return(e+r)*3/4-r}function lI(t){var e,r=nx(t),n=r[0],i=r[1],o=new uI(fI(t,n,i)),s=0,c=i>0?n-4:n,a;for(a=0;a<c;a+=4)e=Wr[t.charCodeAt(a)]<<18|Wr[t.charCodeAt(a+1)]<<12|Wr[t.charCodeAt(a+2)]<<6|Wr[t.charCodeAt(a+3)],o[s++]=e>>16&255,o[s++]=e>>8&255,o[s++]=e&255;return i===2&&(e=Wr[t.charCodeAt(a)]<<2|Wr[t.charCodeAt(a+1)]>>4,o[s++]=e&255),i===1&&(e=Wr[t.charCodeAt(a)]<<10|Wr[t.charCodeAt(a+1)]<<4|Wr[t.charCodeAt(a+2)]>>2,o[s++]=e>>8&255,o[s++]=e&255),o}function hI(t){return Mn[t>>18&63]+Mn[t>>12&63]+Mn[t>>6&63]+Mn[t&63]}function pI(t,e,r){for(var n,i=[],o=e;o<r;o+=3)n=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(t[o+2]&255),i.push(hI(n));return i.join("")}function yI(t){for(var e,r=t.length,n=r%3,i=[],o=16383,s=0,c=r-n;s<c;s+=o)i.push(pI(t,s,s+o>c?c:s+o));return n===1?(e=t[r-1],i.push(Mn[e>>2]+Mn[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(Mn[e>>10]+Mn[e>>4&63]+Mn[e<<2&63]+"=")),i.join("")}});var ox=oe(ry=>{l();ry.read=function(t,e,r,n,i){var o,s,c=i*8-n-1,a=(1<<c)-1,u=a>>1,d=-7,f=r?i-1:0,h=r?-1:1,p=t[e+f];for(f+=h,o=p&(1<<-d)-1,p>>=-d,d+=c;d>0;o=o*256+t[e+f],f+=h,d-=8);for(s=o&(1<<-d)-1,o>>=-d,d+=n;d>0;s=s*256+t[e+f],f+=h,d-=8);if(o===0)o=1-u;else{if(o===a)return s?NaN:(p?-1:1)*(1/0);s=s+Math.pow(2,n),o=o-u}return(p?-1:1)*s*Math.pow(2,o-n)};ry.write=function(t,e,r,n,i,o){var s,c,a,u=o*8-i-1,d=(1<<u)-1,f=d>>1,h=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,g=n?1:-1,y=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(c=isNaN(e)?1:0,s=d):(s=Math.floor(Math.log(e)/Math.LN2),e*(a=Math.pow(2,-s))<1&&(s--,a*=2),s+f>=1?e+=h/a:e+=h*Math.pow(2,1-f),e*a>=2&&(s++,a/=2),s+f>=d?(c=0,s=d):s+f>=1?(c=(e*a-1)*Math.pow(2,i),s=s+f):(c=e*Math.pow(2,f-1)*Math.pow(2,i),s=0));i>=8;t[r+p]=c&255,p+=g,c/=256,i-=8);for(s=s<<i|c,u+=i;u>0;t[r+p]=s&255,p+=g,s/=256,u-=8);t[r+p-g]|=y*128}});var Sr=oe(Ic=>{"use strict";l();var ny=ix(),Bc=ox(),sx=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Ic.Buffer=F;Ic.SlowBuffer=EI;Ic.INSPECT_MAX_BYTES=50;var Tf=2147483647;Ic.kMaxLength=Tf;F.TYPED_ARRAY_SUPPORT=gI();!F.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function gI(){try{var t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(F.prototype,"parent",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.buffer}});Object.defineProperty(F.prototype,"offset",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.byteOffset}});function wi(t){if(t>Tf)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return Object.setPrototypeOf(e,F.prototype),e}function F(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return cy(t)}return ux(t,e,r)}F.poolSize=8192;function ux(t,e,r){if(typeof t=="string")return wI(t,e);if(ArrayBuffer.isView(t))return bI(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Kn(t,ArrayBuffer)||t&&Kn(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Kn(t,SharedArrayBuffer)||t&&Kn(t.buffer,SharedArrayBuffer)))return oy(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return F.from(n,e,r);var i=xI(t);if(i)return i;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return F.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}F.from=function(t,e,r){return ux(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function dx(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function mI(t,e,r){return dx(t),t<=0?wi(t):e!==void 0?typeof r=="string"?wi(t).fill(e,r):wi(t).fill(e):wi(t)}F.alloc=function(t,e,r){return mI(t,e,r)};function cy(t){return dx(t),wi(t<0?0:ay(t)|0)}F.allocUnsafe=function(t){return cy(t)};F.allocUnsafeSlow=function(t){return cy(t)};function wI(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=fx(t,e)|0,n=wi(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function iy(t){for(var e=t.length<0?0:ay(t.length)|0,r=wi(e),n=0;n<e;n+=1)r[n]=t[n]&255;return r}function bI(t){if(Kn(t,Uint8Array)){var e=new Uint8Array(t);return oy(e.buffer,e.byteOffset,e.byteLength)}return iy(t)}function oy(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');var n;return e===void 0&&r===void 0?n=new Uint8Array(t):r===void 0?n=new Uint8Array(t,e):n=new Uint8Array(t,e,r),Object.setPrototypeOf(n,F.prototype),n}function xI(t){if(F.isBuffer(t)){var e=ay(t.length)|0,r=wi(e);return r.length===0||t.copy(r,0,0,e),r}if(t.length!==void 0)return typeof t.length!="number"||uy(t.length)?wi(0):iy(t);if(t.type==="Buffer"&&Array.isArray(t.data))return iy(t.data)}function ay(t){if(t>=Tf)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Tf.toString(16)+" bytes");return t|0}function EI(t){return+t!=t&&(t=0),F.alloc(+t)}F.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==F.prototype};F.compare=function(e,r){if(Kn(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),Kn(r,Uint8Array)&&(r=F.from(r,r.offset,r.byteLength)),!F.isBuffer(e)||!F.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;for(var n=e.length,i=r.length,o=0,s=Math.min(n,i);o<s;++o)if(e[o]!==r[o]){n=e[o],i=r[o];break}return n<i?-1:i<n?1:0};F.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};F.concat=function(e,r){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return F.alloc(0);var n;if(r===void 0)for(r=0,n=0;n<e.length;++n)r+=e[n].length;var i=F.allocUnsafe(r),o=0;for(n=0;n<e.length;++n){var s=e[n];if(Kn(s,Uint8Array))o+s.length>i.length?F.from(s).copy(i,o):Uint8Array.prototype.set.call(i,s,o);else if(F.isBuffer(s))s.copy(i,o);else throw new TypeError('"list" argument must be an Array of Buffers');o+=s.length}return i};function fx(t,e){if(F.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Kn(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return sy(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return mx(t).length;default:if(i)return n?-1:sy(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=fx;function vI(t,e,r){var n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return DI(this,e,r);case"utf8":case"utf-8":return hx(this,e,r);case"ascii":return UI(this,e,r);case"latin1":case"binary":return OI(this,e,r);case"base64":return II(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return kI(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function ps(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}F.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<e;r+=2)ps(this,r,r+1);return this};F.prototype.swap32=function(){var e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<e;r+=4)ps(this,r,r+3),ps(this,r+1,r+2);return this};F.prototype.swap64=function(){var e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<e;r+=8)ps(this,r,r+7),ps(this,r+1,r+6),ps(this,r+2,r+5),ps(this,r+3,r+4);return this};F.prototype.toString=function(){var e=this.length;return e===0?"":arguments.length===0?hx(this,0,e):vI.apply(this,arguments)};F.prototype.toLocaleString=F.prototype.toString;F.prototype.equals=function(e){if(!F.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:F.compare(this,e)===0};F.prototype.inspect=function(){var e="",r=Ic.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"};sx&&(F.prototype[sx]=F.prototype.inspect);F.prototype.compare=function(e,r,n,i,o){if(Kn(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),!F.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),o===void 0&&(o=this.length),r<0||n>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&r>=n)return 0;if(i>=o)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,o>>>=0,this===e)return 0;for(var s=o-i,c=n-r,a=Math.min(s,c),u=this.slice(i,o),d=e.slice(r,n),f=0;f<a;++f)if(u[f]!==d[f]){s=u[f],c=d[f];break}return s<c?-1:c<s?1:0};function lx(t,e,r,n,i){if(t.length===0)return-1;if(typeof r=="string"?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,uy(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=F.from(e,n)),F.isBuffer(e))return e.length===0?-1:cx(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):cx(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function cx(t,e,r,n,i){var o=1,s=t.length,c=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;o=2,s/=2,c/=2,r/=2}function a(p,g){return o===1?p[g]:p.readUInt16BE(g*o)}var u;if(i){var d=-1;for(u=r;u<s;u++)if(a(t,u)===a(e,d===-1?0:u-d)){if(d===-1&&(d=u),u-d+1===c)return d*o}else d!==-1&&(u-=u-d),d=-1}else for(r+c>s&&(r=s-c),u=r;u>=0;u--){for(var f=!0,h=0;h<c;h++)if(a(t,u+h)!==a(e,h)){f=!1;break}if(f)return u}return-1}F.prototype.includes=function(e,r,n){return this.indexOf(e,r,n)!==-1};F.prototype.indexOf=function(e,r,n){return lx(this,e,r,n,!0)};F.prototype.lastIndexOf=function(e,r,n){return lx(this,e,r,n,!1)};function SI(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var o=e.length;n>o/2&&(n=o/2);for(var s=0;s<n;++s){var c=parseInt(e.substr(s*2,2),16);if(uy(c))return s;t[r+s]=c}return s}function AI(t,e,r,n){return _f(sy(e,t.length-r),t,r,n)}function TI(t,e,r,n){return _f(LI(e),t,r,n)}function _I(t,e,r,n){return _f(mx(e),t,r,n)}function BI(t,e,r,n){return _f(PI(e,t.length-r),t,r,n)}F.prototype.write=function(e,r,n,i){if(r===void 0)i="utf8",n=this.length,r=0;else if(n===void 0&&typeof r=="string")i=r,n=this.length,r=0;else if(isFinite(r))r=r>>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var o=this.length-r;if((n===void 0||n>o)&&(n=o),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");for(var s=!1;;)switch(i){case"hex":return SI(this,e,r,n);case"utf8":case"utf-8":return AI(this,e,r,n);case"ascii":case"latin1":case"binary":return TI(this,e,r,n);case"base64":return _I(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return BI(this,e,r,n);default:if(s)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),s=!0}};F.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function II(t,e,r){return e===0&&r===t.length?ny.fromByteArray(t):ny.fromByteArray(t.slice(e,r))}function hx(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var o=t[i],s=null,c=o>239?4:o>223?3:o>191?2:1;if(i+c<=r){var a,u,d,f;switch(c){case 1:o<128&&(s=o);break;case 2:a=t[i+1],(a&192)===128&&(f=(o&31)<<6|a&63,f>127&&(s=f));break;case 3:a=t[i+1],u=t[i+2],(a&192)===128&&(u&192)===128&&(f=(o&15)<<12|(a&63)<<6|u&63,f>2047&&(f<55296||f>57343)&&(s=f));break;case 4:a=t[i+1],u=t[i+2],d=t[i+3],(a&192)===128&&(u&192)===128&&(d&192)===128&&(f=(o&15)<<18|(a&63)<<12|(u&63)<<6|d&63,f>65535&&f<1114112&&(s=f))}}s===null?(s=65533,c=1):s>65535&&(s-=65536,n.push(s>>>10&1023|55296),s=56320|s&1023),n.push(s),i+=c}return RI(n)}var ax=4096;function RI(t){var e=t.length;if(e<=ax)return String.fromCharCode.apply(String,t);for(var r="",n=0;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=ax));return r}function UI(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]&127);return n}function OI(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function DI(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",o=e;o<r;++o)i+=MI[t[o]];return i}function kI(t,e,r){for(var n=t.slice(e,r),i="",o=0;o<n.length-1;o+=2)i+=String.fromCharCode(n[o]+n[o+1]*256);return i}F.prototype.slice=function(e,r){var n=this.length;e=~~e,r=r===void 0?n:~~r,e<0?(e+=n,e<0&&(e=0)):e>n&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),r<e&&(r=e);var i=this.subarray(e,r);return Object.setPrototypeOf(i,F.prototype),i};function Rt(t,e,r){if(t%1!==0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}F.prototype.readUintLE=F.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Rt(e,r,this.length);for(var i=this[e],o=1,s=0;++s<r&&(o*=256);)i+=this[e+s]*o;return i};F.prototype.readUintBE=F.prototype.readUIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Rt(e,r,this.length);for(var i=this[e+--r],o=1;r>0&&(o*=256);)i+=this[e+--r]*o;return i};F.prototype.readUint8=F.prototype.readUInt8=function(e,r){return e=e>>>0,r||Rt(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Rt(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Rt(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};F.prototype.readUint32BE=F.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};F.prototype.readIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Rt(e,r,this.length);for(var i=this[e],o=1,s=0;++s<r&&(o*=256);)i+=this[e+s]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*r)),i};F.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Rt(e,r,this.length);for(var i=r,o=1,s=this[e+--i];i>0&&(o*=256);)s+=this[e+--i]*o;return o*=128,s>=o&&(s-=Math.pow(2,8*r)),s};F.prototype.readInt8=function(e,r){return e=e>>>0,r||Rt(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Rt(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};F.prototype.readInt16BE=function(e,r){e=e>>>0,r||Rt(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};F.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};F.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};F.prototype.readFloatLE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),Bc.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Rt(e,4,this.length),Bc.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Rt(e,8,this.length),Bc.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Rt(e,8,this.length),Bc.read(this,e,!1,52,8)};function ur(t,e,r,n,i,o){if(!F.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<o)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}F.prototype.writeUintLE=F.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var o=Math.pow(2,8*n)-1;ur(this,e,r,n,o,0)}var s=1,c=0;for(this[r]=e&255;++c<n&&(s*=256);)this[r+c]=e/s&255;return r+n};F.prototype.writeUintBE=F.prototype.writeUIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){var o=Math.pow(2,8*n)-1;ur(this,e,r,n,o,0)}var s=n-1,c=1;for(this[r+s]=e&255;--s>=0&&(c*=256);)this[r+s]=e/c&255;return r+n};F.prototype.writeUint8=F.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,1,255,0),this[r]=e&255,r+1};F.prototype.writeUint16LE=F.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeUint16BE=F.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeUint32LE=F.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};F.prototype.writeUint32BE=F.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};F.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var o=Math.pow(2,8*n-1);ur(this,e,r,n,o-1,-o)}var s=0,c=1,a=0;for(this[r]=e&255;++s<n&&(c*=256);)e<0&&a===0&&this[r+s-1]!==0&&(a=1),this[r+s]=(e/c>>0)-a&255;return r+n};F.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){var o=Math.pow(2,8*n-1);ur(this,e,r,n,o-1,-o)}var s=n-1,c=1,a=0;for(this[r+s]=e&255;--s>=0&&(c*=256);)e<0&&a===0&&this[r+s+1]!==0&&(a=1),this[r+s]=(e/c>>0)-a&255;return r+n};F.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};F.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};F.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||ur(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function px(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function yx(t,e,r,n,i){return e=+e,r=r>>>0,i||px(t,e,r,4,34028234663852886e22,-34028234663852886e22),Bc.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return yx(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return yx(this,e,r,!1,n)};function gx(t,e,r,n,i){return e=+e,r=r>>>0,i||px(t,e,r,8,17976931348623157e292,-17976931348623157e292),Bc.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return gx(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return gx(this,e,r,!1,n)};F.prototype.copy=function(e,r,n,i){if(!F.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i<n&&(i=n),i===n||e.length===0||this.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r<i-n&&(i=e.length-r+n);var o=i-n;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(r,n,i):Uint8Array.prototype.set.call(e,this.subarray(n,i),r),o};F.prototype.fill=function(e,r,n,i){if(typeof e=="string"){if(typeof r=="string"?(i=r,r=0,n=this.length):typeof n=="string"&&(i=n,n=this.length),i!==void 0&&typeof i!="string")throw new TypeError("encoding must be a string");if(typeof i=="string"&&!F.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(e.length===1){var o=e.charCodeAt(0);(i==="utf8"&&o<128||i==="latin1")&&(e=o)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;r=r>>>0,n=n===void 0?this.length:n>>>0,e||(e=0);var s;if(typeof e=="number")for(s=r;s<n;++s)this[s]=e;else{var c=F.isBuffer(e)?e:F.from(e,i),a=c.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(s=0;s<n-r;++s)this[s+r]=c[s%a]}return this};var NI=/[^+/0-9A-Za-z-_]/g;function CI(t){if(t=t.split("=")[0],t=t.trim().replace(NI,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function sy(t,e){e=e||1/0;for(var r,n=t.length,i=null,o=[],s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}else if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return o}function LI(t){for(var e=[],r=0;r<t.length;++r)e.push(t.charCodeAt(r)&255);return e}function PI(t,e){for(var r,n,i,o=[],s=0;s<t.length&&!((e-=2)<0);++s)r=t.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}function mx(t){return ny.toByteArray(CI(t))}function _f(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function Kn(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function uy(t){return t!==t}var MI=function(){for(var t="0123456789abcdef",e=new Array(256),r=0;r<16;++r)for(var n=r*16,i=0;i<16;++i)e[n+i]=t[r]+t[i];return e}()});var Ei=oe((PL,Ex)=>{l();var at=Ex.exports={},$n,Hn;function dy(){throw new Error("setTimeout has not been defined")}function fy(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?$n=setTimeout:$n=dy}catch{$n=dy}try{typeof clearTimeout=="function"?Hn=clearTimeout:Hn=fy}catch{Hn=fy}})();function wx(t){if($n===setTimeout)return setTimeout(t,0);if(($n===dy||!$n)&&setTimeout)return $n=setTimeout,setTimeout(t,0);try{return $n(t,0)}catch{try{return $n.call(null,t,0)}catch{return $n.call(this,t,0)}}}function KI(t){if(Hn===clearTimeout)return clearTimeout(t);if((Hn===fy||!Hn)&&clearTimeout)return Hn=clearTimeout,clearTimeout(t);try{return Hn(t)}catch{try{return Hn.call(null,t)}catch{return Hn.call(this,t)}}}var bi=[],Rc=!1,ys,Bf=-1;function $I(){!Rc||!ys||(Rc=!1,ys.length?bi=ys.concat(bi):Bf=-1,bi.length&&bx())}function bx(){if(!Rc){var t=wx($I);Rc=!0;for(var e=bi.length;e;){for(ys=bi,bi=[];++Bf<e;)ys&&ys[Bf].run();Bf=-1,e=bi.length}ys=null,Rc=!1,KI(t)}}at.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];bi.push(new xx(t,e)),bi.length===1&&!Rc&&wx(bx)};function xx(t,e){this.fun=t,this.array=e}xx.prototype.run=function(){this.fun.apply(null,this.array)};at.title="browser";at.browser=!0;at.env={};at.argv=[];at.version="";at.versions={};function xi(){}at.on=xi;at.addListener=xi;at.once=xi;at.off=xi;at.removeListener=xi;at.removeAllListeners=xi;at.emit=xi;at.prependListener=xi;at.prependOnceListener=xi;at.listeners=function(t){return[]};at.binding=function(t){throw new Error("process.binding is not supported")};at.cwd=function(){return"/"};at.chdir=function(t){throw new Error("process.chdir is not supported")};at.umask=function(){return 0}});var b,w,KL,l=cI(()=>{b=Pn(Sr()),w=Pn(Ei()),KL=function(t){function e(){var n=this||self;return delete t.prototype.__magic__,n}if(typeof globalThis=="object")return globalThis;if(this)return e();t.defineProperty(t.prototype,"__magic__",{configurable:!0,get:e});var r=__magic__;return r}(Object)});var jv=oe((mH,Fv)=>{l();var XR=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Cl=()=>XR.now(),QR=t=>t&&t===Math.floor(t)&&t>0&&isFinite(t),V0=t=>t===1/0||QR(t),q0=class t{constructor({max:e=1/0,ttl:r,updateAgeOnGet:n=!1,checkAgeOnGet:i=!1,noUpdateTTL:o=!1,dispose:s,noDisposeOnSet:c=!1}={}){if(this.expirations=Object.create(null),this.data=new Map,this.expirationMap=new Map,r!==void 0&&!V0(r))throw new TypeError("ttl must be positive integer or Infinity if set");if(!V0(e))throw new TypeError("max must be positive integer or Infinity");if(this.ttl=r,this.max=e,this.updateAgeOnGet=!!n,this.checkAgeOnGet=!!i,this.noUpdateTTL=!!o,this.noDisposeOnSet=!!c,s!==void 0){if(typeof s!="function")throw new TypeError("dispose must be function if set");this.dispose=s}this.timer=void 0,this.timerExpiration=void 0}setTimer(e,r){if(this.timerExpiration<e)return;this.timer&&clearTimeout(this.timer);let n=setTimeout(()=>{this.timer=void 0,this.timerExpiration=void 0,this.purgeStale();for(let i in this.expirations){this.setTimer(i,i-Cl());break}},r);n.unref&&n.unref(),this.timerExpiration=e,this.timer=n}cancelTimer(){this.timer&&(clearTimeout(this.timer),this.timerExpiration=void 0,this.timer=void 0)}cancelTimers(){return w.default.emitWarning('TTLCache.cancelTimers has been renamed to TTLCache.cancelTimer (no "s"), and will be removed in the next major version update'),this.cancelTimer()}clear(){let e=this.dispose!==t.prototype.dispose?[...this]:[];this.data.clear(),this.expirationMap.clear(),this.cancelTimer(),this.expirations=Object.create(null);for(let[r,n]of e)this.dispose(n,r,"delete")}setTTL(e,r=this.ttl){let n=this.expirationMap.get(e);if(n!==void 0){let i=this.expirations[n];!i||i.length<=1?delete this.expirations[n]:this.expirations[n]=i.filter(o=>o!==e)}if(r!==1/0){let i=Math.floor(Cl()+r);this.expirationMap.set(e,i),this.expirations[i]||(this.expirations[i]=[],this.setTimer(i,r)),this.expirations[i].push(e)}else this.expirationMap.set(e,1/0)}set(e,r,{ttl:n=this.ttl,noUpdateTTL:i=this.noUpdateTTL,noDisposeOnSet:o=this.noDisposeOnSet}={}){if(!V0(n))throw new TypeError("ttl must be positive integer or Infinity");if(this.expirationMap.has(e)){i||this.setTTL(e,n);let s=this.data.get(e);s!==r&&(this.data.set(e,r),o||this.dispose(s,e,"set"))}else this.setTTL(e,n),this.data.set(e,r);for(;this.size>this.max;)this.purgeToCapacity();return this}has(e){return this.data.has(e)}getRemainingTTL(e){let r=this.expirationMap.get(e);return r===1/0?r:r!==void 0?Math.max(0,Math.ceil(r-Cl())):0}get(e,{updateAgeOnGet:r=this.updateAgeOnGet,ttl:n=this.ttl,checkAgeOnGet:i=this.checkAgeOnGet}={}){let o=this.data.get(e);if(i&&this.getRemainingTTL(e)===0){this.delete(e);return}return r&&this.setTTL(e,n),o}dispose(e,r){}delete(e){let r=this.expirationMap.get(e);if(r!==void 0){let n=this.data.get(e);this.data.delete(e),this.expirationMap.delete(e);let i=this.expirations[r];return i&&(i.length<=1?delete this.expirations[r]:this.expirations[r]=i.filter(o=>o!==e)),this.dispose(n,e,"delete"),this.size===0&&this.cancelTimer(),!0}return!1}purgeToCapacity(){for(let e in this.expirations){let r=this.expirations[e];if(this.size-r.length>=this.max){delete this.expirations[e];let n=[];for(let i of r)n.push([i,this.data.get(i)]),this.data.delete(i),this.expirationMap.delete(i);for(let[i,o]of n)this.dispose(o,i,"evict")}else{let n=this.size-this.max,i=[];for(let o of r.splice(0,n))i.push([o,this.data.get(o)]),this.data.delete(o),this.expirationMap.delete(o);for(let[o,s]of i)this.dispose(s,o,"evict");return}}}get size(){return this.data.size}purgeStale(){let e=Math.ceil(Cl());for(let r in this.expirations){if(r==="Infinity"||r>e)return;let n=[...this.expirations[r]||[]],i=[];delete this.expirations[r];for(let o of n)i.push([o,this.data.get(o)]),this.data.delete(o),this.expirationMap.delete(o);for(let[o,s]of i)this.dispose(s,o,"stale")}this.size===0&&this.cancelTimer()}*entries(){for(let e in this.expirations)for(let r of this.expirations[e])yield[r,this.data.get(r)]}*keys(){for(let e in this.expirations)for(let r of this.expirations[e])yield r}*values(){for(let e in this.expirations)for(let r of this.expirations[e])yield this.data.get(r)}[Symbol.iterator](){return this.entries()}};Fv.exports=q0});var a1=oe(c1=>{"use strict";l();c1.supports=function(...e){let r=e.reduce((n,i)=>Object.assign(n,i),{});return Object.assign(r,{snapshots:r.snapshots||!1,permanence:r.permanence||!1,seek:r.seek||!1,clear:r.clear||!1,getMany:r.getMany||!1,keyIterator:r.keyIterator||!1,valueIterator:r.valueIterator||!1,iteratorNextv:r.iteratorNextv||!1,iteratorAll:r.iteratorAll||!1,status:r.status||!1,createIfMissing:r.createIfMissing||!1,errorIfExists:r.errorIfExists||!1,deferredOpen:r.deferredOpen||!1,promises:r.promises||!1,streams:r.streams||!1,encodings:Object.assign({},r.encodings),events:Object.assign({},r.events),additionalMethods:Object.assign({},r.additionalMethods)})}});var En=oe((HV,u1)=>{"use strict";l();u1.exports=class extends Error{constructor(e,r){super(e||""),typeof r=="object"&&r!==null&&(r.code&&(this.code=String(r.code)),r.expected&&(this.expected=!0),r.transient&&(this.transient=!0),r.cause&&(this.cause=r.cause)),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}}});var ig=oe((qV,d1)=>{"use strict";l();var ng=null;d1.exports=function(){return ng===null&&(ng={textEncoder:new TextEncoder,textDecoder:new TextDecoder}),ng}});var cg=oe(f1=>{"use strict";l();var og=En(),D6=new Set(["buffer","view","utf8"]),sg=class{constructor(e){if(this.encode=e.encode||this.encode,this.decode=e.decode||this.decode,this.name=e.name||this.name,this.format=e.format||this.format,typeof this.encode!="function")throw new TypeError("The 'encode' property must be a function");if(typeof this.decode!="function")throw new TypeError("The 'decode' property must be a function");if(this.encode=this.encode.bind(this),this.decode=this.decode.bind(this),typeof this.name!="string"||this.name==="")throw new TypeError("The 'name' property must be a string");if(typeof this.format!="string"||!D6.has(this.format))throw new TypeError("The 'format' property must be one of 'buffer', 'view', 'utf8'");e.createViewTranscoder&&(this.createViewTranscoder=e.createViewTranscoder),e.createBufferTranscoder&&(this.createBufferTranscoder=e.createBufferTranscoder),e.createUTF8Transcoder&&(this.createUTF8Transcoder=e.createUTF8Transcoder)}get commonName(){return this.name.split("+")[0]}createBufferTranscoder(){throw new og(`Encoding '${this.name}' cannot be transcoded to 'buffer'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createViewTranscoder(){throw new og(`Encoding '${this.name}' cannot be transcoded to 'view'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}createUTF8Transcoder(){throw new og(`Encoding '${this.name}' cannot be transcoded to 'utf8'`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"})}};f1.Encoding=sg});var fg=oe(Pl=>{"use strict";l();var{Buffer:ug}=Sr()||{},{Encoding:dg}=cg(),k6=ig(),nd=class extends dg{constructor(e){super({...e,format:"buffer"})}createViewTranscoder(){return new id({encode:this.encode,decode:e=>this.decode(ug.from(e.buffer,e.byteOffset,e.byteLength)),name:`${this.name}+view`})}createBufferTranscoder(){return this}},id=class extends dg{constructor(e){super({...e,format:"view"})}createBufferTranscoder(){return new nd({encode:e=>{let r=this.encode(e);return ug.from(r.buffer,r.byteOffset,r.byteLength)},decode:this.decode,name:`${this.name}+buffer`})}createViewTranscoder(){return this}},ag=class extends dg{constructor(e){super({...e,format:"utf8"})}createBufferTranscoder(){return new nd({encode:e=>ug.from(this.encode(e),"utf8"),decode:e=>this.decode(e.toString("utf8")),name:`${this.name}+buffer`})}createViewTranscoder(){let{textEncoder:e,textDecoder:r}=k6();return new id({encode:n=>e.encode(this.encode(n)),decode:n=>this.decode(r.decode(n)),name:`${this.name}+view`})}createUTF8Transcoder(){return this}};Pl.BufferFormat=nd;Pl.ViewFormat=id;Pl.UTF8Format=ag});var y1=oe(Ms=>{"use strict";l();var{Buffer:Yt}=Sr()||{Buffer:{isBuffer:()=>!1}},{textEncoder:h1,textDecoder:l1}=ig()(),{BufferFormat:od,ViewFormat:lg,UTF8Format:p1}=fg(),Ml=t=>t;Ms.utf8=new p1({encode:function(t){return Yt.isBuffer(t)?t.toString("utf8"):ArrayBuffer.isView(t)?l1.decode(t):String(t)},decode:Ml,name:"utf8",createViewTranscoder(){return new lg({encode:function(t){return ArrayBuffer.isView(t)?t:h1.encode(t)},decode:function(t){return l1.decode(t)},name:`${this.name}+view`})},createBufferTranscoder(){return new od({encode:function(t){return Yt.isBuffer(t)?t:ArrayBuffer.isView(t)?Yt.from(t.buffer,t.byteOffset,t.byteLength):Yt.from(String(t),"utf8")},decode:function(t){return t.toString("utf8")},name:`${this.name}+buffer`})}});Ms.json=new p1({encode:JSON.stringify,decode:JSON.parse,name:"json"});Ms.buffer=new od({encode:function(t){return Yt.isBuffer(t)?t:ArrayBuffer.isView(t)?Yt.from(t.buffer,t.byteOffset,t.byteLength):Yt.from(String(t),"utf8")},decode:Ml,name:"buffer",createViewTranscoder(){return new lg({encode:function(t){return ArrayBuffer.isView(t)?t:Yt.from(String(t),"utf8")},decode:function(t){return Yt.from(t.buffer,t.byteOffset,t.byteLength)},name:`${this.name}+view`})}});Ms.view=new lg({encode:function(t){return ArrayBuffer.isView(t)?t:h1.encode(t)},decode:Ml,name:"view",createBufferTranscoder(){return new od({encode:function(t){return Yt.isBuffer(t)?t:ArrayBuffer.isView(t)?Yt.from(t.buffer,t.byteOffset,t.byteLength):Yt.from(String(t),"utf8")},decode:Ml,name:`${this.name}+buffer`})}});Ms.hex=new od({encode:function(t){return Yt.isBuffer(t)?t:Yt.from(String(t),"hex")},decode:function(t){return t.toString("hex")},name:"hex"});Ms.base64=new od({encode:function(t){return Yt.isBuffer(t)?t:Yt.from(String(t),"base64")},decode:function(t){return t.toString("base64")},name:"base64"})});var w1=oe(m1=>{"use strict";l();var g1=En(),$l=y1(),{Encoding:N6}=cg(),{BufferFormat:C6,ViewFormat:L6,UTF8Format:P6}=fg(),sd=Symbol("formats"),Kl=Symbol("encodings"),M6=new Set(["buffer","view","utf8"]),hg=class{constructor(e){if(Array.isArray(e)){if(!e.every(r=>M6.has(r)))throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}else throw new TypeError("The first argument 'formats' must be an array");this[Kl]=new Map,this[sd]=new Set(e);for(let r in $l)try{this.encoding(r)}catch(n){if(n.code!=="LEVEL_ENCODING_NOT_SUPPORTED")throw n}}encodings(){return Array.from(new Set(this[Kl].values()))}encoding(e){let r=this[Kl].get(e);if(r===void 0){if(typeof e=="string"&&e!==""){if(r=V6[e],!r)throw new g1(`Encoding '${e}' is not found`,{code:"LEVEL_ENCODING_NOT_FOUND"})}else{if(typeof e!="object"||e===null)throw new TypeError("First argument 'encoding' must be a string or object");r=K6(e)}let{name:n,format:i}=r;if(!this[sd].has(i))if(this[sd].has("view"))r=r.createViewTranscoder();else if(this[sd].has("buffer"))r=r.createBufferTranscoder();else if(this[sd].has("utf8"))r=r.createUTF8Transcoder();else throw new g1(`Encoding '${n}' cannot be transcoded`,{code:"LEVEL_ENCODING_NOT_SUPPORTED"});for(let o of[e,n,r.name,r.commonName])this[Kl].set(o,r)}return r}};m1.Transcoder=hg;function K6(t){if(t instanceof N6)return t;let e="type"in t&&typeof t.type=="string"?t.type:void 0,r=t.name||e||`anonymous-${q6++}`;switch($6(t)){case"view":return new L6({...t,name:r});case"utf8":return new P6({...t,name:r});case"buffer":return new C6({...t,name:r});default:throw new TypeError("Format must be one of 'buffer', 'view', 'utf8'")}}function $6(t){return"format"in t&&t.format!==void 0?t.format:"buffer"in t&&typeof t.buffer=="boolean"?t.buffer?"buffer":"utf8":"code"in t&&Number.isInteger(t.code)?"view":"buffer"}var H6={binary:$l.buffer,"utf-8":$l.utf8},V6={...$l,...H6},q6=0});var aa=oe((QV,pg)=>{"use strict";l();var ca=typeof Reflect=="object"?Reflect:null,b1=ca&&typeof ca.apply=="function"?ca.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Hl;ca&&typeof ca.ownKeys=="function"?Hl=ca.ownKeys:Object.getOwnPropertySymbols?Hl=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Hl=function(e){return Object.getOwnPropertyNames(e)};function F6(t){console&&console.warn&&console.warn(t)}var E1=Number.isNaN||function(e){return e!==e};function Ce(){Ce.init.call(this)}pg.exports=Ce;pg.exports.once=z6;Ce.EventEmitter=Ce;Ce.prototype._events=void 0;Ce.prototype._eventsCount=0;Ce.prototype._maxListeners=void 0;var x1=10;function Vl(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(Ce,"defaultMaxListeners",{enumerable:!0,get:function(){return x1},set:function(t){if(typeof t!="number"||t<0||E1(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");x1=t}});Ce.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};Ce.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||E1(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function v1(t){return t._maxListeners===void 0?Ce.defaultMaxListeners:t._maxListeners}Ce.prototype.getMaxListeners=function(){return v1(this)};Ce.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",o=this._events;if(o!==void 0)i=i&&o.error===void 0;else if(!i)return!1;if(i){var s;if(r.length>0&&(s=r[0]),s instanceof Error)throw s;var c=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw c.context=s,c}var a=o[e];if(a===void 0)return!1;if(typeof a=="function")b1(a,this,r);else for(var u=a.length,d=B1(a,u),n=0;n<u;++n)b1(d[n],this,r);return!0};function S1(t,e,r,n){var i,o,s;if(Vl(r),o=t._events,o===void 0?(o=t._events=Object.create(null),t._eventsCount=0):(o.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),o=t._events),s=o[e]),s===void 0)s=o[e]=r,++t._eventsCount;else if(typeof s=="function"?s=o[e]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),i=v1(t),i>0&&s.length>i&&!s.warned){s.warned=!0;var c=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");c.name="MaxListenersExceededWarning",c.emitter=t,c.type=e,c.count=s.length,F6(c)}return t}Ce.prototype.addListener=function(e,r){return S1(this,e,r,!1)};Ce.prototype.on=Ce.prototype.addListener;Ce.prototype.prependListener=function(e,r){return S1(this,e,r,!0)};function j6(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function A1(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=j6.bind(n);return i.listener=r,n.wrapFn=i,i}Ce.prototype.once=function(e,r){return Vl(r),this.on(e,A1(this,e,r)),this};Ce.prototype.prependOnceListener=function(e,r){return Vl(r),this.prependListener(e,A1(this,e,r)),this};Ce.prototype.removeListener=function(e,r){var n,i,o,s,c;if(Vl(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(o=-1,s=n.length-1;s>=0;s--)if(n[s]===r||n[s].listener===r){c=n[s].listener,o=s;break}if(o<0)return this;o===0?n.shift():W6(n,o),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,c||r)}return this};Ce.prototype.off=Ce.prototype.removeListener;Ce.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var o=Object.keys(n),s;for(i=0;i<o.length;++i)s=o[i],s!=="removeListener"&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function T1(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?G6(i):B1(i,i.length)}Ce.prototype.listeners=function(e){return T1(this,e,!0)};Ce.prototype.rawListeners=function(e){return T1(this,e,!1)};Ce.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):_1.call(t,e)};Ce.prototype.listenerCount=_1;function _1(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ce.prototype.eventNames=function(){return this._eventsCount>0?Hl(this._events):[]};function B1(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function W6(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function G6(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function z6(t,e){return new Promise(function(r,n){function i(s){t.removeListener(e,o),n(s)}function o(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}I1(t,e,o,{once:!0}),e!=="error"&&Y6(t,i,{once:!0})})}function Y6(t,e,r){typeof t.on=="function"&&I1(t,"error",e,r)}function I1(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(o){n.once&&t.removeEventListener(e,i),r(o)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}});var U1=oe((tq,R1)=>{l();R1.exports=typeof queueMicrotask=="function"?queueMicrotask:t=>Promise.resolve().then(t)});var cd=oe(yg=>{"use strict";l();var O1=U1();yg.fromCallback=function(t,e){if(t===void 0){var r=new Promise(function(n,i){t=function(o,s){o?i(o):n(s)}});t[e!==void 0?e:"promise"]=r}else if(typeof t!="function")throw new TypeError("Callback must be a function");return t};yg.fromPromise=function(t,e){if(e===void 0)return t;t.then(function(r){O1(()=>e(null,r))}).catch(function(r){O1(()=>e(r))})}});var ql=oe(gg=>{"use strict";l();gg.getCallback=function(t,e){return typeof t=="function"?t:e};gg.getOptions=function(t,e){return typeof t=="object"&&t!==null?t:e!==void 0?e:{}}});var Po=oe(Gl=>{"use strict";l();var{fromCallback:mg}=cd(),Or=En(),{getOptions:wg,getCallback:D1}=ql(),Ks=Symbol("promise"),ua=Symbol("callback"),Xn=Symbol("working"),$s=Symbol("handleOne"),Mi=Symbol("handleMany"),bg=Symbol("autoClose"),Co=Symbol("finishWork"),Qn=Symbol("returnMany"),Do=Symbol("closing"),ad=Symbol("handleClose"),Fl=Symbol("closed"),ud=Symbol("closeCallbacks"),No=Symbol("keyEncoding"),Hs=Symbol("valueEncoding"),xg=Symbol("abortOnClose"),jl=Symbol("legacy"),Eg=Symbol("keys"),vg=Symbol("values"),ko=Symbol("limit"),Xr=Symbol("count"),Wl=Object.freeze({}),J6=()=>{},k1=!1,dd=class{constructor(e,r,n){if(typeof e!="object"||e===null){let i=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${i}`)}if(typeof r!="object"||r===null)throw new TypeError("The second argument must be an options object");this[Fl]=!1,this[ud]=[],this[Xn]=!1,this[Do]=!1,this[bg]=!1,this[ua]=null,this[$s]=this[$s].bind(this),this[Mi]=this[Mi].bind(this),this[ad]=this[ad].bind(this),this[No]=r[No],this[Hs]=r[Hs],this[jl]=n,this[ko]=Number.isInteger(r.limit)&&r.limit>=0?r.limit:1/0,this[Xr]=0,this[xg]=!!r.abortOnClose,this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get count(){return this[Xr]}get limit(){return this[ko]}next(e){let r;if(e===void 0)r=new Promise((n,i)=>{e=(o,s,c)=>{o?i(o):this[jl]?s===void 0&&c===void 0?n():n([s,c]):n(s)}});else if(typeof e!="function")throw new TypeError("Callback must be a function");return this[Do]?this.nextTick(e,new Or("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(e,new Or("Iterator is busy: cannot call next() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[ua]=e,this[Xr]>=this[ko]?this.nextTick(this[$s],null):this._next(this[$s])),r}_next(e){this.nextTick(e)}nextv(e,r,n){return n=D1(r,n),n=mg(n,Ks),r=wg(r,Wl),Number.isInteger(e)?(this[Do]?this.nextTick(n,new Or("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(n,new Or("Iterator is busy: cannot call nextv() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(e<1&&(e=1),this[ko]<1/0&&(e=Math.min(e,this[ko]-this[Xr])),this[Xn]=!0,this[ua]=n,e<=0?this.nextTick(this[Mi],null,[]):this._nextv(e,r,this[Mi])),n[Ks]):(this.nextTick(n,new TypeError("The first argument 'size' must be an integer")),n[Ks])}_nextv(e,r,n){let i=[],o=(s,c,a)=>{if(s)return n(s);if(this[jl]?c===void 0&&a===void 0:c===void 0)return n(null,i);i.push(this[jl]?[c,a]:c),i.length===e?n(null,i):this._next(o)};this._next(o)}all(e,r){return r=D1(e,r),r=mg(r,Ks),e=wg(e,Wl),this[Do]?this.nextTick(r,new Or("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this[Xn]?this.nextTick(r,new Or("Iterator is busy: cannot call all() until previous call has completed",{code:"LEVEL_ITERATOR_BUSY"})):(this[Xn]=!0,this[ua]=r,this[bg]=!0,this[Xr]>=this[ko]?this.nextTick(this[Mi],null,[]):this._all(e,this[Mi])),r[Ks]}_all(e,r){let n=this[Xr],i=[],o=()=>{let c=this[ko]<1/0?Math.min(1e3,this[ko]-n):1e3;c<=0?this.nextTick(r,null,i):this._nextv(c,Wl,s)},s=(c,a)=>{c?r(c):a.length===0?r(null,i):(i.push.apply(i,a),n+=a.length,o())};o()}[Co](){let e=this[ua];return this[xg]&&e===null?J6:(this[Xn]=!1,this[ua]=null,this[Do]&&this._close(this[ad]),e)}[Qn](e,r,n){this[bg]?this.close(e.bind(null,r,n)):e(r,n)}seek(e,r){if(r=wg(r,Wl),!this[Do]){if(this[Xn])throw new Or("Iterator is busy: cannot call seek() until next() has completed",{code:"LEVEL_ITERATOR_BUSY"});{let n=this.db.keyEncoding(r.keyEncoding||this[No]),i=n.format;r.keyEncoding!==i&&(r={...r,keyEncoding:i});let o=this.db.prefixKey(n.encode(e),i);this._seek(o,r)}}}_seek(e,r){throw new Or("Iterator does not support seek()",{code:"LEVEL_NOT_SUPPORTED"})}close(e){return e=mg(e,Ks),this[Fl]?this.nextTick(e):this[Do]?this[ud].push(e):(this[Do]=!0,this[ud].push(e),this[Xn]?this[xg]&&this[Co]()(new Or("Aborted on iterator close()",{code:"LEVEL_ITERATOR_NOT_OPEN"})):this._close(this[ad])),e[Ks]}_close(e){this.nextTick(e)}[ad](){this[Fl]=!0,this.db.detachResource(this);let e=this[ud];this[ud]=[];for(let r of e)r()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.next())!==void 0;)yield e}finally{this[Fl]||await this.close()}}},da=class extends dd{constructor(e,r){super(e,r,!0),this[Eg]=r.keys!==!1,this[vg]=r.values!==!1}[$s](e,r,n){let i=this[Co]();if(e)return i(e);try{r=this[Eg]&&r!==void 0?this[No].decode(r):void 0,n=this[vg]&&n!==void 0?this[Hs].decode(n):void 0}catch(o){return i(new Lo("entry",o))}r===void 0&&n===void 0||this[Xr]++,i(null,r,n)}[Mi](e,r){let n=this[Co]();if(e)return this[Qn](n,e);try{for(let i of r){let o=i[0],s=i[1];i[0]=this[Eg]&&o!==void 0?this[No].decode(o):void 0,i[1]=this[vg]&&s!==void 0?this[Hs].decode(s):void 0}}catch(i){return this[Qn](n,new Lo("entries",i))}this[Xr]+=r.length,this[Qn](n,null,r)}end(e){return!k1&&typeof console<"u"&&(k1=!0,console.warn(new Or("The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version",{code:"LEVEL_LEGACY"}))),this.close(e)}},Sg=class extends dd{constructor(e,r){super(e,r,!1)}[$s](e,r){let n=this[Co]();if(e)return n(e);try{r=r!==void 0?this[No].decode(r):void 0}catch(i){return n(new Lo("key",i))}r!==void 0&&this[Xr]++,n(null,r)}[Mi](e,r){let n=this[Co]();if(e)return this[Qn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[No].decode(o):void 0}}catch(i){return this[Qn](n,new Lo("keys",i))}this[Xr]+=r.length,this[Qn](n,null,r)}},Ag=class extends dd{constructor(e,r){super(e,r,!1)}[$s](e,r){let n=this[Co]();if(e)return n(e);try{r=r!==void 0?this[Hs].decode(r):void 0}catch(i){return n(new Lo("value",i))}r!==void 0&&this[Xr]++,n(null,r)}[Mi](e,r){let n=this[Co]();if(e)return this[Qn](n,e);try{for(let i=0;i<r.length;i++){let o=r[i];r[i]=o!==void 0?this[Hs].decode(o):void 0}}catch(i){return this[Qn](n,new Lo("values",i))}this[Xr]+=r.length,this[Qn](n,null,r)}},Lo=class extends Or{constructor(e,r){super(`Iterator could not decode ${e}`,{code:"LEVEL_DECODE_ERROR",cause:r})}};for(let t of["_ended property","_nexting property","_end method"])Object.defineProperty(da.prototype,t.split(" ")[0],{get(){throw new Or(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})},set(){throw new Or(`The ${t} has been removed`,{code:"LEVEL_LEGACY"})}});da.keyEncoding=No;da.valueEncoding=Hs;Gl.AbstractIterator=da;Gl.AbstractKeyIterator=Sg;Gl.AbstractValueIterator=Ag});var N1=oe(Tg=>{"use strict";l();var{AbstractKeyIterator:Z6,AbstractValueIterator:X6}=Po(),Vs=Symbol("iterator"),fd=Symbol("callback"),fa=Symbol("handleOne"),qs=Symbol("handleMany"),ld=class extends Z6{constructor(e,r){super(e,r),this[Vs]=e.iterator({...r,keys:!0,values:!1}),this[fa]=this[fa].bind(this),this[qs]=this[qs].bind(this)}},zl=class extends X6{constructor(e,r){super(e,r),this[Vs]=e.iterator({...r,keys:!1,values:!0}),this[fa]=this[fa].bind(this),this[qs]=this[qs].bind(this)}};for(let t of[ld,zl]){let e=t===ld,r=e?n=>n[0]:n=>n[1];t.prototype._next=function(n){this[fd]=n,this[Vs].next(this[fa])},t.prototype[fa]=function(n,i,o){let s=this[fd];n?s(n):s(null,e?i:o)},t.prototype._nextv=function(n,i,o){this[fd]=o,this[Vs].nextv(n,i,this[qs])},t.prototype._all=function(n,i){this[fd]=i,this[Vs].all(n,this[qs])},t.prototype[qs]=function(n,i){let o=this[fd];n?o(n):o(null,i.map(r))},t.prototype._seek=function(n,i){this[Vs].seek(n,i)},t.prototype._close=function(n){this[Vs].close(n)}}Tg.DefaultKeyIterator=ld;Tg.DefaultValueIterator=zl});var C1=oe(eh=>{"use strict";l();var{AbstractIterator:Q6,AbstractKeyIterator:eU,AbstractValueIterator:tU}=Po(),_g=En(),hr=Symbol("nut"),Xl=Symbol("undefer"),Ql=Symbol("factory"),Yl=class extends Q6{constructor(e,r){super(e,r),this[hr]=null,this[Ql]=()=>e.iterator(r),this.db.defer(()=>this[Xl]())}},Jl=class extends eU{constructor(e,r){super(e,r),this[hr]=null,this[Ql]=()=>e.keys(r),this.db.defer(()=>this[Xl]())}},Zl=class extends tU{constructor(e,r){super(e,r),this[hr]=null,this[Ql]=()=>e.values(r),this.db.defer(()=>this[Xl]())}};for(let t of[Yl,Jl,Zl])t.prototype[Xl]=function(){this.db.status==="open"&&(this[hr]=this[Ql]())},t.prototype._next=function(e){this[hr]!==null?this[hr].next(e):this.db.status==="opening"?this.db.defer(()=>this._next(e)):this.nextTick(e,new _g("Iterator is not open: cannot call next() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._nextv=function(e,r,n){this[hr]!==null?this[hr].nextv(e,r,n):this.db.status==="opening"?this.db.defer(()=>this._nextv(e,r,n)):this.nextTick(n,new _g("Iterator is not open: cannot call nextv() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._all=function(e,r){this[hr]!==null?this[hr].all(r):this.db.status==="opening"?this.db.defer(()=>this._all(e,r)):this.nextTick(r,new _g("Iterator is not open: cannot call all() after close()",{code:"LEVEL_ITERATOR_NOT_OPEN"}))},t.prototype._seek=function(e,r){this[hr]!==null?this[hr]._seek(e,r):this.db.status==="opening"&&this.db.defer(()=>this._seek(e,r))},t.prototype._close=function(e){this[hr]!==null?this[hr].close(e):this.db.status==="opening"?this.db.defer(()=>this._close(e)):this.nextTick(e)};eh.DeferredIterator=Yl;eh.DeferredKeyIterator=Jl;eh.DeferredValueIterator=Zl});var Ig=oe(P1=>{"use strict";l();var{fromCallback:L1}=cd(),th=En(),{getCallback:rU,getOptions:nU}=ql(),rh=Symbol("promise"),Qr=Symbol("status"),la=Symbol("operations"),hd=Symbol("finishClose"),ha=Symbol("closeCallbacks"),Bg=class{constructor(e){if(typeof e!="object"||e===null){let r=e===null?"null":typeof e;throw new TypeError(`The first argument must be an abstract-level database, received ${r}`)}this[la]=[],this[ha]=[],this[Qr]="open",this[hd]=this[hd].bind(this),this.db=e,this.db.attachResource(this),this.nextTick=e.nextTick}get length(){return this[la].length}put(e,r,n){if(this[Qr]!=="open")throw new th("Batch is not open: cannot call put() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let i=this.db._checkKey(e)||this.db._checkValue(r);if(i)throw i;let o=n&&n.sublevel!=null?n.sublevel:this.db,s=n,c=o.keyEncoding(n&&n.keyEncoding),a=o.valueEncoding(n&&n.valueEncoding),u=c.format;n={...n,keyEncoding:u,valueEncoding:a.format},o!==this.db&&(n.sublevel=null);let d=o.prefixKey(c.encode(e),u),f=a.encode(r);return this._put(d,f,n),this[la].push({...s,type:"put",key:e,value:r}),this}_put(e,r,n){}del(e,r){if(this[Qr]!=="open")throw new th("Batch is not open: cannot call del() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});let n=this.db._checkKey(e);if(n)throw n;let i=r&&r.sublevel!=null?r.sublevel:this.db,o=r,s=i.keyEncoding(r&&r.keyEncoding),c=s.format;return r={...r,keyEncoding:c},i!==this.db&&(r.sublevel=null),this._del(i.prefixKey(s.encode(e),c),r),this[la].push({...o,type:"del",key:e}),this}_del(e,r){}clear(){if(this[Qr]!=="open")throw new th("Batch is not open: cannot call clear() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"});return this._clear(),this[la]=[],this}_clear(){}write(e,r){return r=rU(e,r),r=L1(r,rh),e=nU(e),this[Qr]!=="open"?this.nextTick(r,new th("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"})):this.length===0?this.close(r):(this[Qr]="writing",this._write(e,n=>{this[Qr]="closing",this[ha].push(()=>r(n)),n||this.db.emit("batch",this[la]),this._close(this[hd])})),r[rh]}_write(e,r){}close(e){return e=L1(e,rh),this[Qr]==="closing"?this[ha].push(e):this[Qr]==="closed"?this.nextTick(e):(this[ha].push(e),this[Qr]!=="writing"&&(this[Qr]="closing",this._close(this[hd]))),e[rh]}_close(e){this.nextTick(e)}[hd](){this[Qr]="closed",this.db.detachResource(this);let e=this[ha];this[ha]=[];for(let r of e)r()}};P1.AbstractChainedBatch=Bg});var K1=oe(M1=>{"use strict";l();var{AbstractChainedBatch:iU}=Ig(),oU=En(),pa=Symbol("encoded"),Rg=class extends iU{constructor(e){super(e),this[pa]=[]}_put(e,r,n){this[pa].push({...n,type:"put",key:e,value:r})}_del(e,r){this[pa].push({...r,type:"del",key:e})}_clear(){this[pa]=[]}_write(e,r){this.db.status==="opening"?this.db.defer(()=>this._write(e,r)):this.db.status==="open"?this[pa].length===0?this.nextTick(r):this.db._batch(this[pa],e,r):this.nextTick(r,new oU("Batch is not open: cannot call write() after write() or close()",{code:"LEVEL_BATCH_NOT_OPEN"}))}};M1.DefaultChainedBatch=Rg});var V1=oe((mq,H1)=>{"use strict";l();var $1=En(),sU=Object.prototype.hasOwnProperty,cU=new Set(["lt","lte","gt","gte"]);H1.exports=function(t,e){let r={};for(let n in t)if(sU.call(t,n)&&!(n==="keyEncoding"||n==="valueEncoding")){if(n==="start"||n==="end")throw new $1(`The legacy range option '${n}' has been removed`,{code:"LEVEL_LEGACY"});if(n==="encoding")throw new $1("The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead",{code:"LEVEL_LEGACY"});cU.has(n)?r[n]=e.encode(t[n]):r[n]=t[n]}return r.reverse=!!r.reverse,r.limit=Number.isInteger(r.limit)&&r.limit>=0?r.limit:-1,r}});var Ug=oe((bq,F1)=>{l();var q1;F1.exports=typeof queueMicrotask=="function"?queueMicrotask.bind(typeof window<"u"?window:globalThis):t=>(q1||(q1=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var G1=oe((Eq,W1)=>{"use strict";l();var j1=Ug();W1.exports=function(t,...e){e.length===0?j1(t):j1(()=>t(...e))}});var z1=oe(nh=>{"use strict";l();var{AbstractIterator:aU,AbstractKeyIterator:uU,AbstractValueIterator:dU}=Po(),ya=Symbol("unfix"),vn=Symbol("iterator"),Fs=Symbol("handleOne"),Mo=Symbol("handleMany"),Ki=Symbol("callback"),pd=class extends aU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ya]=i,this[Fs]=this[Fs].bind(this),this[Mo]=this[Mo].bind(this),this[Ki]=null}[Fs](e,r,n){let i=this[Ki];if(e)return i(e);r!==void 0&&(r=this[ya](r)),i(e,r,n)}[Mo](e,r){let n=this[Ki];if(e)return n(e);for(let i of r){let o=i[0];o!==void 0&&(i[0]=this[ya](o))}n(e,r)}},yd=class extends uU{constructor(e,r,n,i){super(e,r),this[vn]=n,this[ya]=i,this[Fs]=this[Fs].bind(this),this[Mo]=this[Mo].bind(this),this[Ki]=null}[Fs](e,r){let n=this[Ki];if(e)return n(e);r!==void 0&&(r=this[ya](r)),n(e,r)}[Mo](e,r){let n=this[Ki];if(e)return n(e);for(let i=0;i<r.length;i++){let o=r[i];o!==void 0&&(r[i]=this[ya](o))}n(e,r)}},gd=class extends dU{constructor(e,r,n){super(e,r),this[vn]=n}};for(let t of[pd,yd])t.prototype._next=function(e){this[Ki]=e,this[vn].next(this[Fs])},t.prototype._nextv=function(e,r,n){this[Ki]=n,this[vn].nextv(e,r,this[Mo])},t.prototype._all=function(e,r){this[Ki]=r,this[vn].all(e,this[Mo])};for(let t of[gd])t.prototype._next=function(e){this[vn].next(e)},t.prototype._nextv=function(e,r,n){this[vn].nextv(e,r,n)},t.prototype._all=function(e,r){this[vn].all(e,r)};for(let t of[pd,yd,gd])t.prototype._seek=function(e,r){this[vn].seek(e,r)},t.prototype._close=function(e){this[vn].close(e)};nh.AbstractSublevelIterator=pd;nh.AbstractSublevelKeyIterator=yd;nh.AbstractSublevelValueIterator=gd});var X1=oe((Tq,Z1)=>{"use strict";l();var Og=En(),{Buffer:Ng}=Sr()||{},{AbstractSublevelIterator:fU,AbstractSublevelKeyIterator:lU,AbstractSublevelValueIterator:hU}=z1(),$i=Symbol("prefix"),Y1=Symbol("upperBound"),md=Symbol("prefixRange"),Dr=Symbol("parent"),Dg=Symbol("unfix"),J1=new TextEncoder,pU={separator:"!"};Z1.exports=function({AbstractLevel:t}){class e extends t{static defaults(n){if(typeof n=="string")throw new Og("The subleveldown string shorthand for { separator } has been removed",{code:"LEVEL_LEGACY"});if(n&&n.open)throw new Og("The subleveldown open option has been removed",{code:"LEVEL_LEGACY"});return n==null?pU:n.separator?n:{...n,separator:"!"}}constructor(n,i,o){let{separator:s,manifest:c,...a}=e.defaults(o);i=gU(i,s);let u=s.charCodeAt(0)+1,d=n[Dr]||n;if(!J1.encode(i).every(p=>p>u&&p<127))throw new Og(`Prefix must use bytes > ${u} < 127`,{code:"LEVEL_INVALID_PREFIX"});super(yU(d,c),a);let f=(n.prefix||"")+s+i+s,h=f.slice(0,-1)+String.fromCharCode(u);this[Dr]=d,this[$i]=new ih(f),this[Y1]=new ih(h),this[Dg]=new Cg,this.nextTick=d.nextTick}prefixKey(n,i){if(i==="utf8")return this[$i].utf8+n;if(n.byteLength===0)return this[$i][i];if(i==="view"){let o=this[$i].view,s=new Uint8Array(o.byteLength+n.byteLength);return s.set(o,0),s.set(n,o.byteLength),s}else{let o=this[$i].buffer;return Ng.concat([o,n],o.byteLength+n.byteLength)}}[md](n,i){n.gte!==void 0?n.gte=this.prefixKey(n.gte,i):n.gt!==void 0?n.gt=this.prefixKey(n.gt,i):n.gte=this[$i][i],n.lte!==void 0?n.lte=this.prefixKey(n.lte,i):n.lt!==void 0?n.lt=this.prefixKey(n.lt,i):n.lte=this[Y1][i]}get prefix(){return this[$i].utf8}get db(){return this[Dr]}_open(n,i){this[Dr].open({passive:!0},i)}_put(n,i,o,s){this[Dr].put(n,i,o,s)}_get(n,i,o){this[Dr].get(n,i,o)}_getMany(n,i,o){this[Dr].getMany(n,i,o)}_del(n,i,o){this[Dr].del(n,i,o)}_batch(n,i,o){this[Dr].batch(n,i,o)}_clear(n,i){this[md](n,n.keyEncoding),this[Dr].clear(n,i)}_iterator(n){this[md](n,n.keyEncoding);let i=this[Dr].iterator(n),o=this[Dg].get(this[$i].utf8.length,n.keyEncoding);return new fU(this,n,i,o)}_keys(n){this[md](n,n.keyEncoding);let i=this[Dr].keys(n),o=this[Dg].get(this[$i].utf8.length,n.keyEncoding);return new lU(this,n,i,o)}_values(n){this[md](n,n.keyEncoding);let i=this[Dr].values(n);return new hU(this,n,i)}}return{AbstractSublevel:e}};var yU=function(t,e){return{...t.supports,createIfMissing:!1,errorIfExists:!1,events:{},additionalMethods:{},...e,encodings:{utf8:kg(t,"utf8"),buffer:kg(t,"buffer"),view:kg(t,"view")}}},kg=function(t,e){return t.supports.encodings[e]?t.keyEncoding(e).name===e:!1},ih=class{constructor(e){this.utf8=e,this.view=J1.encode(e),this.buffer=Ng?Ng.from(this.view.buffer,0,this.view.byteLength):{}}},Cg=class{constructor(){this.cache=new Map}get(e,r){let n=this.cache.get(r);return n===void 0&&(r==="view"?n=(function(i,o){return o.subarray(i)}).bind(null,e):n=(function(i,o){return o.slice(i)}).bind(null,e),this.cache.set(r,n)),n}},gU=function(t,e){let r=0,n=t.length;for(;r<n&&t[r]===e;)r++;for(;n>r&&t[n-1]===e;)n--;return t.slice(r,n)}});var $g=oe(Kg=>{"use strict";l();var{supports:mU}=a1(),{Transcoder:wU}=w1(),{EventEmitter:bU}=aa(),{fromCallback:Ko}=cd(),Sn=En(),{AbstractIterator:js}=Po(),{DefaultKeyIterator:xU,DefaultValueIterator:EU}=N1(),{DeferredIterator:vU,DeferredKeyIterator:SU,DeferredValueIterator:AU}=C1(),{DefaultChainedBatch:Q1}=K1(),{getCallback:Ws,getOptions:$o}=ql(),oh=V1(),pe=Symbol("promise"),Hi=Symbol("landed"),Gs=Symbol("resources"),Lg=Symbol("closeResources"),wd=Symbol("operations"),bd=Symbol("undefer"),sh=Symbol("deferOpen"),e2=Symbol("options"),we=Symbol("status"),zs=Symbol("defaultOptions"),ga=Symbol("transcoder"),ch=Symbol("keyEncoding"),Pg=Symbol("valueEncoding"),TU=()=>{},xd=class extends bU{constructor(e,r){if(super(),typeof e!="object"||e===null)throw new TypeError("The first argument 'manifest' must be an object");r=$o(r);let{keyEncoding:n,valueEncoding:i,passive:o,...s}=r;this[Gs]=new Set,this[wd]=[],this[sh]=!0,this[e2]=s,this[we]="opening",this.supports=mU(e,{status:!0,promises:!0,clear:!0,getMany:!0,deferredOpen:!0,snapshots:e.snapshots!==!1,permanence:e.permanence!==!1,keyIterator:!0,valueIterator:!0,iteratorNextv:!0,iteratorAll:!0,encodings:e.encodings||{},events:Object.assign({},e.events,{opening:!0,open:!0,closing:!0,closed:!0,put:!0,del:!0,batch:!0,clear:!0})}),this[ga]=new wU(_U(this)),this[ch]=this[ga].encoding(n||"utf8"),this[Pg]=this[ga].encoding(i||"utf8");for(let c of this[ga].encodings())this.supports.encodings[c.commonName]||(this.supports.encodings[c.commonName]=!0);this[zs]={empty:Object.freeze({}),entry:Object.freeze({keyEncoding:this[ch].commonName,valueEncoding:this[Pg].commonName}),key:Object.freeze({keyEncoding:this[ch].commonName})},this.nextTick(()=>{this[sh]&&this.open({passive:!1},TU)})}get status(){return this[we]}keyEncoding(e){return this[ga].encoding(e??this[ch])}valueEncoding(e){return this[ga].encoding(e??this[Pg])}open(e,r){r=Ws(e,r),r=Ko(r,pe),e={...this[e2],...$o(e)},e.createIfMissing=e.createIfMissing!==!1,e.errorIfExists=!!e.errorIfExists;let n=i=>{this[we]==="closing"||this[we]==="opening"?this.once(Hi,i?()=>n(i):n):this[we]!=="open"?r(new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN",cause:i})):r()};return e.passive?this[we]==="opening"?this.once(Hi,n):this.nextTick(n):this[we]==="closed"||this[sh]?(this[sh]=!1,this[we]="opening",this.emit("opening"),this._open(e,i=>{if(i){this[we]="closed",this[Lg](()=>{this.emit(Hi),n(i)}),this[bd]();return}this[we]="open",this[bd](),this.emit(Hi),this[we]==="open"&&this.emit("open"),this[we]==="open"&&this.emit("ready"),n()})):this[we]==="open"?this.nextTick(n):this.once(Hi,()=>this.open(e,r)),r[pe]}_open(e,r){this.nextTick(r)}close(e){e=Ko(e,pe);let r=n=>{this[we]==="opening"||this[we]==="closing"?this.once(Hi,n?r(n):r):this[we]!=="closed"?e(new Sn("Database is not closed",{code:"LEVEL_DATABASE_NOT_CLOSED",cause:n})):e()};if(this[we]==="open"){this[we]="closing",this.emit("closing");let n=i=>{this[we]="open",this[bd](),this.emit(Hi),r(i)};this[Lg](()=>{this._close(i=>{if(i)return n(i);this[we]="closed",this[bd](),this.emit(Hi),this[we]==="closed"&&this.emit("closed"),r()})})}else this[we]==="closed"?this.nextTick(r):this.once(Hi,()=>this.close(e));return e[pe]}[Lg](e){if(this[Gs].size===0)return this.nextTick(e);let r=this[Gs].size,n=!0,i=()=>{--r===0&&(n?this.nextTick(e):e())};for(let o of this[Gs])o.close(i);n=!1,this[Gs].clear()}_close(e){this.nextTick(e)}get(e,r,n){if(n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].entry),this[we]==="opening")return this.defer(()=>this.get(e,r,n)),n[pe];if(ma(this,n))return n[pe];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[pe];let o=this.keyEncoding(r.keyEncoding),s=this.valueEncoding(r.valueEncoding),c=o.format,a=s.format;return(r.keyEncoding!==c||r.valueEncoding!==a)&&(r=Object.assign({},r,{keyEncoding:c,valueEncoding:a})),this._get(this.prefixKey(o.encode(e),c),r,(u,d)=>{if(u)return(u.code==="LEVEL_NOT_FOUND"||u.notFound||/NotFound/i.test(u))&&(u.code||(u.code="LEVEL_NOT_FOUND"),u.notFound||(u.notFound=!0),u.status||(u.status=404)),n(u);try{d=s.decode(d)}catch(f){return n(new Sn("Could not decode value",{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[pe]}_get(e,r,n){this.nextTick(n,new Error("NotFound"))}getMany(e,r,n){if(n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].entry),this[we]==="opening")return this.defer(()=>this.getMany(e,r,n)),n[pe];if(ma(this,n))return n[pe];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'keys' must be an array")),n[pe];if(e.length===0)return this.nextTick(n,null,[]),n[pe];let i=this.keyEncoding(r.keyEncoding),o=this.valueEncoding(r.valueEncoding),s=i.format,c=o.format;(r.keyEncoding!==s||r.valueEncoding!==c)&&(r=Object.assign({},r,{keyEncoding:s,valueEncoding:c}));let a=new Array(e.length);for(let u=0;u<e.length;u++){let d=e[u],f=this._checkKey(d);if(f)return this.nextTick(n,f),n[pe];a[u]=this.prefixKey(i.encode(d),s)}return this._getMany(a,r,(u,d)=>{if(u)return n(u);try{for(let f=0;f<d.length;f++)d[f]!==void 0&&(d[f]=o.decode(d[f]))}catch(f){return n(new Sn(`Could not decode one or more of ${d.length} value(s)`,{code:"LEVEL_DECODE_ERROR",cause:f}))}n(null,d)}),n[pe]}_getMany(e,r,n){this.nextTick(n,null,new Array(e.length).fill(void 0))}put(e,r,n,i){if(i=Ws(n,i),i=Ko(i,pe),n=$o(n,this[zs].entry),this[we]==="opening")return this.defer(()=>this.put(e,r,n,i)),i[pe];if(ma(this,i))return i[pe];let o=this._checkKey(e)||this._checkValue(r);if(o)return this.nextTick(i,o),i[pe];let s=this.keyEncoding(n.keyEncoding),c=this.valueEncoding(n.valueEncoding),a=s.format,u=c.format;(n.keyEncoding!==a||n.valueEncoding!==u)&&(n=Object.assign({},n,{keyEncoding:a,valueEncoding:u}));let d=this.prefixKey(s.encode(e),a),f=c.encode(r);return this._put(d,f,n,h=>{if(h)return i(h);this.emit("put",e,r),i()}),i[pe]}_put(e,r,n,i){this.nextTick(i)}del(e,r,n){if(n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].key),this[we]==="opening")return this.defer(()=>this.del(e,r,n)),n[pe];if(ma(this,n))return n[pe];let i=this._checkKey(e);if(i)return this.nextTick(n,i),n[pe];let o=this.keyEncoding(r.keyEncoding),s=o.format;return r.keyEncoding!==s&&(r=Object.assign({},r,{keyEncoding:s})),this._del(this.prefixKey(o.encode(e),s),r,c=>{if(c)return n(c);this.emit("del",e),n()}),n[pe]}_del(e,r,n){this.nextTick(n)}batch(e,r,n){if(!arguments.length){if(this[we]==="opening")return new Q1(this);if(this[we]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._chainedBatch()}if(typeof e=="function"?n=e:n=Ws(r,n),n=Ko(n,pe),r=$o(r,this[zs].empty),this[we]==="opening")return this.defer(()=>this.batch(e,r,n)),n[pe];if(ma(this,n))return n[pe];if(!Array.isArray(e))return this.nextTick(n,new TypeError("The first argument 'operations' must be an array")),n[pe];if(e.length===0)return this.nextTick(n),n[pe];let i=new Array(e.length),{keyEncoding:o,valueEncoding:s,...c}=r;for(let a=0;a<e.length;a++){if(typeof e[a]!="object"||e[a]===null)return this.nextTick(n,new TypeError("A batch operation must be an object")),n[pe];let u=Object.assign({},e[a]);if(u.type!=="put"&&u.type!=="del")return this.nextTick(n,new TypeError("A batch operation must have a type property that is 'put' or 'del'")),n[pe];let d=this._checkKey(u.key);if(d)return this.nextTick(n,d),n[pe];let f=u.sublevel!=null?u.sublevel:this,h=f.keyEncoding(u.keyEncoding||o),p=h.format;if(u.key=f.prefixKey(h.encode(u.key),p),u.keyEncoding=p,u.type==="put"){let g=this._checkValue(u.value);if(g)return this.nextTick(n,g),n[pe];let y=f.valueEncoding(u.valueEncoding||s);u.value=y.encode(u.value),u.valueEncoding=y.format}f!==this&&(u.sublevel=null),i[a]=u}return this._batch(i,c,a=>{if(a)return n(a);this.emit("batch",e),n()}),n[pe]}_batch(e,r,n){this.nextTick(n)}sublevel(e,r){return this._sublevel(e,Mg.defaults(r))}_sublevel(e,r){return new Mg(this,e,r)}prefixKey(e,r){return e}clear(e,r){if(r=Ws(e,r),r=Ko(r,pe),e=$o(e,this[zs].empty),this[we]==="opening")return this.defer(()=>this.clear(e,r)),r[pe];if(ma(this,r))return r[pe];let n=e,i=this.keyEncoding(e.keyEncoding);return e=oh(e,i),e.keyEncoding=i.format,e.limit===0?this.nextTick(r):this._clear(e,o=>{if(o)return r(o);this.emit("clear",n),r()}),r[pe]}_clear(e,r){this.nextTick(r)}iterator(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=oh(e,r),e.keys=e.keys!==!1,e.values=e.values!==!1,e[js.keyEncoding]=r,e[js.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[we]==="opening")return new vU(this,e);if(this[we]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._iterator(e)}_iterator(e){return new js(this,e)}keys(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=oh(e,r),e[js.keyEncoding]=r,e[js.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[we]==="opening")return new SU(this,e);if(this[we]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._keys(e)}_keys(e){return new xU(this,e)}values(e){let r=this.keyEncoding(e&&e.keyEncoding),n=this.valueEncoding(e&&e.valueEncoding);if(e=oh(e,r),e[js.keyEncoding]=r,e[js.valueEncoding]=n,e.keyEncoding=r.format,e.valueEncoding=n.format,this[we]==="opening")return new AU(this,e);if(this[we]!=="open")throw new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"});return this._values(e)}_values(e){return new EU(this,e)}defer(e){if(typeof e!="function")throw new TypeError("The first argument must be a function");this[wd].push(e)}[bd](){if(this[wd].length===0)return;let e=this[wd];this[wd]=[];for(let r of e)r()}attachResource(e){if(typeof e!="object"||e===null||typeof e.close!="function")throw new TypeError("The first argument must be a resource object");this[Gs].add(e)}detachResource(e){this[Gs].delete(e)}_chainedBatch(){return new Q1(this)}_checkKey(e){if(e==null)return new Sn("Key cannot be null or undefined",{code:"LEVEL_INVALID_KEY"})}_checkValue(e){if(e==null)return new Sn("Value cannot be null or undefined",{code:"LEVEL_INVALID_VALUE"})}};xd.prototype.nextTick=G1();var{AbstractSublevel:Mg}=X1()({AbstractLevel:xd});Kg.AbstractLevel=xd;Kg.AbstractSublevel=Mg;var ma=function(t,e){return t[we]!=="open"?(t.nextTick(e,new Sn("Database is not open",{code:"LEVEL_DATABASE_NOT_OPEN"})),!0):!1},_U=function(t){return Object.keys(t.supports.encodings).filter(e=>!!t.supports.encodings[e])}});var Hg=oe(Ys=>{"use strict";l();Ys.AbstractLevel=$g().AbstractLevel;Ys.AbstractSublevel=$g().AbstractSublevel;Ys.AbstractIterator=Po().AbstractIterator;Ys.AbstractKeyIterator=Po().AbstractKeyIterator;Ys.AbstractValueIterator=Po().AbstractValueIterator;Ys.AbstractChainedBatch=Ig().AbstractChainedBatch});var r2=oe((Oq,t2)=>{l();t2.exports=IU;var BU=Ug();function IU(t,e,r){if(typeof e!="number")throw new Error("second argument must be a Number");let n,i,o,s,c,a=!0,u;Array.isArray(t)?(n=[],o=i=t.length):(s=Object.keys(t),n={},o=i=s.length);function d(h){function p(){r&&r(h,n),r=null}a?BU(p):p()}function f(h,p,g){if(n[h]=g,p&&(c=!0),--o===0||p)d(p);else if(!c&&u<i){let y;s?(y=s[u],u+=1,t[y](function(E,S){f(y,E,S)})):(y=u,u+=1,t[y](function(E,S){f(y,E,S)}))}}u=e,o?s?s.some(function(h,p){return t[h](function(g,y){f(h,g,y)}),p===e-1}):t.some(function(h,p){return h(function(g,y){f(p,g,y)}),p===e-1}):d(null),a=!1}});var Vg=oe((kq,n2)=>{"use strict";l();n2.exports=function(e){let r=e.gte!==void 0?e.gte:e.gt!==void 0?e.gt:void 0,n=e.lte!==void 0?e.lte:e.lt!==void 0?e.lt:void 0,i=e.gte===void 0,o=e.lte===void 0;return r!==void 0&&n!==void 0?IDBKeyRange.bound(r,n,i,o):r!==void 0?IDBKeyRange.lowerBound(r,i):n!==void 0?IDBKeyRange.upperBound(n,o):null}});var qg=oe((Cq,i2)=>{"use strict";l();var RU=new TextEncoder;i2.exports=function(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):RU.encode(t)}});var u2=oe(a2=>{"use strict";l();var{AbstractIterator:UU}=Hg(),o2=Vg(),ah=qg(),ei=Symbol("cache"),Vi=Symbol("finished"),kr=Symbol("options"),qi=Symbol("currentOptions"),Js=Symbol("position"),Fg=Symbol("location"),wa=Symbol("first"),s2={},jg=class extends UU{constructor(e,r,n){super(e,n),this[ei]=[],this[Vi]=this.limit===0,this[kr]=n,this[qi]={...n},this[Js]=void 0,this[Fg]=r,this[wa]=!0}_nextv(e,r,n){if(this[wa]=!1,this[Vi])return this.nextTick(n,null,[]);if(this[ei].length>0)return e=Math.min(e,this[ei].length),this.nextTick(n,null,this[ei].splice(0,e));this[Js]!==void 0&&(this[kr].reverse?(this[qi].lt=this[Js],this[qi].lte=void 0):(this[qi].gt=this[Js],this[qi].gte=void 0));let i;try{i=o2(this[qi])}catch{return this[Vi]=!0,this.nextTick(n,null,[])}let o=this.db.db.transaction([this[Fg]],"readonly"),s=o.objectStore(this[Fg]),c=[];if(this[kr].reverse){let a=!this[kr].values&&s.openKeyCursor?"openKeyCursor":"openCursor";s[a](i,"prev").onsuccess=u=>{let d=u.target.result;if(d){let{key:f,value:h}=d;this[Js]=f,c.push([this[kr].keys&&f!==void 0?ah(f):void 0,this[kr].values&&h!==void 0?ah(h):void 0]),c.length<e?d.continue():c2(o)}else this[Vi]=!0}}else{let a,u,d=()=>{if(a===void 0||u===void 0)return;let f=Math.max(a.length,u.length);f===0||e===1/0?this[Vi]=!0:this[Js]=a[f-1],c.length=f;for(let h=0;h<f;h++){let p=a[h],g=u[h];c[h]=[this[kr].keys&&p!==void 0?ah(p):void 0,this[kr].values&&g!==void 0?ah(g):void 0]}c2(o)};this[kr].keys||e<1/0?s.getAllKeys(i,e<1/0?e:void 0).onsuccess=f=>{a=f.target.result,d()}:(a=[],this.nextTick(d)),this[kr].values?s.getAll(i,e<1/0?e:void 0).onsuccess=f=>{u=f.target.result,d()}:(u=[],this.nextTick(d))}o.onabort=()=>{n(o.error||new Error("aborted by user")),n=null},o.oncomplete=()=>{n(null,c),n=null}}_next(e){if(this[ei].length>0){let[r,n]=this[ei].shift();this.nextTick(e,null,r,n)}else if(this[Vi])this.nextTick(e);else{let r=Math.min(100,this.limit-this.count);this[wa]&&(this[wa]=!1,r=1),this._nextv(r,s2,(n,i)=>{if(n)return e(n);this[ei]=i,this._next(e)})}}_all(e,r){this[wa]=!1;let n=this[ei].splice(0,this[ei].length),i=this.limit-this.count-n.length;if(i<=0)return this.nextTick(r,null,n);this._nextv(i,s2,(o,s)=>{if(o)return r(o);n.length>0&&(s=n.concat(s)),r(null,s)})}_seek(e,r){this[wa]=!0,this[ei]=[],this[Vi]=!1,this[Js]=void 0,this[qi]={...this[kr]};let n;try{n=o2(this[kr])}catch{this[Vi]=!0;return}n!==null&&!n.includes(e)?this[Vi]=!0:this[kr].reverse?this[qi].lte=e:this[qi].gte=e}};a2.Iterator=jg;function c2(t){typeof t.commit=="function"&&t.commit()}});var f2=oe((Kq,d2)=>{"use strict";l();d2.exports=function(e,r,n,i,o){if(i.limit===0)return e.nextTick(o);let s=e.db.transaction([r],"readwrite"),c=s.objectStore(r),a=0;s.oncomplete=function(){o()},s.onabort=function(){o(s.error||new Error("aborted by user"))};let u=c.openKeyCursor?"openKeyCursor":"openCursor",d=i.reverse?"prev":"next";c[u](n,d).onsuccess=function(f){let h=f.target.result;h&&(c.delete(h.key).onsuccess=function(){(i.limit<=0||++a<i.limit)&&h.continue()})}}});var m2=oe(g2=>{"use strict";l();var{AbstractLevel:OU}=Hg(),l2=En(),DU=r2(),{fromCallback:kU}=cd(),{Iterator:NU}=u2(),h2=qg(),CU=f2(),LU=Vg(),y2="level-js-",Ed=Symbol("idb"),Wg=Symbol("namePrefix"),Fi=Symbol("location"),Gg=Symbol("version"),Zs=Symbol("store"),vd=Symbol("onComplete"),p2=Symbol("promise"),uh=class extends OU{constructor(e,r,n){if(typeof r=="function"||typeof n=="function")throw new l2("The levelup-style callback argument has been removed",{code:"LEVEL_LEGACY"});let{prefix:i,version:o,...s}=r||{};if(super({encodings:{view:!0},snapshots:!1,createIfMissing:!1,errorIfExists:!1,seek:!0},s),typeof e!="string")throw new Error("constructor requires a location string argument");this[Fi]=e,this[Wg]=i??y2,this[Gg]=parseInt(o||1,10),this[Ed]=null}get location(){return this[Fi]}get namePrefix(){return this[Wg]}get version(){return this[Gg]}get db(){return this[Ed]}get type(){return"browser-level"}_open(e,r){let n=indexedDB.open(this[Wg]+this[Fi],this[Gg]);n.onerror=function(){r(n.error||new Error("unknown error"))},n.onsuccess=()=>{this[Ed]=n.result,r()},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this[Fi])||o.createObjectStore(this[Fi])}}[Zs](e){return this[Ed].transaction([this[Fi]],e).objectStore(this[Fi])}[vd](e,r){let n=e.transaction;n.onabort=function(){r(n.error||new Error("aborted by user"))},n.oncomplete=function(){r(null,e.result)}}_get(e,r,n){let i=this[Zs]("readonly"),o;try{o=i.get(e)}catch(s){return this.nextTick(n,s)}this[vd](o,function(s,c){if(s)return n(s);if(c===void 0)return n(new l2("Entry not found",{code:"LEVEL_NOT_FOUND"}));n(null,h2(c))})}_getMany(e,r,n){let i=this[Zs]("readonly"),o=e.map(s=>c=>{let a;try{a=i.get(s)}catch(u){return c(u)}a.onsuccess=()=>{let u=a.result;c(null,u===void 0?u:h2(u))},a.onerror=u=>{u.stopPropagation(),c(a.error)}});DU(o,16,n)}_del(e,r,n){let i=this[Zs]("readwrite"),o;try{o=i.delete(e)}catch(s){return this.nextTick(n,s)}this[vd](o,n)}_put(e,r,n,i){let o=this[Zs]("readwrite"),s;try{s=o.put(r,e)}catch(c){return this.nextTick(i,c)}this[vd](s,i)}_iterator(e){return new NU(this,this[Fi],e)}_batch(e,r,n){let i=this[Zs]("readwrite"),o=i.transaction,s=0,c;o.onabort=function(){n(c||o.error||new Error("aborted by user"))},o.oncomplete=function(){n()};function a(){let u=e[s++],d=u.key,f;try{f=u.type==="del"?i.delete(d):i.put(u.value,d)}catch(h){c=h,o.abort();return}s<e.length?f.onsuccess=a:typeof o.commit=="function"&&o.commit()}a()}_clear(e,r){let n,i;try{n=LU(e)}catch{return this.nextTick(r)}if(e.limit>=0)return CU(this,this[Fi],n,e,r);try{let o=this[Zs]("readwrite");i=n?o.delete(n):o.clear()}catch(o){return this.nextTick(r,o)}this[vd](i,r)}_close(e){this[Ed].close(),this.nextTick(e)}};uh.destroy=function(t,e,r){typeof e=="function"&&(r=e,e=y2),r=kU(r,p2);let n=indexedDB.deleteDatabase(e+t);return n.onsuccess=function(){r()},n.onerror=function(i){r(i)},r[p2]};g2.BrowserLevel=uh});var zg=oe(w2=>{l();w2.Level=m2().BrowserLevel});var nt=oe((Jq,b2)=>{"use strict";l();b2.exports={ArrayIsArray(t){return Array.isArray(t)},ArrayPrototypeIncludes(t,e){return t.includes(e)},ArrayPrototypeIndexOf(t,e){return t.indexOf(e)},ArrayPrototypeJoin(t,e){return t.join(e)},ArrayPrototypeMap(t,e){return t.map(e)},ArrayPrototypePop(t,e){return t.pop(e)},ArrayPrototypePush(t,e){return t.push(e)},ArrayPrototypeSlice(t,e,r){return t.slice(e,r)},Error,FunctionPrototypeCall(t,e,...r){return t.call(e,...r)},FunctionPrototypeSymbolHasInstance(t,e){return Function.prototype[Symbol.hasInstance].call(t,e)},MathFloor:Math.floor,Number,NumberIsInteger:Number.isInteger,NumberIsNaN:Number.isNaN,NumberMAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER,NumberMIN_SAFE_INTEGER:Number.MIN_SAFE_INTEGER,NumberParseInt:Number.parseInt,ObjectDefineProperties(t,e){return Object.defineProperties(t,e)},ObjectDefineProperty(t,e,r){return Object.defineProperty(t,e,r)},ObjectGetOwnPropertyDescriptor(t,e){return Object.getOwnPropertyDescriptor(t,e)},ObjectKeys(t){return Object.keys(t)},ObjectSetPrototypeOf(t,e){return Object.setPrototypeOf(t,e)},Promise,PromisePrototypeCatch(t,e){return t.catch(e)},PromisePrototypeThen(t,e,r){return t.then(e,r)},PromiseReject(t){return Promise.reject(t)},PromiseResolve(t){return Promise.resolve(t)},ReflectApply:Reflect.apply,RegExpPrototypeTest(t,e){return t.test(e)},SafeSet:Set,String,StringPrototypeSlice(t,e,r){return t.slice(e,r)},StringPrototypeToLowerCase(t){return t.toLowerCase()},StringPrototypeToUpperCase(t){return t.toUpperCase()},StringPrototypeTrim(t){return t.trim()},Symbol,SymbolFor:Symbol.for,SymbolAsyncIterator:Symbol.asyncIterator,SymbolHasInstance:Symbol.hasInstance,SymbolIterator:Symbol.iterator,SymbolDispose:Symbol.dispose||Symbol("Symbol.dispose"),SymbolAsyncDispose:Symbol.asyncDispose||Symbol("Symbol.asyncDispose"),TypedArrayPrototypeSet(t,e,r){return t.set(e,r)},Boolean,Uint8Array}});var ba=oe((Xq,fh)=>{"use strict";l();var{AbortController:x2,AbortSignal:MU}=typeof self<"u"?self:typeof window<"u"?window:void 0;fh.exports=x2;fh.exports.AbortSignal=MU;fh.exports.default=x2});var Jt=oe((eF,Jg)=>{"use strict";l();var KU=Sr(),{kResistStopPropagation:$U,SymbolDispose:HU}=nt(),VU=globalThis.AbortSignal||ba().AbortSignal,qU=globalThis.AbortController||ba().AbortController,FU=Object.getPrototypeOf(async function(){}).constructor,E2=globalThis.Blob||KU.Blob,jU=typeof E2<"u"?function(e){return e instanceof E2}:function(e){return!1},v2=(t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new ERR_INVALID_ARG_TYPE(e,"AbortSignal",t)},WU=(t,e)=>{if(typeof t!="function")throw new ERR_INVALID_ARG_TYPE(e,"Function",t)},Yg=class extends Error{constructor(e){if(!Array.isArray(e))throw new TypeError(`Expected input to be an Array, got ${typeof e}`);let r="";for(let n=0;n<e.length;n++)r+=` ${e[n].stack}
2
+ `;super(r),this.name="AggregateError",this.errors=e}};Jg.exports={AggregateError:Yg,kEmptyObject:Object.freeze({}),once(t){let e=!1;return function(...r){e||(e=!0,t.apply(this,r))}},createDeferredPromise:function(){let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}},promisify(t){return new Promise((e,r)=>{t((n,...i)=>n?r(n):e(...i))})},debuglog(){return function(){}},format(t,...e){return t.replace(/%([sdifj])/g,function(...[r,n]){let i=e.shift();return n==="f"?i.toFixed(6):n==="j"?JSON.stringify(i):n==="s"&&typeof i=="object"?`${i.constructor!==Object?i.constructor.name:""} {}`.trim():i.toString()})},inspect(t){switch(typeof t){case"string":if(t.includes("'"))if(t.includes('"')){if(!t.includes("`")&&!t.includes("${"))return`\`${t}\``}else return`"${t}"`;return`'${t}'`;case"number":return isNaN(t)?"NaN":Object.is(t,-0)?String(t):t;case"bigint":return`${String(t)}n`;case"boolean":case"undefined":return String(t);case"object":return"{}"}},types:{isAsyncFunction(t){return t instanceof FU},isArrayBufferView(t){return ArrayBuffer.isView(t)}},isBlob:jU,deprecate(t,e){return t},addAbortListener:aa().addAbortListener||function(e,r){if(e===void 0)throw new ERR_INVALID_ARG_TYPE("signal","AbortSignal",e);v2(e,"signal"),WU(r,"listener");let n;return e.aborted?queueMicrotask(()=>r()):(e.addEventListener("abort",r,{__proto__:null,once:!0,[$U]:!0}),n=()=>{e.removeEventListener("abort",r)}),{__proto__:null,[HU](){var i;(i=n)===null||i===void 0||i()}}},AbortSignalAny:VU.any||function(e){if(e.length===1)return e[0];let r=new qU,n=()=>r.abort();return e.forEach(i=>{v2(i,"signals"),i.addEventListener("abort",n,{once:!0})}),r.signal.addEventListener("abort",()=>{e.forEach(i=>i.removeEventListener("abort",n))},{once:!0}),r.signal}};Jg.exports.promisify.custom=Symbol.for("nodejs.util.promisify.custom")});var ir=oe((rF,T2)=>{"use strict";l();var{format:GU,inspect:lh,AggregateError:zU}=Jt(),YU=globalThis.AggregateError||zU,JU=Symbol("kIsNodeError"),ZU=["string","function","number","object","Function","Object","boolean","bigint","symbol"],XU=/^([A-Z][a-z0-9]*)+$/,QU="__node_internal_",hh={};function Qs(t,e){if(!t)throw new hh.ERR_INTERNAL_ASSERTION(e)}function S2(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function e5(t,e,r){if(typeof e=="function")return Qs(e.length<=r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${e.length}).`),e(...r);let n=(e.match(/%[dfijoOs]/g)||[]).length;return Qs(n===r.length,`Code: ${t}; The provided arguments length (${r.length}) does not match the required ones (${n}).`),r.length===0?e:GU(e,...r)}function Mt(t,e,r){r||(r=Error);class n extends r{constructor(...o){super(e5(t,e,o))}toString(){return`${this.name} [${t}]: ${this.message}`}}Object.defineProperties(n.prototype,{name:{value:r.name,writable:!0,enumerable:!1,configurable:!0},toString:{value(){return`${this.name} [${t}]: ${this.message}`},writable:!0,enumerable:!1,configurable:!0}}),n.prototype.code=t,n.prototype[JU]=!0,hh[t]=n}function A2(t){let e=QU+t.name;return Object.defineProperty(t,"name",{value:e}),t}function t5(t,e){if(t&&e&&t!==e){if(Array.isArray(e.errors))return e.errors.push(t),e;let r=new YU([e,t],e.message);return r.code=e.code,r}return t||e}var Zg=class extends Error{constructor(e="The operation was aborted",r=void 0){if(r!==void 0&&typeof r!="object")throw new hh.ERR_INVALID_ARG_TYPE("options","Object",r);super(e,r),this.code="ABORT_ERR",this.name="AbortError"}};Mt("ERR_ASSERTION","%s",Error);Mt("ERR_INVALID_ARG_TYPE",(t,e,r)=>{Qs(typeof t=="string","'name' must be a string"),Array.isArray(e)||(e=[e]);let n="The ";t.endsWith(" argument")?n+=`${t} `:n+=`"${t}" ${t.includes(".")?"property":"argument"} `,n+="must be ";let i=[],o=[],s=[];for(let a of e)Qs(typeof a=="string","All expected entries have to be of type string"),ZU.includes(a)?i.push(a.toLowerCase()):XU.test(a)?o.push(a):(Qs(a!=="object",'The value "object" should be written as "Object"'),s.push(a));if(o.length>0){let a=i.indexOf("object");a!==-1&&(i.splice(i,a,1),o.push("Object"))}if(i.length>0){switch(i.length){case 1:n+=`of type ${i[0]}`;break;case 2:n+=`one of type ${i[0]} or ${i[1]}`;break;default:{let a=i.pop();n+=`one of type ${i.join(", ")}, or ${a}`}}(o.length>0||s.length>0)&&(n+=" or ")}if(o.length>0){switch(o.length){case 1:n+=`an instance of ${o[0]}`;break;case 2:n+=`an instance of ${o[0]} or ${o[1]}`;break;default:{let a=o.pop();n+=`an instance of ${o.join(", ")}, or ${a}`}}s.length>0&&(n+=" or ")}switch(s.length){case 0:break;case 1:s[0].toLowerCase()!==s[0]&&(n+="an "),n+=`${s[0]}`;break;case 2:n+=`one of ${s[0]} or ${s[1]}`;break;default:{let a=s.pop();n+=`one of ${s.join(", ")}, or ${a}`}}if(r==null)n+=`. Received ${r}`;else if(typeof r=="function"&&r.name)n+=`. Received function ${r.name}`;else if(typeof r=="object"){var c;if((c=r.constructor)!==null&&c!==void 0&&c.name)n+=`. Received an instance of ${r.constructor.name}`;else{let a=lh(r,{depth:-1});n+=`. Received ${a}`}}else{let a=lh(r,{colors:!1});a.length>25&&(a=`${a.slice(0,25)}...`),n+=`. Received type ${typeof r} (${a})`}return n},TypeError);Mt("ERR_INVALID_ARG_VALUE",(t,e,r="is invalid")=>{let n=lh(e);return n.length>128&&(n=n.slice(0,128)+"..."),`The ${t.includes(".")?"property":"argument"} '${t}' ${r}. Received ${n}`},TypeError);Mt("ERR_INVALID_RETURN_VALUE",(t,e,r)=>{var n;let i=r!=null&&(n=r.constructor)!==null&&n!==void 0&&n.name?`instance of ${r.constructor.name}`:`type ${typeof r}`;return`Expected ${t} to be returned from the "${e}" function but got ${i}.`},TypeError);Mt("ERR_MISSING_ARGS",(...t)=>{Qs(t.length>0,"At least one arg needs to be specified");let e,r=t.length;switch(t=(Array.isArray(t)?t:[t]).map(n=>`"${n}"`).join(" or "),r){case 1:e+=`The ${t[0]} argument`;break;case 2:e+=`The ${t[0]} and ${t[1]} arguments`;break;default:{let n=t.pop();e+=`The ${t.join(", ")}, and ${n} arguments`}break}return`${e} must be specified`},TypeError);Mt("ERR_OUT_OF_RANGE",(t,e,r)=>{Qs(e,'Missing "range" argument');let n;return Number.isInteger(r)&&Math.abs(r)>2**32?n=S2(String(r)):typeof r=="bigint"?(n=String(r),(r>2n**32n||r<-(2n**32n))&&(n=S2(n)),n+="n"):n=lh(r),`The value of "${t}" is out of range. It must be ${e}. Received ${n}`},RangeError);Mt("ERR_MULTIPLE_CALLBACK","Callback called multiple times",Error);Mt("ERR_METHOD_NOT_IMPLEMENTED","The %s method is not implemented",Error);Mt("ERR_STREAM_ALREADY_FINISHED","Cannot call %s after a stream was finished",Error);Mt("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable",Error);Mt("ERR_STREAM_DESTROYED","Cannot call %s after a stream was destroyed",Error);Mt("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);Mt("ERR_STREAM_PREMATURE_CLOSE","Premature close",Error);Mt("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF",Error);Mt("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event",Error);Mt("ERR_STREAM_WRITE_AFTER_END","write after end",Error);Mt("ERR_UNKNOWN_ENCODING","Unknown encoding: %s",TypeError);T2.exports={AbortError:Zg,aggregateTwoErrors:A2(t5),hideStackFrames:A2,codes:hh}});var Ea=oe((iF,C2)=>{"use strict";l();var{ArrayIsArray:Qg,ArrayPrototypeIncludes:R2,ArrayPrototypeJoin:U2,ArrayPrototypeMap:r5,NumberIsInteger:em,NumberIsNaN:n5,NumberMAX_SAFE_INTEGER:i5,NumberMIN_SAFE_INTEGER:o5,NumberParseInt:s5,ObjectPrototypeHasOwnProperty:c5,RegExpPrototypeExec:O2,String:a5,StringPrototypeToUpperCase:u5,StringPrototypeTrim:d5}=nt(),{hideStackFrames:en,codes:{ERR_SOCKET_BAD_PORT:f5,ERR_INVALID_ARG_TYPE:Zt,ERR_INVALID_ARG_VALUE:xa,ERR_OUT_OF_RANGE:ec,ERR_UNKNOWN_SIGNAL:_2}}=ir(),{normalizeEncoding:l5}=Jt(),{isAsyncFunction:h5,isArrayBufferView:p5}=Jt().types,B2={};function y5(t){return t===(t|0)}function g5(t){return t===t>>>0}var m5=/^[0-7]+$/,w5="must be a 32-bit unsigned integer or an octal string";function b5(t,e,r){if(typeof t>"u"&&(t=r),typeof t=="string"){if(O2(m5,t)===null)throw new xa(e,t,w5);t=s5(t,8)}return D2(t,e),t}var x5=en((t,e,r=o5,n=i5)=>{if(typeof t!="number")throw new Zt(e,"number",t);if(!em(t))throw new ec(e,"an integer",t);if(t<r||t>n)throw new ec(e,`>= ${r} && <= ${n}`,t)}),E5=en((t,e,r=-2147483648,n=2147483647)=>{if(typeof t!="number")throw new Zt(e,"number",t);if(!em(t))throw new ec(e,"an integer",t);if(t<r||t>n)throw new ec(e,`>= ${r} && <= ${n}`,t)}),D2=en((t,e,r=!1)=>{if(typeof t!="number")throw new Zt(e,"number",t);if(!em(t))throw new ec(e,"an integer",t);let n=r?1:0,i=4294967295;if(t<n||t>i)throw new ec(e,`>= ${n} && <= ${i}`,t)});function tm(t,e){if(typeof t!="string")throw new Zt(e,"string",t)}function v5(t,e,r=void 0,n){if(typeof t!="number")throw new Zt(e,"number",t);if(r!=null&&t<r||n!=null&&t>n||(r!=null||n!=null)&&n5(t))throw new ec(e,`${r!=null?`>= ${r}`:""}${r!=null&&n!=null?" && ":""}${n!=null?`<= ${n}`:""}`,t)}var S5=en((t,e,r)=>{if(!R2(r,t)){let i="must be one of: "+U2(r5(r,o=>typeof o=="string"?`'${o}'`:a5(o)),", ");throw new xa(e,t,i)}});function k2(t,e){if(typeof t!="boolean")throw new Zt(e,"boolean",t)}function Xg(t,e,r){return t==null||!c5(t,e)?r:t[e]}var A5=en((t,e,r=null)=>{let n=Xg(r,"allowArray",!1),i=Xg(r,"allowFunction",!1);if(!Xg(r,"nullable",!1)&&t===null||!n&&Qg(t)||typeof t!="object"&&(!i||typeof t!="function"))throw new Zt(e,"Object",t)}),T5=en((t,e)=>{if(t!=null&&typeof t!="object"&&typeof t!="function")throw new Zt(e,"a dictionary",t)}),ph=en((t,e,r=0)=>{if(!Qg(t))throw new Zt(e,"Array",t);if(t.length<r){let n=`must be longer than ${r}`;throw new xa(e,t,n)}});function _5(t,e){ph(t,e);for(let r=0;r<t.length;r++)tm(t[r],`${e}[${r}]`)}function B5(t,e){ph(t,e);for(let r=0;r<t.length;r++)k2(t[r],`${e}[${r}]`)}function I5(t,e){ph(t,e);for(let r=0;r<t.length;r++){let n=t[r],i=`${e}[${r}]`;if(n==null)throw new Zt(i,"AbortSignal",n);N2(n,i)}}function R5(t,e="signal"){if(tm(t,e),B2[t]===void 0)throw B2[u5(t)]!==void 0?new _2(t+" (signals must use all capital letters)"):new _2(t)}var U5=en((t,e="buffer")=>{if(!p5(t))throw new Zt(e,["Buffer","TypedArray","DataView"],t)});function O5(t,e){let r=l5(e),n=t.length;if(r==="hex"&&n%2!==0)throw new xa("encoding",e,`is invalid for data of length ${n}`)}function D5(t,e="Port",r=!0){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&d5(t).length===0||+t!==+t>>>0||t>65535||t===0&&!r)throw new f5(e,t,r);return t|0}var N2=en((t,e)=>{if(t!==void 0&&(t===null||typeof t!="object"||!("aborted"in t)))throw new Zt(e,"AbortSignal",t)}),k5=en((t,e)=>{if(typeof t!="function")throw new Zt(e,"Function",t)}),N5=en((t,e)=>{if(typeof t!="function"||h5(t))throw new Zt(e,"Function",t)}),C5=en((t,e)=>{if(t!==void 0)throw new Zt(e,"undefined",t)});function L5(t,e,r){if(!R2(r,t))throw new Zt(e,`('${U2(r,"|")}')`,t)}var P5=/^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/;function I2(t,e){if(typeof t>"u"||!O2(P5,t))throw new xa(e,t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}function M5(t){if(typeof t=="string")return I2(t,"hints"),t;if(Qg(t)){let e=t.length,r="";if(e===0)return r;for(let n=0;n<e;n++){let i=t[n];I2(i,"hints"),r+=i,n!==e-1&&(r+=", ")}return r}throw new xa("hints",t,'must be an array or string of format "</styles.css>; rel=preload; as=style"')}C2.exports={isInt32:y5,isUint32:g5,parseFileMode:b5,validateArray:ph,validateStringArray:_5,validateBooleanArray:B5,validateAbortSignalArray:I5,validateBoolean:k2,validateBuffer:U5,validateDictionary:T5,validateEncoding:O5,validateFunction:k5,validateInt32:E5,validateInteger:x5,validateNumber:v5,validateObject:A5,validateOneOf:S5,validatePlainFunction:N5,validatePort:D5,validateSignalName:R5,validateString:tm,validateUint32:D2,validateUndefined:C5,validateUnion:L5,validateAbortSignal:N2,validateLinkHeaderValue:M5}});var ri=oe((sF,J2)=>{"use strict";l();var{SymbolAsyncIterator:L2,SymbolIterator:P2,SymbolFor:tc}=nt(),M2=tc("nodejs.stream.destroyed"),K2=tc("nodejs.stream.errored"),rm=tc("nodejs.stream.readable"),nm=tc("nodejs.stream.writable"),$2=tc("nodejs.stream.disturbed"),K5=tc("nodejs.webstream.isClosedPromise"),$5=tc("nodejs.webstream.controllerErrorFunction");function yh(t,e=!1){var r;return!!(t&&typeof t.pipe=="function"&&typeof t.on=="function"&&(!e||typeof t.pause=="function"&&typeof t.resume=="function")&&(!t._writableState||((r=t._readableState)===null||r===void 0?void 0:r.readable)!==!1)&&(!t._writableState||t._readableState))}function gh(t){var e;return!!(t&&typeof t.write=="function"&&typeof t.on=="function"&&(!t._readableState||((e=t._writableState)===null||e===void 0?void 0:e.writable)!==!1))}function H5(t){return!!(t&&typeof t.pipe=="function"&&t._readableState&&typeof t.on=="function"&&typeof t.write=="function")}function ti(t){return t&&(t._readableState||t._writableState||typeof t.write=="function"&&typeof t.on=="function"||typeof t.pipe=="function"&&typeof t.on=="function")}function H2(t){return!!(t&&!ti(t)&&typeof t.pipeThrough=="function"&&typeof t.getReader=="function"&&typeof t.cancel=="function")}function V2(t){return!!(t&&!ti(t)&&typeof t.getWriter=="function"&&typeof t.abort=="function")}function q2(t){return!!(t&&!ti(t)&&typeof t.readable=="object"&&typeof t.writable=="object")}function V5(t){return H2(t)||V2(t)||q2(t)}function q5(t,e){return t==null?!1:e===!0?typeof t[L2]=="function":e===!1?typeof t[P2]=="function":typeof t[L2]=="function"||typeof t[P2]=="function"}function mh(t){if(!ti(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!!(t.destroyed||t[M2]||n!=null&&n.destroyed)}function F2(t){if(!gh(t))return null;if(t.writableEnded===!0)return!0;let e=t._writableState;return e!=null&&e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function F5(t,e){if(!gh(t))return null;if(t.writableFinished===!0)return!0;let r=t._writableState;return r!=null&&r.errored?!1:typeof r?.finished!="boolean"?null:!!(r.finished||e===!1&&r.ended===!0&&r.length===0)}function j5(t){if(!yh(t))return null;if(t.readableEnded===!0)return!0;let e=t._readableState;return!e||e.errored?!1:typeof e?.ended!="boolean"?null:e.ended}function j2(t,e){if(!yh(t))return null;let r=t._readableState;return r!=null&&r.errored?!1:typeof r?.endEmitted!="boolean"?null:!!(r.endEmitted||e===!1&&r.ended===!0&&r.length===0)}function W2(t){return t&&t[rm]!=null?t[rm]:typeof t?.readable!="boolean"?null:mh(t)?!1:yh(t)&&t.readable&&!j2(t)}function G2(t){return t&&t[nm]!=null?t[nm]:typeof t?.writable!="boolean"?null:mh(t)?!1:gh(t)&&t.writable&&!F2(t)}function W5(t,e){return ti(t)?mh(t)?!0:!(e?.readable!==!1&&W2(t)||e?.writable!==!1&&G2(t)):null}function G5(t){var e,r;return ti(t)?t.writableErrored?t.writableErrored:(e=(r=t._writableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function z5(t){var e,r;return ti(t)?t.readableErrored?t.readableErrored:(e=(r=t._readableState)===null||r===void 0?void 0:r.errored)!==null&&e!==void 0?e:null:null}function Y5(t){if(!ti(t))return null;if(typeof t.closed=="boolean")return t.closed;let e=t._writableState,r=t._readableState;return typeof e?.closed=="boolean"||typeof r?.closed=="boolean"?e?.closed||r?.closed:typeof t._closed=="boolean"&&z2(t)?t._closed:null}function z2(t){return typeof t._closed=="boolean"&&typeof t._defaultKeepAlive=="boolean"&&typeof t._removedConnection=="boolean"&&typeof t._removedContLen=="boolean"}function Y2(t){return typeof t._sent100=="boolean"&&z2(t)}function J5(t){var e;return typeof t._consuming=="boolean"&&typeof t._dumped=="boolean"&&((e=t.req)===null||e===void 0?void 0:e.upgradeOrConnect)===void 0}function Z5(t){if(!ti(t))return null;let e=t._writableState,r=t._readableState,n=e||r;return!n&&Y2(t)||!!(n&&n.autoDestroy&&n.emitClose&&n.closed===!1)}function X5(t){var e;return!!(t&&((e=t[$2])!==null&&e!==void 0?e:t.readableDidRead||t.readableAborted))}function Q5(t){var e,r,n,i,o,s,c,a,u,d;return!!(t&&((e=(r=(n=(i=(o=(s=t[K2])!==null&&s!==void 0?s:t.readableErrored)!==null&&o!==void 0?o:t.writableErrored)!==null&&i!==void 0?i:(c=t._readableState)===null||c===void 0?void 0:c.errorEmitted)!==null&&n!==void 0?n:(a=t._writableState)===null||a===void 0?void 0:a.errorEmitted)!==null&&r!==void 0?r:(u=t._readableState)===null||u===void 0?void 0:u.errored)!==null&&e!==void 0?e:!((d=t._writableState)===null||d===void 0)&&d.errored))}J2.exports={isDestroyed:mh,kIsDestroyed:M2,isDisturbed:X5,kIsDisturbed:$2,isErrored:Q5,kIsErrored:K2,isReadable:W2,kIsReadable:rm,kIsClosedPromise:K5,kControllerErrorFunction:$5,kIsWritable:nm,isClosed:Y5,isDuplexNodeStream:H5,isFinished:W5,isIterable:q5,isReadableNodeStream:yh,isReadableStream:H2,isReadableEnded:j5,isReadableFinished:j2,isReadableErrored:z5,isNodeStream:ti,isWebStream:V5,isWritable:G2,isWritableNodeStream:gh,isWritableStream:V2,isWritableEnded:F2,isWritableFinished:F5,isWritableErrored:G5,isServerRequest:J5,isServerResponse:Y2,willEmitClose:Z5,isTransformStream:q2}});var ji=oe((aF,am)=>{l();var Ho=Ei(),{AbortError:oS,codes:e3}=ir(),{ERR_INVALID_ARG_TYPE:t3,ERR_STREAM_PREMATURE_CLOSE:Z2}=e3,{kEmptyObject:om,once:sm}=Jt(),{validateAbortSignal:r3,validateFunction:n3,validateObject:i3,validateBoolean:o3}=Ea(),{Promise:s3,PromisePrototypeThen:c3,SymbolDispose:sS}=nt(),{isClosed:a3,isReadable:X2,isReadableNodeStream:im,isReadableStream:u3,isReadableFinished:Q2,isReadableErrored:eS,isWritable:tS,isWritableNodeStream:rS,isWritableStream:d3,isWritableFinished:nS,isWritableErrored:iS,isNodeStream:f3,willEmitClose:l3,kIsClosedPromise:h3}=ri(),va;function p3(t){return t.setHeader&&typeof t.abort=="function"}var cm=()=>{};function cS(t,e,r){var n,i;if(arguments.length===2?(r=e,e=om):e==null?e=om:i3(e,"options"),n3(r,"callback"),r3(e.signal,"options.signal"),r=sm(r),u3(t)||d3(t))return y3(t,e,r);if(!f3(t))throw new t3("stream",["ReadableStream","WritableStream","Stream"],t);let o=(n=e.readable)!==null&&n!==void 0?n:im(t),s=(i=e.writable)!==null&&i!==void 0?i:rS(t),c=t._writableState,a=t._readableState,u=()=>{t.writable||h()},d=l3(t)&&im(t)===o&&rS(t)===s,f=nS(t,!1),h=()=>{f=!0,t.destroyed&&(d=!1),!(d&&(!t.readable||o))&&(!o||p)&&r.call(t)},p=Q2(t,!1),g=()=>{p=!0,t.destroyed&&(d=!1),!(d&&(!t.writable||s))&&(!s||f)&&r.call(t)},y=T=>{r.call(t,T)},E=a3(t),S=()=>{E=!0;let T=iS(t)||eS(t);if(T&&typeof T!="boolean")return r.call(t,T);if(o&&!p&&im(t,!0)&&!Q2(t,!1))return r.call(t,new Z2);if(s&&!f&&!nS(t,!1))return r.call(t,new Z2);r.call(t)},I=()=>{E=!0;let T=iS(t)||eS(t);if(T&&typeof T!="boolean")return r.call(t,T);r.call(t)},A=()=>{t.req.on("finish",h)};p3(t)?(t.on("complete",h),d||t.on("abort",S),t.req?A():t.on("request",A)):s&&!c&&(t.on("end",u),t.on("close",u)),!d&&typeof t.aborted=="boolean"&&t.on("aborted",S),t.on("end",g),t.on("finish",h),e.error!==!1&&t.on("error",y),t.on("close",S),E?Ho.nextTick(S):c!=null&&c.errorEmitted||a!=null&&a.errorEmitted?d||Ho.nextTick(I):(!o&&(!d||X2(t))&&(f||tS(t)===!1)||!s&&(!d||tS(t))&&(p||X2(t)===!1)||a&&t.req&&t.aborted)&&Ho.nextTick(I);let O=()=>{r=cm,t.removeListener("aborted",S),t.removeListener("complete",h),t.removeListener("abort",S),t.removeListener("request",A),t.req&&t.req.removeListener("finish",h),t.removeListener("end",u),t.removeListener("close",u),t.removeListener("finish",h),t.removeListener("end",g),t.removeListener("error",y),t.removeListener("close",S)};if(e.signal&&!E){let T=()=>{let M=r;O(),M.call(t,new oS(void 0,{cause:e.signal.reason}))};if(e.signal.aborted)Ho.nextTick(T);else{va=va||Jt().addAbortListener;let M=va(e.signal,T),q=r;r=sm((...j)=>{M[sS](),q.apply(t,j)})}}return O}function y3(t,e,r){let n=!1,i=cm;if(e.signal)if(i=()=>{n=!0,r.call(t,new oS(void 0,{cause:e.signal.reason}))},e.signal.aborted)Ho.nextTick(i);else{va=va||Jt().addAbortListener;let s=va(e.signal,i),c=r;r=sm((...a)=>{s[sS](),c.apply(t,a)})}let o=(...s)=>{n||Ho.nextTick(()=>r.apply(t,s))};return c3(t[h3].promise,o,o),cm}function g3(t,e){var r;let n=!1;return e===null&&(e=om),(r=e)!==null&&r!==void 0&&r.cleanup&&(o3(e.cleanup,"cleanup"),n=e.cleanup),new s3((i,o)=>{let s=cS(t,e,c=>{n&&s(),c?o(c):i()})})}am.exports=cS;am.exports.finished=g3});var rc=oe((dF,yS)=>{"use strict";l();var ni=Ei(),{aggregateTwoErrors:m3,codes:{ERR_MULTIPLE_CALLBACK:w3},AbortError:b3}=ir(),{Symbol:dS}=nt(),{kIsDestroyed:x3,isDestroyed:E3,isFinished:v3,isServerRequest:S3}=ri(),fS=dS("kDestroy"),um=dS("kConstruct");function lS(t,e,r){t&&(t.stack,e&&!e.errored&&(e.errored=t),r&&!r.errored&&(r.errored=t))}function A3(t,e){let r=this._readableState,n=this._writableState,i=n||r;return n!=null&&n.destroyed||r!=null&&r.destroyed?(typeof e=="function"&&e(),this):(lS(t,n,r),n&&(n.destroyed=!0),r&&(r.destroyed=!0),i.constructed?aS(this,t,e):this.once(fS,function(o){aS(this,m3(o,t),e)}),this)}function aS(t,e,r){let n=!1;function i(o){if(n)return;n=!0;let s=t._readableState,c=t._writableState;lS(o,c,s),c&&(c.closed=!0),s&&(s.closed=!0),typeof r=="function"&&r(o),o?ni.nextTick(T3,t,o):ni.nextTick(hS,t)}try{t._destroy(e||null,i)}catch(o){i(o)}}function T3(t,e){dm(t,e),hS(t)}function hS(t){let e=t._readableState,r=t._writableState;r&&(r.closeEmitted=!0),e&&(e.closeEmitted=!0),(r!=null&&r.emitClose||e!=null&&e.emitClose)&&t.emit("close")}function dm(t,e){let r=t._readableState,n=t._writableState;n!=null&&n.errorEmitted||r!=null&&r.errorEmitted||(n&&(n.errorEmitted=!0),r&&(r.errorEmitted=!0),t.emit("error",e))}function _3(){let t=this._readableState,e=this._writableState;t&&(t.constructed=!0,t.closed=!1,t.closeEmitted=!1,t.destroyed=!1,t.errored=null,t.errorEmitted=!1,t.reading=!1,t.ended=t.readable===!1,t.endEmitted=t.readable===!1),e&&(e.constructed=!0,e.destroyed=!1,e.closed=!1,e.closeEmitted=!1,e.errored=null,e.errorEmitted=!1,e.finalCalled=!1,e.prefinished=!1,e.ended=e.writable===!1,e.ending=e.writable===!1,e.finished=e.writable===!1)}function fm(t,e,r){let n=t._readableState,i=t._writableState;if(i!=null&&i.destroyed||n!=null&&n.destroyed)return this;n!=null&&n.autoDestroy||i!=null&&i.autoDestroy?t.destroy(e):e&&(e.stack,i&&!i.errored&&(i.errored=e),n&&!n.errored&&(n.errored=e),r?ni.nextTick(dm,t,e):dm(t,e))}function B3(t,e){if(typeof t._construct!="function")return;let r=t._readableState,n=t._writableState;r&&(r.constructed=!1),n&&(n.constructed=!1),t.once(um,e),!(t.listenerCount(um)>1)&&ni.nextTick(I3,t)}function I3(t){let e=!1;function r(n){if(e){fm(t,n??new w3);return}e=!0;let i=t._readableState,o=t._writableState,s=o||i;i&&(i.constructed=!0),o&&(o.constructed=!0),s.destroyed?t.emit(fS,n):n?fm(t,n,!0):ni.nextTick(R3,t)}try{t._construct(n=>{ni.nextTick(r,n)})}catch(n){ni.nextTick(r,n)}}function R3(t){t.emit(um)}function uS(t){return t?.setHeader&&typeof t.abort=="function"}function pS(t){t.emit("close")}function U3(t,e){t.emit("error",e),ni.nextTick(pS,t)}function O3(t,e){!t||E3(t)||(!e&&!v3(t)&&(e=new b3),S3(t)?(t.socket=null,t.destroy(e)):uS(t)?t.abort():uS(t.req)?t.req.abort():typeof t.destroy=="function"?t.destroy(e):typeof t.close=="function"?t.close():e?ni.nextTick(U3,t,e):ni.nextTick(pS,t),t.destroyed||(t[x3]=!0))}yS.exports={construct:B3,destroyer:O3,destroy:A3,undestroy:_3,errorOrDestroy:fm}});var xh=oe((lF,mS)=>{"use strict";l();var{ArrayIsArray:D3,ObjectSetPrototypeOf:gS}=nt(),{EventEmitter:wh}=aa();function bh(t){wh.call(this,t)}gS(bh.prototype,wh.prototype);gS(bh,wh);bh.prototype.pipe=function(t,e){let r=this;function n(d){t.writable&&t.write(d)===!1&&r.pause&&r.pause()}r.on("data",n);function i(){r.readable&&r.resume&&r.resume()}t.on("drain",i),!t._isStdio&&(!e||e.end!==!1)&&(r.on("end",s),r.on("close",c));let o=!1;function s(){o||(o=!0,t.end())}function c(){o||(o=!0,typeof t.destroy=="function"&&t.destroy())}function a(d){u(),wh.listenerCount(this,"error")===0&&this.emit("error",d)}lm(r,"error",a),lm(t,"error",a);function u(){r.removeListener("data",n),t.removeListener("drain",i),r.removeListener("end",s),r.removeListener("close",c),r.removeListener("error",a),t.removeListener("error",a),r.removeListener("end",u),r.removeListener("close",u),t.removeListener("close",u)}return r.on("end",u),r.on("close",u),t.on("close",u),t.emit("pipe",r),t};function lm(t,e,r){if(typeof t.prependListener=="function")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):D3(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}mS.exports={Stream:bh,prependListener:lm}});var Sd=oe((pF,Eh)=>{"use strict";l();var{SymbolDispose:k3}=nt(),{AbortError:wS,codes:N3}=ir(),{isNodeStream:bS,isWebStream:C3,kControllerErrorFunction:L3}=ri(),P3=ji(),{ERR_INVALID_ARG_TYPE:xS}=N3,hm,M3=(t,e)=>{if(typeof t!="object"||!("aborted"in t))throw new xS(e,"AbortSignal",t)};Eh.exports.addAbortSignal=function(e,r){if(M3(e,"signal"),!bS(r)&&!C3(r))throw new xS("stream",["ReadableStream","WritableStream","Stream"],r);return Eh.exports.addAbortSignalNoValidate(e,r)};Eh.exports.addAbortSignalNoValidate=function(t,e){if(typeof t!="object"||!("aborted"in t))return e;let r=bS(e)?()=>{e.destroy(new wS(void 0,{cause:t.reason}))}:()=>{e[L3](new wS(void 0,{cause:t.reason}))};if(t.aborted)r();else{hm=hm||Jt().addAbortListener;let n=hm(t,r);P3(e,n[k3])}return e}});var SS=oe((mF,vS)=>{"use strict";l();var{StringPrototypeSlice:ES,SymbolIterator:K3,TypedArrayPrototypeSet:vh,Uint8Array:$3}=nt(),{Buffer:pm}=Sr(),{inspect:H3}=Jt();vS.exports=class{constructor(){this.head=null,this.tail=null,this.length=0}push(e){let r={data:e,next:null};this.length>0?this.tail.next=r:this.head=r,this.tail=r,++this.length}unshift(e){let r={data:e,next:this.head};this.length===0&&(this.tail=r),this.head=r,++this.length}shift(){if(this.length===0)return;let e=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,e}clear(){this.head=this.tail=null,this.length=0}join(e){if(this.length===0)return"";let r=this.head,n=""+r.data;for(;(r=r.next)!==null;)n+=e+r.data;return n}concat(e){if(this.length===0)return pm.alloc(0);let r=pm.allocUnsafe(e>>>0),n=this.head,i=0;for(;n;)vh(r,n.data,i),i+=n.data.length,n=n.next;return r}consume(e,r){let n=this.head.data;if(e<n.length){let i=n.slice(0,e);return this.head.data=n.slice(e),i}return e===n.length?this.shift():r?this._getString(e):this._getBuffer(e)}first(){return this.head.data}*[K3](){for(let e=this.head;e;e=e.next)yield e.data}_getString(e){let r="",n=this.head,i=0;do{let o=n.data;if(e>o.length)r+=o,e-=o.length;else{e===o.length?(r+=o,++i,n.next?this.head=n.next:this.head=this.tail=null):(r+=ES(o,0,e),this.head=n,n.data=ES(o,e));break}++i}while((n=n.next)!==null);return this.length-=i,r}_getBuffer(e){let r=pm.allocUnsafe(e),n=e,i=this.head,o=0;do{let s=i.data;if(e>s.length)vh(r,s,n-e),e-=s.length;else{e===s.length?(vh(r,s,n-e),++o,i.next?this.head=i.next:this.head=this.tail=null):(vh(r,new $3(s.buffer,s.byteOffset,e),n-e),this.head=i,i.data=s.slice(e));break}++o}while((i=i.next)!==null);return this.length-=o,r}[Symbol.for("nodejs.util.inspect.custom")](e,r){return H3(this,{...r,depth:0,customInspect:!1})}}});var Ad=oe((bF,BS)=>{"use strict";l();var{MathFloor:V3,NumberIsInteger:q3}=nt(),{validateInteger:F3}=Ea(),{ERR_INVALID_ARG_VALUE:j3}=ir().codes,AS=16*1024,TS=16;function W3(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function _S(t){return t?TS:AS}function G3(t,e){F3(e,"value",0),t?TS=e:AS=e}function z3(t,e,r,n){let i=W3(e,n,r);if(i!=null){if(!q3(i)||i<0){let o=n?`options.${r}`:"options.highWaterMark";throw new j3(o,i)}return V3(i)}return _S(t.objectMode)}BS.exports={getHighWaterMark:z3,getDefaultHighWaterMark:_S,setDefaultHighWaterMark:G3}});var US=oe((ym,RS)=>{l();var Sh=Sr(),ii=Sh.Buffer;function IS(t,e){for(var r in t)e[r]=t[r]}ii.from&&ii.alloc&&ii.allocUnsafe&&ii.allocUnsafeSlow?RS.exports=Sh:(IS(Sh,ym),ym.Buffer=nc);function nc(t,e,r){return ii(t,e,r)}nc.prototype=Object.create(ii.prototype);IS(ii,nc);nc.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return ii(t,e,r)};nc.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=ii(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};nc.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ii(t)};nc.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Sh.SlowBuffer(t)}});var kS=oe(DS=>{"use strict";l();var mm=US().Buffer,OS=mm.isEncoding||function(t){switch(t=""+t,t&&t.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function Y3(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function J3(t){var e=Y3(t);if(typeof e!="string"&&(mm.isEncoding===OS||!OS(t)))throw new Error("Unknown encoding: "+t);return e||t}DS.StringDecoder=Td;function Td(t){this.encoding=J3(t);var e;switch(this.encoding){case"utf16le":this.text=rO,this.end=nO,e=4;break;case"utf8":this.fillLast=Q3,e=4;break;case"base64":this.text=iO,this.end=oO,e=3;break;default:this.write=sO,this.end=cO;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=mm.allocUnsafe(e)}Td.prototype.write=function(t){if(t.length===0)return"";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<t.length?e?e+this.text(t,r):this.text(t,r):e||""};Td.prototype.end=tO;Td.prototype.text=eO;Td.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};function gm(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function Z3(t,e,r){var n=e.length-1;if(n<r)return 0;var i=gm(e[n]);return i>=0?(i>0&&(t.lastNeed=i-1),i):--n<r||i===-2?0:(i=gm(e[n]),i>=0?(i>0&&(t.lastNeed=i-2),i):--n<r||i===-2?0:(i=gm(e[n]),i>=0?(i>0&&(i===2?i=0:t.lastNeed=i-3),i):0))}function X3(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,"\uFFFD";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,"\uFFFD";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,"\uFFFD"}}function Q3(t){var e=this.lastTotal-this.lastNeed,r=X3(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function eO(t,e){var r=Z3(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)}function tO(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"\uFFFD":e}function rO(t,e){if((t.length-e)%2===0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function nO(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function iO(t,e){var r=(t.length-e)%3;return r===0?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function oO(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function sO(t){return t.toString(this.encoding)}function cO(t){return t&&t.length?this.write(t):""}});var wm=oe((AF,PS)=>{"use strict";l();var NS=Ei(),{PromisePrototypeThen:aO,SymbolAsyncIterator:CS,SymbolIterator:LS}=nt(),{Buffer:uO}=Sr(),{ERR_INVALID_ARG_TYPE:dO,ERR_STREAM_NULL_VALUES:fO}=ir().codes;function lO(t,e,r){let n;if(typeof e=="string"||e instanceof uO)return new t({objectMode:!0,...r,read(){this.push(e),this.push(null)}});let i;if(e&&e[CS])i=!0,n=e[CS]();else if(e&&e[LS])i=!1,n=e[LS]();else throw new dO("iterable",["Iterable"],e);let o=new t({objectMode:!0,highWaterMark:1,...r}),s=!1;o._read=function(){s||(s=!0,a())},o._destroy=function(u,d){aO(c(u),()=>NS.nextTick(d,u),f=>NS.nextTick(d,f||u))};async function c(u){let d=u!=null,f=typeof n.throw=="function";if(d&&f){let{value:h,done:p}=await n.throw(u);if(await h,p)return}if(typeof n.return=="function"){let{value:h}=await n.return();await h}}async function a(){for(;;){try{let{value:u,done:d}=i?await n.next():n.next();if(d)o.push(null);else{let f=u&&typeof u.then=="function"?await u:u;if(f===null)throw s=!1,new fO;if(o.push(f))continue;s=!1}}catch(u){o.destroy(u)}break}}return o}PS.exports=lO});var Bd=oe((_F,tA)=>{l();var An=Ei(),{ArrayPrototypeIndexOf:hO,NumberIsInteger:pO,NumberIsNaN:yO,NumberParseInt:gO,ObjectDefineProperties:_m,ObjectKeys:mO,ObjectSetPrototypeOf:$S,Promise:HS,SafeSet:wO,SymbolAsyncDispose:bO,SymbolAsyncIterator:xO,Symbol:EO}=nt();tA.exports=ye;ye.ReadableState=Bh;var{EventEmitter:vO}=aa(),{Stream:Vo,prependListener:SO}=xh(),{Buffer:bm}=Sr(),{addAbortSignal:AO}=Sd(),VS=ji(),be=Jt().debuglog("stream",t=>{be=t}),TO=SS(),Ta=rc(),{getHighWaterMark:_O,getDefaultHighWaterMark:BO}=Ad(),{aggregateTwoErrors:MS,codes:{ERR_INVALID_ARG_TYPE:IO,ERR_METHOD_NOT_IMPLEMENTED:RO,ERR_OUT_OF_RANGE:UO,ERR_STREAM_PUSH_AFTER_EOF:OO,ERR_STREAM_UNSHIFT_AFTER_END_EVENT:DO},AbortError:kO}=ir(),{validateObject:NO}=Ea(),ic=EO("kPaused"),{StringDecoder:qS}=kS(),CO=wm();$S(ye.prototype,Vo.prototype);$S(ye,Vo);var xm=()=>{},{errorOrDestroy:Sa}=Ta,Aa=1,LO=2,FS=4,_d=8,jS=16,Ah=32,Th=64,WS=128,PO=256,MO=512,KO=1024,Am=2048,Tm=4096,$O=8192,HO=16384,VO=32768,GS=65536,qO=1<<17,FO=1<<18;function St(t){return{enumerable:!1,get(){return(this.state&t)!==0},set(e){e?this.state|=t:this.state&=~t}}}_m(Bh.prototype,{objectMode:St(Aa),ended:St(LO),endEmitted:St(FS),reading:St(_d),constructed:St(jS),sync:St(Ah),needReadable:St(Th),emittedReadable:St(WS),readableListening:St(PO),resumeScheduled:St(MO),errorEmitted:St(KO),emitClose:St(Am),autoDestroy:St(Tm),destroyed:St($O),closed:St(HO),closeEmitted:St(VO),multiAwaitDrain:St(GS),readingMore:St(qO),dataEmitted:St(FO)});function Bh(t,e,r){typeof r!="boolean"&&(r=e instanceof oi()),this.state=Am|Tm|jS|Ah,t&&t.objectMode&&(this.state|=Aa),r&&t&&t.readableObjectMode&&(this.state|=Aa),this.highWaterMark=t?_O(this,t,"readableHighWaterMark",r):BO(!1),this.buffer=new TO,this.length=0,this.pipes=[],this.flowing=null,this[ic]=null,t&&t.emitClose===!1&&(this.state&=~Am),t&&t.autoDestroy===!1&&(this.state&=~Tm),this.errored=null,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.awaitDrainWriters=null,this.decoder=null,this.encoding=null,t&&t.encoding&&(this.decoder=new qS(t.encoding),this.encoding=t.encoding)}function ye(t){if(!(this instanceof ye))return new ye(t);let e=this instanceof oi();this._readableState=new Bh(t,this,e),t&&(typeof t.read=="function"&&(this._read=t.read),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&!e&&AO(t.signal,this)),Vo.call(this,t),Ta.construct(this,()=>{this._readableState.needReadable&&_h(this,this._readableState)})}ye.prototype.destroy=Ta.destroy;ye.prototype._undestroy=Ta.undestroy;ye.prototype._destroy=function(t,e){e(t)};ye.prototype[vO.captureRejectionSymbol]=function(t){this.destroy(t)};ye.prototype[bO]=function(){let t;return this.destroyed||(t=this.readableEnded?null:new kO,this.destroy(t)),new HS((e,r)=>VS(this,n=>n&&n!==t?r(n):e(null)))};ye.prototype.push=function(t,e){return zS(this,t,e,!1)};ye.prototype.unshift=function(t,e){return zS(this,t,e,!0)};function zS(t,e,r,n){be("readableAddChunk",e);let i=t._readableState,o;if(i.state&Aa||(typeof e=="string"?(r=r||i.defaultEncoding,i.encoding!==r&&(n&&i.encoding?e=bm.from(e,r).toString(i.encoding):(e=bm.from(e,r),r=""))):e instanceof bm?r="":Vo._isUint8Array(e)?(e=Vo._uint8ArrayToBuffer(e),r=""):e!=null&&(o=new IO("chunk",["string","Buffer","Uint8Array"],e))),o)Sa(t,o);else if(e===null)i.state&=~_d,GO(t,i);else if(i.state&Aa||e&&e.length>0)if(n)if(i.state&FS)Sa(t,new DO);else{if(i.destroyed||i.errored)return!1;Em(t,i,e,!0)}else if(i.ended)Sa(t,new OO);else{if(i.destroyed||i.errored)return!1;i.state&=~_d,i.decoder&&!r?(e=i.decoder.write(e),i.objectMode||e.length!==0?Em(t,i,e,!1):_h(t,i)):Em(t,i,e,!1)}else n||(i.state&=~_d,_h(t,i));return!i.ended&&(i.length<i.highWaterMark||i.length===0)}function Em(t,e,r,n){e.flowing&&e.length===0&&!e.sync&&t.listenerCount("data")>0?(e.state&GS?e.awaitDrainWriters.clear():e.awaitDrainWriters=null,e.dataEmitted=!0,t.emit("data",r)):(e.length+=e.objectMode?1:r.length,n?e.buffer.unshift(r):e.buffer.push(r),e.state&Th&&Ih(t)),_h(t,e)}ye.prototype.isPaused=function(){let t=this._readableState;return t[ic]===!0||t.flowing===!1};ye.prototype.setEncoding=function(t){let e=new qS(t);this._readableState.decoder=e,this._readableState.encoding=this._readableState.decoder.encoding;let r=this._readableState.buffer,n="";for(let i of r)n+=e.write(i);return r.clear(),n!==""&&r.push(n),this._readableState.length=n.length,this};var jO=1073741824;function WO(t){if(t>jO)throw new UO("size","<= 1GiB",t);return t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++,t}function KS(t,e){return t<=0||e.length===0&&e.ended?0:e.state&Aa?1:yO(t)?e.flowing&&e.length?e.buffer.first().length:e.length:t<=e.length?t:e.ended?e.length:0}ye.prototype.read=function(t){be("read",t),t===void 0?t=NaN:pO(t)||(t=gO(t,10));let e=this._readableState,r=t;if(t>e.highWaterMark&&(e.highWaterMark=WO(t)),t!==0&&(e.state&=~WS),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return be("read: emitReadable",e.length,e.ended),e.length===0&&e.ended?vm(this):Ih(this),null;if(t=KS(t,e),t===0&&e.ended)return e.length===0&&vm(this),null;let n=(e.state&Th)!==0;if(be("need readable",n),(e.length===0||e.length-t<e.highWaterMark)&&(n=!0,be("length less than watermark",n)),e.ended||e.reading||e.destroyed||e.errored||!e.constructed)n=!1,be("reading, ended or constructing",n);else if(n){be("do read"),e.state|=_d|Ah,e.length===0&&(e.state|=Th);try{this._read(e.highWaterMark)}catch(o){Sa(this,o)}e.state&=~Ah,e.reading||(t=KS(r,e))}let i;return t>0?i=QS(t,e):i=null,i===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.multiAwaitDrain?e.awaitDrainWriters.clear():e.awaitDrainWriters=null),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&vm(this)),i!==null&&!e.errorEmitted&&!e.closeEmitted&&(e.dataEmitted=!0,this.emit("data",i)),i};function GO(t,e){if(be("onEofChunk"),!e.ended){if(e.decoder){let r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?Ih(t):(e.needReadable=!1,e.emittedReadable=!0,YS(t))}}function Ih(t){let e=t._readableState;be("emitReadable",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(be("emitReadable",e.flowing),e.emittedReadable=!0,An.nextTick(YS,t))}function YS(t){let e=t._readableState;be("emitReadable_",e.destroyed,e.length,e.ended),!e.destroyed&&!e.errored&&(e.length||e.ended)&&(t.emit("readable"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,ZS(t)}function _h(t,e){!e.readingMore&&e.constructed&&(e.readingMore=!0,An.nextTick(zO,t,e))}function zO(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&e.length===0);){let r=e.length;if(be("maybeReadMore read 0"),t.read(0),r===e.length)break}e.readingMore=!1}ye.prototype._read=function(t){throw new RO("_read()")};ye.prototype.pipe=function(t,e){let r=this,n=this._readableState;n.pipes.length===1&&(n.multiAwaitDrain||(n.multiAwaitDrain=!0,n.awaitDrainWriters=new wO(n.awaitDrainWriters?[n.awaitDrainWriters]:[]))),n.pipes.push(t),be("pipe count=%d opts=%j",n.pipes.length,e);let o=(!e||e.end!==!1)&&t!==An.stdout&&t!==An.stderr?c:E;n.endEmitted?An.nextTick(o):r.once("end",o),t.on("unpipe",s);function s(S,I){be("onunpipe"),S===r&&I&&I.hasUnpiped===!1&&(I.hasUnpiped=!0,d())}function c(){be("onend"),t.end()}let a,u=!1;function d(){be("cleanup"),t.removeListener("close",g),t.removeListener("finish",y),a&&t.removeListener("drain",a),t.removeListener("error",p),t.removeListener("unpipe",s),r.removeListener("end",c),r.removeListener("end",E),r.removeListener("data",h),u=!0,a&&n.awaitDrainWriters&&(!t._writableState||t._writableState.needDrain)&&a()}function f(){u||(n.pipes.length===1&&n.pipes[0]===t?(be("false write response, pause",0),n.awaitDrainWriters=t,n.multiAwaitDrain=!1):n.pipes.length>1&&n.pipes.includes(t)&&(be("false write response, pause",n.awaitDrainWriters.size),n.awaitDrainWriters.add(t)),r.pause()),a||(a=YO(r,t),t.on("drain",a))}r.on("data",h);function h(S){be("ondata");let I=t.write(S);be("dest.write",I),I===!1&&f()}function p(S){if(be("onerror",S),E(),t.removeListener("error",p),t.listenerCount("error")===0){let I=t._writableState||t._readableState;I&&!I.errorEmitted?Sa(t,S):t.emit("error",S)}}SO(t,"error",p);function g(){t.removeListener("finish",y),E()}t.once("close",g);function y(){be("onfinish"),t.removeListener("close",g),E()}t.once("finish",y);function E(){be("unpipe"),r.unpipe(t)}return t.emit("pipe",r),t.writableNeedDrain===!0?f():n.flowing||(be("pipe resume"),r.resume()),t};function YO(t,e){return function(){let n=t._readableState;n.awaitDrainWriters===e?(be("pipeOnDrain",1),n.awaitDrainWriters=null):n.multiAwaitDrain&&(be("pipeOnDrain",n.awaitDrainWriters.size),n.awaitDrainWriters.delete(e)),(!n.awaitDrainWriters||n.awaitDrainWriters.size===0)&&t.listenerCount("data")&&t.resume()}}ye.prototype.unpipe=function(t){let e=this._readableState,r={hasUnpiped:!1};if(e.pipes.length===0)return this;if(!t){let i=e.pipes;e.pipes=[],this.pause();for(let o=0;o<i.length;o++)i[o].emit("unpipe",this,{hasUnpiped:!1});return this}let n=hO(e.pipes,t);return n===-1?this:(e.pipes.splice(n,1),e.pipes.length===0&&this.pause(),t.emit("unpipe",this,r),this)};ye.prototype.on=function(t,e){let r=Vo.prototype.on.call(this,t,e),n=this._readableState;return t==="data"?(n.readableListening=this.listenerCount("readable")>0,n.flowing!==!1&&this.resume()):t==="readable"&&!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.flowing=!1,n.emittedReadable=!1,be("on readable",n.length,n.reading),n.length?Ih(this):n.reading||An.nextTick(JO,this)),r};ye.prototype.addListener=ye.prototype.on;ye.prototype.removeListener=function(t,e){let r=Vo.prototype.removeListener.call(this,t,e);return t==="readable"&&An.nextTick(JS,this),r};ye.prototype.off=ye.prototype.removeListener;ye.prototype.removeAllListeners=function(t){let e=Vo.prototype.removeAllListeners.apply(this,arguments);return(t==="readable"||t===void 0)&&An.nextTick(JS,this),e};function JS(t){let e=t._readableState;e.readableListening=t.listenerCount("readable")>0,e.resumeScheduled&&e[ic]===!1?e.flowing=!0:t.listenerCount("data")>0?t.resume():e.readableListening||(e.flowing=null)}function JO(t){be("readable nexttick read 0"),t.read(0)}ye.prototype.resume=function(){let t=this._readableState;return t.flowing||(be("resume"),t.flowing=!t.readableListening,ZO(this,t)),t[ic]=!1,this};function ZO(t,e){e.resumeScheduled||(e.resumeScheduled=!0,An.nextTick(XO,t,e))}function XO(t,e){be("resume",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit("resume"),ZS(t),e.flowing&&!e.reading&&t.read(0)}ye.prototype.pause=function(){return be("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(be("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState[ic]=!0,this};function ZS(t){let e=t._readableState;for(be("flow",e.flowing);e.flowing&&t.read()!==null;);}ye.prototype.wrap=function(t){let e=!1;t.on("data",n=>{!this.push(n)&&t.pause&&(e=!0,t.pause())}),t.on("end",()=>{this.push(null)}),t.on("error",n=>{Sa(this,n)}),t.on("close",()=>{this.destroy()}),t.on("destroy",()=>{this.destroy()}),this._read=()=>{e&&t.resume&&(e=!1,t.resume())};let r=mO(t);for(let n=1;n<r.length;n++){let i=r[n];this[i]===void 0&&typeof t[i]=="function"&&(this[i]=t[i].bind(t))}return this};ye.prototype[xO]=function(){return XS(this)};ye.prototype.iterator=function(t){return t!==void 0&&NO(t,"options"),XS(this,t)};function XS(t,e){typeof t.read!="function"&&(t=ye.wrap(t,{objectMode:!0}));let r=QO(t,e);return r.stream=t,r}async function*QO(t,e){let r=xm;function n(s){this===t?(r(),r=xm):r=s}t.on("readable",n);let i,o=VS(t,{writable:!1},s=>{i=s?MS(i,s):null,r(),r=xm});try{for(;;){let s=t.destroyed?null:t.read();if(s!==null)yield s;else{if(i)throw i;if(i===null)return;await new HS(n)}}}catch(s){throw i=MS(i,s),i}finally{(i||e?.destroyOnReturn!==!1)&&(i===void 0||t._readableState.autoDestroy)?Ta.destroyer(t,null):(t.off("readable",n),o())}}_m(ye.prototype,{readable:{__proto__:null,get(){let t=this._readableState;return!!t&&t.readable!==!1&&!t.destroyed&&!t.errorEmitted&&!t.endEmitted},set(t){this._readableState&&(this._readableState.readable=!!t)}},readableDidRead:{__proto__:null,enumerable:!1,get:function(){return this._readableState.dataEmitted}},readableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._readableState.readable!==!1&&(this._readableState.destroyed||this._readableState.errored)&&!this._readableState.endEmitted)}},readableHighWaterMark:{__proto__:null,enumerable:!1,get:function(){return this._readableState.highWaterMark}},readableBuffer:{__proto__:null,enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}},readableFlowing:{__proto__:null,enumerable:!1,get:function(){return this._readableState.flowing},set:function(t){this._readableState&&(this._readableState.flowing=t)}},readableLength:{__proto__:null,enumerable:!1,get(){return this._readableState.length}},readableObjectMode:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.objectMode:!1}},readableEncoding:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.encoding:null}},errored:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.errored:null}},closed:{__proto__:null,get(){return this._readableState?this._readableState.closed:!1}},destroyed:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.destroyed:!1},set(t){this._readableState&&(this._readableState.destroyed=t)}},readableEnded:{__proto__:null,enumerable:!1,get(){return this._readableState?this._readableState.endEmitted:!1}}});_m(Bh.prototype,{pipesCount:{__proto__:null,get(){return this.pipes.length}},paused:{__proto__:null,get(){return this[ic]!==!1},set(t){this[ic]=!!t}}});ye._fromList=QS;function QS(t,e){if(e.length===0)return null;let r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(e.decoder?r=e.buffer.join(""):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function vm(t){let e=t._readableState;be("endReadable",e.endEmitted),e.endEmitted||(e.ended=!0,An.nextTick(eD,e,t))}function eD(t,e){if(be("endReadableNT",t.endEmitted,t.length),!t.errored&&!t.closeEmitted&&!t.endEmitted&&t.length===0){if(t.endEmitted=!0,e.emit("end"),e.writable&&e.allowHalfOpen===!1)An.nextTick(tD,e);else if(t.autoDestroy){let r=e._writableState;(!r||r.autoDestroy&&(r.finished||r.writable===!1))&&e.destroy()}}}function tD(t){t.writable&&!t.writableEnded&&!t.destroyed&&t.end()}ye.from=function(t,e){return CO(ye,t,e)};var Sm;function eA(){return Sm===void 0&&(Sm={}),Sm}ye.fromWeb=function(t,e){return eA().newStreamReadableFromReadableStream(t,e)};ye.toWeb=function(t,e){return eA().newReadableStreamFromStreamReadable(t,e)};ye.wrap=function(t,e){var r,n;return new ye({objectMode:(r=(n=t.readableObjectMode)!==null&&n!==void 0?n:t.objectMode)!==null&&r!==void 0?r:!0,...e,destroy(i,o){Ta.destroyer(t,i),o(i)}}).wrap(t)}});var kh=oe((IF,hA)=>{l();var oc=Ei(),{ArrayPrototypeSlice:iA,Error:rD,FunctionPrototypeSymbolHasInstance:oA,ObjectDefineProperty:sA,ObjectDefineProperties:nD,ObjectSetPrototypeOf:cA,StringPrototypeToLowerCase:iD,Symbol:oD,SymbolHasInstance:sD}=nt();hA.exports=it;it.WritableState=Ud;var{EventEmitter:cD}=aa(),Id=xh().Stream,{Buffer:Rh}=Sr(),Dh=rc(),{addAbortSignal:aD}=Sd(),{getHighWaterMark:uD,getDefaultHighWaterMark:dD}=Ad(),{ERR_INVALID_ARG_TYPE:fD,ERR_METHOD_NOT_IMPLEMENTED:lD,ERR_MULTIPLE_CALLBACK:aA,ERR_STREAM_CANNOT_PIPE:hD,ERR_STREAM_DESTROYED:Rd,ERR_STREAM_ALREADY_FINISHED:pD,ERR_STREAM_NULL_VALUES:yD,ERR_STREAM_WRITE_AFTER_END:gD,ERR_UNKNOWN_ENCODING:uA}=ir().codes,{errorOrDestroy:_a}=Dh;cA(it.prototype,Id.prototype);cA(it,Id);function Rm(){}var Ba=oD("kOnFinished");function Ud(t,e,r){typeof r!="boolean"&&(r=e instanceof oi()),this.objectMode=!!(t&&t.objectMode),r&&(this.objectMode=this.objectMode||!!(t&&t.writableObjectMode)),this.highWaterMark=t?uD(this,t,"writableHighWaterMark",r):dD(!1),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;let n=!!(t&&t.decodeStrings===!1);this.decodeStrings=!n,this.defaultEncoding=t&&t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=wD.bind(void 0,e),this.writecb=null,this.writelen=0,this.afterWriteTickInfo=null,Oh(this),this.pendingcb=0,this.constructed=!0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!t||t.emitClose!==!1,this.autoDestroy=!t||t.autoDestroy!==!1,this.errored=null,this.closed=!1,this.closeEmitted=!1,this[Ba]=[]}function Oh(t){t.buffered=[],t.bufferedIndex=0,t.allBuffers=!0,t.allNoop=!0}Ud.prototype.getBuffer=function(){return iA(this.buffered,this.bufferedIndex)};sA(Ud.prototype,"bufferedRequestCount",{__proto__:null,get(){return this.buffered.length-this.bufferedIndex}});function it(t){let e=this instanceof oi();if(!e&&!oA(it,this))return new it(t);this._writableState=new Ud(t,this,e),t&&(typeof t.write=="function"&&(this._write=t.write),typeof t.writev=="function"&&(this._writev=t.writev),typeof t.destroy=="function"&&(this._destroy=t.destroy),typeof t.final=="function"&&(this._final=t.final),typeof t.construct=="function"&&(this._construct=t.construct),t.signal&&aD(t.signal,this)),Id.call(this,t),Dh.construct(this,()=>{let r=this._writableState;r.writing||Om(this,r),Dm(this,r)})}sA(it,sD,{__proto__:null,value:function(t){return oA(this,t)?!0:this!==it?!1:t&&t._writableState instanceof Ud}});it.prototype.pipe=function(){_a(this,new hD)};function dA(t,e,r,n){let i=t._writableState;if(typeof r=="function")n=r,r=i.defaultEncoding;else{if(!r)r=i.defaultEncoding;else if(r!=="buffer"&&!Rh.isEncoding(r))throw new uA(r);typeof n!="function"&&(n=Rm)}if(e===null)throw new yD;if(!i.objectMode)if(typeof e=="string")i.decodeStrings!==!1&&(e=Rh.from(e,r),r="buffer");else if(e instanceof Rh)r="buffer";else if(Id._isUint8Array(e))e=Id._uint8ArrayToBuffer(e),r="buffer";else throw new fD("chunk",["string","Buffer","Uint8Array"],e);let o;return i.ending?o=new gD:i.destroyed&&(o=new Rd("write")),o?(oc.nextTick(n,o),_a(t,o,!0),o):(i.pendingcb++,mD(t,i,e,r,n))}it.prototype.write=function(t,e,r){return dA(this,t,e,r)===!0};it.prototype.cork=function(){this._writableState.corked++};it.prototype.uncork=function(){let t=this._writableState;t.corked&&(t.corked--,t.writing||Om(this,t))};it.prototype.setDefaultEncoding=function(e){if(typeof e=="string"&&(e=iD(e)),!Rh.isEncoding(e))throw new uA(e);return this._writableState.defaultEncoding=e,this};function mD(t,e,r,n,i){let o=e.objectMode?1:r.length;e.length+=o;let s=e.length<e.highWaterMark;return s||(e.needDrain=!0),e.writing||e.corked||e.errored||!e.constructed?(e.buffered.push({chunk:r,encoding:n,callback:i}),e.allBuffers&&n!=="buffer"&&(e.allBuffers=!1),e.allNoop&&i!==Rm&&(e.allNoop=!1)):(e.writelen=o,e.writecb=i,e.writing=!0,e.sync=!0,t._write(r,n,e.onwrite),e.sync=!1),s&&!e.errored&&!e.destroyed}function rA(t,e,r,n,i,o,s){e.writelen=n,e.writecb=s,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new Rd("write")):r?t._writev(i,e.onwrite):t._write(i,o,e.onwrite),e.sync=!1}function nA(t,e,r,n){--e.pendingcb,n(r),Um(e),_a(t,r)}function wD(t,e){let r=t._writableState,n=r.sync,i=r.writecb;if(typeof i!="function"){_a(t,new aA);return}r.writing=!1,r.writecb=null,r.length-=r.writelen,r.writelen=0,e?(e.stack,r.errored||(r.errored=e),t._readableState&&!t._readableState.errored&&(t._readableState.errored=e),n?oc.nextTick(nA,t,r,e,i):nA(t,r,e,i)):(r.buffered.length>r.bufferedIndex&&Om(t,r),n?r.afterWriteTickInfo!==null&&r.afterWriteTickInfo.cb===i?r.afterWriteTickInfo.count++:(r.afterWriteTickInfo={count:1,cb:i,stream:t,state:r},oc.nextTick(bD,r.afterWriteTickInfo)):fA(t,r,1,i))}function bD({stream:t,state:e,count:r,cb:n}){return e.afterWriteTickInfo=null,fA(t,e,r,n)}function fA(t,e,r,n){for(!e.ending&&!t.destroyed&&e.length===0&&e.needDrain&&(e.needDrain=!1,t.emit("drain"));r-- >0;)e.pendingcb--,n();e.destroyed&&Um(e),Dm(t,e)}function Um(t){if(t.writing)return;for(let i=t.bufferedIndex;i<t.buffered.length;++i){var e;let{chunk:o,callback:s}=t.buffered[i],c=t.objectMode?1:o.length;t.length-=c,s((e=t.errored)!==null&&e!==void 0?e:new Rd("write"))}let r=t[Ba].splice(0);for(let i=0;i<r.length;i++){var n;r[i]((n=t.errored)!==null&&n!==void 0?n:new Rd("end"))}Oh(t)}function Om(t,e){if(e.corked||e.bufferProcessing||e.destroyed||!e.constructed)return;let{buffered:r,bufferedIndex:n,objectMode:i}=e,o=r.length-n;if(!o)return;let s=n;if(e.bufferProcessing=!0,o>1&&t._writev){e.pendingcb-=o-1;let c=e.allNoop?Rm:u=>{for(let d=s;d<r.length;++d)r[d].callback(u)},a=e.allNoop&&s===0?r:iA(r,s);a.allBuffers=e.allBuffers,rA(t,e,!0,e.length,a,"",c),Oh(e)}else{do{let{chunk:c,encoding:a,callback:u}=r[s];r[s++]=null;let d=i?1:c.length;rA(t,e,!1,d,c,a,u)}while(s<r.length&&!e.writing);s===r.length?Oh(e):s>256?(r.splice(0,s),e.bufferedIndex=0):e.bufferedIndex=s}e.bufferProcessing=!1}it.prototype._write=function(t,e,r){if(this._writev)this._writev([{chunk:t,encoding:e}],r);else throw new lD("_write()")};it.prototype._writev=null;it.prototype.end=function(t,e,r){let n=this._writableState;typeof t=="function"?(r=t,t=null,e=null):typeof e=="function"&&(r=e,e=null);let i;if(t!=null){let o=dA(this,t,e);o instanceof rD&&(i=o)}return n.corked&&(n.corked=1,this.uncork()),i||(!n.errored&&!n.ending?(n.ending=!0,Dm(this,n,!0),n.ended=!0):n.finished?i=new pD("end"):n.destroyed&&(i=new Rd("end"))),typeof r=="function"&&(i||n.finished?oc.nextTick(r,i):n[Ba].push(r)),this};function Uh(t){return t.ending&&!t.destroyed&&t.constructed&&t.length===0&&!t.errored&&t.buffered.length===0&&!t.finished&&!t.writing&&!t.errorEmitted&&!t.closeEmitted}function xD(t,e){let r=!1;function n(i){if(r){_a(t,i??aA());return}if(r=!0,e.pendingcb--,i){let o=e[Ba].splice(0);for(let s=0;s<o.length;s++)o[s](i);_a(t,i,e.sync)}else Uh(e)&&(e.prefinished=!0,t.emit("prefinish"),e.pendingcb++,oc.nextTick(Im,t,e))}e.sync=!0,e.pendingcb++;try{t._final(n)}catch(i){n(i)}e.sync=!1}function ED(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final=="function"&&!e.destroyed?(e.finalCalled=!0,xD(t,e)):(e.prefinished=!0,t.emit("prefinish")))}function Dm(t,e,r){Uh(e)&&(ED(t,e),e.pendingcb===0&&(r?(e.pendingcb++,oc.nextTick((n,i)=>{Uh(i)?Im(n,i):i.pendingcb--},t,e)):Uh(e)&&(e.pendingcb++,Im(t,e))))}function Im(t,e){e.pendingcb--,e.finished=!0;let r=e[Ba].splice(0);for(let n=0;n<r.length;n++)r[n]();if(t.emit("finish"),e.autoDestroy){let n=t._readableState;(!n||n.autoDestroy&&(n.endEmitted||n.readable===!1))&&t.destroy()}}nD(it.prototype,{closed:{__proto__:null,get(){return this._writableState?this._writableState.closed:!1}},destroyed:{__proto__:null,get(){return this._writableState?this._writableState.destroyed:!1},set(t){this._writableState&&(this._writableState.destroyed=t)}},writable:{__proto__:null,get(){let t=this._writableState;return!!t&&t.writable!==!1&&!t.destroyed&&!t.errored&&!t.ending&&!t.ended},set(t){this._writableState&&(this._writableState.writable=!!t)}},writableFinished:{__proto__:null,get(){return this._writableState?this._writableState.finished:!1}},writableObjectMode:{__proto__:null,get(){return this._writableState?this._writableState.objectMode:!1}},writableBuffer:{__proto__:null,get(){return this._writableState&&this._writableState.getBuffer()}},writableEnded:{__proto__:null,get(){return this._writableState?this._writableState.ending:!1}},writableNeedDrain:{__proto__:null,get(){let t=this._writableState;return t?!t.destroyed&&!t.ending&&t.needDrain:!1}},writableHighWaterMark:{__proto__:null,get(){return this._writableState&&this._writableState.highWaterMark}},writableCorked:{__proto__:null,get(){return this._writableState?this._writableState.corked:0}},writableLength:{__proto__:null,get(){return this._writableState&&this._writableState.length}},errored:{__proto__:null,enumerable:!1,get(){return this._writableState?this._writableState.errored:null}},writableAborted:{__proto__:null,enumerable:!1,get:function(){return!!(this._writableState.writable!==!1&&(this._writableState.destroyed||this._writableState.errored)&&!this._writableState.finished)}}});var vD=Dh.destroy;it.prototype.destroy=function(t,e){let r=this._writableState;return!r.destroyed&&(r.bufferedIndex<r.buffered.length||r[Ba].length)&&oc.nextTick(Um,r),vD.call(this,t,e),this};it.prototype._undestroy=Dh.undestroy;it.prototype._destroy=function(t,e){e(t)};it.prototype[cD.captureRejectionSymbol]=function(t){this.destroy(t)};var Bm;function lA(){return Bm===void 0&&(Bm={}),Bm}it.fromWeb=function(t,e){return lA().newStreamWritableFromWritableStream(t,e)};it.toWeb=function(t){return lA().newWritableStreamFromStreamWritable(t)}});var IA=oe((UF,BA)=>{l();var km=Ei(),SD=Sr(),{isReadable:AD,isWritable:TD,isIterable:pA,isNodeStream:_D,isReadableNodeStream:yA,isWritableNodeStream:gA,isDuplexNodeStream:BD,isReadableStream:mA,isWritableStream:wA}=ri(),bA=ji(),{AbortError:TA,codes:{ERR_INVALID_ARG_TYPE:ID,ERR_INVALID_RETURN_VALUE:xA}}=ir(),{destroyer:Ra}=rc(),RD=oi(),_A=Bd(),UD=kh(),{createDeferredPromise:EA}=Jt(),vA=wm(),SA=globalThis.Blob||SD.Blob,OD=typeof SA<"u"?function(e){return e instanceof SA}:function(e){return!1},DD=globalThis.AbortController||ba().AbortController,{FunctionPrototypeCall:AA}=nt(),qo=class extends RD{constructor(e){super(e),e?.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),e?.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)}};BA.exports=function t(e,r){if(BD(e))return e;if(yA(e))return Ia({readable:e});if(gA(e))return Ia({writable:e});if(_D(e))return Ia({writable:!1,readable:!1});if(mA(e))return Ia({readable:_A.fromWeb(e)});if(wA(e))return Ia({writable:UD.fromWeb(e)});if(typeof e=="function"){let{value:i,write:o,final:s,destroy:c}=kD(e);if(pA(i))return vA(qo,i,{objectMode:!0,write:o,final:s,destroy:c});let a=i?.then;if(typeof a=="function"){let u,d=AA(a,i,f=>{if(f!=null)throw new xA("nully","body",f)},f=>{Ra(u,f)});return u=new qo({objectMode:!0,readable:!1,write:o,final(f){s(async()=>{try{await d,km.nextTick(f,null)}catch(h){km.nextTick(f,h)}})},destroy:c})}throw new xA("Iterable, AsyncIterable or AsyncFunction",r,i)}if(OD(e))return t(e.arrayBuffer());if(pA(e))return vA(qo,e,{objectMode:!0,writable:!1});if(mA(e?.readable)&&wA(e?.writable))return qo.fromWeb(e);if(typeof e?.writable=="object"||typeof e?.readable=="object"){let i=e!=null&&e.readable?yA(e?.readable)?e?.readable:t(e.readable):void 0,o=e!=null&&e.writable?gA(e?.writable)?e?.writable:t(e.writable):void 0;return Ia({readable:i,writable:o})}let n=e?.then;if(typeof n=="function"){let i;return AA(n,e,o=>{o!=null&&i.push(o),i.push(null)},o=>{Ra(i,o)}),i=new qo({objectMode:!0,writable:!1,read(){}})}throw new ID(r,["Blob","ReadableStream","WritableStream","Stream","Iterable","AsyncIterable","Function","{ readable, writable } pair","Promise"],e)};function kD(t){let{promise:e,resolve:r}=EA(),n=new DD,i=n.signal;return{value:t(async function*(){for(;;){let s=e;e=null;let{chunk:c,done:a,cb:u}=await s;if(km.nextTick(u),a)return;if(i.aborted)throw new TA(void 0,{cause:i.reason});({promise:e,resolve:r}=EA()),yield c}}(),{signal:i}),write(s,c,a){let u=r;r=null,u({chunk:s,done:!1,cb:a})},final(s){let c=r;r=null,c({done:!0,cb:s})},destroy(s,c){n.abort(),c(s)}}}function Ia(t){let e=t.readable&&typeof t.readable.read!="function"?_A.wrap(t.readable):t.readable,r=t.writable,n=!!AD(e),i=!!TD(r),o,s,c,a,u;function d(f){let h=a;a=null,h?h(f):f&&u.destroy(f)}return u=new qo({readableObjectMode:!!(e!=null&&e.readableObjectMode),writableObjectMode:!!(r!=null&&r.writableObjectMode),readable:n,writable:i}),i&&(bA(r,f=>{i=!1,f&&Ra(e,f),d(f)}),u._write=function(f,h,p){r.write(f,h)?p():o=p},u._final=function(f){r.end(),s=f},r.on("drain",function(){if(o){let f=o;o=null,f()}}),r.on("finish",function(){if(s){let f=s;s=null,f()}})),n&&(bA(e,f=>{n=!1,f&&Ra(e,f),d(f)}),e.on("readable",function(){if(c){let f=c;c=null,f()}}),e.on("end",function(){u.push(null)}),u._read=function(){for(;;){let f=e.read();if(f===null){c=u._read;return}if(!u.push(f))return}}),u._destroy=function(f,h){!f&&a!==null&&(f=new TA),c=null,o=null,s=null,a===null?h(f):(a=h,Ra(r,f),Ra(e,f))},u}});var oi=oe((DF,OA)=>{"use strict";l();var{ObjectDefineProperties:ND,ObjectGetOwnPropertyDescriptor:Wi,ObjectKeys:CD,ObjectSetPrototypeOf:RA}=nt();OA.exports=Tn;var Lm=Bd(),tn=kh();RA(Tn.prototype,Lm.prototype);RA(Tn,Lm);{let t=CD(tn.prototype);for(let e=0;e<t.length;e++){let r=t[e];Tn.prototype[r]||(Tn.prototype[r]=tn.prototype[r])}}function Tn(t){if(!(this instanceof Tn))return new Tn(t);Lm.call(this,t),tn.call(this,t),t?(this.allowHalfOpen=t.allowHalfOpen!==!1,t.readable===!1&&(this._readableState.readable=!1,this._readableState.ended=!0,this._readableState.endEmitted=!0),t.writable===!1&&(this._writableState.writable=!1,this._writableState.ending=!0,this._writableState.ended=!0,this._writableState.finished=!0)):this.allowHalfOpen=!0}ND(Tn.prototype,{writable:{__proto__:null,...Wi(tn.prototype,"writable")},writableHighWaterMark:{__proto__:null,...Wi(tn.prototype,"writableHighWaterMark")},writableObjectMode:{__proto__:null,...Wi(tn.prototype,"writableObjectMode")},writableBuffer:{__proto__:null,...Wi(tn.prototype,"writableBuffer")},writableLength:{__proto__:null,...Wi(tn.prototype,"writableLength")},writableFinished:{__proto__:null,...Wi(tn.prototype,"writableFinished")},writableCorked:{__proto__:null,...Wi(tn.prototype,"writableCorked")},writableEnded:{__proto__:null,...Wi(tn.prototype,"writableEnded")},writableNeedDrain:{__proto__:null,...Wi(tn.prototype,"writableNeedDrain")},destroyed:{__proto__:null,get(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set(t){this._readableState&&this._writableState&&(this._readableState.destroyed=t,this._writableState.destroyed=t)}}});var Nm;function UA(){return Nm===void 0&&(Nm={}),Nm}Tn.fromWeb=function(t,e){return UA().newStreamDuplexFromReadableWritablePair(t,e)};Tn.toWeb=function(t){return UA().newReadableWritablePairFromDuplex(t)};var Cm;Tn.from=function(t){return Cm||(Cm=IA()),Cm(t,"body")}});var Km=oe((NF,kA)=>{"use strict";l();var{ObjectSetPrototypeOf:DA,Symbol:LD}=nt();kA.exports=Gi;var{ERR_METHOD_NOT_IMPLEMENTED:PD}=ir().codes,Mm=oi(),{getHighWaterMark:MD}=Ad();DA(Gi.prototype,Mm.prototype);DA(Gi,Mm);var Od=LD("kCallback");function Gi(t){if(!(this instanceof Gi))return new Gi(t);let e=t?MD(this,t,"readableHighWaterMark",!0):null;e===0&&(t={...t,highWaterMark:null,readableHighWaterMark:e,writableHighWaterMark:t.writableHighWaterMark||0}),Mm.call(this,t),this._readableState.sync=!1,this[Od]=null,t&&(typeof t.transform=="function"&&(this._transform=t.transform),typeof t.flush=="function"&&(this._flush=t.flush)),this.on("prefinish",KD)}function Pm(t){typeof this._flush=="function"&&!this.destroyed?this._flush((e,r)=>{if(e){t?t(e):this.destroy(e);return}r!=null&&this.push(r),this.push(null),t&&t()}):(this.push(null),t&&t())}function KD(){this._final!==Pm&&Pm.call(this)}Gi.prototype._final=Pm;Gi.prototype._transform=function(t,e,r){throw new PD("_transform()")};Gi.prototype._write=function(t,e,r){let n=this._readableState,i=this._writableState,o=n.length;this._transform(t,e,(s,c)=>{if(s){r(s);return}c!=null&&this.push(c),i.ended||o===n.length||n.length<n.highWaterMark?r():this[Od]=r})};Gi.prototype._read=function(){if(this[Od]){let t=this[Od];this[Od]=null,t()}}});var Hm=oe((LF,CA)=>{"use strict";l();var{ObjectSetPrototypeOf:NA}=nt();CA.exports=Ua;var $m=Km();NA(Ua.prototype,$m.prototype);NA(Ua,$m);function Ua(t){if(!(this instanceof Ua))return new Ua(t);$m.call(this,t)}Ua.prototype._transform=function(t,e,r){r(null,t)}});var Ph=oe((MF,$A)=>{l();var Dd=Ei(),{ArrayIsArray:$D,Promise:HD,SymbolAsyncIterator:VD,SymbolDispose:qD}=nt(),Lh=ji(),{once:FD}=Jt(),jD=rc(),LA=oi(),{aggregateTwoErrors:WD,codes:{ERR_INVALID_ARG_TYPE:Jm,ERR_INVALID_RETURN_VALUE:Vm,ERR_MISSING_ARGS:GD,ERR_STREAM_DESTROYED:zD,ERR_STREAM_PREMATURE_CLOSE:YD},AbortError:JD}=ir(),{validateFunction:ZD,validateAbortSignal:XD}=Ea(),{isIterable:sc,isReadable:qm,isReadableNodeStream:Ch,isNodeStream:PA,isTransformStream:Oa,isWebStream:QD,isReadableStream:Fm,isReadableFinished:e4}=ri(),t4=globalThis.AbortController||ba().AbortController,jm,Wm,Gm;function MA(t,e,r){let n=!1;t.on("close",()=>{n=!0});let i=Lh(t,{readable:e,writable:r},o=>{n=!o});return{destroy:o=>{n||(n=!0,jD.destroyer(t,o||new zD("pipe")))},cleanup:i}}function r4(t){return ZD(t[t.length-1],"streams[stream.length - 1]"),t.pop()}function zm(t){if(sc(t))return t;if(Ch(t))return n4(t);throw new Jm("val",["Readable","Iterable","AsyncIterable"],t)}async function*n4(t){Wm||(Wm=Bd()),yield*Wm.prototype[VD].call(t)}async function Nh(t,e,r,{end:n}){let i,o=null,s=u=>{if(u&&(i=u),o){let d=o;o=null,d()}},c=()=>new HD((u,d)=>{i?d(i):o=()=>{i?d(i):u()}});e.on("drain",s);let a=Lh(e,{readable:!1},s);try{e.writableNeedDrain&&await c();for await(let u of t)e.write(u)||await c();n&&(e.end(),await c()),r()}catch(u){r(i!==u?WD(i,u):u)}finally{a(),e.off("drain",s)}}async function Ym(t,e,r,{end:n}){Oa(e)&&(e=e.writable);let i=e.getWriter();try{for await(let o of t)await i.ready,i.write(o).catch(()=>{});await i.ready,n&&await i.close(),r()}catch(o){try{await i.abort(o),r(o)}catch(s){r(s)}}}function i4(...t){return KA(t,FD(r4(t)))}function KA(t,e,r){if(t.length===1&&$D(t[0])&&(t=t[0]),t.length<2)throw new GD("streams");let n=new t4,i=n.signal,o=r?.signal,s=[];XD(o,"options.signal");function c(){g(new JD)}Gm=Gm||Jt().addAbortListener;let a;o&&(a=Gm(o,c));let u,d,f=[],h=0;function p(A){g(A,--h===0)}function g(A,O){var T;if(A&&(!u||u.code==="ERR_STREAM_PREMATURE_CLOSE")&&(u=A),!(!u&&!O)){for(;f.length;)f.shift()(u);(T=a)===null||T===void 0||T[qD](),n.abort(),O&&(u||s.forEach(M=>M()),Dd.nextTick(e,u,d))}}let y;for(let A=0;A<t.length;A++){let O=t[A],T=A<t.length-1,M=A>0,q=T||r?.end!==!1,j=A===t.length-1;if(PA(O)){let $=function(X){X&&X.name!=="AbortError"&&X.code!=="ERR_STREAM_PREMATURE_CLOSE"&&p(X)};var I=$;if(q){let{destroy:X,cleanup:Q}=MA(O,T,M);f.push(X),qm(O)&&j&&s.push(Q)}O.on("error",$),qm(O)&&j&&s.push(()=>{O.removeListener("error",$)})}if(A===0)if(typeof O=="function"){if(y=O({signal:i}),!sc(y))throw new Vm("Iterable, AsyncIterable or Stream","source",y)}else sc(O)||Ch(O)||Oa(O)?y=O:y=LA.from(O);else if(typeof O=="function"){if(Oa(y)){var E;y=zm((E=y)===null||E===void 0?void 0:E.readable)}else y=zm(y);if(y=O(y,{signal:i}),T){if(!sc(y,!0))throw new Vm("AsyncIterable",`transform[${A-1}]`,y)}else{var S;jm||(jm=Hm());let $=new jm({objectMode:!0}),X=(S=y)===null||S===void 0?void 0:S.then;if(typeof X=="function")h++,X.call(y,_=>{d=_,_!=null&&$.write(_),q&&$.end(),Dd.nextTick(p)},_=>{$.destroy(_),Dd.nextTick(p,_)});else if(sc(y,!0))h++,Nh(y,$,p,{end:q});else if(Fm(y)||Oa(y)){let _=y.readable||y;h++,Nh(_,$,p,{end:q})}else throw new Vm("AsyncIterable or Promise","destination",y);y=$;let{destroy:Q,cleanup:G}=MA(y,!1,!0);f.push(Q),j&&s.push(G)}}else if(PA(O)){if(Ch(y)){h+=2;let $=o4(y,O,p,{end:q});qm(O)&&j&&s.push($)}else if(Oa(y)||Fm(y)){let $=y.readable||y;h++,Nh($,O,p,{end:q})}else if(sc(y))h++,Nh(y,O,p,{end:q});else throw new Jm("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else if(QD(O)){if(Ch(y))h++,Ym(zm(y),O,p,{end:q});else if(Fm(y)||sc(y))h++,Ym(y,O,p,{end:q});else if(Oa(y))h++,Ym(y.readable,O,p,{end:q});else throw new Jm("val",["Readable","Iterable","AsyncIterable","ReadableStream","TransformStream"],y);y=O}else y=LA.from(O)}return(i!=null&&i.aborted||o!=null&&o.aborted)&&Dd.nextTick(c),y}function o4(t,e,r,{end:n}){let i=!1;if(e.on("close",()=>{i||r(new YD)}),t.pipe(e,{end:!1}),n){let s=function(){i=!0,e.end()};var o=s;e4(t)?Dd.nextTick(s):t.once("end",s)}else r();return Lh(t,{readable:!0,writable:!1},s=>{let c=t._readableState;s&&s.code==="ERR_STREAM_PREMATURE_CLOSE"&&c&&c.ended&&!c.errored&&!c.errorEmitted?t.once("end",r).once("error",r):r(s)}),Lh(e,{readable:!1,writable:!0},r)}$A.exports={pipelineImpl:KA,pipeline:i4}});var Xm=oe(($F,WA)=>{"use strict";l();var{pipeline:s4}=Ph(),Mh=oi(),{destroyer:c4}=rc(),{isNodeStream:Kh,isReadable:HA,isWritable:VA,isWebStream:Zm,isTransformStream:cc,isWritableStream:qA,isReadableStream:FA}=ri(),{AbortError:a4,codes:{ERR_INVALID_ARG_VALUE:jA,ERR_MISSING_ARGS:u4}}=ir(),d4=ji();WA.exports=function(...e){if(e.length===0)throw new u4("streams");if(e.length===1)return Mh.from(e[0]);let r=[...e];if(typeof e[0]=="function"&&(e[0]=Mh.from(e[0])),typeof e[e.length-1]=="function"){let p=e.length-1;e[p]=Mh.from(e[p])}for(let p=0;p<e.length;++p)if(!(!Kh(e[p])&&!Zm(e[p]))){if(p<e.length-1&&!(HA(e[p])||FA(e[p])||cc(e[p])))throw new jA(`streams[${p}]`,r[p],"must be readable");if(p>0&&!(VA(e[p])||qA(e[p])||cc(e[p])))throw new jA(`streams[${p}]`,r[p],"must be writable")}let n,i,o,s,c;function a(p){let g=s;s=null,g?g(p):p?c.destroy(p):!h&&!f&&c.destroy()}let u=e[0],d=s4(e,a),f=!!(VA(u)||qA(u)||cc(u)),h=!!(HA(d)||FA(d)||cc(d));if(c=new Mh({writableObjectMode:!!(u!=null&&u.writableObjectMode),readableObjectMode:!!(d!=null&&d.readableObjectMode),writable:f,readable:h}),f){if(Kh(u))c._write=function(g,y,E){u.write(g,y)?E():n=E},c._final=function(g){u.end(),i=g},u.on("drain",function(){if(n){let g=n;n=null,g()}});else if(Zm(u)){let y=(cc(u)?u.writable:u).getWriter();c._write=async function(E,S,I){try{await y.ready,y.write(E).catch(()=>{}),I()}catch(A){I(A)}},c._final=async function(E){try{await y.ready,y.close().catch(()=>{}),i=E}catch(S){E(S)}}}let p=cc(d)?d.readable:d;d4(p,()=>{if(i){let g=i;i=null,g()}})}if(h){if(Kh(d))d.on("readable",function(){if(o){let p=o;o=null,p()}}),d.on("end",function(){c.push(null)}),c._read=function(){for(;;){let p=d.read();if(p===null){o=c._read;return}if(!c.push(p))return}};else if(Zm(d)){let g=(cc(d)?d.readable:d).getReader();c._read=async function(){for(;;)try{let{value:y,done:E}=await g.read();if(!c.push(y))return;if(E){c.push(null);return}}catch{return}}}}return c._destroy=function(p,g){!p&&s!==null&&(p=new a4),o=null,n=null,i=null,s===null?g(p):(s=g,Kh(d)&&c4(d,p))},c}});var rT=oe((VF,tw)=>{"use strict";l();var f4=globalThis.AbortController||ba().AbortController,{codes:{ERR_INVALID_ARG_VALUE:l4,ERR_INVALID_ARG_TYPE:kd,ERR_MISSING_ARGS:h4,ERR_OUT_OF_RANGE:p4},AbortError:si}=ir(),{validateAbortSignal:ac,validateInteger:GA,validateObject:uc}=Ea(),y4=nt().Symbol("kWeak"),g4=nt().Symbol("kResistStopPropagation"),{finished:m4}=ji(),w4=Xm(),{addAbortSignalNoValidate:b4}=Sd(),{isWritable:x4,isNodeStream:E4}=ri(),{deprecate:v4}=Jt(),{ArrayPrototypePush:S4,Boolean:A4,MathFloor:zA,Number:T4,NumberIsNaN:_4,Promise:YA,PromiseReject:JA,PromiseResolve:B4,PromisePrototypeThen:ZA,Symbol:QA}=nt(),$h=QA("kEmpty"),XA=QA("kEof");function I4(t,e){if(e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal"),E4(t)&&!x4(t))throw new l4("stream",t,"must be writable");let r=w4(this,t);return e!=null&&e.signal&&b4(e.signal,r),r}function Hh(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal");let r=1;e?.concurrency!=null&&(r=zA(e.concurrency));let n=r-1;return e?.highWaterMark!=null&&(n=zA(e.highWaterMark)),GA(r,"options.concurrency",1),GA(n,"options.highWaterMark",0),n+=r,(async function*(){let o=Jt().AbortSignalAny([e?.signal].filter(A4)),s=this,c=[],a={signal:o},u,d,f=!1,h=0;function p(){f=!0,g()}function g(){h-=1,y()}function y(){d&&!f&&h<r&&c.length<n&&(d(),d=null)}async function E(){try{for await(let S of s){if(f)return;if(o.aborted)throw new si;try{if(S=t(S,a),S===$h)continue;S=B4(S)}catch(I){S=JA(I)}h+=1,ZA(S,g,p),c.push(S),u&&(u(),u=null),!f&&(c.length>=n||h>=r)&&await new YA(I=>{d=I})}c.push(XA)}catch(S){let I=JA(S);ZA(I,g,p),c.push(I)}finally{f=!0,u&&(u(),u=null)}}E();try{for(;;){for(;c.length>0;){let S=await c[0];if(S===XA)return;if(o.aborted)throw new si;S!==$h&&(yield S),c.shift(),y()}await new YA(S=>{u=S})}}finally{f=!0,d&&(d(),d=null)}}).call(this)}function R4(t=void 0){return t!=null&&uc(t,"options"),t?.signal!=null&&ac(t.signal,"options.signal"),(async function*(){let r=0;for await(let i of this){var n;if(t!=null&&(n=t.signal)!==null&&n!==void 0&&n.aborted)throw new si({cause:t.signal.reason});yield[r++,i]}}).call(this)}async function eT(t,e=void 0){for await(let r of ew.call(this,t,e))return!0;return!1}async function U4(t,e=void 0){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);return!await eT.call(this,async(...r)=>!await t(...r),e)}async function O4(t,e){for await(let r of ew.call(this,t,e))return r}async function D4(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i),$h}for await(let n of Hh.call(this,r,e));}function ew(t,e){if(typeof t!="function")throw new kd("fn",["Function","AsyncFunction"],t);async function r(n,i){return await t(n,i)?n:$h}return Hh.call(this,r,e)}var Qm=class extends h4{constructor(){super("reduce"),this.message="Reduce of an empty stream requires an initial value"}};async function k4(t,e,r){var n;if(typeof t!="function")throw new kd("reducer",["Function","AsyncFunction"],t);r!=null&&uc(r,"options"),r?.signal!=null&&ac(r.signal,"options.signal");let i=arguments.length>1;if(r!=null&&(n=r.signal)!==null&&n!==void 0&&n.aborted){let u=new si(void 0,{cause:r.signal.reason});throw this.once("error",()=>{}),await m4(this.destroy(u)),u}let o=new f4,s=o.signal;if(r!=null&&r.signal){let u={once:!0,[y4]:this,[g4]:!0};r.signal.addEventListener("abort",()=>o.abort(),u)}let c=!1;try{for await(let u of this){var a;if(c=!0,r!=null&&(a=r.signal)!==null&&a!==void 0&&a.aborted)throw new si;i?e=await t(e,u,{signal:s}):(e=u,i=!0)}if(!c&&!i)throw new Qm}finally{o.abort()}return e}async function N4(t){t!=null&&uc(t,"options"),t?.signal!=null&&ac(t.signal,"options.signal");let e=[];for await(let n of this){var r;if(t!=null&&(r=t.signal)!==null&&r!==void 0&&r.aborted)throw new si(void 0,{cause:t.signal.reason});S4(e,n)}return e}function C4(t,e){let r=Hh.call(this,t,e);return(async function*(){for await(let i of r)yield*i}).call(this)}function tT(t){if(t=T4(t),_4(t))return 0;if(t<0)throw new p4("number",">= 0",t);return t}function L4(t,e=void 0){return e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal"),t=tT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new si;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new si;t--<=0&&(yield o)}}).call(this)}function P4(t,e=void 0){return e!=null&&uc(e,"options"),e?.signal!=null&&ac(e.signal,"options.signal"),t=tT(t),(async function*(){var n;if(e!=null&&(n=e.signal)!==null&&n!==void 0&&n.aborted)throw new si;for await(let o of this){var i;if(e!=null&&(i=e.signal)!==null&&i!==void 0&&i.aborted)throw new si;if(t-- >0&&(yield o),t<=0)return}}).call(this)}tw.exports.streamReturningOperators={asIndexedPairs:v4(R4,"readable.asIndexedPairs will be removed in a future version."),drop:L4,filter:ew,flatMap:C4,map:Hh,take:P4,compose:I4};tw.exports.promiseReturningOperators={every:U4,forEach:D4,reduce:k4,toArray:N4,some:eT,find:O4}});var rw=oe((FF,nT)=>{"use strict";l();var{ArrayPrototypePop:M4,Promise:K4}=nt(),{isIterable:$4,isNodeStream:H4,isWebStream:V4}=ri(),{pipelineImpl:q4}=Ph(),{finished:F4}=ji();nw();function j4(...t){return new K4((e,r)=>{let n,i,o=t[t.length-1];if(o&&typeof o=="object"&&!H4(o)&&!$4(o)&&!V4(o)){let s=M4(t);n=s.signal,i=s.end}q4(t,(s,c)=>{s?r(s):e(c)},{signal:n,end:i})})}nT.exports={finished:F4,pipeline:j4}});var nw=oe((WF,lT)=>{l();var{Buffer:W4}=Sr(),{ObjectDefineProperty:zi,ObjectKeys:sT,ReflectApply:cT}=nt(),{promisify:{custom:aT}}=Jt(),{streamReturningOperators:iT,promiseReturningOperators:oT}=rT(),{codes:{ERR_ILLEGAL_CONSTRUCTOR:uT}}=ir(),G4=Xm(),{setDefaultHighWaterMark:z4,getDefaultHighWaterMark:Y4}=Ad(),{pipeline:dT}=Ph(),{destroyer:J4}=rc(),fT=ji(),iw=rw(),Nd=ri(),qe=lT.exports=xh().Stream;qe.isDestroyed=Nd.isDestroyed;qe.isDisturbed=Nd.isDisturbed;qe.isErrored=Nd.isErrored;qe.isReadable=Nd.isReadable;qe.isWritable=Nd.isWritable;qe.Readable=Bd();for(let t of sT(iT)){let r=function(...n){if(new.target)throw uT();return qe.Readable.from(cT(e,this,n))};ow=r;let e=iT[t];zi(r,"name",{__proto__:null,value:e.name}),zi(r,"length",{__proto__:null,value:e.length}),zi(qe.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var ow;for(let t of sT(oT)){let r=function(...i){if(new.target)throw uT();return cT(e,this,i)};ow=r;let e=oT[t];zi(r,"name",{__proto__:null,value:e.name}),zi(r,"length",{__proto__:null,value:e.length}),zi(qe.Readable.prototype,t,{__proto__:null,value:r,enumerable:!1,configurable:!0,writable:!0})}var ow;qe.Writable=kh();qe.Duplex=oi();qe.Transform=Km();qe.PassThrough=Hm();qe.pipeline=dT;var{addAbortSignal:Z4}=Sd();qe.addAbortSignal=Z4;qe.finished=fT;qe.destroy=J4;qe.compose=G4;qe.setDefaultHighWaterMark=z4;qe.getDefaultHighWaterMark=Y4;zi(qe,"promises",{__proto__:null,configurable:!0,enumerable:!0,get(){return iw}});zi(dT,aT,{__proto__:null,enumerable:!0,get(){return iw.pipeline}});zi(fT,aT,{__proto__:null,enumerable:!0,get(){return iw.finished}});qe.Stream=qe;qe._isUint8Array=function(e){return e instanceof Uint8Array};qe._uint8ArrayToBuffer=function(e){return W4.from(e.buffer,e.byteOffset,e.byteLength)}});var sw=oe((zF,lt)=>{"use strict";l();var At=nw(),X4=rw(),Q4=At.Readable.destroy;lt.exports=At.Readable;lt.exports._uint8ArrayToBuffer=At._uint8ArrayToBuffer;lt.exports._isUint8Array=At._isUint8Array;lt.exports.isDisturbed=At.isDisturbed;lt.exports.isErrored=At.isErrored;lt.exports.isReadable=At.isReadable;lt.exports.Readable=At.Readable;lt.exports.Writable=At.Writable;lt.exports.Duplex=At.Duplex;lt.exports.Transform=At.Transform;lt.exports.PassThrough=At.PassThrough;lt.exports.addAbortSignal=At.addAbortSignal;lt.exports.finished=At.finished;lt.exports.destroy=At.destroy;lt.exports.destroy=Q4;lt.exports.pipeline=At.pipeline;lt.exports.compose=At.compose;Object.defineProperty(At,"promises",{configurable:!0,enumerable:!0,get(){return X4}});lt.exports.Stream=At.Stream;lt.exports.default=lt.exports});var N_=oe((Rp,k_)=>{l();(function(t,e){typeof Rp=="object"&&typeof k_<"u"?e(Rp):typeof define=="function"&&define.amd?define(["exports"],e):e(t.URI=t.URI||{})})(Rp,function(t){"use strict";function e(){for(var B=arguments.length,v=Array(B),k=0;k<B;k++)v[k]=arguments[k];if(v.length>1){v[0]=v[0].slice(0,-1);for(var K=v.length-1,H=1;H<K;++H)v[H]=v[H].slice(1,-1);return v[K]=v[K].slice(1),v.join("")}else return v[0]}function r(B){return"(?:"+B+")"}function n(B){return B===void 0?"undefined":B===null?"null":Object.prototype.toString.call(B).split(" ").pop().split("]").shift().toLowerCase()}function i(B){return B.toUpperCase()}function o(B){return B!=null?B instanceof Array?B:typeof B.length!="number"||B.split||B.setInterval||B.call?[B]:Array.prototype.slice.call(B):[]}function s(B,v){var k=B;if(v)for(var K in v)k[K]=v[K];return k}function c(B){var v="[A-Za-z]",k="[\\x0D]",K="[0-9]",H="[\\x22]",te=e(K,"[A-Fa-f]"),fe="[\\x0A]",Ee="[\\x20]",Re=r(r("%[EFef]"+te+"%"+te+te+"%"+te+te)+"|"+r("%[89A-Fa-f]"+te+"%"+te+te)+"|"+r("%"+te+te)),pt="[\\:\\/\\?\\#\\[\\]\\@]",xe="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",Qe=e(pt,xe),yt=B?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",ze=B?"[\\uE000-\\uF8FF]":"[]",Se=e(v,K,"[\\-\\.\\_\\~]",yt),et=r(v+e(v,K,"[\\+\\-\\.]")+"*"),De=r(r(Re+"|"+e(Se,xe,"[\\:]"))+"*"),ds=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("[1-9]"+K)+"|"+K),Er=r(r("25[0-5]")+"|"+r("2[0-4]"+K)+"|"+r("1"+K+K)+"|"+r("0?[1-9]"+K)+"|0?0?"+K),Fr=r(Er+"\\."+Er+"\\."+Er+"\\."+Er),Me=r(te+"{1,4}"),vr=r(r(Me+"\\:"+Me)+"|"+Fr),jr=r(r(Me+"\\:")+"{6}"+vr),Ln=r("\\:\\:"+r(Me+"\\:")+"{5}"+vr),fs=r(r(Me)+"?\\:\\:"+r(Me+"\\:")+"{4}"+vr),yi=r(r(r(Me+"\\:")+"{0,1}"+Me)+"?\\:\\:"+r(Me+"\\:")+"{3}"+vr),lu=r(r(r(Me+"\\:")+"{0,2}"+Me)+"?\\:\\:"+r(Me+"\\:")+"{2}"+vr),xf=r(r(r(Me+"\\:")+"{0,3}"+Me)+"?\\:\\:"+Me+"\\:"+vr),Ef=r(r(r(Me+"\\:")+"{0,4}"+Me)+"?\\:\\:"+vr),Ec=r(r(r(Me+"\\:")+"{0,5}"+Me)+"?\\:\\:"+Me),vc=r(r(r(Me+"\\:")+"{0,6}"+Me)+"?\\:\\:"),gi=r([jr,Ln,fs,yi,lu,xf,Ef,Ec,vc].join("|")),Sc=r(r(Se+"|"+Re)+"+"),Xp=r(gi+"\\%25"+Sc),ls=r(gi+r("\\%25|\\%(?!"+te+"{2})")+Sc),YB=r("[vV]"+te+"+\\."+e(Se,xe,"[\\:]")+"+"),JB=r("\\["+r(ls+"|"+gi+"|"+YB)+"\\]"),Xb=r(r(Re+"|"+e(Se,xe))+"*"),hu=r(JB+"|"+Fr+"(?!"+Xb+")|"+Xb),pu=r(K+"*"),Qb=r(r(De+"@")+"?"+hu+r("\\:"+pu)+"?"),yu=r(Re+"|"+e(Se,xe,"[\\:\\@]")),ZB=r(yu+"*"),ex=r(yu+"+"),XB=r(r(Re+"|"+e(Se,xe,"[\\@]"))+"+"),mi=r(r("\\/"+ZB)+"*"),Ac=r("\\/"+r(ex+mi)+"?"),Qp=r(XB+mi),vf=r(ex+mi),Tc="(?!"+yu+")",vL=r(mi+"|"+Ac+"|"+Qp+"|"+vf+"|"+Tc),_c=r(r(yu+"|"+e("[\\/\\?]",ze))+"*"),gu=r(r(yu+"|[\\/\\?]")+"*"),tx=r(r("\\/\\/"+Qb+mi)+"|"+Ac+"|"+vf+"|"+Tc),QB=r(et+"\\:"+tx+r("\\?"+_c)+"?"+r("\\#"+gu)+"?"),eI=r(r("\\/\\/"+Qb+mi)+"|"+Ac+"|"+Qp+"|"+Tc),tI=r(eI+r("\\?"+_c)+"?"+r("\\#"+gu)+"?"),SL=r(QB+"|"+tI),AL=r(et+"\\:"+tx+r("\\?"+_c)+"?"),TL="^("+et+")\\:"+r(r("\\/\\/("+r("("+De+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?)")+"?("+mi+"|"+Ac+"|"+vf+"|"+Tc+")")+r("\\?("+_c+")")+"?"+r("\\#("+gu+")")+"?$",_L="^(){0}"+r(r("\\/\\/("+r("("+De+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?)")+"?("+mi+"|"+Ac+"|"+Qp+"|"+Tc+")")+r("\\?("+_c+")")+"?"+r("\\#("+gu+")")+"?$",BL="^("+et+")\\:"+r(r("\\/\\/("+r("("+De+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?)")+"?("+mi+"|"+Ac+"|"+vf+"|"+Tc+")")+r("\\?("+_c+")")+"?$",IL="^"+r("\\#("+gu+")")+"?$",RL="^"+r("("+De+")@")+"?("+hu+")"+r("\\:("+pu+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",v,K,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",Se,xe),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",Se,xe),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",Se,xe),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",Se,xe),"g"),NOT_QUERY:new RegExp(e("[^\\%]",Se,xe,"[\\:\\@\\/\\?]",ze),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",Se,xe,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",Se,xe),"g"),UNRESERVED:new RegExp(Se,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",Se,Qe),"g"),PCT_ENCODED:new RegExp(Re,"g"),IPV4ADDRESS:new RegExp("^("+Fr+")$"),IPV6ADDRESS:new RegExp("^\\[?("+gi+")"+r(r("\\%25|\\%(?!"+te+"{2})")+"("+Sc+")")+"?\\]?$")}}var a=c(!1),u=c(!0),d=function(){function B(v,k){var K=[],H=!0,te=!1,fe=void 0;try{for(var Ee=v[Symbol.iterator](),Re;!(H=(Re=Ee.next()).done)&&(K.push(Re.value),!(k&&K.length===k));H=!0);}catch(pt){te=!0,fe=pt}finally{try{!H&&Ee.return&&Ee.return()}finally{if(te)throw fe}}return K}return function(v,k){if(Array.isArray(v))return v;if(Symbol.iterator in Object(v))return B(v,k);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),f=function(B){if(Array.isArray(B)){for(var v=0,k=Array(B.length);v<B.length;v++)k[v]=B[v];return k}else return Array.from(B)},h=2147483647,p=36,g=1,y=26,E=38,S=700,I=72,A=128,O="-",T=/^xn--/,M=/[^\0-\x7E]/,q=/[\x2E\u3002\uFF0E\uFF61]/g,j={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},$=p-g,X=Math.floor,Q=String.fromCharCode;function G(B){throw new RangeError(j[B])}function _(B,v){for(var k=[],K=B.length;K--;)k[K]=v(B[K]);return k}function D(B,v){var k=B.split("@"),K="";k.length>1&&(K=k[0]+"@",B=k[1]),B=B.replace(q,".");var H=B.split("."),te=_(H,v).join(".");return K+te}function x(B){for(var v=[],k=0,K=B.length;k<K;){var H=B.charCodeAt(k++);if(H>=55296&&H<=56319&&k<K){var te=B.charCodeAt(k++);(te&64512)==56320?v.push(((H&1023)<<10)+(te&1023)+65536):(v.push(H),k--)}else v.push(H)}return v}var U=function(v){return String.fromCodePoint.apply(String,f(v))},L=function(v){return v-48<10?v-22:v-65<26?v-65:v-97<26?v-97:p},N=function(v,k){return v+22+75*(v<26)-((k!=0)<<5)},R=function(v,k,K){var H=0;for(v=K?X(v/S):v>>1,v+=X(v/k);v>$*y>>1;H+=p)v=X(v/$);return X(H+($+1)*v/(v+E))},C=function(v){var k=[],K=v.length,H=0,te=A,fe=I,Ee=v.lastIndexOf(O);Ee<0&&(Ee=0);for(var Re=0;Re<Ee;++Re)v.charCodeAt(Re)>=128&&G("not-basic"),k.push(v.charCodeAt(Re));for(var pt=Ee>0?Ee+1:0;pt<K;){for(var xe=H,Qe=1,yt=p;;yt+=p){pt>=K&&G("invalid-input");var ze=L(v.charCodeAt(pt++));(ze>=p||ze>X((h-H)/Qe))&&G("overflow"),H+=ze*Qe;var Se=yt<=fe?g:yt>=fe+y?y:yt-fe;if(ze<Se)break;var et=p-Se;Qe>X(h/et)&&G("overflow"),Qe*=et}var De=k.length+1;fe=R(H-xe,De,xe==0),X(H/De)>h-te&&G("overflow"),te+=X(H/De),H%=De,k.splice(H++,0,te)}return String.fromCodePoint.apply(String,k)},P=function(v){var k=[];v=x(v);var K=v.length,H=A,te=0,fe=I,Ee=!0,Re=!1,pt=void 0;try{for(var xe=v[Symbol.iterator](),Qe;!(Ee=(Qe=xe.next()).done);Ee=!0){var yt=Qe.value;yt<128&&k.push(Q(yt))}}catch(ls){Re=!0,pt=ls}finally{try{!Ee&&xe.return&&xe.return()}finally{if(Re)throw pt}}var ze=k.length,Se=ze;for(ze&&k.push(O);Se<K;){var et=h,De=!0,ds=!1,Er=void 0;try{for(var Fr=v[Symbol.iterator](),Me;!(De=(Me=Fr.next()).done);De=!0){var vr=Me.value;vr>=H&&vr<et&&(et=vr)}}catch(ls){ds=!0,Er=ls}finally{try{!De&&Fr.return&&Fr.return()}finally{if(ds)throw Er}}var jr=Se+1;et-H>X((h-te)/jr)&&G("overflow"),te+=(et-H)*jr,H=et;var Ln=!0,fs=!1,yi=void 0;try{for(var lu=v[Symbol.iterator](),xf;!(Ln=(xf=lu.next()).done);Ln=!0){var Ef=xf.value;if(Ef<H&&++te>h&&G("overflow"),Ef==H){for(var Ec=te,vc=p;;vc+=p){var gi=vc<=fe?g:vc>=fe+y?y:vc-fe;if(Ec<gi)break;var Sc=Ec-gi,Xp=p-gi;k.push(Q(N(gi+Sc%Xp,0))),Ec=X(Sc/Xp)}k.push(Q(N(Ec,0))),fe=R(te,jr,Se==ze),te=0,++Se}}}catch(ls){fs=!0,yi=ls}finally{try{!Ln&&lu.return&&lu.return()}finally{if(fs)throw yi}}++te,++H}return k.join("")},V=function(v){return D(v,function(k){return T.test(k)?C(k.slice(4).toLowerCase()):k})},J=function(v){return D(v,function(k){return M.test(k)?"xn--"+P(k):k})},z={version:"2.1.0",ucs2:{decode:x,encode:U},decode:C,encode:P,toASCII:J,toUnicode:V},W={};function Y(B){var v=B.charCodeAt(0),k=void 0;return v<16?k="%0"+v.toString(16).toUpperCase():v<128?k="%"+v.toString(16).toUpperCase():v<2048?k="%"+(v>>6|192).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase():k="%"+(v>>12|224).toString(16).toUpperCase()+"%"+(v>>6&63|128).toString(16).toUpperCase()+"%"+(v&63|128).toString(16).toUpperCase(),k}function Z(B){for(var v="",k=0,K=B.length;k<K;){var H=parseInt(B.substr(k+1,2),16);if(H<128)v+=String.fromCharCode(H),k+=3;else if(H>=194&&H<224){if(K-k>=6){var te=parseInt(B.substr(k+4,2),16);v+=String.fromCharCode((H&31)<<6|te&63)}else v+=B.substr(k,6);k+=6}else if(H>=224){if(K-k>=9){var fe=parseInt(B.substr(k+4,2),16),Ee=parseInt(B.substr(k+7,2),16);v+=String.fromCharCode((H&15)<<12|(fe&63)<<6|Ee&63)}else v+=B.substr(k,9);k+=9}else v+=B.substr(k,3),k+=3}return v}function ue(B,v){function k(K){var H=Z(K);return H.match(v.UNRESERVED)?H:K}return B.scheme&&(B.scheme=String(B.scheme).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_SCHEME,"")),B.userinfo!==void 0&&(B.userinfo=String(B.userinfo).replace(v.PCT_ENCODED,k).replace(v.NOT_USERINFO,Y).replace(v.PCT_ENCODED,i)),B.host!==void 0&&(B.host=String(B.host).replace(v.PCT_ENCODED,k).toLowerCase().replace(v.NOT_HOST,Y).replace(v.PCT_ENCODED,i)),B.path!==void 0&&(B.path=String(B.path).replace(v.PCT_ENCODED,k).replace(B.scheme?v.NOT_PATH:v.NOT_PATH_NOSCHEME,Y).replace(v.PCT_ENCODED,i)),B.query!==void 0&&(B.query=String(B.query).replace(v.PCT_ENCODED,k).replace(v.NOT_QUERY,Y).replace(v.PCT_ENCODED,i)),B.fragment!==void 0&&(B.fragment=String(B.fragment).replace(v.PCT_ENCODED,k).replace(v.NOT_FRAGMENT,Y).replace(v.PCT_ENCODED,i)),B}function ee(B){return B.replace(/^0*(.*)/,"$1")||"0"}function ce(B,v){var k=B.match(v.IPV4ADDRESS)||[],K=d(k,2),H=K[1];return H?H.split(".").map(ee).join("."):B}function Ie(B,v){var k=B.match(v.IPV6ADDRESS)||[],K=d(k,3),H=K[1],te=K[2];if(H){for(var fe=H.toLowerCase().split("::").reverse(),Ee=d(fe,2),Re=Ee[0],pt=Ee[1],xe=pt?pt.split(":").map(ee):[],Qe=Re.split(":").map(ee),yt=v.IPV4ADDRESS.test(Qe[Qe.length-1]),ze=yt?7:8,Se=Qe.length-ze,et=Array(ze),De=0;De<ze;++De)et[De]=xe[De]||Qe[Se+De]||"";yt&&(et[ze-1]=ce(et[ze-1],v));var ds=et.reduce(function(jr,Ln,fs){if(!Ln||Ln==="0"){var yi=jr[jr.length-1];yi&&yi.index+yi.length===fs?yi.length++:jr.push({index:fs,length:1})}return jr},[]),Er=ds.sort(function(jr,Ln){return Ln.length-jr.length})[0],Fr=void 0;if(Er&&Er.length>1){var Me=et.slice(0,Er.index),vr=et.slice(Er.index+Er.length);Fr=Me.join(":")+"::"+vr.join(":")}else Fr=et.join(":");return te&&(Fr+="%"+te),Fr}else return B}var Pe=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Ge="".match(/(){0}/)[1]===void 0;function wt(B){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k={},K=v.iri!==!1?u:a;v.reference==="suffix"&&(B=(v.scheme?v.scheme+":":"")+"//"+B);var H=B.match(Pe);if(H){Ge?(k.scheme=H[1],k.userinfo=H[3],k.host=H[4],k.port=parseInt(H[5],10),k.path=H[6]||"",k.query=H[7],k.fragment=H[8],isNaN(k.port)&&(k.port=H[5])):(k.scheme=H[1]||void 0,k.userinfo=B.indexOf("@")!==-1?H[3]:void 0,k.host=B.indexOf("//")!==-1?H[4]:void 0,k.port=parseInt(H[5],10),k.path=H[6]||"",k.query=B.indexOf("?")!==-1?H[7]:void 0,k.fragment=B.indexOf("#")!==-1?H[8]:void 0,isNaN(k.port)&&(k.port=B.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?H[4]:void 0)),k.host&&(k.host=Ie(ce(k.host,K),K)),k.scheme===void 0&&k.userinfo===void 0&&k.host===void 0&&k.port===void 0&&!k.path&&k.query===void 0?k.reference="same-document":k.scheme===void 0?k.reference="relative":k.fragment===void 0?k.reference="absolute":k.reference="uri",v.reference&&v.reference!=="suffix"&&v.reference!==k.reference&&(k.error=k.error||"URI is not a "+v.reference+" reference.");var te=W[(v.scheme||k.scheme||"").toLowerCase()];if(!v.unicodeSupport&&(!te||!te.unicodeSupport)){if(k.host&&(v.domainHost||te&&te.domainHost))try{k.host=z.toASCII(k.host.replace(K.PCT_ENCODED,Z).toLowerCase())}catch(fe){k.error=k.error||"Host's domain name can not be converted to ASCII via punycode: "+fe}ue(k,a)}else ue(k,K);te&&te.parse&&te.parse(k,v)}else k.error=k.error||"URI can not be parsed.";return k}function pi(B,v){var k=v.iri!==!1?u:a,K=[];return B.userinfo!==void 0&&(K.push(B.userinfo),K.push("@")),B.host!==void 0&&K.push(Ie(ce(String(B.host),k),k).replace(k.IPV6ADDRESS,function(H,te,fe){return"["+te+(fe?"%25"+fe:"")+"]"})),(typeof B.port=="number"||typeof B.port=="string")&&(K.push(":"),K.push(String(B.port))),K.length?K.join(""):void 0}var uo=/^\.\.?\//,au=/^\/\.(\/|$)/,pf=/^\/\.\.(\/|$)/,Yp=/^\/?(?:.|\n)*?(?=\/|$)/;function fo(B){for(var v=[];B.length;)if(B.match(uo))B=B.replace(uo,"");else if(B.match(au))B=B.replace(au,"/");else if(B.match(pf))B=B.replace(pf,"/"),v.pop();else if(B==="."||B==="..")B="";else{var k=B.match(Yp);if(k){var K=k[0];B=B.slice(K.length),v.push(K)}else throw new Error("Unexpected dot segment condition")}return v.join("")}function Vr(B){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},k=v.iri?u:a,K=[],H=W[(v.scheme||B.scheme||"").toLowerCase()];if(H&&H.serialize&&H.serialize(B,v),B.host&&!k.IPV6ADDRESS.test(B.host)){if(v.domainHost||H&&H.domainHost)try{B.host=v.iri?z.toUnicode(B.host):z.toASCII(B.host.replace(k.PCT_ENCODED,Z).toLowerCase())}catch(Ee){B.error=B.error||"Host's domain name can not be converted to "+(v.iri?"Unicode":"ASCII")+" via punycode: "+Ee}}ue(B,k),v.reference!=="suffix"&&B.scheme&&(K.push(B.scheme),K.push(":"));var te=pi(B,v);if(te!==void 0&&(v.reference!=="suffix"&&K.push("//"),K.push(te),B.path&&B.path.charAt(0)!=="/"&&K.push("/")),B.path!==void 0){var fe=B.path;!v.absolutePath&&(!H||!H.absolutePath)&&(fe=fo(fe)),te===void 0&&(fe=fe.replace(/^\/\//,"/%2F")),K.push(fe)}return B.query!==void 0&&(K.push("?"),K.push(B.query)),B.fragment!==void 0&&(K.push("#"),K.push(B.fragment)),K.join("")}function uu(B,v){var k=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},K=arguments[3],H={};return K||(B=wt(Vr(B,k),k),v=wt(Vr(v,k),k)),k=k||{},!k.tolerant&&v.scheme?(H.scheme=v.scheme,H.userinfo=v.userinfo,H.host=v.host,H.port=v.port,H.path=fo(v.path||""),H.query=v.query):(v.userinfo!==void 0||v.host!==void 0||v.port!==void 0?(H.userinfo=v.userinfo,H.host=v.host,H.port=v.port,H.path=fo(v.path||""),H.query=v.query):(v.path?(v.path.charAt(0)==="/"?H.path=fo(v.path):((B.userinfo!==void 0||B.host!==void 0||B.port!==void 0)&&!B.path?H.path="/"+v.path:B.path?H.path=B.path.slice(0,B.path.lastIndexOf("/")+1)+v.path:H.path=v.path,H.path=fo(H.path)),H.query=v.query):(H.path=B.path,v.query!==void 0?H.query=v.query:H.query=B.query),H.userinfo=B.userinfo,H.host=B.host,H.port=B.port),H.scheme=B.scheme),H.fragment=v.fragment,H}function yf(B,v,k){var K=s({scheme:"null"},k);return Vr(uu(wt(B,K),wt(v,K),K,!0),K)}function du(B,v){return typeof B=="string"?B=Vr(wt(B,v),v):n(B)==="object"&&(B=wt(Vr(B,v),v)),B}function gf(B,v,k){return typeof B=="string"?B=Vr(wt(B,k),k):n(B)==="object"&&(B=Vr(B,k)),typeof v=="string"?v=Vr(wt(v,k),k):n(v)==="object"&&(v=Vr(v,k)),B===v}function mf(B,v){return B&&B.toString().replace(!v||!v.iri?a.ESCAPE:u.ESCAPE,Y)}function qr(B,v){return B&&B.toString().replace(!v||!v.iri?a.PCT_ENCODED:u.PCT_ENCODED,Z)}var lo={scheme:"http",domainHost:!0,parse:function(v,k){return v.host||(v.error=v.error||"HTTP URIs must have a host."),v},serialize:function(v,k){var K=String(v.scheme).toLowerCase()==="https";return(v.port===(K?443:80)||v.port==="")&&(v.port=void 0),v.path||(v.path="/"),v}},fu={scheme:"https",domainHost:lo.domainHost,parse:lo.parse,serialize:lo.serialize};function wf(B){return typeof B.secure=="boolean"?B.secure:String(B.scheme).toLowerCase()==="wss"}var us={scheme:"ws",domainHost:!0,parse:function(v,k){var K=v;return K.secure=wf(K),K.resourceName=(K.path||"/")+(K.query?"?"+K.query:""),K.path=void 0,K.query=void 0,K},serialize:function(v,k){if((v.port===(wf(v)?443:80)||v.port==="")&&(v.port=void 0),typeof v.secure=="boolean"&&(v.scheme=v.secure?"wss":"ws",v.secure=void 0),v.resourceName){var K=v.resourceName.split("?"),H=d(K,2),te=H[0],fe=H[1];v.path=te&&te!=="/"?te:void 0,v.query=fe,v.resourceName=void 0}return v.fragment=void 0,v}},bf={scheme:"wss",domainHost:us.domainHost,parse:us.parse,serialize:us.serialize},Jp={},MB=!0,Gb="[A-Za-z0-9\\-\\.\\_\\~"+(MB?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",Cn="[0-9A-Fa-f]",KB=r(r("%[EFef]"+Cn+"%"+Cn+Cn+"%"+Cn+Cn)+"|"+r("%[89A-Fa-f]"+Cn+"%"+Cn+Cn)+"|"+r("%"+Cn+Cn)),$B="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",HB="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",VB=e(HB,'[\\"\\\\]'),qB="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",FB=new RegExp(Gb,"g"),xc=new RegExp(KB,"g"),jB=new RegExp(e("[^]",$B,"[\\.]",'[\\"]',VB),"g"),zb=new RegExp(e("[^]",Gb,qB),"g"),WB=zb;function Zp(B){var v=Z(B);return v.match(FB)?v:B}var Yb={scheme:"mailto",parse:function(v,k){var K=v,H=K.to=K.path?K.path.split(","):[];if(K.path=void 0,K.query){for(var te=!1,fe={},Ee=K.query.split("&"),Re=0,pt=Ee.length;Re<pt;++Re){var xe=Ee[Re].split("=");switch(xe[0]){case"to":for(var Qe=xe[1].split(","),yt=0,ze=Qe.length;yt<ze;++yt)H.push(Qe[yt]);break;case"subject":K.subject=qr(xe[1],k);break;case"body":K.body=qr(xe[1],k);break;default:te=!0,fe[qr(xe[0],k)]=qr(xe[1],k);break}}te&&(K.headers=fe)}K.query=void 0;for(var Se=0,et=H.length;Se<et;++Se){var De=H[Se].split("@");if(De[0]=qr(De[0]),k.unicodeSupport)De[1]=qr(De[1],k).toLowerCase();else try{De[1]=z.toASCII(qr(De[1],k).toLowerCase())}catch(ds){K.error=K.error||"Email address's domain name can not be converted to ASCII via punycode: "+ds}H[Se]=De.join("@")}return K},serialize:function(v,k){var K=v,H=o(v.to);if(H){for(var te=0,fe=H.length;te<fe;++te){var Ee=String(H[te]),Re=Ee.lastIndexOf("@"),pt=Ee.slice(0,Re).replace(xc,Zp).replace(xc,i).replace(jB,Y),xe=Ee.slice(Re+1);try{xe=k.iri?z.toUnicode(xe):z.toASCII(qr(xe,k).toLowerCase())}catch(Se){K.error=K.error||"Email address's domain name can not be converted to "+(k.iri?"Unicode":"ASCII")+" via punycode: "+Se}H[te]=pt+"@"+xe}K.path=H.join(",")}var Qe=v.headers=v.headers||{};v.subject&&(Qe.subject=v.subject),v.body&&(Qe.body=v.body);var yt=[];for(var ze in Qe)Qe[ze]!==Jp[ze]&&yt.push(ze.replace(xc,Zp).replace(xc,i).replace(zb,Y)+"="+Qe[ze].replace(xc,Zp).replace(xc,i).replace(WB,Y));return yt.length&&(K.query=yt.join("&")),K}},GB=/^([^\:]+)\:(.*)/,Jb={scheme:"urn",parse:function(v,k){var K=v.path&&v.path.match(GB),H=v;if(K){var te=k.scheme||H.scheme||"urn",fe=K[1].toLowerCase(),Ee=K[2],Re=te+":"+(k.nid||fe),pt=W[Re];H.nid=fe,H.nss=Ee,H.path=void 0,pt&&(H=pt.parse(H,k))}else H.error=H.error||"URN can not be parsed.";return H},serialize:function(v,k){var K=k.scheme||v.scheme||"urn",H=v.nid,te=K+":"+(k.nid||H),fe=W[te];fe&&(v=fe.serialize(v,k));var Ee=v,Re=v.nss;return Ee.path=(H||k.nid)+":"+Re,Ee}},zB=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,Zb={scheme:"urn:uuid",parse:function(v,k){var K=v;return K.uuid=K.nss,K.nss=void 0,!k.tolerant&&(!K.uuid||!K.uuid.match(zB))&&(K.error=K.error||"UUID is not valid."),K},serialize:function(v,k){var K=v;return K.nss=(v.uuid||"").toLowerCase(),K}};W[lo.scheme]=lo,W[fu.scheme]=fu,W[us.scheme]=us,W[bf.scheme]=bf,W[Yb.scheme]=Yb,W[Jb.scheme]=Jb,W[Zb.scheme]=Zb,t.SCHEMES=W,t.pctEncChar=Y,t.pctDecChars=Z,t.parse=wt,t.removeDotSegments=fo,t.serialize=Vr,t.resolveComponents=uu,t.resolve=yf,t.normalize=du,t.equal=gf,t.escapeComponent=mf,t.unescapeComponent=qr,Object.defineProperty(t,"__esModule",{value:!0})})});var L_=oe((xZ,C_)=>{"use strict";l();C_.exports=function t(e){if(typeof e=="number"&&isNaN(e))throw new Error("NaN is not allowed");if(typeof e=="number"&&!isFinite(e))throw new Error("Infinity is not allowed");return e===null||typeof e!="object"?JSON.stringify(e):e.toJSON instanceof Function?t(e.toJSON()):Array.isArray(e)?`[${e.reduce((i,o,s)=>`${i}${s===0?"":","}${t(o===void 0||typeof o=="symbol"?null:o)}`,"")}]`:`{${Object.keys(e).sort().reduce((n,i)=>{if(e[i]===void 0||typeof e[i]=="symbol")return n;let o=n.length===0?"":",";return`${n}${o}${t(i)}:${t(e[i])}`},"")}}`}});var Y_=oe((SQ,z_)=>{l();var Za=1e3,Xa=Za*60,Qa=Xa*60,gc=Qa*24,NC=gc*7,CC=gc*365.25;z_.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return LC(t);if(r==="number"&&isFinite(t))return e.long?MC(t):PC(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function LC(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*CC;case"weeks":case"week":case"w":return r*NC;case"days":case"day":case"d":return r*gc;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Qa;case"minutes":case"minute":case"mins":case"min":case"m":return r*Xa;case"seconds":case"second":case"secs":case"sec":case"s":return r*Za;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function PC(t){var e=Math.abs(t);return e>=gc?Math.round(t/gc)+"d":e>=Qa?Math.round(t/Qa)+"h":e>=Xa?Math.round(t/Xa)+"m":e>=Za?Math.round(t/Za)+"s":t+"ms"}function MC(t){var e=Math.abs(t);return e>=gc?Np(t,e,gc,"day"):e>=Qa?Np(t,e,Qa,"hour"):e>=Xa?Np(t,e,Xa,"minute"):e>=Za?Np(t,e,Za,"second"):t+" ms"}function Np(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});l();l();l();l();var gs=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ms(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function mu(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function pn(t,...e){if(!ms(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function If(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mu(t.outputLen),mu(t.blockLen)}function Oc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Sx(t,e){pn(t);let r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Vn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Rf(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function yn(t,e){return t<<32-e|t>>>e}function wu(t,e){return t<<e|t>>>32-e>>>0}var Ax=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",HI=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ct(t){if(pn(t),Ax)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=HI[t[r]];return e}var vi={_0:48,_9:57,A:65,F:70,a:97,f:102};function vx(t){if(t>=vi._0&&t<=vi._9)return t-vi._0;if(t>=vi.A&&t<=vi.F)return t-(vi.A-10);if(t>=vi.a&&t<=vi.f)return t-(vi.a-10)}function Ar(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ax)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=vx(t.charCodeAt(o)),c=vx(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function ws(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function bu(t){return typeof t=="string"&&(t=ws(t)),pn(t),t}function ut(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];pn(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var Uc=class{};function Uf(t){let e=n=>t().update(bu(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Tr(t=32){if(gs&&typeof gs.getRandomValues=="function")return gs.getRandomValues(new Uint8Array(t));if(gs&&typeof gs.randomBytes=="function")return Uint8Array.from(gs.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}l();l();l();l();l();function VI(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}function ly(t,e,r){return t&e^~t&r}function hy(t,e,r){return t&e^t&r^e&r}var Dc=class extends Uc{constructor(e,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Rf(this.buffer)}update(e){Oc(this),e=bu(e),pn(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Rf(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Oc(this),Sx(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Vn(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;VI(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Rf(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=c,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},Si=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var qI=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]),ho=new Uint32Array(64),py=class extends Dc{constructor(e=32){super(64,e,8,!1),this.A=Si[0]|0,this.B=Si[1]|0,this.C=Si[2]|0,this.D=Si[3]|0,this.E=Si[4]|0,this.F=Si[5]|0,this.G=Si[6]|0,this.H=Si[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)ho[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=ho[f-15],p=ho[f-2],g=yn(h,7)^yn(h,18)^h>>>3,y=yn(p,17)^yn(p,19)^p>>>10;ho[f]=y+ho[f-7]+g+ho[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=yn(c,6)^yn(c,11)^yn(c,25),p=d+h+ly(c,a,u)+qI[f]+ho[f]|0,y=(yn(n,2)^yn(n,13)^yn(n,22))+hy(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Vn(ho)}destroy(){this.set(0,0,0,0,0,0,0,0),Vn(this.buffer)}};var Oe=Uf(()=>new py);l();l();l();var Of=class extends Uc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,If(e);let n=bu(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);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),Vn(o)}update(e){return Oc(this),this.iHash.update(e),this}digestInto(e){Oc(this),pn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},yy=(t,e,r)=>new Of(t,e).update(r).digest();yy.create=(t,e)=>new Of(t,e);l();var wy=BigInt(0),my=BigInt(1);function xu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function po(t,e,r=""){let n=ms(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let s=r&&`"${r}" `,c=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+c+", got "+a)}return t}function Eu(t){let e=t.toString(16);return e.length&1?"0"+e:e}function Tx(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?wy:BigInt("0x"+t)}function Ai(t){return Tx(Ct(t))}function by(t){return pn(t),Tx(Ct(Uint8Array.from(t).reverse()))}function kc(t,e){return Ar(t.toString(16).padStart(e*2,"0"))}function xy(t,e){return kc(t,e).reverse()}function ot(t,e,r){let n;if(typeof e=="string")try{n=Ar(e)}catch(o){throw new Error(t+" must be hex string or Uint8Array, cause: "+o)}else if(ms(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function vu(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}var gy=t=>typeof t=="bigint"&&wy<=t;function Su(t,e,r){return gy(t)&&gy(e)&&gy(r)&&e<=t&&t<r}function _x(t,e,r,n){if(!Su(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Df(t){let e;for(e=0;t>wy;t>>=my,e+=1);return e}var yo=t=>(my<<BigInt(t))-my;function Bx(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=p=>new Uint8Array(p),i=p=>Uint8Array.of(p),o=n(t),s=n(t),c=0,a=()=>{o.fill(1),s.fill(0),c=0},u=(...p)=>r(s,o,...p),d=(p=n(0))=>{s=u(i(0),p),o=u(),p.length!==0&&(s=u(i(1),p),o=u())},f=()=>{if(c++>=1e3)throw new Error("drbg: tried 1000 values");let p=0,g=[];for(;p<e;){o=u();let y=o.slice();g.push(y),p+=o.length}return ut(...g)};return(p,g)=>{a(),d(p);let y;for(;!(y=g(f()));)d();return a(),y}}function Au(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(i,o,s){let c=t[i];if(s&&c===void 0)return;let a=typeof c;if(a!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${a}`)}Object.entries(e).forEach(([i,o])=>n(i,o,!1)),Object.entries(r).forEach(([i,o])=>n(i,o,!0))}function Ey(t){let e=new WeakMap;return(r,...n)=>{let i=e.get(r);if(i!==void 0)return i;let o=t(r,...n);return e.set(r,o),o}}l();l();var er=BigInt(0),qt=BigInt(1),bs=BigInt(2),Ux=BigInt(3),Ox=BigInt(4),Dx=BigInt(5),FI=BigInt(7),kx=BigInt(8),jI=BigInt(9),Nx=BigInt(16);function _r(t,e){let r=t%e;return r>=er?r:e+r}function Br(t,e,r){let n=t;for(;e-- >er;)n*=n,n%=r;return n}function Ix(t,e){if(t===er)throw new Error("invert: expected non-zero number");if(e<=er)throw new Error("invert: expected positive modulus, got "+e);let r=_r(t,e),n=e,i=er,o=qt,s=qt,c=er;for(;r!==er;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==qt)throw new Error("invert: does not exist");return _r(i,e)}function vy(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Cx(t,e){let r=(t.ORDER+qt)/Ox,n=t.pow(e,r);return vy(t,n,e),n}function WI(t,e){let r=(t.ORDER-Dx)/kx,n=t.mul(e,bs),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,bs),i),c=t.mul(o,t.sub(s,t.ONE));return vy(t,c,e),c}function GI(t){let e=go(t),r=Lx(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+FI)/Nx;return(c,a)=>{let u=c.pow(a,s),d=c.mul(u,n),f=c.mul(u,i),h=c.mul(u,o),p=c.eql(c.sqr(d),a),g=c.eql(c.sqr(f),a);u=c.cmov(u,d,p),d=c.cmov(h,f,g);let y=c.eql(c.sqr(d),a),E=c.cmov(u,d,y);return vy(c,E,a),E}}function Lx(t){if(t<Ux)throw new Error("sqrt is not defined for small field");let e=t-qt,r=0;for(;e%bs===er;)e/=bs,r++;let n=bs,i=go(t);for(;Rx(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Cx;let o=i.pow(n,e),s=(e+qt)/bs;return function(a,u){if(a.is0(u))return u;if(Rx(a,u)!==1)throw new Error("Cannot find square root");let d=r,f=a.mul(a.ONE,o),h=a.pow(u,e),p=a.pow(u,s);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let g=1,y=a.sqr(h);for(;!a.eql(y,a.ONE);)if(g++,y=a.sqr(y),g===d)throw new Error("Cannot find square root");let E=qt<<BigInt(d-g-1),S=a.pow(f,E);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function zI(t){return t%Ox===Ux?Cx:t%kx===Dx?WI:t%Nx===jI?GI(t):Lx(t)}var YI=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Sy(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=YI.reduce((n,i)=>(n[i]="function",n),e);return Au(t,r),t}function JI(t,e,r){if(r<er)throw new Error("invalid exponent, negatives unsupported");if(r===er)return t.ONE;if(r===qt)return e;let n=t.ONE,i=e;for(;r>er;)r&qt&&(n=t.mul(n,i)),i=t.sqr(i),r>>=qt;return n}function kf(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((s,c,a)=>t.is0(c)?s:(n[a]=s,t.mul(s,c)),t.ONE),o=t.inv(i);return e.reduceRight((s,c,a)=>t.is0(c)?s:(n[a]=t.mul(s,n[a]),t.mul(s,c)),o),n}function Rx(t,e){let r=(t.ORDER-qt)/bs,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),s=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function Nf(t,e){e!==void 0&&mu(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function go(t,e,r=!1,n={}){if(t<=er)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,o,s=!1,c;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");let h=e;h.BITS&&(i=h.BITS),h.sqrt&&(o=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(s=h.modFromBytes),c=h.allowedLengths}else typeof e=="number"&&(i=e),n.sqrt&&(o=n.sqrt);let{nBitLength:a,nByteLength:u}=Nf(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let d,f=Object.freeze({ORDER:t,isLE:r,BITS:a,BYTES:u,MASK:yo(a),ZERO:er,ONE:qt,allowedLengths:c,create:h=>_r(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return er<=h&&h<t},is0:h=>h===er,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&qt)===qt,neg:h=>_r(-h,t),eql:(h,p)=>h===p,sqr:h=>_r(h*h,t),add:(h,p)=>_r(h+p,t),sub:(h,p)=>_r(h-p,t),mul:(h,p)=>_r(h*p,t),pow:(h,p)=>JI(f,h,p),div:(h,p)=>_r(h*Ix(p,t),t),sqrN:h=>h*h,addN:(h,p)=>h+p,subN:(h,p)=>h-p,mulN:(h,p)=>h*p,inv:h=>Ix(h,t),sqrt:o||(h=>(d||(d=zI(t)),d(f,h))),toBytes:h=>r?xy(h,u):kc(h,u),fromBytes:(h,p=!0)=>{if(c){if(!c.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+h.length);let y=new Uint8Array(u);y.set(h,r?0:y.length-h.length),h=y}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let g=r?by(h):Ai(h);if(s&&(g=_r(g,t)),!p&&!f.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:h=>kf(f,h),cmov:(h,p,g)=>g?p:h});return Object.freeze(f)}function Px(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Ay(t){let e=Px(t);return e+Math.ceil(e/2)}function Cf(t,e,r=!1){let n=t.length,i=Px(e),o=Ay(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?by(t):Ai(t),c=_r(s,e-qt)+qt;return r?xy(c,i):kc(c,i)}var Nc=BigInt(0),xs=BigInt(1);function Tu(t,e){let r=e.negate();return t?r:e}function Pf(t,e){let r=kf(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function Hx(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ty(t,e){Hx(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=yo(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function Mx(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,c=Number(t&i),a=t>>s;c>n&&(c-=o,a+=xs);let u=e*n,d=u+Math.abs(c)-1,f=c===0,h=c<0,p=e%2!==0;return{nextN:a,offset:d,isZero:f,isNeg:h,isNegF:p,offsetF:u}}function ZI(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function XI(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}var _y=new WeakMap,Vx=new WeakMap;function By(t){return Vx.get(t)||1}function Kx(t){if(t!==Nc)throw new Error("invalid wNAF")}var Lf=class{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>Nc;)r&xs&&(n=n.add(i)),i=i.double(),r>>=xs;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=Ty(r,this.bits),o=[],s=e,c=s;for(let a=0;a<n;a++){c=s,o.push(c);for(let u=1;u<i;u++)c=c.add(s),o.push(c);s=c.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=Ty(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=Mx(n,c,s);n=a,d?o=o.add(Tu(h,r[p])):i=i.add(Tu(f,r[u]))}return Kx(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=Ty(e,this.bits);for(let s=0;s<o.windows&&n!==Nc;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=Mx(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return Kx(n),i}getPrecomputes(e,r,n){let i=_y.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),_y.set(r,i))),i}cached(e,r,n){let i=By(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=By(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){Hx(r,this.bits),Vx.set(e,r),_y.delete(e)}hasCache(e){return By(e)!==1}};function qx(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>Nc||n>Nc;)r&xs&&(o=o.add(i)),n&xs&&(s=s.add(i)),i=i.double(),r>>=xs,n>>=xs;return{p1:o,p2:s}}function Fx(t,e,r,n){ZI(r,t),XI(n,e);let i=r.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");let s=t.ZERO,c=Df(BigInt(i)),a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);let u=yo(a),d=new Array(Number(u)+1).fill(s),f=Math.floor((e.BITS-1)/a)*a,h=s;for(let p=f;p>=0;p-=a){d.fill(s);for(let y=0;y<o;y++){let E=n[y],S=Number(E>>BigInt(p)&u);d[S]=d[S].add(r[y])}let g=s;for(let y=d.length-1,E=s;y>0;y--)E=E.add(d[y]),g=g.add(E);if(h=h.add(g),p!==0)for(let y=0;y<a;y++)h=h.double()}return h}function $x(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Sy(e),e}else return go(t,{isLE:r})}function jx(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>Nc))throw new Error(`CURVE.${a} must be positive bigint`)}let i=$x(e.p,r.Fp,n),o=$x(e.n,r.Fn,n),c=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of c)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}var Wx=(t,e)=>(t+(t>=0?e:-e)/Gx)/e;function QI(t,e,r){let[[n,i],[o,s]]=e,c=Wx(s*t,r),a=Wx(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<_i,h=d<_i;f&&(u=-u),h&&(d=-d);let p=yo(Math.ceil(Df(r)/2))+Cc;if(u<_i||u>=p||d<_i||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Ry(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Iy(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return xu(r.lowS,"lowS"),xu(r.prehash,"prehash"),r.format!==void 0&&Ry(r.format),r}var Uy=class extends Error{constructor(e=""){super(e)}},Ti={Err:Uy,_tlv:{encode:(t,e)=>{let{Err:r}=Ti;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=Eu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?Eu(i.length/2|128):"";return Eu(t)+o+i+e},decode(t,e){let{Err:r}=Ti,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=a,s<128)throw new r("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+s);if(c.length!==s)throw new r("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=Ti;if(t<_i)throw new e("integer: negative integers are not allowed");let r=Eu(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=Ti;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ai(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=Ti,i=ot("signature",t),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:c,l:a}=n.decode(2,o),{v:u,l:d}=n.decode(2,a);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=Ti,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},_i=BigInt(0),Cc=BigInt(1),Gx=BigInt(2),Mf=BigInt(3),e8=BigInt(4);function mo(t,e){let{BYTES:r}=t,n;if(typeof e=="bigint")n=e;else{let i=ot("private key",e);try{n=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function t8(t,e={}){let r=jx("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Au(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});let{endo:a}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=Yx(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(G,_,D){let{x,y:U}=_.toAffine(),L=n.toBytes(x);if(xu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return ut(zx(N),L)}else return ut(Uint8Array.of(4),L,n.toBytes(U))}function h(G){po(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,x=G.length,U=G[0],L=G.subarray(1);if(x===_&&(U===2||U===3)){let N=n.fromBytes(L);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let R=y(N),C;try{C=n.sqrt(R)}catch(J){let z=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(C);return(U&1)===1!==P&&(C=n.neg(C)),{x:N,y:C}}else if(x===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!E(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${x}, expected compressed=${_} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let _=n.sqr(G),D=n.mul(_,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function E(G,_){let D=n.sqr(_),x=y(G);return n.eql(D,x)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,Mf),e8),I=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,I)))throw new Error("bad curve params: a or b");function A(G,_,D=!1){if(!n.isValid(_)||D&&n.is0(_))throw new Error(`bad point coordinate ${G}`);return _}function O(G){if(!(G instanceof $))throw new Error("ProjectivePoint expected")}function T(G){if(!a||!a.basises)throw new Error("no endo");return QI(G,a.basises,i.ORDER)}let M=Ey((G,_)=>{let{X:D,Y:x,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:x};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(x,_),C=n.mul(U,_);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x:N,y:R}}),q=Ey(G=>{if(G.is0()){if(e.allowInfinityPoint&&!n.is0(G.Y))return;throw new Error("bad point: ZERO")}let{x:_,y:D}=G.toAffine();if(!n.isValid(_)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(_,D))throw new Error("bad point: equation left != right");if(!G.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(G,_,D,x,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=Tu(x,_),D=Tu(U,D),_.add(D)}class ${constructor(_,D,x){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:x}=_||{};if(!_||!n.isValid(D)||!n.isValid(x))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(x)?$.ZERO:new $(D,x,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(po(_,void 0,"point")));return D.assertValidity(),D}static fromHex(_){return $.fromBytes(ot("pointHex",_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,D=!0){return Q.createCache(this,_),D||this.multiply(Mf),this}assertValidity(){q(this)}hasEvenY(){let{y:_}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(_)}equals(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(x,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:_,b:D}=o,x=n.mul(D,Mf),{X:U,Y:L,Z:N}=this,R=n.ZERO,C=n.ZERO,P=n.ZERO,V=n.mul(U,U),J=n.mul(L,L),z=n.mul(N,N),W=n.mul(U,L);return W=n.add(W,W),P=n.mul(U,N),P=n.add(P,P),R=n.mul(_,P),C=n.mul(x,z),C=n.add(R,C),R=n.sub(J,C),C=n.add(J,C),C=n.mul(R,C),R=n.mul(W,R),P=n.mul(x,P),z=n.mul(_,z),W=n.sub(V,z),W=n.mul(_,W),W=n.add(W,P),P=n.add(V,V),V=n.add(P,V),V=n.add(V,z),V=n.mul(V,W),C=n.add(C,V),z=n.mul(L,N),z=n.add(z,z),V=n.mul(z,W),R=n.sub(R,V),P=n.mul(z,J),P=n.add(P,P),P=n.add(P,P),new $(R,C,P)}add(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,Mf),W=n.mul(D,L),Y=n.mul(x,N),Z=n.mul(U,R),ue=n.add(D,x),ee=n.add(L,N);ue=n.mul(ue,ee),ee=n.add(W,Y),ue=n.sub(ue,ee),ee=n.add(D,U);let ce=n.add(L,R);return ee=n.mul(ee,ce),ce=n.add(W,Z),ee=n.sub(ee,ce),ce=n.add(x,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,Z),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,Z),V=n.add(C,V),C=n.sub(Y,V),V=n.add(Y,V),P=n.mul(C,V),Y=n.add(W,W),Y=n.add(Y,W),Z=n.mul(J,Z),ee=n.mul(z,ee),Y=n.add(Y,Z),Z=n.sub(W,Z),Z=n.mul(J,Z),ee=n.add(ee,Z),W=n.mul(Y,ee),P=n.add(P,W),W=n.mul(ce,ee),C=n.mul(ue,C),C=n.sub(C,W),W=n.mul(ue,Y),V=n.mul(ce,V),V=n.add(V,W),new $(C,P,V)}subtract(_){return this.add(_.negate())}is0(){return this.equals($.ZERO)}multiply(_){let{endo:D}=e;if(!i.isValidNot0(_))throw new Error("invalid scalar: out of range");let x,U,L=N=>Q.cached(this,N,R=>Pf($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(_),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),x=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);x=N,U=R}return Pf($,[x,U])[0]}multiplyUnsafe(_){let{endo:D}=e,x=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===_i||x.is0())return $.ZERO;if(_===Cc)return x;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=qx($,x,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(x,_)}multiplyAndAddUnsafe(_,D,x){let U=this.multiplyUnsafe(D).add(_.multiplyUnsafe(x));return U.is0()?void 0:U}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===Cc?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===Cc?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return xu(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Ct(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(_=!0){return this.toBytes(_)}_setWindowSize(_){this.precompute(_)}static normalizeZ(_){return Pf($,_)}static msm(_,D){return Fx($,i,_,D)}static fromPrivateKey(_){return $.BASE.multiply(mo(i,_))}}$.BASE=new $(o.Gx,o.Gy,n.ONE),$.ZERO=new $(n.ZERO,n.ONE,n.ZERO),$.Fp=n,$.Fn=i;let X=i.BITS,Q=new Lf($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function zx(t){return Uint8Array.of(t?2:3)}function Yx(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function r8(t,e={}){let{Fn:r}=t,n=e.randomBytes||Tr,i=Object.assign(Yx(t.Fp,r),{seed:Ay(r.ORDER)});function o(p){try{return!!mo(r,p)}catch{return!1}}function s(p,g){let{publicKey:y,publicKeyUncompressed:E}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==E?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return Cf(po(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(mo(r,p)).toBytes(g)}function u(p){let g=c(p);return{secretKey:g,publicKey:a(g)}}function d(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;let{secretKey:g,publicKey:y,publicKeyUncompressed:E}=i;if(r.allowedLengths||g===y)return;let S=ot("key",p).length;return S===y||S===E}function f(p,g,y=!0){if(d(p)===!0)throw new Error("first arg must be private key");if(d(g)===!1)throw new Error("second arg must be public key");let E=mo(r,p);return t.fromHex(g).multiply(E).toBytes(y)}return Object.freeze({getPublicKey:a,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:c,isValidPrivateKey:o,randomPrivateKey:c,normPrivateKeyToScalar:p=>mo(r,p),precompute(p=8,g=t.BASE){return g.precompute(p,!1)}},lengths:i})}function n8(t,e,r={}){If(e),Au(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});let n=r.randomBytes||Tr,i=r.hmac||((D,...x)=>yy(e,D,ut(...x))),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=r8(t,r),g={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},y="compact";function E(D){let x=c>>Cc;return D>x}function S(D,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return x}function I(D,x){Ry(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return po(D,L,`${x} signature`)}class A{constructor(x,U,L){this.r=S("r",x),this.s=S("s",U),L!=null&&(this.recovery=L),Object.freeze(this)}static fromBytes(x,U=y){I(x,U);let L;if(U==="der"){let{r:P,s:V}=Ti.toSig(po(x));return new A(P,V)}U==="recovered"&&(L=x[0],U="compact",x=x.subarray(1));let N=s.BYTES,R=x.subarray(0,N),C=x.subarray(N,N*2);return new A(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(x,U){return this.fromBytes(Ar(x),U)}addRecoveryBit(x){return new A(this.r,this.s,x)}recoverPublicKey(x){let U=o.ORDER,{r:L,s:N,recovery:R}=this;if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");if(c*Gx<U&&R>1)throw new Error("recovery id is ambiguous for h>1 curve");let P=R===2||R===3?L+c:L;if(!o.isValid(P))throw new Error("recovery id 2 or 3 invalid");let V=o.toBytes(P),J=t.fromBytes(ut(zx((R&1)===0),V)),z=s.inv(P),W=T(ot("msgHash",x)),Y=s.create(-W*z),Z=s.create(N*z),ue=t.BASE.multiplyUnsafe(Y).add(J.multiplyUnsafe(Z));if(ue.is0())throw new Error("point at infinify");return ue.assertValidity(),ue}hasHighS(){return E(this.s)}toBytes(x=y){if(Ry(x),x==="der")return Ar(Ti.hexFromSig(this));let U=s.toBytes(this.r),L=s.toBytes(this.s);if(x==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return ut(Uint8Array.of(this.recovery),U,L)}return ut(U,L)}toHex(x){return Ct(this.toBytes(x))}assertValidity(){}static fromCompact(x){return A.fromBytes(ot("sig",x),"compact")}static fromDER(x){return A.fromBytes(ot("sig",x),"der")}normalizeS(){return this.hasHighS()?new A(this.r,s.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ct(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ct(this.toBytes("compact"))}}let O=r.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let U=Ai(x),L=x.length*8-a;return L>0?U>>BigInt(L):U},T=r.bits2int_modN||function(x){return s.create(O(x))},M=yo(a);function q(D){return _x("num < 2^"+a,D,_i,M),s.toBytes(D)}function j(D,x){return po(D,void 0,"message"),x?po(e(D),void 0,"prehashed message"):D}function $(D,x,U){if(["recovered","canonical"].some(Y=>Y in U))throw new Error("sign() legacy options not supported");let{lowS:L,prehash:N,extraEntropy:R}=Iy(U,g);D=j(D,N);let C=T(D),P=mo(s,x),V=[q(P),q(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(ot("extraEntropy",Y))}let J=ut(...V),z=C;function W(Y){let Z=O(Y);if(!s.isValidNot0(Z))return;let ue=s.inv(Z),ee=t.BASE.multiply(Z).toAffine(),ce=s.create(ee.x);if(ce===_i)return;let Ie=s.create(ue*s.create(z+ce*P));if(Ie===_i)return;let Pe=(ee.x===ce?0:2)|Number(ee.y&Cc),Ge=Ie;return L&&E(Ie)&&(Ge=s.neg(Ie),Pe^=1),new A(ce,Ge,Pe)}return{seed:J,k2sig:W}}function X(D,x,U={}){D=ot("message",D);let{seed:L,k2sig:N}=$(D,x,U);return Bx(e.outputLen,s.BYTES,i)(L,N)}function Q(D){let x,U=typeof D=="string"||ms(D),L=!U&&D!==null&&typeof D=="object"&&typeof D.r=="bigint"&&typeof D.s=="bigint";if(!U&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(L)x=new A(D.r,D.s);else if(U){try{x=A.fromBytes(ot("sig",D),"der")}catch(N){if(!(N instanceof Ti.Err))throw N}if(!x)try{x=A.fromBytes(ot("sig",D),"compact")}catch{return!1}}return x||!1}function G(D,x,U,L={}){let{lowS:N,prehash:R,format:C}=Iy(L,g);if(U=ot("publicKey",U),x=j(ot("message",x),R),"strict"in L)throw new Error("options.strict was renamed to lowS");let P=C===void 0?Q(D):A.fromBytes(ot("sig",D),C);if(P===!1)return!1;try{let V=t.fromBytes(U);if(N&&P.hasHighS())return!1;let{r:J,s:z}=P,W=T(x),Y=s.inv(z),Z=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(Z).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,x,U={}){let{prehash:L}=Iy(U,g);return x=j(x,L),A.fromBytes(D,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:X,verify:G,recoverPublicKey:_,Signature:A,hash:e})}function i8(t){let e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp,n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(s=>Math.ceil(s/2)))):void 0,i=go(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),o={Fp:r,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:o}}function o8(t){let{CURVE:e,curveOpts:r}=i8(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function s8(t,e){let r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Nf(r.Fn.ORDER,r.Fn.BITS))})}function Jx(t){let{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=o8(t),o=t8(e,r),s=n8(o,n,i);return s8(t,s)}function Zx(t,e){let r=n=>Jx({...t,hash:n});return{...r(e),create:r}}var Lc={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},c8={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},a8=BigInt(0),Xx=BigInt(1),Oy=BigInt(2);function u8(t){let e=Lc.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=Br(d,r,e)*d%e,h=Br(f,r,e)*d%e,p=Br(h,Oy,e)*u%e,g=Br(p,i,e)*p%e,y=Br(g,o,e)*g%e,E=Br(y,c,e)*y%e,S=Br(E,a,e)*E%e,I=Br(S,c,e)*y%e,A=Br(I,r,e)*d%e,O=Br(A,s,e)*g%e,T=Br(O,n,e)*u%e,M=Br(T,Oy,e);if(!Kf.eql(Kf.sqr(M),t))throw new Error("Cannot find square root");return M}var Kf=go(Lc.p,{sqrt:u8}),wo=Zx({...Lc,Fp:Kf,lowS:!0,endo:c8},Oe),Qx={};function $f(t,...e){let r=Qx[t];if(r===void 0){let n=Oe(ws(t));r=ut(n,n),Qx[t]=r}return Oe(ut(r,...e))}var ky=t=>t.toBytes(!0).slice(1),Pc=wo.Point,Ny=t=>t%Oy===a8;function Dy(t){let{Fn:e,BASE:r}=Pc,n=mo(e,t),i=r.multiply(n);return{scalar:Ny(i.y)?n:e.neg(n),bytes:ky(i)}}function tE(t){let e=Kf;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),i=e.sqrt(n);Ny(i)||(i=e.neg(i));let o=Pc.fromAffine({x:t,y:i});return o.assertValidity(),o}var _u=Ai;function rE(...t){return Pc.Fn.create(_u($f("BIP0340/challenge",...t)))}function eE(t){return Dy(t).bytes}function d8(t,e,r=Tr(32)){let{Fn:n}=Pc,i=ot("message",t),{bytes:o,scalar:s}=Dy(e),c=ot("auxRand",r,32),a=n.toBytes(s^_u($f("BIP0340/aux",c))),u=$f("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Dy(u),h=rE(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!nE(p,i,o))throw new Error("sign: Invalid signature produced");return p}function nE(t,e,r){let{Fn:n,BASE:i}=Pc,o=ot("signature",t,64),s=ot("message",e),c=ot("publicKey",r,32);try{let a=tE(_u(c)),u=_u(o.subarray(0,32));if(!Su(u,Xx,Lc.p))return!1;let d=_u(o.subarray(32,64));if(!Su(d,Xx,Lc.n))return!1;let f=rE(n.toBytes(u),ky(a),s),h=i.multiplyUnsafe(d).add(a.multiplyUnsafe(n.neg(f))),{x:p,y:g}=h.toAffine();return!(h.is0()||!Ny(g)||p!==u)}catch{return!1}}var Ir=(()=>{let r=(i=Tr(48))=>Cf(i,Lc.n);wo.utils.randomSecretKey;function n(i){let o=r(i);return{secretKey:o,publicKey:eE(o)}}return{keygen:n,getPublicKey:eE,sign:d8,verify:nE,Point:Pc,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:$f,lift_x:tE,pointToBytes:ky,numberToBytesBE:kc,bytesToNumberBE:Ai,mod:_r},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();var f8=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),oE=Uint8Array.from(new Array(16).fill(0).map((t,e)=>e)),l8=oE.map(t=>(9*t+5)%16),sE=(()=>{let r=[[oE],[l8]];for(let n=0;n<4;n++)for(let i of r)i.push(i[n].map(o=>f8[o]));return r})(),cE=sE[0],aE=sE[1],uE=[[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(t=>Uint8Array.from(t)),h8=cE.map((t,e)=>t.map(r=>uE[e][r])),p8=aE.map((t,e)=>t.map(r=>uE[e][r])),y8=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),g8=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function iE(t,e,r,n){return t===0?e^r^n:t===1?e&r|~e&n:t===2?(e|~r)^n:t===3?e&n|r&~n:e^(r|~n)}var Hf=new Uint32Array(16),Cy=class extends Dc{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:r,h2:n,h3:i,h4:o}=this;return[e,r,n,i,o]}set(e,r,n,i,o){this.h0=e|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=o|0}process(e,r){for(let p=0;p<16;p++,r+=4)Hf[p]=e.getUint32(r,!0);let n=this.h0|0,i=n,o=this.h1|0,s=o,c=this.h2|0,a=c,u=this.h3|0,d=u,f=this.h4|0,h=f;for(let p=0;p<5;p++){let g=4-p,y=y8[p],E=g8[p],S=cE[p],I=aE[p],A=h8[p],O=p8[p];for(let T=0;T<16;T++){let M=wu(n+iE(p,o,c,u)+Hf[S[T]]+y,A[T])+f|0;n=f,f=u,u=wu(c,10)|0,c=o,o=M}for(let T=0;T<16;T++){let M=wu(i+iE(g,s,a,d)+Hf[I[T]]+E,O[T])+h|0;i=h,h=d,d=wu(a,10)|0,a=s,s=M}}this.set(this.h1+c+d|0,this.h2+u+h|0,this.h3+f+i|0,this.h4+n+s|0,this.h0+o+a|0)}roundClean(){Vn(Hf)}destroy(){this.destroyed=!0,Vn(this.buffer),this.set(0,0,0,0,0)}},dE=Uf(()=>new Cy);l();l();function Mc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function m8(t,...e){if(!Mc(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function yE(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function My(t){if(typeof t!="function")throw new Error("function expected");return!0}function Kc(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Iu(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function qf(t){if(!Array.isArray(t))throw new Error("array expected")}function gE(t,e){if(!yE(!0,e))throw new Error(`${t}: array of strings expected`)}function Ky(t,e){if(!yE(!1,e))throw new Error(`${t}: array of numbers expected`)}function Ru(...t){let e=o=>o,r=(o,s)=>c=>o(s(c)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function jf(t){let e=typeof t=="string"?t.split(""):t,r=e.length;gE("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(qf(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${t}`);return e[o]})),decode:i=>(qf(i),i.map(o=>{Kc("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function Wf(t=""){return Kc("join",t),{encode:e=>(gE("join.decode",e),e.join(t)),decode:e=>(Kc("join.decode",e),e.split(t))}}function w8(t){return My(t),{encode:e=>e,decode:e=>t(e)}}function fE(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(qf(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(Iu(c),c<0||c>=e)throw new Error(`invalid integer: ${c}`);return c}),s=o.length;for(;;){let c=0,a=!0;for(let u=n;u<s;u++){let d=o[u],f=e*c,h=f+d;if(!Number.isSafeInteger(h)||f/e!==c||h-d!==f)throw new Error("convertRadix: carry overflow");let p=h/r;c=h%r;let g=Math.floor(p);if(o[u]=g,!Number.isSafeInteger(g)||g*r+c!==h)throw new Error("convertRadix: carry overflow");if(a)g?a=!1:n=u;else continue}if(i.push(c),a)break}for(let c=0;c<t.length-1&&t[c]===0;c++)i.push(0);return i.reverse()}var mE=(t,e)=>e===0?t:mE(e,t%e),Ff=(t,e)=>t+(e-mE(t,e)),Vf=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Ly(t,e,r,n){if(qf(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(Ff(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Ff(e,r)}`);let i=0,o=0,s=Vf[e],c=Vf[r]-1,a=[];for(let u of t){if(Iu(u),u>=s)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,o+e>32)throw new Error(`convertRadix2: carry overflow pos=${o} from=${e}`);for(o+=e;o>=r;o-=r)a.push((i>>o-r&c)>>>0);let d=Vf[o];if(d===void 0)throw new Error("invalid carry");i&=d-1}if(i=i<<r-o&c,!n&&o>=e)throw new Error("Excess padding");if(!n&&i>0)throw new Error(`Non-zero padding: ${i}`);return n&&o>0&&a.push(i>>>0),a}function b8(t){Iu(t);let e=2**8;return{encode:r=>{if(!Mc(r))throw new Error("radix.encode input should be Uint8Array");return fE(Array.from(r),e,t)},decode:r=>(Ky("radix.decode",r),Uint8Array.from(fE(r,t,e)))}}function $y(t,e=!1){if(Iu(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ff(8,t)>32||Ff(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Mc(r))throw new Error("radix2.encode input should be Uint8Array");return Ly(Array.from(r),8,t,!e)},decode:r=>(Ky("radix2.decode",r),Uint8Array.from(Ly(r,t,8,e)))}}function lE(t){return My(t),function(...e){try{return t.apply(null,e)}catch{}}}function x8(t,e){return Iu(t),My(e),{encode(r){if(!Mc(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!Mc(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=r.slice(-t),o=e(n).slice(0,t);for(let s=0;s<t;s++)if(o[s]!==i[s])throw new Error("Invalid checksum");return n}}}var $c=Ru($y(6),jf("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Wf("")),E8=t=>Ru(b8(58),jf(t),Wf("")),Gf=E8("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var wE=t=>Ru(x8(4,e=>t(t(e))),Gf);var Py=Ru(jf("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),Wf("")),hE=[996825010,642813549,513874426,1027748829,705979059];function Bu(t){let e=t>>25,r=(t&33554431)<<5;for(let n=0;n<hE.length;n++)(e>>n&1)===1&&(r^=hE[n]);return r}function pE(t,e,r=1){let n=t.length,i=1;for(let o=0;o<n;o++){let s=t.charCodeAt(o);if(s<33||s>126)throw new Error(`Invalid prefix (${t})`);i=Bu(i)^s>>5}i=Bu(i);for(let o=0;o<n;o++)i=Bu(i)^t.charCodeAt(o)&31;for(let o of e)i=Bu(i)^o;for(let o=0;o<6;o++)i=Bu(i);return i^=r,Py.encode(Ly([i%Vf[30]],30,5,!1))}function bE(t){let e=t==="bech32"?1:734539939,r=$y(5),n=r.decode,i=r.encode,o=lE(n);function s(f,h,p=90){Kc("bech32.encode prefix",f),Mc(h)&&(h=Array.from(h)),Ky("bech32.encode",h);let g=f.length;if(g===0)throw new TypeError(`Invalid prefix length ${g}`);let y=g+7+h.length;if(p!==!1&&y>p)throw new TypeError(`Length ${y} exceeds limit ${p}`);let E=f.toLowerCase(),S=pE(E,h,e);return`${E}1${Py.encode(h)}${S}`}function c(f,h=90){Kc("bech32.decode input",f);let p=f.length;if(p<8||h!==!1&&p>h)throw new TypeError(`invalid string length: ${p} (${f}). Expected (8..${h})`);let g=f.toLowerCase();if(f!==g&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");let y=g.lastIndexOf("1");if(y===0||y===-1)throw new Error('Letter "1" must be present between prefix and data only');let E=g.slice(0,y),S=g.slice(y+1);if(S.length<6)throw new Error("Data must be at least 6 characters long");let I=Py.decode(S).slice(0,-6),A=pE(E,I,e);if(!S.endsWith(A))throw new Error(`Invalid checksum in ${f}: expected "${A}"`);return{prefix:E,words:I}}let a=lE(c);function u(f){let{prefix:h,words:p}=c(f,!1);return{prefix:h,words:p,bytes:n(p)}}function d(f,h){return s(f,i(h))}return{encode:s,decode:c,encodeFromBytes:d,decodeToBytes:u,decodeUnsafe:a,fromWords:n,fromWordsUnsafe:o,toWords:i}}var zf=bE("bech32"),Hc=bE("bech32m"),xE={encode:t=>new TextDecoder().decode(t),decode:t=>new TextEncoder().encode(t)},v8=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S8={encode(t){return m8(t),t.toHex()},decode(t){return Kc("hex",t),Uint8Array.fromHex(t)}},Ae=v8?S8:Ru($y(4),jf("0123456789abcdef"),Wf(""),w8(t=>{if(typeof t!="string"||t.length%2!==0)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}));var $e=new Uint8Array,Fy=new Uint8Array([0]);function Vc(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}function Gr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function A8(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!Gr(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var jy=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function qc(t){return Object.prototype.toString.call(t)==="[object Object]"}function qn(t){return Number.isSafeInteger(t)}var Yf={equalBytes:Vc,isBytes:Gr,isCoder:Rr,checkBounds:vE,concatBytes:A8,createView:jy,isPlainObject:qc},EE=t=>{if(t!==null&&typeof t!="string"&&!Rr(t)&&!Gr(t)&&!qn(t))throw new Error(`lengthCoder: expected null | number | Uint8Array | CoderType, got ${t} (${typeof t})`);return{encodeStream(e,r){if(t===null)return;if(Rr(t))return t.encodeStream(e,r);let n;if(typeof t=="number"?n=t:typeof t=="string"&&(n=Bi.resolve(e.stack,t)),typeof n=="bigint"&&(n=Number(n)),n===void 0||n!==r)throw e.err(`Wrong length: ${n} len=${t} exp=${r} (${typeof r})`)},decodeStream(e){let r;if(Rr(t)?r=Number(t.decodeStream(e)):typeof t=="number"?r=t:typeof t=="string"&&(r=Bi.resolve(e.stack,t)),typeof r=="bigint"&&(r=Number(r)),typeof r!="number")throw e.err(`Wrong length: ${r}`);return r}}},Ut={BITS:32,FULL_MASK:-1>>>0,len:t=>Math.ceil(t/32),create:t=>new Uint32Array(Ut.len(t)),clean:t=>t.fill(0),debug:t=>Array.from(t).map(e=>(e>>>0).toString(2).padStart(32,"0")),checkLen:(t,e)=>{if(Ut.len(e)!==t.length)throw new Error(`wrong length=${t.length}. Expected: ${Ut.len(e)}`)},chunkLen:(t,e,r)=>{if(e<0)throw new Error(`wrong pos=${e}`);if(e+r>t)throw new Error(`wrong range=${e}/${r} of ${t}`)},set:(t,e,r,n=!0)=>!n&&t[e]&r?!1:(t[e]|=r,!0),pos:(t,e)=>({chunk:Math.floor((t+e)/32),mask:1<<32-(t+e)%32-1}),indices:(t,e,r=!1)=>{Ut.checkLen(t,e);let{FULL_MASK:n,BITS:i}=Ut,o=i-e%i,s=o?n>>>o<<o:n,c=[];for(let a=0;a<t.length;a++){let u=t[a];if(r&&(u=~u),a===t.length-1&&(u&=s),u!==0)for(let d=0;d<i;d++){let f=1<<i-d-1;u&f&&c.push(a*i+d)}}return c},range:t=>{let e=[],r;for(let n of t)r===void 0||n!==r.pos+r.length?e.push(r={pos:n,length:1}):r.length+=1;return e},rangeDebug:(t,e,r=!1)=>`[${Ut.range(Ut.indices(t,e,r)).map(n=>`(${n.pos}/${n.length})`).join(", ")}]`,setRange:(t,e,r,n,i=!0)=>{Ut.chunkLen(e,r,n);let{FULL_MASK:o,BITS:s}=Ut,c=r%s?Math.floor(r/s):void 0,a=r+n,u=a%s?Math.floor(a/s):void 0;if(c!==void 0&&c===u)return Ut.set(t,c,o>>>s-n<<s-n-r,i);if(c!==void 0&&!Ut.set(t,c,o>>>r%s,i))return!1;let d=c!==void 0?c+1:r/s,f=u!==void 0?u:a/s;for(let h=d;h<f;h++)if(!Ut.set(t,h,o,i))return!1;return!(u!==void 0&&c!==u&&!Ut.set(t,u,o<<s-a%s,i))}},Bi={pushObj:(t,e,r)=>{let n={obj:e};t.push(n),r((i,o)=>{n.field=i,o(),n.field=void 0}),t.pop()},path:t=>{let e=[];for(let r of t)r.field!==void 0&&e.push(r.field);return e.join("/")},err:(t,e,r)=>{let n=new Error(`${t}(${Bi.path(e)}): ${typeof r=="string"?r:r.message}`);return r instanceof Error&&r.stack&&(n.stack=r.stack),n},resolve:(t,e)=>{let r=e.split("/"),n=t.map(s=>s.obj),i=0;for(;i<r.length&&r[i]==="..";i++)n.pop();let o=n.pop();for(;i<r.length;i++){if(!o||o[r[i]]===void 0)return;o=o[r[i]]}return o}},Hy=class t{constructor(e,r={},n=[],i=void 0,o=0){this.pos=0,this.bitBuf=0,this.bitPos=0,this.data=e,this.opts=r,this.stack=n,this.parent=i,this.parentOffset=o,this.view=jy(e)}_enablePointers(){if(this.parent)return this.parent._enablePointers();this.bs||(this.bs=Ut.create(this.data.length),Ut.setRange(this.bs,this.data.length,0,this.pos,this.opts.allowMultipleReads))}markBytesBS(e,r){return this.parent?this.parent.markBytesBS(this.parentOffset+e,r):!r||!this.bs?!0:Ut.setRange(this.bs,this.data.length,e,r,!1)}markBytes(e){let r=this.pos;this.pos+=e;let n=this.markBytesBS(r,e);if(!this.opts.allowMultipleReads&&!n)throw this.err(`multiple read pos=${this.pos} len=${e}`);return n}pushObj(e,r){return Bi.pushObj(this.stack,e,r)}readView(e,r){if(!Number.isFinite(e))throw this.err(`readView: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readView: Unexpected end of buffer");let n=r(this.view,this.pos);return this.markBytes(e),n}absBytes(e){if(e>this.data.length)throw new Error("Unexpected end of buffer");return this.data.subarray(e)}finish(){if(!this.opts.allowUnreadBytes){if(this.bitPos)throw this.err(`${this.bitPos} bits left after unpack: ${Ae.encode(this.data.slice(this.pos))}`);if(this.bs&&!this.parent){let e=Ut.indices(this.bs,this.data.length,!0);if(e.length){let r=Ut.range(e).map(({pos:n,length:i})=>`(${n}/${i})[${Ae.encode(this.data.subarray(n,n+i))}]`).join(", ");throw this.err(`unread byte ranges: ${r} (total=${this.data.length})`)}else return}if(!this.isEnd())throw this.err(`${this.leftBytes} bytes ${this.bitPos} bits left after unpack: ${Ae.encode(this.data.slice(this.pos))}`)}}err(e){return Bi.err("Reader",this.stack,e)}offsetReader(e){if(e>this.data.length)throw this.err("offsetReader: Unexpected end of buffer");return new t(this.absBytes(e),this.opts,this.stack,this,e)}bytes(e,r=!1){if(this.bitPos)throw this.err("readBytes: bitPos not empty");if(!Number.isFinite(e))throw this.err(`readBytes: wrong length=${e}`);if(this.pos+e>this.data.length)throw this.err("readBytes: Unexpected end of buffer");let n=this.data.subarray(this.pos,this.pos+e);return r||this.markBytes(e),n}byte(e=!1){if(this.bitPos)throw this.err("readByte: bitPos not empty");if(this.pos+1>this.data.length)throw this.err("readBytes: Unexpected end of buffer");let r=this.data[this.pos];return e||this.markBytes(1),r}get leftBytes(){return this.data.length-this.pos}get totalBytes(){return this.data.length}isEnd(){return this.pos>=this.data.length&&!this.bitPos}bits(e){if(e>32)throw this.err("BitReader: cannot read more than 32 bits in single call");let r=0;for(;e;){this.bitPos||(this.bitBuf=this.byte(),this.bitPos=8);let n=Math.min(e,this.bitPos);this.bitPos-=n,r=r<<n|this.bitBuf>>this.bitPos&2**n-1,this.bitBuf&=2**this.bitPos-1,e-=n}return r>>>0}find(e,r=this.pos){if(!Gr(e))throw this.err(`find: needle is not bytes! ${e}`);if(this.bitPos)throw this.err("findByte: bitPos not empty");if(!e.length)throw this.err("find: needle is empty");for(let n=r;(n=this.data.indexOf(e[0],n))!==-1;n++){if(n===-1||this.data.length-n<e.length)return;if(Vc(e,this.data.subarray(n,n+e.length)))return n}}},Vy=class{constructor(e=[]){this.pos=0,this.buffers=[],this.ptrs=[],this.bitBuf=0,this.bitPos=0,this.viewBuf=new Uint8Array(8),this.finished=!1,this.stack=e,this.view=jy(this.viewBuf)}pushObj(e,r){return Bi.pushObj(this.stack,e,r)}writeView(e,r){if(this.finished)throw this.err("buffer: finished");if(!qn(e)||e>8)throw new Error(`wrong writeView length=${e}`);r(this.view),this.bytes(this.viewBuf.slice(0,e)),this.viewBuf.fill(0)}err(e){if(this.finished)throw this.err("buffer: finished");return Bi.err("Reader",this.stack,e)}bytes(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeBytes: ends with non-empty bit buffer");this.buffers.push(e),this.pos+=e.length}byte(e){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("writeByte: ends with non-empty bit buffer");this.buffers.push(new Uint8Array([e])),this.pos++}finish(e=!0){if(this.finished)throw this.err("buffer: finished");if(this.bitPos)throw this.err("buffer: ends with non-empty bit buffer");let r=this.buffers.concat(this.ptrs.map(o=>o.buffer)),n=r.map(o=>o.length).reduce((o,s)=>o+s,0),i=new Uint8Array(n);for(let o=0,s=0;o<r.length;o++){let c=r[o];i.set(c,s),s+=c.length}for(let o=this.pos,s=0;s<this.ptrs.length;s++){let c=this.ptrs[s];i.set(c.ptr.encode(o),c.pos),o+=c.buffer.length}if(e){this.buffers=[];for(let o of this.ptrs)o.buffer.fill(0);this.ptrs=[],this.finished=!0,this.bitBuf=0}return i}bits(e,r){if(r>32)throw this.err("writeBits: cannot write more than 32 bits in single call");if(e>=2**r)throw this.err(`writeBits: value (${e}) >= 2**bits (${r})`);for(;r;){let n=Math.min(r,8-this.bitPos);this.bitBuf=this.bitBuf<<n|e>>r-n,this.bitPos+=n,r-=n,e&=2**r-1,this.bitPos===8&&(this.bitPos=0,this.buffers.push(new Uint8Array([this.bitBuf])),this.pos++)}}},qy=t=>Uint8Array.from(t).reverse();function vE(t,e,r){if(r){let n=2n**(e-1n);if(t<-n||t>=n)throw new Error(`value out of signed bounds. Expected ${-n} <= ${t} < ${n}`)}else if(0n>t||t>=2n**e)throw new Error(`value out of unsigned bounds. Expected 0 <= ${t} < ${2n**e}`)}function SE(t){return{encodeStream:t.encodeStream,decodeStream:t.decodeStream,size:t.size,encode:e=>{let r=new Vy;return t.encodeStream(r,e),r.finish()},decode:(e,r={})=>{let n=new Hy(e,r),i=t.decodeStream(n);return n.finish(),i}}}function Ft(t,e){if(!Rr(t))throw new Error(`validate: invalid inner value ${t}`);if(typeof e!="function")throw new Error("validate: fn should be function");return SE({size:t.size,encodeStream:(r,n)=>{let i;try{i=e(n)}catch(o){throw r.err(o)}t.encodeStream(r,i)},decodeStream:r=>{let n=t.decodeStream(r);try{return e(n)}catch(i){throw r.err(i)}}})}var jt=t=>{let e=SE(t);return t.validate?Ft(e,t.validate):e},Jf=t=>qc(t)&&typeof t.decode=="function"&&typeof t.encode=="function";function Rr(t){return qc(t)&&Jf(t)&&typeof t.encodeStream=="function"&&typeof t.decodeStream=="function"&&(t.size===void 0||qn(t.size))}function T8(){return{encode:t=>{if(!Array.isArray(t))throw new Error("array expected");let e={};for(let r of t){if(!Array.isArray(r)||r.length!==2)throw new Error("array of two elements expected");let n=r[0],i=r[1];if(e[n]!==void 0)throw new Error(`key(${n}) appears twice in struct`);e[n]=i}return e},decode:t=>{if(!qc(t))throw new Error(`expected plain object, got ${t}`);return Object.entries(t)}}}var _8={encode:t=>{if(typeof t!="bigint")throw new Error(`expected bigint, got ${typeof t}`);if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error(`element bigger than MAX_SAFE_INTEGER=${t}`);return Number(t)},decode:t=>{if(!qn(t))throw new Error("element is not a safe integer");return BigInt(t)}};function B8(t){if(!qc(t))throw new Error("plain object expected");return{encode:e=>{if(!qn(e)||!(e in t))throw new Error(`wrong value ${e}`);return t[e]},decode:e=>{if(typeof e!="string")throw new Error(`wrong value ${typeof e}`);return t[e]}}}function I8(t,e=!1){if(!qn(t))throw new Error(`decimal/precision: wrong value ${t}`);if(typeof e!="boolean")throw new Error(`decimal/round: expected boolean, got ${typeof e}`);let r=10n**BigInt(t);return{encode:n=>{if(typeof n!="bigint")throw new Error(`expected bigint, got ${typeof n}`);let i=(n<0n?-n:n).toString(10),o=i.length-t;o<0&&(i=i.padStart(i.length-o,"0"),o=0);let s=i.length-1;for(;s>=o&&i[s]==="0";s--);let c=i.slice(0,o),a=i.slice(o,s+1);return c||(c="0"),n<0n&&(c="-"+c),a?`${c}.${a}`:c},decode:n=>{if(typeof n!="string")throw new Error(`expected string, got ${typeof n}`);if(n==="-0")throw new Error("negative zero is not allowed");let i=!1;if(n.startsWith("-")&&(i=!0,n=n.slice(1)),!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))throw new Error(`wrong string value=${n}`);let o=n.indexOf(".");o=o===-1?n.length:o;let s=n.slice(0,o),c=n.slice(o+1).replace(/0+$/,""),a=BigInt(s)*r;if(!e&&c.length>t)throw new Error(`fractional part cannot be represented with this precision (num=${n}, prec=${t})`);let u=Math.min(c.length,t),d=BigInt(c.slice(0,u))*10n**BigInt(t-u),f=a+d;return i?-f:f}}}function R8(t){if(!Array.isArray(t))throw new Error(`expected array, got ${typeof t}`);for(let e of t)if(!Jf(e))throw new Error(`wrong base coder ${e}`);return{encode:e=>{for(let r of t){let n=r.encode(e);if(n!==void 0)return n}throw new Error(`match/encode: cannot find match in ${e}`)},decode:e=>{for(let r of t){let n=r.decode(e);if(n!==void 0)return n}throw new Error(`match/decode: cannot find match in ${e}`)}}}var AE=t=>{if(!Jf(t))throw new Error("BaseCoder expected");return{encode:t.decode,decode:t.encode}},Ii={dict:T8,numberBigint:_8,tsEnum:B8,decimal:I8,match:R8,reverse:AE};var Wy=(t,e=!1,r=!1,n=!0)=>{if(!qn(t))throw new Error(`bigint/size: wrong value ${t}`);if(typeof e!="boolean")throw new Error(`bigint/le: expected boolean, got ${typeof e}`);if(typeof r!="boolean")throw new Error(`bigint/signed: expected boolean, got ${typeof r}`);if(typeof n!="boolean")throw new Error(`bigint/sized: expected boolean, got ${typeof n}`);let i=BigInt(t),o=2n**(8n*i-1n);return jt({size:n?t:void 0,encodeStream:(s,c)=>{r&&c<0&&(c=c|o);let a=[];for(let d=0;d<t;d++)a.push(Number(c&255n)),c>>=8n;let u=new Uint8Array(a).reverse();if(!n){let d=0;for(d=0;d<u.length&&u[d]===0;d++);u=u.subarray(d)}s.bytes(e?u.reverse():u)},decodeStream:s=>{let c=s.bytes(n?t:Math.min(t,s.leftBytes)),a=e?c:qy(c),u=0n;for(let d=0;d<a.length;d++)u|=BigInt(a[d])<<8n*BigInt(d);return r&&u&o&&(u=(u^o)-o),u},validate:s=>{if(typeof s!="bigint")throw new Error(`bigint: invalid value: ${s}`);return vE(s,8n*i,!!r),s}})};var TE=Wy(32,!1);var Fc=Wy(8,!0);var _E=Wy(8,!0,!0);var U8=(t,e)=>jt({size:t,encodeStream:(r,n)=>r.writeView(t,i=>e.write(i,n)),decodeStream:r=>r.readView(t,e.read),validate:r=>{if(typeof r!="number")throw new Error(`viewCoder: expected number, got ${typeof r}`);return e.validate&&e.validate(r),r}}),Uu=(t,e,r)=>{let n=t*8,i=2**(n-1),o=a=>{if(!qn(a))throw new Error(`sintView: value is not safe integer: ${a}`);if(a<-i||a>=i)throw new Error(`sintView: value out of bounds. Expected ${-i} <= ${a} < ${i}`)},s=2**n,c=a=>{if(!qn(a))throw new Error(`uintView: value is not safe integer: ${a}`);if(0>a||a>=s)throw new Error(`uintView: value out of bounds. Expected 0 <= ${a} < ${s}`)};return U8(t,{write:r.write,read:r.read,validate:e?o:c})},Te=Uu(4,!1,{read:(t,e)=>t.getUint32(e,!0),write:(t,e)=>t.setUint32(0,e,!0)}),BE=Uu(4,!1,{read:(t,e)=>t.getUint32(e,!1),write:(t,e)=>t.setUint32(0,e,!1)}),bo=Uu(4,!0,{read:(t,e)=>t.getInt32(e,!0),write:(t,e)=>t.setInt32(0,e,!0)});var Gy=Uu(2,!1,{read:(t,e)=>t.getUint16(e,!0),write:(t,e)=>t.setUint16(0,e,!0)});var mn=Uu(1,!1,{read:(t,e)=>t.getUint8(e),write:(t,e)=>t.setUint8(0,e)});var He=(t,e=!1)=>{if(typeof e!="boolean")throw new Error(`bytes/le: expected boolean, got ${typeof e}`);let r=EE(t),n=Gr(t);return jt({size:typeof t=="number"?t:void 0,encodeStream:(i,o)=>{n||r.encodeStream(i,o.length),i.bytes(e?qy(o):o),n&&i.bytes(t)},decodeStream:i=>{let o;if(n){let s=i.find(t);if(!s)throw i.err("bytes: cannot find terminator");o=i.bytes(s-i.pos),i.bytes(t.length)}else o=i.bytes(t===null?i.leftBytes:r.decodeStream(i));return e?qy(o):o},validate:i=>{if(!Gr(i))throw new Error(`bytes: invalid value ${i}`);return i}})};function IE(t,e){if(!Rr(e))throw new Error(`prefix: invalid inner value ${e}`);return gn(He(t),AE(e))}var Zf=(t,e=!1)=>Ft(gn(He(t,e),xE),r=>{if(typeof r!="string")throw new Error(`expected string, got ${typeof r}`);return r});var RE=(t,e={isLE:!1,with0x:!1})=>{let r=gn(He(t,e.isLE),Ae),n=e.with0x;if(typeof n!="boolean")throw new Error(`hex/with0x: expected boolean, got ${typeof n}`);return n&&(r=gn(r,{encode:i=>`0x${i}`,decode:i=>{if(!i.startsWith("0x"))throw new Error("hex(with0x=true).encode input should start with 0x");return i.slice(2)}})),r};function gn(t,e){if(!Rr(t))throw new Error(`apply: invalid inner value ${t}`);if(!Jf(e))throw new Error(`apply: invalid base value ${t}`);return jt({size:t.size,encodeStream:(r,n)=>{let i;try{i=e.decode(n)}catch(o){throw r.err(""+o)}return t.encodeStream(r,i)},decodeStream:r=>{let n=t.decodeStream(r);try{return e.encode(n)}catch(i){throw r.err(""+i)}}})}var UE=(t,e=!1)=>{if(!Gr(t))throw new Error(`flag/flagValue: expected Uint8Array, got ${typeof t}`);if(typeof e!="boolean")throw new Error(`flag/xor: expected boolean, got ${typeof e}`);return jt({size:t.length,encodeStream:(r,n)=>{!!n!==e&&r.bytes(t)},decodeStream:r=>{let n=r.leftBytes>=t.length;return n&&(n=Vc(r.bytes(t.length,!0),t),n&&r.bytes(t.length)),n!==e},validate:r=>{if(r!==void 0&&typeof r!="boolean")throw new Error(`flag: expected boolean value or undefined, got ${typeof r}`);return r}})};function OE(t,e,r){if(!Rr(e))throw new Error(`flagged: invalid inner value ${e}`);if(typeof t!="string"&&!Rr(e))throw new Error(`flagged: wrong path=${t}`);return jt({encodeStream:(n,i)=>{typeof t=="string"?Bi.resolve(n.stack,t)?e.encodeStream(n,i):r&&e.encodeStream(n,r):(t.encodeStream(n,!!i),i?e.encodeStream(n,i):r&&e.encodeStream(n,r))},decodeStream:n=>{let i=!1;if(typeof t=="string"?i=!!Bi.resolve(n.stack,t):i=t.decodeStream(n),i)return e.decodeStream(n);r&&e.decodeStream(n)}})}function Xf(t,e,r=!0){if(!Rr(t))throw new Error(`magic: invalid inner value ${t}`);if(typeof r!="boolean")throw new Error(`magic: expected boolean, got ${typeof r}`);return jt({size:t.size,encodeStream:(n,i)=>t.encodeStream(n,e),decodeStream:n=>{let i=t.decodeStream(n);if(r&&typeof i!="object"&&i!==e||Gr(e)&&!Vc(e,i))throw n.err(`magic: invalid value: ${i} !== ${e}`)},validate:n=>{if(n!==void 0)throw new Error(`magic: wrong value=${typeof n}`);return n}})}function DE(t){let e=0;for(let r of t){if(r.size===void 0)return;if(!qn(r.size))throw new Error(`sizeof: wrong element size=${e}`);e+=r.size}return e}function bt(t){if(!qc(t))throw new Error(`struct: expected plain object, got ${t}`);for(let e in t)if(!Rr(t[e]))throw new Error(`struct: field ${e} is not CoderType`);return jt({size:DE(Object.values(t)),encodeStream:(e,r)=>{e.pushObj(r,n=>{for(let i in t)n(i,()=>t[i].encodeStream(e,r[i]))})},decodeStream:e=>{let r={};return e.pushObj(r,n=>{for(let i in t)n(i,()=>r[i]=t[i].decodeStream(e))}),r},validate:e=>{if(typeof e!="object"||e===null)throw new Error(`struct: invalid value ${e}`);return e}})}function kE(t){if(!Array.isArray(t))throw new Error(`Packed.Tuple: got ${typeof t} instead of array`);for(let e=0;e<t.length;e++)if(!Rr(t[e]))throw new Error(`tuple: field ${e} is not CoderType`);return jt({size:DE(t),encodeStream:(e,r)=>{if(!Array.isArray(r))throw e.err(`tuple: invalid value ${r}`);e.pushObj(r,n=>{for(let i=0;i<t.length;i++)n(`${i}`,()=>t[i].encodeStream(e,r[i]))})},decodeStream:e=>{let r=[];return e.pushObj(r,n=>{for(let i=0;i<t.length;i++)n(`${i}`,()=>r.push(t[i].decodeStream(e)))}),r},validate:e=>{if(!Array.isArray(e))throw new Error(`tuple: invalid value ${e}`);if(e.length!==t.length)throw new Error(`tuple: wrong length=${e.length}, expected ${t.length}`);return e}})}function Wt(t,e){if(!Rr(e))throw new Error(`array: invalid inner value ${e}`);let r=EE(typeof t=="string"?`../${t}`:t);return jt({size:typeof t=="number"&&e.size?t*e.size:void 0,encodeStream:(n,i)=>{let o=n;o.pushObj(i,s=>{Gr(t)||r.encodeStream(n,i.length);for(let c=0;c<i.length;c++)s(`${c}`,()=>{let a=i[c],u=n.pos;if(e.encodeStream(n,a),Gr(t)){if(t.length>o.pos-u)return;let d=o.finish(!1).subarray(u,o.pos);if(Vc(d.subarray(0,t.length),t))throw o.err(`array: inner element encoding same as separator. elm=${a} data=${d}`)}})}),Gr(t)&&n.bytes(t)},decodeStream:n=>{let i=[];return n.pushObj(i,o=>{if(t===null)for(let s=0;!n.isEnd()&&(o(`${s}`,()=>i.push(e.decodeStream(n))),!(e.size&&n.leftBytes<e.size));s++);else if(Gr(t))for(let s=0;;s++){if(Vc(n.bytes(t.length,!0),t)){n.bytes(t.length);break}o(`${s}`,()=>i.push(e.decodeStream(n)))}else{let s;o("arrayLen",()=>s=r.decodeStream(n));for(let c=0;c<s;c++)o(`${c}`,()=>i.push(e.decodeStream(n)))}}),i},validate:n=>{if(!Array.isArray(n))throw new Error(`array: invalid value ${n}`);return n}})}var tl=wo.ProjectivePoint,el=wo.CURVE.n,ke=Yf.isBytes,Fn=Yf.concatBytes,st=Yf.equalBytes;var jc=t=>dE(Oe(t)),Ri=(...t)=>Oe(Oe(Fn(...t))),YP=Ir.utils.randomPrivateKey,rl=Ir.getPublicKey,zy=wo.getPublicKey,NE=t=>t.r<el/2n;function CE(t,e,r=!1){let n=wo.sign(t,e);if(r&&!NE(n)){let i=new Uint8Array(32),o=0;for(;!NE(n);)if(i.set(Te.encode(o++)),n=wo.sign(t,e,{extraEntropy:i}),o>4294967295)throw new Error("lowR counter overflow: report the error")}return n.toDERRawBytes()}var Yy=Ir.sign,Ou=Ir.utils.taggedHash,xt;(function(t){t[t.ecdsa=0]="ecdsa",t[t.schnorr=1]="schnorr"})(xt||(xt={}));function xo(t,e){let r=t.length;if(e===xt.ecdsa){if(r===32)throw new Error("Expected non-Schnorr key");return tl.fromHex(t),t}else if(e===xt.schnorr){if(r!==32)throw new Error("Expected 32-byte Schnorr key");return Ir.utils.lift_x(Ir.utils.bytesToNumberBE(t)),t}else throw new Error("Unknown key type")}function LE(t,e){let r=Ir.utils,n=r.taggedHash("TapTweak",t,e),i=r.bytesToNumberBE(n);if(i>=el)throw new Error("tweak higher than curve order");return i}function PE(t,e=Uint8Array.of()){let r=Ir.utils,n=r.bytesToNumberBE(t),i=tl.fromPrivateKey(n),o=i.hasEvenY()?n:r.mod(-n,el),s=r.pointToBytes(i),c=LE(s,e);return r.numberToBytesBE(r.mod(o+c,el),32)}function Du(t,e){let r=Ir.utils,n=LE(t,e),o=r.lift_x(r.bytesToNumberBE(t)).add(tl.fromPrivateKey(n)),s=o.hasEvenY()?0:1;return[r.pointToBytes(o),s]}var nl=Oe(tl.BASE.toRawBytes(!1)),zr={bech32:"bc",pubKeyHash:0,scriptHash:5,wif:128},Jy={bech32:"tb",pubKeyHash:111,scriptHash:196,wif:239};function ku(t,e){if(!ke(t)||!ke(e))throw new Error(`cmp: wrong type a=${typeof t} b=${typeof e}`);let r=Math.min(t.length,e.length);for(let n=0;n<r;n++)if(t[n]!=e[n])return Math.sign(t[n]-e[n]);return Math.sign(t.length-e.length)}l();l();l();var gt;(function(t){t[t.OP_0=0]="OP_0",t[t.PUSHDATA1=76]="PUSHDATA1",t[t.PUSHDATA2=77]="PUSHDATA2",t[t.PUSHDATA4=78]="PUSHDATA4",t[t["1NEGATE"]=79]="1NEGATE",t[t.RESERVED=80]="RESERVED",t[t.OP_1=81]="OP_1",t[t.OP_2=82]="OP_2",t[t.OP_3=83]="OP_3",t[t.OP_4=84]="OP_4",t[t.OP_5=85]="OP_5",t[t.OP_6=86]="OP_6",t[t.OP_7=87]="OP_7",t[t.OP_8=88]="OP_8",t[t.OP_9=89]="OP_9",t[t.OP_10=90]="OP_10",t[t.OP_11=91]="OP_11",t[t.OP_12=92]="OP_12",t[t.OP_13=93]="OP_13",t[t.OP_14=94]="OP_14",t[t.OP_15=95]="OP_15",t[t.OP_16=96]="OP_16",t[t.NOP=97]="NOP",t[t.VER=98]="VER",t[t.IF=99]="IF",t[t.NOTIF=100]="NOTIF",t[t.VERIF=101]="VERIF",t[t.VERNOTIF=102]="VERNOTIF",t[t.ELSE=103]="ELSE",t[t.ENDIF=104]="ENDIF",t[t.VERIFY=105]="VERIFY",t[t.RETURN=106]="RETURN",t[t.TOALTSTACK=107]="TOALTSTACK",t[t.FROMALTSTACK=108]="FROMALTSTACK",t[t["2DROP"]=109]="2DROP",t[t["2DUP"]=110]="2DUP",t[t["3DUP"]=111]="3DUP",t[t["2OVER"]=112]="2OVER",t[t["2ROT"]=113]="2ROT",t[t["2SWAP"]=114]="2SWAP",t[t.IFDUP=115]="IFDUP",t[t.DEPTH=116]="DEPTH",t[t.DROP=117]="DROP",t[t.DUP=118]="DUP",t[t.NIP=119]="NIP",t[t.OVER=120]="OVER",t[t.PICK=121]="PICK",t[t.ROLL=122]="ROLL",t[t.ROT=123]="ROT",t[t.SWAP=124]="SWAP",t[t.TUCK=125]="TUCK",t[t.CAT=126]="CAT",t[t.SUBSTR=127]="SUBSTR",t[t.LEFT=128]="LEFT",t[t.RIGHT=129]="RIGHT",t[t.SIZE=130]="SIZE",t[t.INVERT=131]="INVERT",t[t.AND=132]="AND",t[t.OR=133]="OR",t[t.XOR=134]="XOR",t[t.EQUAL=135]="EQUAL",t[t.EQUALVERIFY=136]="EQUALVERIFY",t[t.RESERVED1=137]="RESERVED1",t[t.RESERVED2=138]="RESERVED2",t[t["1ADD"]=139]="1ADD",t[t["1SUB"]=140]="1SUB",t[t["2MUL"]=141]="2MUL",t[t["2DIV"]=142]="2DIV",t[t.NEGATE=143]="NEGATE",t[t.ABS=144]="ABS",t[t.NOT=145]="NOT",t[t["0NOTEQUAL"]=146]="0NOTEQUAL",t[t.ADD=147]="ADD",t[t.SUB=148]="SUB",t[t.MUL=149]="MUL",t[t.DIV=150]="DIV",t[t.MOD=151]="MOD",t[t.LSHIFT=152]="LSHIFT",t[t.RSHIFT=153]="RSHIFT",t[t.BOOLAND=154]="BOOLAND",t[t.BOOLOR=155]="BOOLOR",t[t.NUMEQUAL=156]="NUMEQUAL",t[t.NUMEQUALVERIFY=157]="NUMEQUALVERIFY",t[t.NUMNOTEQUAL=158]="NUMNOTEQUAL",t[t.LESSTHAN=159]="LESSTHAN",t[t.GREATERTHAN=160]="GREATERTHAN",t[t.LESSTHANOREQUAL=161]="LESSTHANOREQUAL",t[t.GREATERTHANOREQUAL=162]="GREATERTHANOREQUAL",t[t.MIN=163]="MIN",t[t.MAX=164]="MAX",t[t.WITHIN=165]="WITHIN",t[t.RIPEMD160=166]="RIPEMD160",t[t.SHA1=167]="SHA1",t[t.SHA256=168]="SHA256",t[t.HASH160=169]="HASH160",t[t.HASH256=170]="HASH256",t[t.CODESEPARATOR=171]="CODESEPARATOR",t[t.CHECKSIG=172]="CHECKSIG",t[t.CHECKSIGVERIFY=173]="CHECKSIGVERIFY",t[t.CHECKMULTISIG=174]="CHECKMULTISIG",t[t.CHECKMULTISIGVERIFY=175]="CHECKMULTISIGVERIFY",t[t.NOP1=176]="NOP1",t[t.CHECKLOCKTIMEVERIFY=177]="CHECKLOCKTIMEVERIFY",t[t.CHECKSEQUENCEVERIFY=178]="CHECKSEQUENCEVERIFY",t[t.NOP4=179]="NOP4",t[t.NOP5=180]="NOP5",t[t.NOP6=181]="NOP6",t[t.NOP7=182]="NOP7",t[t.NOP8=183]="NOP8",t[t.NOP9=184]="NOP9",t[t.NOP10=185]="NOP10",t[t.CHECKSIGADD=186]="CHECKSIGADD",t[t.INVALID=255]="INVALID"})(gt||(gt={}));function Zy(t=6,e=!1){return jt({encodeStream:(r,n)=>{if(n===0n)return;let i=n<0,o=BigInt(n),s=[];for(let c=i?-o:o;c;c>>=8n)s.push(Number(c&0xffn));s[s.length-1]>=128?s.push(i?128:0):i&&(s[s.length-1]|=128),r.bytes(new Uint8Array(s))},decodeStream:r=>{let n=r.leftBytes;if(n>t)throw new Error(`ScriptNum: number (${n}) bigger than limit=${t}`);if(n===0)return 0n;if(e){let s=r.bytes(n,!0);if(!(s[s.length-1]&127)&&(n<=1||!(s[s.length-2]&128)))throw new Error("Non-minimally encoded ScriptNum")}let i=0,o=0n;for(let s=0;s<n;++s)i=r.byte(),o|=BigInt(i)<<8n*BigInt(s);return i>=128&&(o&=2n**BigInt(n*8)-1n>>1n,o=-o),o}})}function $E(t,e=4,r=!0){if(typeof t=="number")return t;if(ke(t))try{let n=Zy(e,r).decode(t);return n>Number.MAX_SAFE_INTEGER?void 0:Number(n)}catch{return}}var Ye=jt({encodeStream:(t,e)=>{for(let r of e){if(typeof r=="string"){if(gt[r]===void 0)throw new Error(`Unknown opcode=${r}`);t.byte(gt[r]);continue}else if(typeof r=="number"){if(r===0){t.byte(0);continue}else if(1<=r&&r<=16){t.byte(gt.OP_1-1+r);continue}}if(typeof r=="number"&&(r=Zy().encode(BigInt(r))),!ke(r))throw new Error(`Wrong Script OP=${r} (${typeof r})`);let n=r.length;n<gt.PUSHDATA1?t.byte(n):n<=255?(t.byte(gt.PUSHDATA1),t.byte(n)):n<=65535?(t.byte(gt.PUSHDATA2),t.bytes(Gy.encode(n))):(t.byte(gt.PUSHDATA4),t.bytes(Te.encode(n))),t.bytes(r)}},decodeStream:t=>{let e=[];for(;!t.isEnd();){let r=t.byte();if(gt.OP_0<r&&r<=gt.PUSHDATA4){let n;if(r<gt.PUSHDATA1)n=r;else if(r===gt.PUSHDATA1)n=mn.decodeStream(t);else if(r===gt.PUSHDATA2)n=Gy.decodeStream(t);else if(r===gt.PUSHDATA4)n=Te.decodeStream(t);else throw new Error("Should be not possible");e.push(t.bytes(n))}else if(r===0)e.push(0);else if(gt.OP_1<=r&&r<=gt.OP_16)e.push(r-(gt.OP_1-1));else{let n=gt[r];if(n===void 0)throw new Error(`Unknown opcode=${r.toString(16)}`);e.push(n)}}return e}}),KE={253:[253,2,253n,65535n],254:[254,4,65536n,4294967295n],255:[255,8,4294967296n,18446744073709551615n]},Wc=jt({encodeStream:(t,e)=>{if(typeof e=="number"&&(e=BigInt(e)),0n<=e&&e<=252n)return t.byte(Number(e));for(let[r,n,i,o]of Object.values(KE))if(!(i>e||e>o)){t.byte(r);for(let s=0;s<n;s++)t.byte(Number(e>>8n*BigInt(s)&0xffn));return}throw t.err(`VarInt too big: ${e}`)},decodeStream:t=>{let e=t.byte();if(e<=252)return BigInt(e);let[r,n,i]=KE[e],o=0n;for(let s=0;s<n;s++)o|=BigInt(t.byte())<<8n*BigInt(s);if(o<i)throw t.err(`Wrong CompactSize(${8*n})`);return o}}),Ur=gn(Wc,Ii.numberBigint),dr=He(Wc),Gc=Wt(Ur,dr),il=t=>Wt(Wc,t),HE=bt({txid:He(32,!0),index:Te,finalScriptSig:dr,sequence:Te}),Ui=bt({amount:Fc,script:dr}),O8=bt({version:bo,segwitFlag:UE(new Uint8Array([0,1])),inputs:il(HE),outputs:il(Ui),witnesses:OE("segwitFlag",Wt("inputs/length",Gc)),lockTime:Te});function D8(t){if(t.segwitFlag&&t.witnesses&&!t.witnesses.length)throw new Error("Segwit flag with empty witnesses array");return t}var Oi=Ft(O8,D8),Es=bt({version:bo,inputs:il(HE),outputs:il(Ui),lockTime:Te});var Qy=Ft(He(null),t=>xo(t,xt.ecdsa)),ol=Ft(He(32),t=>xo(t,xt.schnorr)),VE=Ft(He(null),t=>{if(t.length!==64&&t.length!==65)throw new Error("Schnorr signature should be 64 or 65 bytes long");return t}),sl=bt({fingerprint:BE,path:Wt(null,Te)}),jE=bt({hashes:Wt(Ur,He(32)),der:sl}),k8=He(78),N8=bt({pubKey:ol,leafHash:He(32)}),C8=bt({version:mn,internalKey:He(32),merklePath:Wt(null,He(32))}),Di=Ft(C8,t=>{if(t.merklePath.length>128)throw new Error("TaprootControlBlock: merklePath should be of length 0..128 (inclusive)");return t}),L8=Wt(null,bt({depth:mn,version:mn,script:dr})),Et=He(null),qE=He(20),Nu=He(32),cl={unsignedTx:[0,!1,Es,[0],[0],!1],xpub:[1,k8,sl,[],[0,2],!1],txVersion:[2,!1,Te,[2],[2],!1],fallbackLocktime:[3,!1,Te,[],[2],!1],inputCount:[4,!1,Ur,[2],[2],!1],outputCount:[5,!1,Ur,[2],[2],!1],txModifiable:[6,!1,mn,[],[2],!1],version:[251,!1,Te,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},Cu={nonWitnessUtxo:[0,!1,Oi,[],[0,2],!1],witnessUtxo:[1,!1,Ui,[],[0,2],!1],partialSig:[2,Qy,Et,[],[0,2],!1],sighashType:[3,!1,Te,[],[0,2],!1],redeemScript:[4,!1,Et,[],[0,2],!1],witnessScript:[5,!1,Et,[],[0,2],!1],bip32Derivation:[6,Qy,sl,[],[0,2],!1],finalScriptSig:[7,!1,Et,[],[0,2],!1],finalScriptWitness:[8,!1,Gc,[],[0,2],!1],porCommitment:[9,!1,Et,[],[0,2],!1],ripemd160:[10,qE,Et,[],[0,2],!1],sha256:[11,Nu,Et,[],[0,2],!1],hash160:[12,qE,Et,[],[0,2],!1],hash256:[13,Nu,Et,[],[0,2],!1],txid:[14,!1,Nu,[2],[2],!0],index:[15,!1,Te,[2],[2],!0],sequence:[16,!1,Te,[],[2],!0],requiredTimeLocktime:[17,!1,Te,[],[2],!1],requiredHeightLocktime:[18,!1,Te,[],[2],!1],tapKeySig:[19,!1,VE,[],[0,2],!1],tapScriptSig:[20,N8,VE,[],[0,2],!1],tapLeafScript:[21,Di,Et,[],[0,2],!1],tapBip32Derivation:[22,Nu,jE,[],[0,2],!1],tapInternalKey:[23,!1,ol,[],[0,2],!1],tapMerkleRoot:[24,!1,Nu,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},WE=["txid","sequence","index","witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknown"],GE=["partialSig","finalScriptSig","finalScriptWitness","tapKeySig","tapScriptSig"],Lu={redeemScript:[0,!1,Et,[],[0,2],!1],witnessScript:[1,!1,Et,[],[0,2],!1],bip32Derivation:[2,Qy,sl,[],[0,2],!1],amount:[3,!1,_E,[2],[2],!0],script:[4,!1,Et,[2],[2],!0],tapInternalKey:[5,!1,ol,[],[0,2],!1],tapTree:[6,!1,L8,[],[0,2],!1],tapBip32Derivation:[7,ol,jE,[],[0,2],!1],proprietary:[252,Et,Et,[],[0,2],!1]},zE=[],FE=Wt(Fy,bt({key:IE(Ur,bt({type:Ur,key:He(null)})),value:He(Ur)}));function e0(t){let[e,r,n,i,o,s]=t;return{type:e,kc:r,vc:n,reqInc:i,allowInc:o,silentIgnore:s}}var nM=bt({type:Ur,key:He(null)});function t0(t){let e={};for(let r in t){let[n,i,o]=t[r];e[n]=[r,i,o]}return jt({encodeStream:(r,n)=>{let i=[];for(let o in t){let s=n[o];if(s===void 0)continue;let[c,a,u]=t[o];if(!a)i.push({key:{type:c,key:$e},value:u.encode(s)});else{let d=s.map(([f,h])=>[a.encode(f),u.encode(h)]);d.sort((f,h)=>ku(f[0],h[0]));for(let[f,h]of d)i.push({key:{key:f,type:c},value:h})}}if(n.unknown){n.unknown.sort((o,s)=>ku(o[0].key,s[0].key));for(let[o,s]of n.unknown)i.push({key:o,value:s})}FE.encodeStream(r,i)},decodeStream:r=>{let n=FE.decodeStream(r),i={},o={};for(let s of n){let c="unknown",a=s.key.key,u=s.value;if(e[s.key.type]){let[d,f,h]=e[s.key.type];if(c=d,!f&&a.length)throw new Error(`PSBT: Non-empty key for ${c} (key=${Ae.encode(a)} value=${Ae.encode(u)}`);if(a=f?f.decode(a):void 0,u=h.decode(u),!f){if(i[c])throw new Error(`PSBT: Same keys: ${c} (key=${a} value=${u})`);i[c]=u,o[c]=!0;continue}}else a={type:s.key.type,key:s.key.key};if(o[c])throw new Error(`PSBT: Key type with empty key and no key=${c} val=${u}`);i[c]||(i[c]=[]),i[c].push([a,u])}return i}})}var al=Ft(t0(Cu),t=>{if(t.finalScriptWitness&&!t.finalScriptWitness.length)throw new Error("validateInput: empty finalScriptWitness");if(t.partialSig&&!t.partialSig.length)throw new Error("Empty partialSig");if(t.partialSig)for(let[e]of t.partialSig)xo(e,xt.ecdsa);if(t.bip32Derivation)for(let[e]of t.bip32Derivation)xo(e,xt.ecdsa);if(t.requiredTimeLocktime!==void 0&&t.requiredTimeLocktime<5e8)throw new Error(`validateInput: wrong timeLocktime=${t.requiredTimeLocktime}`);if(t.requiredHeightLocktime!==void 0&&(t.requiredHeightLocktime<=0||t.requiredHeightLocktime>=5e8))throw new Error(`validateInput: wrong heighLocktime=${t.requiredHeightLocktime}`);if(t.tapLeafScript)for(let[e,r]of t.tapLeafScript){if((e.version&254)!==r[r.length-1])throw new Error("validateInput: tapLeafScript version mimatch");if(r[r.length-1]&1)throw new Error("validateInput: tapLeafScript version has parity bit!")}return t}),ul=Ft(t0(Lu),t=>{if(t.bip32Derivation)for(let[e]of t.bip32Derivation)xo(e,xt.ecdsa);return t}),YE=Ft(t0(cl),t=>{if((t.version||0)===0){if(!t.unsignedTx)throw new Error("PSBTv0: missing unsignedTx");for(let r of t.unsignedTx.inputs)if(r.finalScriptSig&&r.finalScriptSig.length)throw new Error("PSBTv0: input scriptSig found in unsignedTx")}return t}),P8=bt({magic:Xf(Zf(new Uint8Array([255])),"psbt"),global:YE,inputs:Wt("global/unsignedTx/inputs/length",al),outputs:Wt(null,ul)}),M8=bt({magic:Xf(Zf(new Uint8Array([255])),"psbt"),global:YE,inputs:Wt("global/inputCount",al),outputs:Wt("global/outputCount",ul)}),iM=bt({magic:Xf(Zf(new Uint8Array([255])),"psbt"),items:Wt(null,gn(Wt(Fy,kE([RE(Ur),He(Wc)])),Ii.dict()))});function Xy(t,e,r){for(let n in r){if(n==="unknown"||!e[n])continue;let{allowInc:i}=e0(e[n]);if(!i.includes(t))throw new Error(`PSBTv${t}: field ${n} is not allowed`)}for(let n in e){let{reqInc:i}=e0(e[n]);if(i.includes(t)&&r[n]===void 0)throw new Error(`PSBTv${t}: missing required field ${n}`)}}function r0(t,e,r){let n={};for(let i in r){let o=i;if(o!=="unknown"){if(!e[o])continue;let{allowInc:s,silentIgnore:c}=e0(e[o]);if(!s.includes(t)){if(c)continue;throw new Error(`Failed to serialize in PSBTv${t}: ${o} but versions allows inclusion=${s}`)}}n[o]=r[o]}return n}function JE(t){let e=t&&t.global&&t.global.version||0;Xy(e,cl,t.global);for(let s of t.inputs)Xy(e,Cu,s);for(let s of t.outputs)Xy(e,Lu,s);let r=e?t.global.inputCount:t.global.unsignedTx.inputs.length;if(t.inputs.length<r)throw new Error("Not enough inputs");let n=t.inputs.slice(r);if(n.length>1||n.length&&Object.keys(n[0]).length)throw new Error(`Unexpected inputs left in tx=${n}`);let i=e?t.global.outputCount:t.global.unsignedTx.outputs.length;if(t.outputs.length<i)throw new Error("Not outputs inputs");let o=t.outputs.slice(i);if(o.length>1||o.length&&Object.keys(o[0]).length)throw new Error(`Unexpected outputs left in tx=${o}`);return t}function dl(t,e,r,n,i){let o={...r,...e};for(let s in t){let c=s,[a,u,d]=t[c],f=n&&!n.includes(s);if(e[s]===void 0&&s in e){if(f)throw new Error(`Cannot remove signed field=${s}`);delete o[s]}else if(u){let h=r&&r[s]?r[s]:[],p=e[c];if(p){if(!Array.isArray(p))throw new Error(`keyMap(${s}): KV pairs should be [k, v][]`);p=p.map(E=>{if(E.length!==2)throw new Error(`keyMap(${s}): KV pairs should be [k, v][]`);return[typeof E[0]=="string"?u.decode(Ae.decode(E[0])):E[0],typeof E[1]=="string"?d.decode(Ae.decode(E[1])):E[1]]});let g={},y=(E,S,I)=>{if(g[E]===void 0){g[E]=[S,I];return}let A=Ae.encode(d.encode(g[E][1])),O=Ae.encode(d.encode(I));if(A!==O)throw new Error(`keyMap(${c}): same key=${E} oldVal=${A} newVal=${O}`)};for(let[E,S]of h){let I=Ae.encode(u.encode(E));y(I,E,S)}for(let[E,S]of p){let I=Ae.encode(u.encode(E));if(S===void 0){if(f)throw new Error(`Cannot remove signed field=${c}/${E}`);delete g[I]}else y(I,E,S)}o[c]=Object.values(g)}}else if(typeof o[s]=="string")o[s]=d.decode(Ae.decode(o[s]));else if(f&&s in e&&r&&r[s]!==void 0&&!st(d.encode(e[s]),d.encode(r[s])))throw new Error(`Cannot change signed field=${s}`)}for(let s in o)if(!t[s]){if(i&&s==="unknown")continue;delete o[s]}return o}var n0=Ft(P8,JE),i0=Ft(M8,JE);var $8={encode(t){if(!(t.length!==2||t[0]!==1||!ke(t[1])||Ae.encode(t[1])!=="4e73"))return{type:"p2a",script:Ye.encode(t)}},decode:t=>{if(t.type==="p2a")return[1,Ae.decode("4e73")]}};function Eo(t,e){try{return xo(t,e),!0}catch{return!1}}var H8={encode(t){if(!(t.length!==2||!ke(t[0])||!Eo(t[0],xt.ecdsa)||t[1]!=="CHECKSIG"))return{type:"pk",pubkey:t[0]}},decode:t=>t.type==="pk"?[t.pubkey,"CHECKSIG"]:void 0},V8={encode(t){if(!(t.length!==5||t[0]!=="DUP"||t[1]!=="HASH160"||!ke(t[2]))&&!(t[3]!=="EQUALVERIFY"||t[4]!=="CHECKSIG"))return{type:"pkh",hash:t[2]}},decode:t=>t.type==="pkh"?["DUP","HASH160",t.hash,"EQUALVERIFY","CHECKSIG"]:void 0},q8={encode(t){if(!(t.length!==3||t[0]!=="HASH160"||!ke(t[1])||t[2]!=="EQUAL"))return{type:"sh",hash:t[1]}},decode:t=>t.type==="sh"?["HASH160",t.hash,"EQUAL"]:void 0},F8={encode(t){if(!(t.length!==2||t[0]!==0||!ke(t[1]))&&t[1].length===32)return{type:"wsh",hash:t[1]}},decode:t=>t.type==="wsh"?[0,t.hash]:void 0},j8={encode(t){if(!(t.length!==2||t[0]!==0||!ke(t[1]))&&t[1].length===20)return{type:"wpkh",hash:t[1]}},decode:t=>t.type==="wpkh"?[0,t.hash]:void 0},W8={encode(t){let e=t.length-1;if(t[e]!=="CHECKMULTISIG")return;let r=t[0],n=t[e-1];if(typeof r!="number"||typeof n!="number")return;let i=t.slice(1,-2);if(n===i.length){for(let o of i)if(!ke(o))return;return{type:"ms",m:r,pubkeys:i}}},decode:t=>t.type==="ms"?[t.m,...t.pubkeys,t.pubkeys.length,"CHECKMULTISIG"]:void 0},G8={encode(t){if(!(t.length!==2||t[0]!==1||!ke(t[1])))return{type:"tr",pubkey:t[1]}},decode:t=>t.type==="tr"?[1,t.pubkey]:void 0},z8={encode(t){let e=t.length-1;if(t[e]!=="CHECKSIG")return;let r=[];for(let n=0;n<e;n++){let i=t[n];if(n&1){if(i!=="CHECKSIGVERIFY"||n===e-1)return;continue}if(!ke(i))return;r.push(i)}return{type:"tr_ns",pubkeys:r}},decode:t=>{if(t.type!=="tr_ns")return;let e=[];for(let r=0;r<t.pubkeys.length-1;r++)e.push(t.pubkeys[r],"CHECKSIGVERIFY");return e.push(t.pubkeys[t.pubkeys.length-1],"CHECKSIG"),e}},Y8={encode(t){let e=t.length-1;if(t[e]!=="NUMEQUAL"||t[1]!=="CHECKSIG")return;let r=[],n=$E(t[e-1]);if(typeof n=="number"){for(let i=0;i<e-1;i++){let o=t[i];if(i&1){if(o!==(i===1?"CHECKSIG":"CHECKSIGADD"))throw new Error("OutScript.encode/tr_ms: wrong element");continue}if(!ke(o))throw new Error("OutScript.encode/tr_ms: wrong key element");r.push(o)}return{type:"tr_ms",pubkeys:r,m:n}}},decode:t=>{if(t.type!=="tr_ms")return;let e=[t.pubkeys[0],"CHECKSIG"];for(let r=1;r<t.pubkeys.length;r++)e.push(t.pubkeys[r],"CHECKSIGADD");return e.push(t.m,"NUMEQUAL"),e}},J8={encode(t){return{type:"unknown",script:Ye.encode(t)}},decode:t=>t.type==="unknown"?Ye.decode(t.script):void 0},Z8=[$8,H8,V8,q8,F8,j8,W8,G8,z8,Y8,J8],X8=gn(Ye,Ii.match(Z8)),Je=Ft(X8,t=>{if(t.type==="pk"&&!Eo(t.pubkey,xt.ecdsa))throw new Error("OutScript/pk: wrong key");if((t.type==="pkh"||t.type==="sh"||t.type==="wpkh")&&(!ke(t.hash)||t.hash.length!==20))throw new Error(`OutScript/${t.type}: wrong hash`);if(t.type==="wsh"&&(!ke(t.hash)||t.hash.length!==32))throw new Error("OutScript/wsh: wrong hash");if(t.type==="tr"&&(!ke(t.pubkey)||!Eo(t.pubkey,xt.schnorr)))throw new Error("OutScript/tr: wrong taproot public key");if((t.type==="ms"||t.type==="tr_ns"||t.type==="tr_ms")&&!Array.isArray(t.pubkeys))throw new Error("OutScript/multisig: wrong pubkeys array");if(t.type==="ms"){let e=t.pubkeys.length;for(let r of t.pubkeys)if(!Eo(r,xt.ecdsa))throw new Error("OutScript/multisig: wrong pubkey");if(t.m<=0||e>16||t.m>e)throw new Error("OutScript/multisig: invalid params")}if(t.type==="tr_ns"||t.type==="tr_ms"){for(let e of t.pubkeys)if(!Eo(e,xt.schnorr))throw new Error(`OutScript/${t.type}: wrong pubkey`)}if(t.type==="tr_ms"){let e=t.pubkeys.length;if(t.m<=0||e>999||t.m>e)throw new Error("OutScript/tr_ms: invalid params")}return t});function ZE(t,e){if(!st(t.hash,Oe(e)))throw new Error("checkScript: wsh wrong witnessScript hash");let r=Je.decode(e);if(r.type==="tr"||r.type==="tr_ns"||r.type==="tr_ms")throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2SH`);if(r.type==="wpkh"||r.type==="sh")throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2WSH`)}function d0(t,e,r){if(t){let n=Je.decode(t);if(n.type==="tr_ns"||n.type==="tr_ms"||n.type==="ms"||n.type=="pk")throw new Error(`checkScript: non-wrapped ${n.type}`);if(n.type==="sh"&&e){if(!st(n.hash,jc(e)))throw new Error("checkScript: sh wrong redeemScript hash");let i=Je.decode(e);if(i.type==="tr"||i.type==="tr_ns"||i.type==="tr_ms")throw new Error(`checkScript: P2${i.type} cannot be wrapped in P2SH`);if(i.type==="sh")throw new Error("checkScript: P2SH cannot be wrapped in P2SH")}n.type==="wsh"&&r&&ZE(n,r)}if(e){let n=Je.decode(e);n.type==="wsh"&&r&&ZE(n,r)}}var ki=(t,e=zr)=>{if(!Eo(t,xt.ecdsa))throw new Error("P2PKH: invalid publicKey");let r=jc(t);return{type:"pkh",script:Je.encode({type:"pkh",hash:r}),address:Yr(e).encode({type:"pkh",hash:r}),hash:r}};var vs=(t,e=zr)=>{if(!Eo(t,xt.ecdsa))throw new Error("P2WPKH: invalid publicKey");if(t.length===65)throw new Error("P2WPKH: uncompressed public key");let r=jc(t);return{type:"wpkh",script:Je.encode({type:"wpkh",hash:r}),address:Yr(e).encode({type:"wpkh",hash:r}),hash:r}};function Q8(t,e,r=!1,n){let i=Je.decode(t);if(i.type==="unknown"){if(n){let c=gn(Ye,Ii.match(n)).decode(t);if(c!==void 0){if(typeof c.type!="string"||!c.type.startsWith("tr_"))throw new Error(`P2TR: invalid custom type=${c.type}`);return}}if(r)return}if(!["tr_ns","tr_ms"].includes(i.type))throw new Error(`P2TR: invalid leaf script=${i.type}`);let o=i;if(!r&&o.pubkeys)for(let s of o.pubkeys){if(st(s,nl))throw new Error("Unspendable taproot key in leaf script");if(st(s,e))throw new Error("Using P2TR with leaf script with same key as internal key is not supported")}}function QE(t){let e=Array.from(t);for(;e.length>=2;){e.sort((s,c)=>(c.weight||1)-(s.weight||1));let n=e.pop(),i=e.pop(),o=(i?.weight||1)+(n?.weight||1);e.push({weight:o,childs:[i?.childs||i,n?.childs||n]})}let r=e[0];return r?.childs||r}function s0(t,e=[]){if(!t)throw new Error("taprootAddPath: empty tree");if(t.type==="leaf")return{...t,path:e};if(t.type!=="branch")throw new Error(`taprootAddPath: wrong type=${t}`);return{...t,path:e,left:s0(t.left,[t.right.hash,...e]),right:s0(t.right,[t.left.hash,...e])}}function c0(t){if(!t)throw new Error("taprootAddPath: empty tree");if(t.type==="leaf")return[t];if(t.type!=="branch")throw new Error(`taprootWalkTree: wrong type=${t}`);return[...c0(t.left),...c0(t.right)]}function a0(t,e,r=!1,n){if(!t)throw new Error("taprootHashTree: empty tree");if(Array.isArray(t)&&t.length===1&&(t=t[0]),!Array.isArray(t)){let{leafVersion:a,script:u}=t;if(t.tapLeafScript||t.tapMerkleRoot&&!st(t.tapMerkleRoot,$e))throw new Error("P2TR: tapRoot leafScript cannot have tree");let d=typeof u=="string"?Ae.decode(u):u;if(!ke(d))throw new Error(`checkScript: wrong script type=${d}`);return Q8(d,e,r,n),{type:"leaf",version:a,script:d,hash:Pu(d,a)}}if(t.length!==2&&(t=QE(t)),t.length!==2)throw new Error("hashTree: non binary tree!");let i=a0(t[0],e,r,n),o=a0(t[1],e,r,n),[s,c]=[i.hash,o.hash];return ku(c,s)===-1&&([s,c]=[c,s]),{type:"branch",left:i,right:o,hash:Ou("TapBranch",s,c)}}var u0=192,Pu=(t,e=u0)=>Ou("TapLeaf",new Uint8Array([e]),dr.encode(t));function Ss(t,e,r=zr,n=!1,i){if(!t&&!e)throw new Error("p2tr: should have pubKey or scriptTree (or both)");let o=typeof t=="string"?Ae.decode(t):t||nl;if(!Eo(o,xt.schnorr))throw new Error("p2tr: non-schnorr pubkey");if(e){let s=s0(a0(e,o,n,i)),c=s.hash,[a,u]=Du(o,c),d=c0(s).map(f=>({...f,controlBlock:Di.encode({version:(f.version||u0)+u,internalKey:o,merklePath:f.path})}));return{type:"tr",script:Je.encode({type:"tr",pubkey:a}),address:Yr(r).encode({type:"tr",pubkey:a}),tweakedPubkey:a,tapInternalKey:o,leaves:d,tapLeafScript:d.map(f=>[Di.decode(f.controlBlock),Fn(f.script,new Uint8Array([f.version||u0]))]),tapMerkleRoot:c}}else{let s=Du(o,$e)[0];return{type:"tr",script:Je.encode({type:"tr",pubkey:s}),address:Yr(r).encode({type:"tr",pubkey:s}),tweakedPubkey:s,tapInternalKey:o}}}var ev=wE(Oe);function tv(t,e){if(e.length<2||e.length>40)throw new Error("Witness: invalid length");if(t>16)throw new Error("Witness: invalid version");if(t===0&&!(e.length===20||e.length===32))throw new Error("Witness: invalid length for version")}function o0(t,e,r=zr){tv(t,e);let n=t===0?zf:Hc;return n.encode(r.bech32,[t].concat(n.toWords(e)))}function XE(t,e){return ev.encode(Fn(Uint8Array.from(e),t))}function Yr(t=zr){return{encode(e){let{type:r}=e;if(r==="wpkh")return o0(0,e.hash,t);if(r==="wsh")return o0(0,e.hash,t);if(r==="tr")return o0(1,e.pubkey,t);if(r==="pkh")return XE(e.hash,[t.pubKeyHash]);if(r==="sh")return XE(e.hash,[t.scriptHash]);throw new Error(`Unknown address type=${r}`)},decode(e){if(e.length<14||e.length>74)throw new Error("Invalid address length");if(t.bech32&&e.toLowerCase().startsWith(`${t.bech32}1`)){let n;try{if(n=zf.decode(e),n.words[0]!==0)throw new Error(`bech32: wrong version=${n.words[0]}`)}catch{if(n=Hc.decode(e),n.words[0]===0)throw new Error(`bech32m: wrong version=${n.words[0]}`)}if(n.prefix!==t.bech32)throw new Error(`wrong bech32 prefix=${n.prefix}`);let[i,...o]=n.words,s=zf.fromWords(o);if(tv(i,s),i===0&&s.length===32)return{type:"wsh",hash:s};if(i===0&&s.length===20)return{type:"wpkh",hash:s};if(i===1&&s.length===32)return{type:"tr",pubkey:s};throw new Error("Unknown witness program")}let r=ev.decode(e);if(r.length!==21)throw new Error("Invalid base58 address");if(r[0]===t.pubKeyHash)return{type:"pkh",hash:r.slice(1)};if(r[0]===t.scriptHash)return{type:"sh",hash:r.slice(1)};throw new Error(`Invalid address prefix=${r[0]}`)}}}l();var fl=new Uint8Array(32),eR={amount:0xffffffffffffffffn,script:$e},tR=t=>Math.ceil(t/4),rR=8,nR=2,As=0,p0=4294967295,iR=Ii.decimal(rR),Ku=(t,e)=>t===void 0?e:t;function hl(t){if(Array.isArray(t))return t.map(e=>hl(e));if(ke(t))return Uint8Array.from(t);if(["number","bigint","boolean","string","undefined"].includes(typeof t))return t;if(t===null)return t;if(typeof t=="object")return Object.fromEntries(Object.entries(t).map(([e,r])=>[e,hl(r)]));throw new Error(`cloneDeep: unknown type=${t} (${typeof t})`)}var Ve;(function(t){t[t.DEFAULT=0]="DEFAULT",t[t.ALL=1]="ALL",t[t.NONE=2]="NONE",t[t.SINGLE=3]="SINGLE",t[t.ANYONECANPAY=128]="ANYONECANPAY"})(Ve||(Ve={}));var vo;(function(t){t[t.DEFAULT=0]="DEFAULT",t[t.ALL=1]="ALL",t[t.NONE=2]="NONE",t[t.SINGLE=3]="SINGLE",t[t.DEFAULT_ANYONECANPAY=128]="DEFAULT_ANYONECANPAY",t[t.ALL_ANYONECANPAY=129]="ALL_ANYONECANPAY",t[t.NONE_ANYONECANPAY=130]="NONE_ANYONECANPAY",t[t.SINGLE_ANYONECANPAY=131]="SINGLE_ANYONECANPAY"})(vo||(vo={}));function oR(t,e,r,n=$e){return st(r,e)&&(t=PE(t,n),e=rl(t)),{privKey:t,pubKey:e}}function Ts(t){if(t.script===void 0||t.amount===void 0)throw new Error("Transaction/output: script and amount required");return{script:t.script,amount:t.amount}}function Mu(t){if(t.txid===void 0||t.index===void 0)throw new Error("Transaction/input: txid and index required");return{txid:t.txid,index:t.index,sequence:Ku(t.sequence,p0),finalScriptSig:Ku(t.finalScriptSig,$e)}}function f0(t){for(let e in t){let r=e;WE.includes(r)||delete t[r]}}var l0=bt({txid:He(32,!0),index:Te});function sR(t){if(typeof t!="number"||typeof vo[t]!="string")throw new Error(`Invalid SigHash=${t}`);return t}function rv(t){let e=t&31;return{isAny:!!(t&Ve.ANYONECANPAY),isNone:e===Ve.NONE,isSingle:e===Ve.SINGLE}}function cR(t){if(t!==void 0&&{}.toString.call(t)!=="[object Object]")throw new Error(`Wrong object type for transaction options: ${t}`);let e={...t,version:Ku(t.version,nR),lockTime:Ku(t.lockTime,0),PSBTVersion:Ku(t.PSBTVersion,0)};if(typeof e.allowUnknowInput<"u"&&(t.allowUnknownInputs=e.allowUnknowInput),typeof e.allowUnknowOutput<"u"&&(t.allowUnknownOutputs=e.allowUnknowOutput),typeof e.lockTime!="number")throw new Error("Transaction lock time should be number");if(Te.encode(e.lockTime),e.PSBTVersion!==0&&e.PSBTVersion!==2)throw new Error(`Unknown PSBT version ${e.PSBTVersion}`);for(let r of["allowUnknownVersion","allowUnknownOutputs","allowUnknownInputs","disableScriptCheck","bip174jsCompat","allowLegacyWitnessUtxo","lowR"]){let n=e[r];if(n!==void 0&&typeof n!="boolean")throw new Error(`Transation options wrong type: ${r}=${n} (${typeof n})`)}if(e.allowUnknownVersion?typeof e.version=="number":![-1,0,1,2,3].includes(e.version))throw new Error(`Unknown version: ${e.version}`);if(e.customScripts!==void 0){let r=e.customScripts;if(!Array.isArray(r))throw new Error(`wrong custom scripts type (expected array): customScripts=${r} (${typeof r})`);for(let n of r){if(typeof n.encode!="function"||typeof n.decode!="function")throw new Error(`wrong script=${n} (${typeof n})`);if(n.finalizeTaproot!==void 0&&typeof n.finalizeTaproot!="function")throw new Error(`wrong script=${n} (${typeof n})`)}}return Object.freeze(e)}function nv(t){if(t.nonWitnessUtxo&&t.index!==void 0){let e=t.nonWitnessUtxo.outputs.length-1;if(t.index>e)throw new Error(`validateInput: index(${t.index}) not in nonWitnessUtxo`);let r=t.nonWitnessUtxo.outputs[t.index];if(t.witnessUtxo&&(!st(t.witnessUtxo.script,r.script)||t.witnessUtxo.amount!==r.amount))throw new Error("validateInput: witnessUtxo different from nonWitnessUtxo");if(t.txid){if(t.nonWitnessUtxo.outputs.length-1<t.index)throw new Error("nonWitnessUtxo: incorect output index");let i=_s.fromRaw(Oi.encode(t.nonWitnessUtxo),{allowUnknownOutputs:!0,disableScriptCheck:!0,allowUnknownInputs:!0}),o=Ae.encode(t.txid);if(i.isFinal&&i.id!==o)throw new Error(`nonWitnessUtxo: wrong txid, exp=${o} got=${i.id}`)}}return t}function ll(t){if(t.nonWitnessUtxo){if(t.index===void 0)throw new Error("Unknown input index");return t.nonWitnessUtxo.outputs[t.index]}else{if(t.witnessUtxo)return t.witnessUtxo;throw new Error("Cannot find previous output info")}}function iv(t,e,r,n=!1,i=!1){let{nonWitnessUtxo:o,txid:s}=t;typeof o=="string"&&(o=Ae.decode(o)),ke(o)&&(o=Oi.decode(o)),!("nonWitnessUtxo"in t)&&o===void 0&&(o=e?.nonWitnessUtxo),typeof s=="string"&&(s=Ae.decode(s)),s===void 0&&(s=e?.txid);let c={...e,...t,nonWitnessUtxo:o,txid:s};!("nonWitnessUtxo"in t)&&c.nonWitnessUtxo===void 0&&delete c.nonWitnessUtxo,c.sequence===void 0&&(c.sequence=p0),c.tapMerkleRoot===null&&delete c.tapMerkleRoot,c=dl(Cu,c,e,r,i),al.encode(c);let a;return c.nonWitnessUtxo&&c.index!==void 0?a=c.nonWitnessUtxo.outputs[c.index]:c.witnessUtxo&&(a=c.witnessUtxo),a&&!n&&d0(a&&a.script,c.redeemScript,c.witnessScript),c}function h0(t,e=!1){let r="legacy",n=Ve.ALL,i=ll(t),o=Je.decode(i.script),s=o.type,c=o,a=[o];if(o.type==="tr")return n=Ve.DEFAULT,{txType:"taproot",type:"tr",last:o,lastScript:i.script,defaultSighash:n,sighash:t.sighashType||n};{if((o.type==="wpkh"||o.type==="wsh")&&(r="segwit"),o.type==="sh"){if(!t.redeemScript)throw new Error("inputType: sh without redeemScript");let h=Je.decode(t.redeemScript);(h.type==="wpkh"||h.type==="wsh")&&(r="segwit"),a.push(h),c=h,s+=`-${h.type}`}if(c.type==="wsh"){if(!t.witnessScript)throw new Error("inputType: wsh without witnessScript");let h=Je.decode(t.witnessScript);h.type==="wsh"&&(r="segwit"),a.push(h),c=h,s+=`-${h.type}`}let u=a[a.length-1];if(u.type==="sh"||u.type==="wsh")throw new Error("inputType: sh/wsh cannot be terminal type");let d=Je.encode(u),f={type:s,txType:r,last:u,lastScript:d,defaultSighash:n,sighash:t.sighashType||n};if(r==="legacy"&&!e&&!t.nonWitnessUtxo)throw new Error("Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure");return f}}var _s=class t{constructor(e={}){this.global={},this.inputs=[],this.outputs=[];let r=this.opts=cR(e);r.lockTime!==As&&(this.global.fallbackLocktime=r.lockTime),this.global.txVersion=r.version}static fromRaw(e,r={}){let n=Oi.decode(e),i=new t({...r,version:n.version,lockTime:n.lockTime});for(let o of n.outputs)i.addOutput(o);if(i.outputs=n.outputs,i.inputs=n.inputs,n.witnesses)for(let o=0;o<n.witnesses.length;o++)i.inputs[o].finalScriptWitness=n.witnesses[o];return i}static fromPSBT(e,r={}){let n;try{n=n0.decode(e)}catch(f){try{n=i0.decode(e)}catch{throw f}}let i=n.global.version||0;if(i!==0&&i!==2)throw new Error(`Wrong PSBT version=${i}`);let o=n.global.unsignedTx,s=i===0?o?.version:n.global.txVersion,c=i===0?o?.lockTime:n.global.fallbackLocktime,a=new t({...r,version:s,lockTime:c,PSBTVersion:i}),u=i===0?o?.inputs.length:n.global.inputCount;a.inputs=n.inputs.slice(0,u).map((f,h)=>nv({finalScriptSig:$e,...n.global.unsignedTx?.inputs[h],...f}));let d=i===0?o?.outputs.length:n.global.outputCount;return a.outputs=n.outputs.slice(0,d).map((f,h)=>({...f,...n.global.unsignedTx?.outputs[h]})),a.global={...n.global,txVersion:s},c!==As&&(a.global.fallbackLocktime=c),a}toPSBT(e=this.opts.PSBTVersion){if(e!==0&&e!==2)throw new Error(`Wrong PSBT version=${e}`);let r=this.inputs.map(o=>nv(r0(e,Cu,o)));for(let o of r)o.partialSig&&!o.partialSig.length&&delete o.partialSig,o.finalScriptSig&&!o.finalScriptSig.length&&delete o.finalScriptSig,o.finalScriptWitness&&!o.finalScriptWitness.length&&delete o.finalScriptWitness;let n=this.outputs.map(o=>r0(e,Lu,o)),i={...this.global};return e===0?(i.unsignedTx=Es.decode(Es.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Mu).map(o=>({...o,finalScriptSig:$e})),outputs:this.outputs.map(Ts)})),delete i.fallbackLocktime,delete i.txVersion):(i.version=e,i.txVersion=this.version,i.inputCount=this.inputs.length,i.outputCount=this.outputs.length,i.fallbackLocktime&&i.fallbackLocktime===As&&delete i.fallbackLocktime),this.opts.bip174jsCompat&&(r.length||r.push({}),n.length||n.push({})),(e===0?n0:i0).encode({global:i,inputs:r,outputs:n})}get lockTime(){let e=As,r=0,n=As,i=0;for(let o of this.inputs)o.requiredHeightLocktime&&(e=Math.max(e,o.requiredHeightLocktime),r++),o.requiredTimeLocktime&&(n=Math.max(n,o.requiredTimeLocktime),i++);return r&&r>=i?e:n!==As?n:this.global.fallbackLocktime||As}get version(){if(this.global.txVersion===void 0)throw new Error("No global.txVersion");return this.global.txVersion}inputStatus(e){this.checkInputIdx(e);let r=this.inputs[e];return r.finalScriptSig&&r.finalScriptSig.length||r.finalScriptWitness&&r.finalScriptWitness.length?"finalized":r.tapKeySig||r.tapScriptSig&&r.tapScriptSig.length||r.partialSig&&r.partialSig.length?"signed":"unsigned"}inputSighash(e){this.checkInputIdx(e);let r=this.inputs[e].sighashType,n=r===void 0?Ve.DEFAULT:r,i=n===Ve.DEFAULT?Ve.ALL:n&3;return{sigInputs:n&Ve.ANYONECANPAY,sigOutputs:i}}signStatus(){let e=!0,r=!0,n=[],i=[];for(let o=0;o<this.inputs.length;o++){if(this.inputStatus(o)==="unsigned")continue;let{sigInputs:c,sigOutputs:a}=this.inputSighash(o);if(c===Ve.ANYONECANPAY?n.push(o):e=!1,a===Ve.ALL)r=!1;else if(a===Ve.SINGLE)i.push(o);else if(a!==Ve.NONE)throw new Error(`Wrong signature hash output type: ${a}`)}return{addInput:e,addOutput:r,inputs:n,outputs:i}}get isFinal(){for(let e=0;e<this.inputs.length;e++)if(this.inputStatus(e)!=="finalized")return!1;return!0}get hasWitnesses(){let e=!1;for(let r of this.inputs)r.finalScriptWitness&&r.finalScriptWitness.length&&(e=!0);return e}get weight(){if(!this.isFinal)throw new Error("Transaction is not finalized");let e=32,r=this.outputs.map(Ts);e+=4*Ur.encode(this.outputs.length).length;for(let n of r)e+=32+4*dr.encode(n.script).length;this.hasWitnesses&&(e+=2),e+=4*Ur.encode(this.inputs.length).length;for(let n of this.inputs)e+=160+4*dr.encode(n.finalScriptSig||$e).length,this.hasWitnesses&&n.finalScriptWitness&&(e+=Gc.encode(n.finalScriptWitness).length);return e}get vsize(){return tR(this.weight)}toBytes(e=!1,r=!1){return Oi.encode({version:this.version,lockTime:this.lockTime,inputs:this.inputs.map(Mu).map(n=>({...n,finalScriptSig:e&&n.finalScriptSig||$e})),outputs:this.outputs.map(Ts),witnesses:this.inputs.map(n=>n.finalScriptWitness||[]),segwitFlag:r&&this.hasWitnesses})}get unsignedTx(){return this.toBytes(!1,!1)}get hex(){return Ae.encode(this.toBytes(!0,this.hasWitnesses))}get hash(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Ae.encode(Ri(this.toBytes(!0)))}get id(){if(!this.isFinal)throw new Error("Transaction is not finalized");return Ae.encode(Ri(this.toBytes(!0)).reverse())}checkInputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.inputs.length)throw new Error(`Wrong input index=${e}`)}getInput(e){return this.checkInputIdx(e),hl(this.inputs[e])}get inputsLength(){return this.inputs.length}addInput(e,r=!1){if(!r&&!this.signStatus().addInput)throw new Error("Tx has signed inputs, cannot add new one");return this.inputs.push(iv(e,void 0,void 0,this.opts.disableScriptCheck)),this.inputs.length-1}updateInput(e,r,n=!1){this.checkInputIdx(e);let i;if(!n){let o=this.signStatus();(!o.addInput||o.inputs.includes(e))&&(i=GE)}this.inputs[e]=iv(r,this.inputs[e],i,this.opts.disableScriptCheck,this.opts.allowUnknown)}checkOutputIdx(e){if(!Number.isSafeInteger(e)||0>e||e>=this.outputs.length)throw new Error(`Wrong output index=${e}`)}getOutput(e){return this.checkOutputIdx(e),hl(this.outputs[e])}getOutputAddress(e,r=zr){let n=this.getOutput(e);if(n.script)return Yr(r).encode(Je.decode(n.script))}get outputsLength(){return this.outputs.length}normalizeOutput(e,r,n){let{amount:i,script:o}=e;if(i===void 0&&(i=r?.amount),typeof i!="bigint")throw new Error(`Wrong amount type, should be of type bigint in sats, but got ${i} of type ${typeof i}`);typeof o=="string"&&(o=Ae.decode(o)),o===void 0&&(o=r?.script);let s={...r,...e,amount:i,script:o};if(s.amount===void 0&&delete s.amount,s=dl(Lu,s,r,n,this.opts.allowUnknown),ul.encode(s),s.script&&!this.opts.allowUnknownOutputs&&Je.decode(s.script).type==="unknown")throw new Error("Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure");return this.opts.disableScriptCheck||d0(s.script,s.redeemScript,s.witnessScript),s}addOutput(e,r=!1){if(!r&&!this.signStatus().addOutput)throw new Error("Tx has signed outputs, cannot add new one");return this.outputs.push(this.normalizeOutput(e)),this.outputs.length-1}updateOutput(e,r,n=!1){this.checkOutputIdx(e);let i;if(!n){let o=this.signStatus();(!o.addOutput||o.outputs.includes(e))&&(i=zE)}this.outputs[e]=this.normalizeOutput(r,this.outputs[e],i)}addOutputAddress(e,r,n=zr){return this.addOutput({script:Je.encode(Yr(n).decode(e)),amount:r})}get fee(){let e=0n;for(let n of this.inputs){let i=ll(n);if(!i)throw new Error("Empty input amount");e+=i.amount}let r=this.outputs.map(Ts);for(let n of r)e-=n.amount;return e}preimageLegacy(e,r,n){let{isAny:i,isNone:o,isSingle:s}=rv(n);if(e<0||!Number.isSafeInteger(e))throw new Error(`Invalid input idx=${e}`);if(s&&e>=this.outputs.length||e>=this.inputs.length)return TE.encode(1n);r=Ye.encode(Ye.decode(r).filter(d=>d!=="CODESEPARATOR"));let c=this.inputs.map(Mu).map((d,f)=>({...d,finalScriptSig:f===e?r:$e}));i?c=[c[e]]:(o||s)&&(c=c.map((d,f)=>({...d,sequence:f===e?d.sequence:0})));let a=this.outputs.map(Ts);o?a=[]:s&&(a=a.slice(0,e).fill(eR).concat([a[e]]));let u=Oi.encode({lockTime:this.lockTime,version:this.version,segwitFlag:!1,inputs:c,outputs:a});return Ri(u,bo.encode(n))}preimageWitnessV0(e,r,n,i){let{isAny:o,isNone:s,isSingle:c}=rv(n),a=fl,u=fl,d=fl,f=this.inputs.map(Mu),h=this.outputs.map(Ts);o||(a=Ri(...f.map(l0.encode))),!o&&!c&&!s&&(u=Ri(...f.map(g=>Te.encode(g.sequence)))),!c&&!s?d=Ri(...h.map(Ui.encode)):c&&e<h.length&&(d=Ri(Ui.encode(h[e])));let p=f[e];return Ri(bo.encode(this.version),a,u,He(32,!0).encode(p.txid),Te.encode(p.index),dr.encode(r),Fc.encode(i),Te.encode(p.sequence),d,Te.encode(this.lockTime),Te.encode(n))}preimageWitnessV1(e,r,n,i,o=-1,s,c=192,a){if(!Array.isArray(i)||this.inputs.length!==i.length)throw new Error(`Invalid amounts array=${i}`);if(!Array.isArray(r)||this.inputs.length!==r.length)throw new Error(`Invalid prevOutScript array=${r}`);let u=[mn.encode(0),mn.encode(n),bo.encode(this.version),Te.encode(this.lockTime)],d=n===Ve.DEFAULT?Ve.ALL:n&3,f=n&Ve.ANYONECANPAY,h=this.inputs.map(Mu),p=this.outputs.map(Ts);f!==Ve.ANYONECANPAY&&u.push(...[h.map(l0.encode),i.map(Fc.encode),r.map(dr.encode),h.map(y=>Te.encode(y.sequence))].map(y=>Oe(Fn(...y)))),d===Ve.ALL&&u.push(Oe(Fn(...p.map(Ui.encode))));let g=(a?1:0)|(s?2:0);if(u.push(new Uint8Array([g])),f===Ve.ANYONECANPAY){let y=h[e];u.push(l0.encode(y),Fc.encode(i[e]),dr.encode(r[e]),Te.encode(y.sequence))}else u.push(Te.encode(e));return g&1&&u.push(Oe(dr.encode(a||$e))),d===Ve.SINGLE&&u.push(e<p.length?Oe(Ui.encode(p[e])):fl),s&&u.push(Pu(s,c),mn.encode(0),bo.encode(o)),Ou("TapSighash",...u)}signIdx(e,r,n,i){this.checkInputIdx(r);let o=this.inputs[r],s=h0(o,this.opts.allowLegacyWitnessUtxo);if(!ke(e)){if(!o.bip32Derivation||!o.bip32Derivation.length)throw new Error("bip32Derivation: empty");let d=o.bip32Derivation.filter(h=>h[1].fingerprint==e.fingerprint).map(([h,{path:p}])=>{let g=e;for(let y of p)g=g.deriveChild(y);if(!st(g.publicKey,h))throw new Error("bip32Derivation: wrong pubKey");if(!g.privateKey)throw new Error("bip32Derivation: no privateKey");return g});if(!d.length)throw new Error(`bip32Derivation: no items with fingerprint=${e.fingerprint}`);let f=!1;for(let h of d)this.signIdx(h.privateKey,r)&&(f=!0);return f}n?n.forEach(sR):n=[s.defaultSighash];let c=s.sighash;if(!n.includes(c))throw new Error(`Input with not allowed sigHash=${c}. Allowed: ${n.join(", ")}`);let{sigOutputs:a}=this.inputSighash(r);if(a===Ve.SINGLE&&r>=this.outputs.length)throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${r}`);let u=ll(o);if(s.txType==="taproot"){let d=this.inputs.map(ll),f=d.map(E=>E.script),h=d.map(E=>E.amount),p=!1,g=rl(e),y=o.tapMerkleRoot||$e;if(o.tapInternalKey){let{pubKey:E,privKey:S}=oR(e,g,o.tapInternalKey,y),[I,A]=Du(o.tapInternalKey,y);if(st(I,E)){let O=this.preimageWitnessV1(r,f,c,h),T=Fn(Yy(O,S,i),c!==Ve.DEFAULT?new Uint8Array([c]):$e);this.updateInput(r,{tapKeySig:T},!0),p=!0}}if(o.tapLeafScript){o.tapScriptSig=o.tapScriptSig||[];for(let[E,S]of o.tapLeafScript){let I=S.subarray(0,-1),A=Ye.decode(I),O=S[S.length-1],T=Pu(I,O);if(A.findIndex($=>ke($)&&st($,g))===-1)continue;let q=this.preimageWitnessV1(r,f,c,h,void 0,I,O),j=Fn(Yy(q,e,i),c!==Ve.DEFAULT?new Uint8Array([c]):$e);this.updateInput(r,{tapScriptSig:[[{pubKey:g,leafHash:T},j]]},!0),p=!0}}if(!p)throw new Error("No taproot scripts signed");return!0}else{let d=zy(e),f=!1,h=jc(d);for(let y of Ye.decode(s.lastScript))ke(y)&&(st(y,d)||st(y,h))&&(f=!0);if(!f)throw new Error(`Input script doesn't have pubKey: ${s.lastScript}`);let p;if(s.txType==="legacy")p=this.preimageLegacy(r,s.lastScript,c);else if(s.txType==="segwit"){let y=s.lastScript;s.last.type==="wpkh"&&(y=Je.encode({type:"pkh",hash:s.last.hash})),p=this.preimageWitnessV0(r,y,c,u.amount)}else throw new Error(`Transaction/sign: unknown tx type: ${s.txType}`);let g=CE(p,e,this.opts.lowR);this.updateInput(r,{partialSig:[[d,Fn(g,new Uint8Array([c]))]]},!0)}return!0}sign(e,r,n){let i=0;for(let o=0;o<this.inputs.length;o++)try{this.signIdx(e,o,r,n)&&i++}catch{}if(!i)throw new Error("No inputs signed");return i}finalizeIdx(e){if(this.checkInputIdx(e),this.fee<0n)throw new Error("Outputs spends more than inputs amount");let r=this.inputs[e],n=h0(r,this.opts.allowLegacyWitnessUtxo);if(n.txType==="taproot"){if(r.tapKeySig)r.finalScriptWitness=[r.tapKeySig];else if(r.tapLeafScript&&r.tapScriptSig){let a=r.tapLeafScript.sort((u,d)=>Di.encode(u[0]).length-Di.encode(d[0]).length);for(let[u,d]of a){let f=d.slice(0,-1),h=d[d.length-1],p=Je.decode(f),g=Pu(f,h),y=r.tapScriptSig.filter(S=>st(S[0].leafHash,g)),E=[];if(p.type==="tr_ms"){let S=p.m,I=p.pubkeys,A=0;for(let O of I){let T=y.findIndex(M=>st(M[0].pubKey,O));if(A===S||T===-1){E.push($e);continue}E.push(y[T][1]),A++}if(A!==S)continue}else if(p.type==="tr_ns"){for(let S of p.pubkeys){let I=y.findIndex(A=>st(A[0].pubKey,S));I!==-1&&E.push(y[I][1])}if(E.length!==p.pubkeys.length)continue}else if(p.type==="unknown"&&this.opts.allowUnknownInputs){let S=Ye.decode(f);if(E=y.map(([{pubKey:I},A])=>{let O=S.findIndex(T=>ke(T)&&st(T,I));if(O===-1)throw new Error("finalize/taproot: cannot find position of pubkey in script");return{signature:A,pos:O}}).sort((I,A)=>I.pos-A.pos).map(I=>I.signature),!E.length)continue}else{let S=this.opts.customScripts;if(S)for(let I of S){if(!I.finalizeTaproot)continue;let A=Ye.decode(f),O=I.encode(A);if(O===void 0)continue;let T=I.finalizeTaproot(f,O,y);if(T){r.finalScriptWitness=T.concat(Di.encode(u)),r.finalScriptSig=$e,f0(r);return}}throw new Error("Finalize: Unknown tapLeafScript")}r.finalScriptWitness=E.reverse().concat([f,Di.encode(u)]);break}if(!r.finalScriptWitness)throw new Error("finalize/taproot: empty witness")}else throw new Error("finalize/taproot: unknown input");r.finalScriptSig=$e,f0(r);return}if(!r.partialSig||!r.partialSig.length)throw new Error("Not enough partial sign");let i=$e,o=[];if(n.last.type==="ms"){let a=n.last.m,u=n.last.pubkeys,d=[];for(let f of u){let h=r.partialSig.find(p=>st(f,p[0]));h&&d.push(h[1])}if(d=d.slice(0,a),d.length!==a)throw new Error(`Multisig: wrong signatures count, m=${a} n=${u.length} signatures=${d.length}`);i=Ye.encode([0,...d])}else if(n.last.type==="pk")i=Ye.encode([r.partialSig[0][1]]);else if(n.last.type==="pkh")i=Ye.encode([r.partialSig[0][1],r.partialSig[0][0]]);else if(n.last.type==="wpkh")i=$e,o=[r.partialSig[0][1],r.partialSig[0][0]];else if(n.last.type==="unknown"&&!this.opts.allowUnknownInputs)throw new Error("Unknown inputs not allowed");let s,c;if(n.type.includes("wsh-")&&(i.length&&n.lastScript.length&&(o=Ye.decode(i).map(a=>{if(a===0)return $e;if(ke(a))return a;throw new Error(`Wrong witness op=${a}`)})),o=o.concat(n.lastScript)),n.txType==="segwit"&&(c=o),n.type.startsWith("sh-wsh-")?s=Ye.encode([Ye.encode([0,Oe(n.lastScript)])]):n.type.startsWith("sh-")?s=Ye.encode([...Ye.decode(i),n.lastScript]):n.type.startsWith("wsh-")||n.txType!=="segwit"&&(s=i),!s&&!c)throw new Error("Unknown error finalizing input");s&&(r.finalScriptSig=s),c&&(r.finalScriptWitness=c),f0(r)}finalize(){for(let e=0;e<this.inputs.length;e++)this.finalizeIdx(e)}extract(){if(!this.isFinal)throw new Error("Transaction has unfinalized inputs");if(!this.outputs.length)throw new Error("Transaction has no outputs");if(this.fee<0n)throw new Error("Outputs spends more than inputs amount");return this.toBytes(!0,!0)}combine(e){for(let i of["PSBTVersion","version","lockTime"])if(this.opts[i]!==e.opts[i])throw new Error(`Transaction/combine: different ${i} this=${this.opts[i]} other=${e.opts[i]}`);for(let i of["inputs","outputs"])if(this[i].length!==e[i].length)throw new Error(`Transaction/combine: different ${i} length this=${this[i].length} other=${e[i].length}`);let r=this.global.unsignedTx?Es.encode(this.global.unsignedTx):$e,n=e.global.unsignedTx?Es.encode(e.global.unsignedTx):$e;if(!st(r,n))throw new Error("Transaction/combine: different unsigned tx");this.global=dl(cl,this.global,e.global,void 0,this.opts.allowUnknown);for(let i=0;i<this.inputs.length;i++)this.updateInput(i,e.inputs[i],!0);for(let i=0;i<this.outputs.length;i++)this.updateOutput(i,e.outputs[i],!0);return this}clone(){return t.fromPSBT(this.toPSBT(this.opts.PSBTVersion),this.opts)}};l();l();l();l();l();function ov(t,e){var r="",n=e&&e.include,i=e&&e.exclude;i&&typeof i=="string"&&(i=[i]),n&&n.sort();var o=new WeakMap,s=e&&e.allowCircular,c=e&&e.filterUndefined,a=e&&e.undefinedInArrayToNull;return u(t,""),r;function u(d,f){if(d===null||typeof d!="object"||d.toJSON!=null)r+=JSON.stringify(d);else if(Array.isArray(d)){var h=o.get(d);if(h!==void 0&&f.startsWith(h)){if(!s)throw new Error("Circular reference detected");r+='"[Circular]"';return}o.set(d,f),r+="[";var p=!1;d.forEach(function(S,I){p&&(r+=","),p=!0,a&&S===void 0&&(S=null),u(S,f+"["+I+"]")}),r+="]"}else{var h=o.get(d);if(h!==void 0&&f.startsWith(h)){if(!s)throw new Error("Circular reference detected");r+='"[Circular]"';return}o.set(d,f),r+="{";var g=!1,y=function(I){i&&i.includes(I)||(g&&(r+=","),g=!0,r+=JSON.stringify(I),r+=":",u(d[I],f+"."+I))};if(f===""&&n)n.forEach(function(I){d.hasOwnProperty(I)&&y(I)});else{var E=Object.keys(d);c&&(E=E.filter(function(I){return d[I]!==void 0})),E.sort(),E.forEach(function(I){y(I)})}r+="}"}}}function sv(t,e){return ov(t,{allowCircular:e,filterUndefined:!0,undefinedInArrayToNull:!0})}l();var y0;(function(t){t.INVALID_DID="INVALID_DID",t.METHOD_NOT_SUPPORTED="METHOD_NOT_SUPPORTED",t.INTERNAL_ERROR="INTERNAL_ERROR",t.INVALID_DID_DOCUMENT="INVALID_DID_DOCUMENT",t.INVALID_DID_UPDATE="INVALID_DID_UPDATE",t.INVALID_DID_DOCUMENT_LENGTH="INVALID_DID_DOCUMENT_LENGTH",t.INVALID_DID_URL="INVALID_DID_URL",t.INVALID_PREVIOUS_DID_PROOF="INVALID_PREVIOUS_DID_PROOF",t.INVALID_PUBLIC_KEY="INVALID_PUBLIC_KEY",t.INVALID_PUBLIC_KEY_MULTIBASE="INVALID_PUBLIC_KEY_MULTIBASE",t.INVALID_PUBLIC_KEY_LENGTH="INVALID_PUBLIC_KEY_LENGTH",t.INVALID_PUBLIC_KEY_TYPE="INVALID_PUBLIC_KEY_TYPE",t.INVALID_SIGNATURE="INVALID_SIGNATURE",t.NOT_FOUND="NOT_FOUND",t.REPRESENTATION_NOT_SUPPORTED="REPRESENTATION_NOT_SUPPORTED",t.UNSUPPORTED_PUBLIC_KEY_TYPE="UNSUPPORTED_PUBLIC_KEY_TYPE",t.PROOF_VERIFICATION_ERROR="PROOF_VERIFICATION_ERROR",t.PROOF_GENERATION_ERROR="PROOF_GENERATION_ERROR",t.PROOF_SERIALIZATION_ERROR="PROOF_SERIALIZATION_ERROR",t.PROOF_PARSING_ERROR="PROOF_PARSING_ERROR",t.VERIFICATION_METHOD_ERROR="VERIFICATION_METHOD_ERROR",t.LATE_PUBLISHING_ERROR="LATE_PUBLISHING_ERROR",t.INVALID_SIDECAR_DATA="INVALID_SIDECAR_DATA",t.MISSING_UPDATE_DATA="MISSING_UPDATE_DATA",t.INVALID_UPDATE="INVALID_UPDATE",t.INVALID_DOMAIN_ERROR="INVALID_DOMAIN_ERROR",t.MISSING_RESOLUTION_OPTIONS="MISSING_RESOLUTION_OPTIONS"})(y0||(y0={}));var{INVALID_DID:Lt,METHOD_NOT_SUPPORTED:pl,INTERNAL_ERROR:cv,INVALID_DID_DOCUMENT:Ue,INVALID_DID_UPDATE:Ne,INVALID_DID_URL:GM,INVALID_PREVIOUS_DID_PROOF:zM,INVALID_PUBLIC_KEY:YM,INVALID_PUBLIC_KEY_MULTIBASE:JM,INVALID_PUBLIC_KEY_LENGTH:ZM,INVALID_PUBLIC_KEY_TYPE:XM,INVALID_SIGNATURE:QM,PROOF_VERIFICATION_ERROR:Wn,PROOF_GENERATION_ERROR:Ao,PROOF_SERIALIZATION_ERROR:av,PROOF_PARSING_ERROR:eK,VERIFICATION_METHOD_ERROR:yl,LATE_PUBLISHING_ERROR:g0,INVALID_SIDECAR_DATA:tK,MISSING_UPDATE_DATA:rK,MISSING_RESOLUTION_OPTIONS:nK}=y0;var Gt=class t extends Error{name="DidMethodError";type="DidMethodError";data;constructor(e,r={}){super(e),this.type=r.type??this.type,this.name=r.name??this.name,this.data=r.data,Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace?.(this,t)}},tt=class extends Gt{constructor(e,r="MethodError",n){super(e,{type:r,name:r,data:n})}},mt=class extends Gt{constructor(e,r="IdentifierError",n){super(e,{type:r,name:r,data:n})}},vt=class extends Gt{constructor(e,r="UpdateError",n){super(e,{type:r,name:r,data:n})}},rt=class extends Gt{constructor(e,r="ResolveError",n){super(e,{type:r,name:r,data:n})}};var Ze=class extends Gt{constructor(e,r="DidDocumentError",n){super(e,{type:r,name:r,data:n})}},So=class extends Gt{constructor(e,r="CryptosuiteError",n){super(e,{type:r,name:r,data:n})}},Jr=class extends Gt{constructor(e,r="DataIntegrityProofError",n){super(e,{type:r,name:r,data:n})}},wn=class extends Gt{constructor(e,r="KeyPairError",n){super(e,{type:r,name:r,data:n})}},jn=class extends Gt{constructor(e,r="SecretKeyError",n){super(e,{type:r,name:r,data:n})}},Bs=class extends Gt{constructor(e,r="PublicKeyError",n){super(e,{type:r,name:r,data:n})}},bn=class extends Gt{constructor(e,r="MultikeyError",n){super(e,{type:r,name:r,data:n})}};var zc=class extends Gt{constructor(e,r="CanonicalizationError",n){super(e,{type:r,name:r,data:n})}};var aR=new Set(["jcs"]),uR=new Set(["hex","base58","base64urlnopad"]);function m0(t){let e=t.toLowerCase();if(!aR.has(e))throw new zc(`Unsupported algorithm: ${t}`,"ALGORITHM_ERROR");return e}function w0(t){let e=t.toLowerCase();if(!uR.has(e))throw new zc(`Unsupported encoding: ${t}`,"ENCODING_ERROR");return e}function tr(t,e="jcs"){switch(m0(e)){case"jcs":{let n=JSON.parse(JSON.stringify(t));return sv(n)}default:throw new zc(`Unsupported algorithm: ${e}`,"ALGORITHM_ERROR")}}function To(t){return Oe(t)}function Zr(t,e="base64urlnopad"){switch(w0(e)){case"hex":return Ae.encode(t);case"base58":return Gf.encode(t);case"base64urlnopad":return $c.encode(t)}}function Is(t,e="base64urlnopad"){switch(w0(e)){case"hex":return Ae.decode(t);case"base58":return Gf.decode(t);case"base64urlnopad":return $c.decode(t)}}function Yc(t,e="jcs"){return To(tr(t,m0(e)))}function Gn(t,e){let r=m0(e?.algorithm??"jcs"),n=w0(e?.encoding??"base64urlnopad");return Zr(To(tr(t,r)),n)}l();l();var b0={};Sf(b0,{JsonPatchError:()=>ct,_areEquals:()=>Vu,applyOperation:()=>Rs,applyPatch:()=>vl,applyReducer:()=>pR,deepClone:()=>lR,getValueByPointer:()=>xl,validate:()=>dv,validator:()=>El});l();l();var dR=function(){var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,i){n.__proto__=i}||function(n,i){for(var o in i)i.hasOwnProperty(o)&&(n[o]=i[o])},t(e,r)};return function(e,r){t(e,r);function n(){this.constructor=e}e.prototype=r===null?Object.create(r):(n.prototype=r.prototype,new n)}}(),fR=Object.prototype.hasOwnProperty;function ml(t,e){return fR.call(t,e)}function wl(t){if(Array.isArray(t)){for(var e=new Array(t.length),r=0;r<e.length;r++)e[r]=""+r;return e}if(Object.keys)return Object.keys(t);var n=[];for(var i in t)ml(t,i)&&n.push(i);return n}function Pt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function bl(t){for(var e=0,r=t.length,n;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}function zn(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function $u(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function gl(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,r=t.length;e<r;e++)if(gl(t[e]))return!0}else if(typeof t=="object"){for(var n=wl(t),i=n.length,o=0;o<i;o++)if(gl(t[n[o]]))return!0}}return!1}function uv(t,e){var r=[t];for(var n in e){var i=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof i<"u"&&r.push(n+": "+i)}return r.join(`
3
+ `)}var Hu=function(t){dR(e,t);function e(r,n,i,o,s){var c=this.constructor,a=t.call(this,uv(r,{name:n,index:i,operation:o,tree:s}))||this;return a.name=n,a.index=i,a.operation=o,a.tree=s,Object.setPrototypeOf(a,c.prototype),a.message=uv(r,{name:n,index:i,operation:o,tree:s}),a}return e}(Error);var ct=Hu,lR=Pt,Jc={add:function(t,e,r){return t[e]=this.value,{newDocument:r}},remove:function(t,e,r){var n=t[e];return delete t[e],{newDocument:r,removed:n}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:function(t,e,r){var n=xl(r,this.path);n&&(n=Pt(n));var i=Rs(r,{op:"remove",path:this.from}).removed;return Rs(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},copy:function(t,e,r){var n=xl(r,this.from);return Rs(r,{op:"add",path:this.path,value:Pt(n)}),{newDocument:r}},test:function(t,e,r){return{newDocument:r,test:Vu(t[e],this.value)}},_get:function(t,e,r){return this.value=t[e],{newDocument:r}}},hR={add:function(t,e,r){return bl(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},remove:function(t,e,r){var n=t.splice(e,1);return{newDocument:r,removed:n[0]}},replace:function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},move:Jc.move,copy:Jc.copy,test:Jc.test,_get:Jc._get};function xl(t,e){if(e=="")return t;var r={op:"_get",path:e};return Rs(t,r),r.value}function Rs(t,e,r,n,i,o){if(r===void 0&&(r=!1),n===void 0&&(n=!0),i===void 0&&(i=!0),o===void 0&&(o=0),r&&(typeof r=="function"?r(e,0,t,e.path):El(e,0)),e.path===""){var s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=xl(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Vu(t,e.value),s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(r)throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return s}}else{n||(t=Pt(t));var c=e.path||"",a=c.split("/"),u=t,d=1,f=a.length,h=void 0,p=void 0,g=void 0;for(typeof r=="function"?g=r:g=El;;){if(p=a[d],p&&p.indexOf("~")!=-1&&(p=$u(p)),i&&(p=="__proto__"||p=="prototype"&&d>0&&a[d-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(r&&h===void 0&&(u[p]===void 0?h=a.slice(0,d).join("/"):d==f-1&&(h=e.path),h!==void 0&&g(e,0,t,h)),d++,Array.isArray(u)){if(p==="-")p=u.length;else{if(r&&!bl(p))throw new ct("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",o,e,t);bl(p)&&(p=~~p)}if(d>=f){if(r&&e.op==="add"&&p>u.length)throw new ct("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,t);var s=hR[e.op].call(e,u,p,t);if(s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}}else if(d>=f){var s=Jc[e.op].call(e,u,p,t);if(s.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(u=u[p],r&&d<f&&(!u||typeof u!="object"))throw new ct("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function vl(t,e,r,n,i){if(n===void 0&&(n=!0),i===void 0&&(i=!0),r&&!Array.isArray(e))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=Pt(t));for(var o=new Array(e.length),s=0,c=e.length;s<c;s++)o[s]=Rs(t,e[s],r,!0,i,s),t=o[s].newDocument;return o.newDocument=t,o}function pR(t,e,r){var n=Rs(t,e);if(n.test===!1)throw new ct("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}function El(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new ct("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Jc[t.op]){if(typeof t.path!="string")throw new ct("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ct('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ct("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&gl(t.value))throw new ct("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var i=t.path.split("/").length,o=n.split("/").length;if(i!==o+1&&i!==o)throw new ct("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new ct("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var s={op:"_get",path:t.from,value:void 0},c=dv([s],r);if(c&&c.name==="OPERATION_PATH_UNRESOLVABLE")throw new ct("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new ct("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}function dv(t,e,r){try{if(!Array.isArray(t))throw new ct("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)vl(Pt(e),Pt(t),r||!0);else{r=r||El;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof ct)return i;throw i}}function Vu(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),i,o,s;if(r&&n){if(o=t.length,o!=e.length)return!1;for(i=o;i--!==0;)if(!Vu(t[i],e[i]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(o=c.length,o!==Object.keys(e).length)return!1;for(i=o;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=o;i--!==0;)if(s=c[i],!Vu(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var S0={};Sf(S0,{compare:()=>vR,generate:()=>x0,observe:()=>ER,unobserve:()=>xR});l();var E0=new WeakMap,yR=function(){function t(e){this.observers=new Map,this.obj=e}return t}(),gR=function(){function t(e,r){this.callback=e,this.observer=r}return t}();function mR(t){return E0.get(t)}function wR(t,e){return t.observers.get(e)}function bR(t,e){t.observers.delete(e.callback)}function xR(t,e){e.unobserve()}function ER(t,e){var r=[],n,i=mR(t);if(!i)i=new yR(t),E0.set(t,i);else{var o=wR(i,e);n=o&&o.observer}if(n)return n;if(n={},i.value=Pt(t),e){n.callback=e,n.next=null;var s=function(){x0(n)},c=function(){clearTimeout(n.next),n.next=setTimeout(s)};typeof window<"u"&&(window.addEventListener("mouseup",c),window.addEventListener("keyup",c),window.addEventListener("mousedown",c),window.addEventListener("keydown",c),window.addEventListener("change",c))}return n.patches=r,n.object=t,n.unobserve=function(){x0(n),clearTimeout(n.next),bR(i,n),typeof window<"u"&&(window.removeEventListener("mouseup",c),window.removeEventListener("keyup",c),window.removeEventListener("mousedown",c),window.removeEventListener("keydown",c),window.removeEventListener("change",c))},i.observers.set(e,new gR(e,n)),n}function x0(t,e){e===void 0&&(e=!1);var r=E0.get(t.object);v0(r.value,t.object,t.patches,"",e),t.patches.length&&vl(r.value,t.patches);var n=t.patches;return n.length>0&&(t.patches=[],t.callback&&t.callback(n)),n}function v0(t,e,r,n,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=wl(e),s=wl(t),c=!1,a=!1,u=s.length-1;u>=0;u--){var d=s[u],f=t[d];if(ml(e,d)&&!(e[d]===void 0&&f!==void 0&&Array.isArray(e)===!1)){var h=e[d];typeof f=="object"&&f!=null&&typeof h=="object"&&h!=null&&Array.isArray(f)===Array.isArray(h)?v0(f,h,r,n+"/"+zn(d),i):f!==h&&(c=!0,i&&r.push({op:"test",path:n+"/"+zn(d),value:Pt(f)}),r.push({op:"replace",path:n+"/"+zn(d),value:Pt(h)}))}else Array.isArray(t)===Array.isArray(e)?(i&&r.push({op:"test",path:n+"/"+zn(d),value:Pt(f)}),r.push({op:"remove",path:n+"/"+zn(d)}),a=!0):(i&&r.push({op:"test",path:n,value:t}),r.push({op:"replace",path:n,value:e}),c=!0)}if(!(!a&&o.length==s.length))for(var u=0;u<o.length;u++){var d=o[u];!ml(t,d)&&e[d]!==void 0&&r.push({op:"add",path:n+"/"+zn(d),value:Pt(e[d])})}}}function vR(t,e,r){r===void 0&&(r=!1);var n=[];return v0(t,e,n,"",r),n}var fv=Object.assign({},b0,S0,{JsonPatchError:Hu,deepClone:Pt,escapePathComponent:zn,unescapePathComponent:$u});var{applyPatch:SR,compare:AR,deepClone:TR}=fv,Zc=class{static apply(e,r,n={}){let i=n.mutate??!1,o=n.clone??TR,s=i?e:o(e),c=this.validateOperations(r);if(c)throw new tt("Invalid JSON Patch operations","JSON_PATCH_APPLY_ERROR",{error:c});try{let a=SR(s,r,!1,i);if(a.newDocument===void 0)throw new tt("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{result:a});return a.newDocument}catch(a){throw new tt("JSON Patch application failed","JSON_PATCH_APPLY_ERROR",{error:a})}}static diff(e,r,n=""){let i=AR(e??{},r??{});if(!n)return i;let o=n.endsWith("/")?n.slice(0,-1):n;return i.map(s=>({...s,path:this.joinPointer(o,s.path)}))}static joinPointer(e,r){if(!e)return r;let n=e.startsWith("/")?e:`/${e}`;return`${this.escapeSegmentPath(n)}${r}`}static escapeSegmentPath(e){return e.split("/").map((r,n)=>n===0?r:r.replace(/~/g,"~0").replace(/\//g,"~1")).join("/")}static validateOperations(e){if(!Array.isArray(e))return new Error("Operations must be an array");for(let r of e){if(!r||typeof r!="object")return new Error("Operation must be an object");if(typeof r.op!="string")return new Error("Operation.op must be a string");if(typeof r.path!="string")return new Error("Operation.path must be a string");if((r.op==="move"||r.op==="copy")&&typeof r.from!="string")return new Error(`Operation.from must be a string for op=${r.op}`)}return null}};l();var _o;(function(t){t.KEY="KEY",t.EXTERNAL="EXTERNAL"})(_o||(_o={}));var Sl;(function(t){t.k="k",t.x="x"})(Sl||(Sl={}));var qu;(function(t){t[t.bitcoin=0]="bitcoin",t[t.signet=1]="signet",t[t.regtest=2]="regtest",t[t.testnet3=3]="testnet3",t[t.testnet4=4]="testnet4",t[t.mutinynet=5]="mutinynet"})(qu||(qu={}));l();var Bo=class{static toISOStringNonFractional(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new Error(`Invalid date: ${e}`);return e.toISOString().replace(/\.\d{3}Z$/,"Z")}static toUnixSeconds(e=new Date){let r=e.getTime();if(Number.isNaN(r))throw new Error(`Invalid date: ${e}`);return Math.floor(e.getTime()/1e3)}static dateStringToTimestamp(e){let r=new Date(e);return Number.isNaN(r.getTime())?new Date(0):r}static blocktimeToTimestamp(e){return new Date(e*1e3)}static isValidXsdDateTime(e){if(!e)return!1;let r=/^-?(\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})?$/,n=e.match(r);if(!n)return!1;let[,i,o,s,c,a,u,,d]=n,f=parseInt(i,10),h=parseInt(o,10),p=parseInt(s,10),g=parseInt(c,10),y=parseInt(a,10),E=parseInt(u,10);if(f===0||h<1||h>12)return!1;let S=[31,28,31,30,31,30,31,31,30,31,30,31],I=f%4===0&&f%100!==0||f%400===0,A=h===2&&I?29:S[h-1];if(p<1||p>A)return!1;if(g===24){if(y!==0||E!==0)return!1}else if(g>23)return!1;if(y>59||E>59)return!1;if(d&&d!=="Z"){let O=d.match(/^[+-](\d{2}):(\d{2})$/);if(O){let T=parseInt(O[1],10),M=parseInt(O[2],10);if(T>14||T===14&&M!==0||M>59)return!1}}return!0}};l();var Us=class{static isObject(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let r=Object.getPrototypeOf(e);return r===Object.prototype||r===null}static isParsable(e){if(typeof e!="string")return!1;try{return JSON.parse(e),!0}catch{return!1}}static isUnprototyped(e){return e===null||typeof e!="object"?!1:Object.getPrototypeOf(e)===null}static normalize(e){return this.cloneInternal(e,{stripPrototypes:!0})}static copy(e){return{...e}}static clone(e){return typeof structuredClone=="function"?structuredClone(e):this.cloneInternal(e)}static cloneReplace(e,r,n){return this.cloneInternal(e,{transform:i=>typeof i=="string"?i.replace(r,n):i})}static deepEqual(e,r,n=new WeakMap,i=0){if(i>1024)throw new Error("Maximum comparison depth exceeded");if(Object.is(e,r))return!0;if(typeof e!=typeof r||e===null||r===null||typeof e!="object")return!1;if(n.get(e)===r)return!0;if(n.set(e,r),ArrayBuffer.isView(e)&&ArrayBuffer.isView(r)){let c=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),a=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);if(c.byteLength!==a.byteLength)return!1;for(let u=0;u<c.byteLength;u++)if(c[u]!==a[u])return!1;return!0}if(e instanceof Date&&r instanceof Date)return e.getTime()===r.getTime();if(e instanceof Set&&r instanceof Set){if(e.size!==r.size)return!1;for(let c of e){let a=!1;for(let u of r)if(this.deepEqual(c,u,n,i+1)){a=!0;break}if(!a)return!1}return!0}if(e instanceof Map&&r instanceof Map){if(e.size!==r.size)return!1;for(let[c,a]of e){let u=!1;if(r.has(c))u=this.deepEqual(a,r.get(c),n,i+1);else for(let[d,f]of r)if(this.deepEqual(c,d,n,i+1)&&this.deepEqual(a,f,n,i+1)){u=!0;break}if(!u)return!1}return!0}if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return!1;for(let c=0;c<e.length;c++)if(!this.deepEqual(e[c],r[c],n,i+1))return!1;return!0}let o=Object.keys(e),s=Object.keys(r);if(o.length!==s.length)return!1;for(let c of o)if(!Object.prototype.hasOwnProperty.call(r,c)||!this.deepEqual(e[c],r[c],n,i+1))return!1;return!0}static deleteKeys(e,r){let n=new Set(r.map(o=>typeof o=="number"?o.toString():o)),i=o=>{if(Array.isArray(o))return o.map(s=>i(s));if(o&&typeof o=="object"){let s={};for(let c of Object.keys(o))n.has(c)||(s[c]=i(o[c]));return s}return o};return i(e)}static sanitize(e){let r=n=>{if(Array.isArray(n))return n.filter(i=>i!==void 0).map(i=>r(i));if(n&&typeof n=="object"){let i={};for(let[o,s]of Object.entries(n)){let c=r(s);c!==void 0&&(i[o]=c)}return i}return n};return r(e)}static cloneInternal(e,r={},n=new WeakMap,i=0){if(i>1024)throw new Error("Maximum clone depth exceeded");let o=r.transform?r.transform(e):e;if(o!==e||typeof e!="object"||e===null)return o;if(n.has(e))throw new Error("Cannot clone circular structure");if(Array.isArray(e)){let c=[];n.set(e,c);for(let a of e)c.push(this.cloneInternal(a,r,n,i+1));return c}if(ArrayBuffer.isView(e)){if(e instanceof DataView)return new DataView(e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));if(typeof e.slice=="function")return e.slice()}if(e instanceof Date)return new Date(e.getTime());let s=r.stripPrototypes?{}:Object.create(Object.getPrototypeOf(e));n.set(e,s);for(let c of Object.keys(e))s[c]=this.cloneInternal(e[c],r,n,i+1);return s}};l();var rr=class extends tt{constructor(e,r="BeaconError",n){super(e,r,n)}},lv=class extends tt{constructor(e,r="SingletonBeaconError",n){super(e,r,n)}},hv=class extends tt{constructor(e,r="AggregateBeaconError",n){super(e,r,n)}},pv=class extends tt{constructor(e,r="CASBeaconError",n){super(e,r,n)}},Fu=class extends tt{constructor(e,r="SMTBeaconError",n){super(e,r,n)}};l();l();l();l();l();l();l();l();l();l();l();l();l();l();l();var CR={bech32:"bcrt",pubKeyHash:111,scriptHash:196,wif:239};function Io(t){switch(t){case"bitcoin":return zr;case"testnet3":case"testnet4":case"signet":case"mutinynet":return Jy;case"regtest":return CR;default:throw new Error(`Unknown network "${t}"`)}}l();var ju=class{satsPerVbyte;constructor(e=5){if(e<0||!Number.isFinite(e))throw new Error(`Invalid satsPerVbyte: ${e}`);this.satsPerVbyte=e}async estimateFee(e){if(e<0||!Number.isFinite(e))throw new Error(`Invalid vsize: ${e}`);return BigInt(Math.ceil(e*this.satsPerVbyte))}};l();var T0="0000000000000000000000000000000000000000000000000000000000000000",_0="4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b";l();var B0;(function(t){t[t.hex=0]="hex",t[t.json=1]="json",t[t.jsonext=2]="jsonext",t[t.jsonextprev=3]="jsonextprev"})(B0||(B0={}));var I0=new ju(5);var MR=160,KR=155,$R=240,HR={p2pkh:$R,p2wpkh:KR,p2tr:MR},gv={p2pkh:34,p2wpkh:31,p2tr:43},mv={p2pkh:546,p2wpkh:294,p2tr:330};function wv(t,e){return HR[t]-gv[t]+gv[e]}function bv(t,e){let r=Yr(e).decode(t);if(r.type==="pkh")return"p2pkh";if(r.type==="wpkh")return"p2wpkh";if(r.type==="tr")return"p2tr";throw new rr(`Unsupported singleton beacon address type "${r.type}". Expected P2PKH, P2WPKH, or P2TR (taproot key-path).`,"UNSUPPORTED_BEACON_ADDRESS_TYPE",{address:t,kind:r.type})}function VR(t,e,r){return t==="p2pkh"?ki(e,r).address:t==="p2wpkh"?vs(e,r).address:Ss(e.slice(1,33),void 0,r).address}function xv(t,e,r){if(!r||r===t)return t;try{Yr(e).decode(r)}catch{throw new rr(`Invalid change address "${r}" for network "${e}".`,"INVALID_CHANGE_ADDRESS",{changeAddress:r,network:e})}return r}function Ev(t,e){try{return bv(t,e)}catch{return"p2tr"}}function vv(t){return Ye.encode(["RETURN",t])}var R0=546;function qR(t,e){if(t.status.block_height!==e.status.block_height)return t.status.block_height-e.status.block_height;let r=t.txid.localeCompare(e.txid);return r!==0?r:t.vout-e.vout}function FR(t,e){if(!t.length)throw new rr("No UTXOs found, please fund address!","UNFUNDED_BEACON_ADDRESS",{address:e});let r=t.filter(i=>i.status.confirmed===!0),n=r.filter(i=>i.value>R0);if(!n.length){let i=r.length===0?`all ${t.length} UTXO(s) are unconfirmed`:`all ${r.length} confirmed UTXO(s) are at or below the ${R0}-sat dust limit`;throw new rr(`No spendable UTXO at beacon address: ${i}.`,"NO_SPENDABLE_BEACON_UTXO",{address:e,total:t.length,confirmed:r.length,dustLimit:R0})}return[...n].sort(qR)[0]}async function Sv(t,e){let r=await e.rest.address.getUtxos(t),n=FR(r,t),i=await e.rest.transaction.getHex(n.txid);return{utxo:n,prevTxBytes:Ar(i)}}async function T7(t){let e=t.feeEstimator??I0,{utxo:r,prevTxBytes:n}=await Sv(t.beaconAddress,t.bitcoin),i=xv(t.beaconAddress,t.network,t.changeAddress),o=Je.encode(Yr(t.network).decode(t.beaconAddress)),s=Ev(i,t.network),c=await e.estimateFee(wv("p2tr",s));if(BigInt(r.value)<=c)throw new rr(`UTXO value (${r.value}) insufficient to cover fee (${c}).`,"INSUFFICIENT_FUNDS",{address:t.beaconAddress,valueSats:r.value,feeSats:c});let a=new _s({allowUnknownOutputs:!0});a.addInput({txid:r.txid,index:r.vout,nonWitnessUtxo:n,witnessUtxo:{amount:BigInt(r.value),script:o},tapInternalKey:t.internalPubkey});let u=BigInt(r.value)-c;return u>=BigInt(mv[s])&&a.addOutputAddress(i,u,t.network),a.addOutput({script:vv(t.signalBytes),amount:0n}),{tx:a,prevOutScripts:[o],prevOutValues:[BigInt(r.value)],beaconAddress:t.beaconAddress,changeAddress:i,utxo:r,feeSats:c,scriptKind:"p2tr"}}async function jR(t,e,r,n,i,o){let s=n.publicKey;if(r==="p2pkh"){let u=vo.ALL,d=t.preimageLegacy(e,i,u),f=n.sign(d,"ecdsa"),h=ut(f,new Uint8Array([u]));return t.updateInput(e,{partialSig:[[s,h]]},!0),t.finalize(),t.hex}if(r==="p2wpkh"){let u=Je.decode(i);if(u.type!=="wpkh")throw new rr(`Expected P2WPKH prev-output script, got "${u.type}".`,"PREVOUT_SCRIPT_MISMATCH",{kind:r,observedScriptType:u.type});let d=Je.encode({type:"pkh",hash:u.hash}),f=vo.ALL,h=t.preimageWitnessV0(e,d,f,o),p=n.sign(h,"ecdsa"),g=ut(p,new Uint8Array([f]));return t.updateInput(e,{partialSig:[[s,g]]},!0),t.finalize(),t.hex}let c=t.preimageWitnessV1(e,[i],vo.DEFAULT,[o]),a=n.sign(c,"bip341");return t.updateInput(e,{tapKeySig:a}),t.finalize(),t.hex}var Ro=class{service;constructor(e){this.service=e}async buildSignAndBroadcast(e,r,n,i){let o=i?.feeEstimator??I0,s=this.service.serviceEndpoint.replace("bitcoin:",""),{utxo:c,prevTxBytes:a}=await Sv(s,n),u=await this.buildSinglePartyTx({signalBytes:e,beaconAddress:s,utxo:c,prevTxBytes:a,signer:r,bitcoin:n,feeEstimator:o,changeAddress:i?.changeAddress}),d=await this.signSinglePartyTx(u,r);return this.broadcastRawTx(n,d)}async buildSinglePartyTx(e){let r=e.bitcoin.data,n=e.signer.publicKey,i=bv(e.beaconAddress,r),o=xv(e.beaconAddress,r,e.changeAddress),s=VR(i,n,r);if(s!==e.beaconAddress)throw new rr(`Signer pubkey produces ${i.toUpperCase()} address "${s}", but beacon address is "${e.beaconAddress}".`,"SIGNER_KEY_MISMATCH",{kind:i,address:e.beaconAddress,derivedAddress:s});let c=Ev(o,r),a=await e.feeEstimator.estimateFee(wv(i,c)),u=BigInt(e.utxo.value);if(u<=a)throw new rr(`UTXO value (${e.utxo.value}) insufficient to cover fee (${a}).`,"INSUFFICIENT_FUNDS",{address:e.beaconAddress,valueSats:e.utxo.value,feeSats:a});let d=new _s({allowUnknownOutputs:!0}),f;if(i==="p2pkh")f=ki(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes});else if(i==="p2wpkh")f=vs(n,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes,witnessUtxo:{amount:u,script:f}});else{let p=n.slice(1,33);f=Ss(p,void 0,r).script,d.addInput({txid:e.utxo.txid,index:e.utxo.vout,nonWitnessUtxo:e.prevTxBytes,witnessUtxo:{amount:u,script:f},tapInternalKey:p})}let h=u-a;return h>=BigInt(mv[c])&&d.addOutputAddress(o,h,r),d.addOutput({script:vv(e.signalBytes),amount:0n}),{tx:d,prevOutScripts:[f],prevOutValues:[u],beaconAddress:e.beaconAddress,changeAddress:o,utxo:e.utxo,feeSats:a,scriptKind:i}}async signSinglePartyTx(e,r){return jR(e.tx,0,e.scriptKind,r,e.prevOutScripts[0],e.prevOutValues[0])}async broadcastRawTx(e,r){return e.rest.transaction.send(r)}};l();var Al=class extends Ro{constructor(e){super({...e,type:"CASBeacon"})}processSignals(e,r){let n=new Array,i=new Array,o=this.service.id.split("#")[0];for(let s of e){let c=s.signalBytes,a=r.casMap.get(c);if(!a){i.push({kind:"NeedCASAnnouncement",announcementHash:c,beaconServiceId:this.service.id});continue}let u=a[o];if(!u)continue;let d=Zr(Is(u,"base64urlnopad"),"hex"),f=r.updateMap.get(d);if(!f){i.push({kind:"NeedSignedUpdate",updateHash:d,beaconServiceId:this.service.id});continue}n.push([f,s.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=this.service.id.split("#")[0],s=Gn(e),c={[o]:s},a=To(tr(c));return await this.buildSignAndBroadcast(a,r,n,i),i?.casPublish&&await i.casPublish(c),e}};l();l();var Tl=class extends Ro{constructor(e){super({...e,type:"SingletonBeacon"})}processSignals(e,r){let n=new Array,i=new Array;for(let o of e){let s=o.signalBytes,c=r.updateMap.get(s);if(!c){i.push({kind:"NeedSignedUpdate",updateHash:s,beaconServiceId:this.service.id});continue}n.push([c,o.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=To(tr(e));return await this.buildSignAndBroadcast(o,r,n,i),e}};l();l();l();var WR=new Uint8Array(32),U0=1n<<BigInt(256),Av=(()=>{let t=new Array(257),e=U0>>1n;for(let r=0;r<256;r++)t[r]=e,e>>=1n;return t[256]=0n,t})();l();l();l();function Wu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Yn(t,e=""){if(!Number.isSafeInteger(t)||t<0){let r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${t}`)}}function ve(t,e,r=""){let n=Wu(t),i=t?.length,o=e!==void 0;if(!n||o&&i!==e){let s=r&&`"${r}" `,c=o?` of length ${e}`:"",a=n?`length=${i}`:`type=${typeof t}`;throw new Error(s+"expected Uint8Array"+c+", got "+a)}return t}function _l(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Yn(t.outputLen),Yn(t.blockLen)}function Xc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function _v(t,e){ve(t,void 0,"digestInto() output");let r=e.outputLen;if(t.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Os(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Bl(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function xn(t,e){return t<<32-e|t>>>e}var Bv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",GR=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ds(t){if(ve(t),Bv)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=GR[t[r]];return e}var Ni={_0:48,_9:57,A:65,F:70,a:97,f:102};function Tv(t){if(t>=Ni._0&&t<=Ni._9)return t-Ni._0;if(t>=Ni.A&&t<=Ni.F)return t-(Ni.A-10);if(t>=Ni.a&&t<=Ni.f)return t-(Ni.a-10)}function ks(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Bv)return Uint8Array.fromHex(t);let e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=Tv(t.charCodeAt(o)),c=Tv(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function fr(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];ve(i),e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}function Iv(t,e={}){let r=(i,o)=>t(o).update(i).digest(),n=t(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.create=i=>t(i),Object.assign(r,e),Object.freeze(r)}function Ns(t=32){let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(t))}var Rv=t=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,t])});var D0=BigInt(0),O0=BigInt(1);function Gu(t,e=""){if(typeof t!="boolean"){let r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Uv(t){if(typeof t=="bigint"){if(!Il(t))throw new Error("positive bigint expected, got "+t)}else Yn(t);return t}function zu(t){let e=Uv(t).toString(16);return e.length&1?"0"+e:e}function Ov(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?D0:BigInt("0x"+t)}function Uo(t){return Ov(Ds(t))}function k0(t){return Ov(Ds(zR(ve(t)).reverse()))}function Rl(t,e){Yn(e),t=Uv(t);let r=ks(t.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function N0(t,e){return Rl(t,e).reverse()}function Qc(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function zR(t){return Uint8Array.from(t)}function Dv(t){return Uint8Array.from(t,(e,r)=>{let n=e.charCodeAt(0);if(e.length!==1||n>127)throw new Error(`string contains non-ASCII character "${t[r]}" with code ${n} at position ${r}`);return n})}var Il=t=>typeof t=="bigint"&&D0<=t;function YR(t,e,r){return Il(t)&&Il(e)&&Il(r)&&e<=t&&t<r}function kv(t,e,r,n){if(!YR(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function C0(t){let e;for(e=0;t>D0;t>>=O0,e+=1);return e}var Yu=t=>(O0<<BigInt(t))-O0;function Nv(t,e,r){if(Yn(t,"hashLen"),Yn(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");let n=E=>new Uint8Array(E),i=Uint8Array.of(),o=Uint8Array.of(0),s=Uint8Array.of(1),c=1e3,a=n(t),u=n(t),d=0,f=()=>{a.fill(1),u.fill(0),d=0},h=(...E)=>r(u,fr(a,...E)),p=(E=i)=>{u=h(o,E),a=h(),E.length!==0&&(u=h(s,E),a=h())},g=()=>{if(d++>=c)throw new Error("drbg: tried max amount of iterations");let E=0,S=[];for(;E<e;){a=h();let I=a.slice();S.push(I),E+=a.length}return fr(...S)};return(E,S)=>{f(),p(E);let I;for(;!(I=S(g()));)p();return f(),I}}function Ju(t,e={},r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(o,s,c){let a=t[o];if(c&&a===void 0)return;let u=typeof a;if(u!==s||a===null)throw new Error(`param "${o}" is invalid: expected ${s}, got ${u}`)}let i=(o,s)=>Object.entries(o).forEach(([c,a])=>n(c,a,s));i(e,!1),i(r,!0)}function L0(t){let e=new WeakMap;return(r,...n)=>{let i=e.get(r);if(i!==void 0)return i;let o=t(r,...n);return e.set(r,o),o}}function P0(t){return t.length===32}function Ul(t){if(!P0(t))throw new RangeError(`Invalid hash: expected ${32} bytes, got ${t.length}`)}function dt(...t){return Oe(ut(...t))}function Zu(t){Ul(t);let e=0n;for(let r of t)e=e<<8n|BigInt(r);return e}function M0(t){let e=new Uint8Array(32),r=t;for(let n=31;n>=0;n--)e[n]=Number(r&0xffn),r>>=8n;if(r!==0n)throw new RangeError("Value exceeds 256 bits");return e}function K0(t){Ul(t);let e="";for(let r of t)e+=r.toString(16).padStart(2,"0");return e}function $0(t,e){return!P0(t)||!P0(e)?!1:Qc(t,e)}function ea(t){return Ul(t),$c.encode(t)}function Jn(t){let e=$c.decode(t);if(e.length!==32)throw new RangeError(`Invalid base64url hash: expected ${32} decoded bytes, got ${e.length}`);return e}l();l();var Cv;(function(t){t[t.Pending=0]="Pending",t[t.Valid=1]="Valid",t[t.Invalid=2]="Invalid"})(Cv||(Cv={}));l();l();var Oo=256;function ta(t,e){return Number(t>>BigInt(e)&1n)}var Lv=(()=>{let t=new Array(Oo+1),e=new Uint8Array(32);for(let r=0;r<=Oo;r++)e=dt(e,e),t[r]=e;return t})();function Ol(t,e){if(t.length===0)return Lv[e];if(e===0)return t[0].leaf;let r=Oo-e,n=[],i=[];for(let o of t)(ta(o.index,r)===0?n:i).push(o);return dt(Ol(n,e-1),Ol(i,e-1))}function Pv(t){return Ol(t,Oo)}function Mv(t,e){let r=0n,n=[];for(let i=1;i<=Oo;i++){let o=Oo-i,s=[];for(let c of t){if(c.index===e)continue;let a=!0;for(let u=0;u<o;u++)if(ta(c.index,u)!==ta(e,u)){a=!1;break}a&&ta(c.index,o)!==ta(e,o)&&s.push(c)}s.length===0?r|=1n<<BigInt(o):n.push(Ol(s,i-1))}return{collapsed:r,hashes:n}}function Kv(t,e,r,n,i){let o=n,s=0;for(let c=0;c<Oo;c++){let a=Oo-1-c,u;if((t>>BigInt(a)&1n)===1n)u=Lv[c];else{if(s>=e.length)return!1;u=e[s++]}o=ta(r,a)===1?dt(u,o):dt(o,u)}return s===e.length&&$0(o,i)}l();var JR=new TextEncoder;function Dl(t){return Zu(dt(JR.encode(t)))}function $v(t,e){return dt(dt(t),dt(e))}function Hv(t){return dt(dt(t))}l();function Vv(t,e,r){let n={id:ea(t),collapsed:ea(M0(e.collapsed)),hashes:e.hashes.map(i=>ea(i))};return r?.nonce&&(n.nonce=ea(r.nonce)),r?.updateId&&(n.updateId=ea(r.updateId)),n}function ZR(t){let e={rootHash:Jn(t.id),collapsed:Zu(Jn(t.collapsed)),hashes:t.hashes.map(r=>Jn(r))};return t.nonce&&(e.nonce=Jn(t.nonce)),t.updateId&&(e.updateId=Jn(t.updateId)),e}function qv(t,e,r){let{rootHash:n,collapsed:i,hashes:o}=ZR(t);return Kv(i,o,e,r,n)}l();var kl=class{#e=new Map;#t=new Map;#n=null;#r=null;constructor(e=!0){}addEntries(e){for(let r of e){let n=Dl(r.did);if(this.#e.has(n))throw new RangeError(`Duplicate DID index for: ${r.did}`);this.#e.set(n,r),this.#t.set(r.did,n)}this.#n=null,this.#r=null}finalize(){let e=[];for(let[r,n]of this.#e){let i=n.signedUpdate!==void 0?$v(n.nonce,n.signedUpdate):Hv(n.nonce);e.push({index:r,leaf:i})}this.#n=e,this.#r=Pv(e)}get rootHash(){if(this.#r===null)throw new Error("Tree not finalized: call finalize() first");return this.#r}proof(e){let r=this.#t.get(e);if(r===void 0)throw new RangeError(`DID not in tree: ${e}`);if(this.#n===null||this.#r===null)throw new Error("Tree not finalized: call finalize() first");let n=this.#e.get(r),i=Mv(this.#n,r),o=n.signedUpdate!==void 0?dt(n.signedUpdate):void 0;return Vv(this.#r,i,{nonce:n.nonce,updateId:o})}reset(){this.#n=null,this.#r=null}};var Nl=class extends Ro{constructor(e){super({...e,type:"SMTBeacon"})}processSignals(e,r){let n=new Array,i=new Array,o=this.service.id.split("#")[0];for(let s of e){let c=r.smtMap.get(s.signalBytes);if(!c){i.push({kind:"NeedSMTProof",smtRootHash:s.signalBytes,beaconServiceId:this.service.id});continue}if(!c.nonce)throw new Fu("SMT proof missing required nonce field.","INVALID_SMT_PROOF",{smtProof:c,did:o});let a=Dl(o),u=Jn(c.nonce),d=c.updateId?dt(dt(u),Jn(c.updateId)):dt(dt(u));if(!qv(c,a,d))throw new Fu("SMT proof verification failed.","INVALID_SMT_PROOF",{smtProof:c,did:o});if(!c.updateId)continue;let h=K0(Jn(c.updateId)),p=r.updateMap.get(h);if(!p){i.push({kind:"NeedSignedUpdate",updateHash:h,beaconServiceId:this.service.id});continue}n.push([p,s.blockMetadata])}return{updates:n,needs:i}}async broadcastSignal(e,r,n,i){let o=this.service.id.split("#")[0],s=new TextEncoder().encode(tr(e)),c=Tr(32),a=new kl;return a.addEntries([{did:o,nonce:c,signedUpdate:s}]),a.finalize(),await this.buildSignAndBroadcast(a.rootHash,r,n,i),e}};var ra=class{static establish(e){switch(e.type){case"SingletonBeacon":return new Tl(e);case"CASBeacon":return new Al(e);case"SMTBeacon":return new Nl(e);default:throw new tt("Invalid Beacon Type","INVALID_BEACON_ERROR",e)}}};l();l();l();l();l();l();var Li;(function(t){t.authentication="authentication",t.assertionMethod="assertionMethod",t.keyAgreement="keyAgreement",t.capabilityInvocation="capabilityInvocation",t.capabilityDelegation="capabilityDelegation"})(Li||(Li={}));l();var ft={"@context":"https://w3id.org/did-resolution/v1",didResolutionMetadata:{},didDocument:null,didDocumentMetadata:{}};l();var me=class t{constructor({method:e,id:r,path:n,query:i,fragment:o,params:s}){this.uri=`did:${e}:${r}`,this.method=e,this.id=r,this.path=n,this.query=i,this.fragment=o,this.params=s}static parse(e){if(!e)return null;let r=t.DID_URI_PATTERN.exec(e);if(!r||!r.groups)return null;let{method:n,id:i,path:o,query:s,fragment:c}=r.groups,a={uri:`did:${n}:${i}`,method:n,id:i};if(o&&(a.path=o),s&&(a.query=s.slice(1)),c&&(a.fragment=c.slice(1)),s){let u={},d=s.slice(1).split("&");for(let f of d){let[h,p]=f.split("=");u[h]=p}a.params=u}return a}};me.METHOD_PATTERN="([a-z0-9]+)";me.PCT_ENCODED_PATTERN="(?:%[0-9a-fA-F]{2})";me.ID_CHAR_PATTERN=`(?:[a-zA-Z0-9._-]|${me.PCT_ENCODED_PATTERN})`;me.METHOD_ID_PATTERN=`((?:${me.ID_CHAR_PATTERN}*:)*(${me.ID_CHAR_PATTERN}+))`;me.PATH_PATTERN="(/[^#?]*)?";me.QUERY_PATTERN="([?][^#]*)?";me.FRAGMENT_PATTERN="(#.*)?";me.DID_URI_PATTERN=new RegExp(`^did:(?<method>${me.METHOD_PATTERN}):(?<id>${me.METHOD_ID_PATTERN})(?<path>${me.PATH_PATTERN})(?<query>${me.QUERY_PATTERN})(?<fragment>${me.FRAGMENT_PATTERN})$`);l();var re=class t extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,this.name="DidError",Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,t)}},ie;(function(t){t.InvalidDid="invalidDid",t.MethodNotSupported="methodNotSupported",t.InternalError="internalError",t.InvalidDidDocument="invalidDidDocument",t.InvalidDidDocumentLength="invalidDidDocumentLength",t.InvalidDidUrl="invalidDidUrl",t.InvalidPreviousDidProof="invalidPreviousDidProof",t.InvalidPublicKey="invalidPublicKey",t.InvalidPublicKeyLength="invalidPublicKeyLength",t.InvalidPublicKeyType="invalidPublicKeyType",t.InvalidSignature="invalidSignature",t.NotFound="notFound",t.RepresentationNotSupported="representationNotSupported",t.UnsupportedPublicKeyType="unsupportedPublicKeyType"})(ie||(ie={}));l();l();l();l();l();var e6=Pn(jv(),1);l();l();l();l();var EH=new Uint8Array(0);function Wv(t,e){if(t===e)return!0;if(t.byteLength!==e.byteLength)return!1;for(let r=0;r<t.byteLength;r++)if(t[r]!==e[r])return!1;return!0}function na(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}l();function r6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,E=0,S=0,I=g.length;S!==I&&g[S]===0;)S++,y++;for(var A=(I-S)*d+1>>>0,O=new Uint8Array(A);S!==I;){for(var T=g[S],M=0,q=A-1;(T!==0||M<E)&&q!==-1;q--,M++)T+=256*O[q]>>>0,O[q]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");E=M,S++}for(var j=A-E;j!==A&&O[j]===0;)j++;for(var $=a.repeat(y);j<A;++j)$+=t.charAt(O[j]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var E=0,S=0;g[y]===a;)E++,y++;for(var I=(g.length-y)*u+1>>>0,A=new Uint8Array(I);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=I-1;(O!==0||T<S)&&M!==-1;M--,T++)O+=c*A[M]>>>0,A[M]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=T,y++}if(g[y]!==" "){for(var q=I-S;q!==I&&A[q]===0;)q++;for(var j=new Uint8Array(E+(I-q)),$=E;q!==I;)j[$++]=A[q++];return j}}}function p(g){var y=h(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var n6=r6,i6=n6,Gv=i6;var F0=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},j0=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return zv(this,e)}},W0=class{decoders;constructor(e){this.decoders=e}or(e){return zv(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function zv(t,e){return new W0({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var G0=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new F0(e,r,n),this.decoder=new j0(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function Yv({name:t,prefix:e,encode:r,decode:n}){return new G0(t,e,r,n)}function z0({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=Gv(r,t);return Yv({prefix:e,name:t,encode:n,decode:o=>na(i(o))})}function o6(t,e,r,n){let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),c=0,a=0,u=0;for(let d=0;d<o;++d){let f=i[t[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s}function s6(t,e,r){let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,o+=e[i&c>>s];if(s!==0&&(o+=e[i&c<<r-s]),n)for(;o.length*r&7;)o+="=";return o}function nr({name:t,prefix:e,bitsPerChar:r,alphabet:n}){return Yv({prefix:e,name:t,encode(i){return s6(i,n,r)},decode(i){return o6(i,n,r,t)}})}var Xu=nr({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),UH=nr({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),OH=nr({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),DH=nr({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),kH=nr({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),NH=nr({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),CH=nr({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),LH=nr({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Y0=nr({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});l();var lr=z0({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$H=z0({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var FH=nr({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),jH=nr({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zn=nr({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),WH=nr({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});l();function Jv(t){return t.byteOffset!==0||t.byteLength!==t.buffer.byteLength}function Zv(t){return typeof t!="object"||t===null?!1:typeof t[Symbol.asyncIterator]=="function"}function ia(t){let r=Object.prototype.toString.call(t).match(/\s([a-zA-Z0-9]+)/),[n,i]=r;return i}var Qu=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Xv=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(o){r[o]=t[o]&&function(s){return new Promise(function(c,a){s=t[o](s),i(c,a,s.done,s.value)})}}function i(o,s,c,a){Promise.resolve(a).then(function(u){o({value:u,done:c})},s)}},Ll=new TextEncoder,Cs=new TextDecoder,ne=class t{constructor(e,r){this.data=e,this.format=r}static arrayBuffer(e){return new t(e,"ArrayBuffer")}static asyncIterable(e){if(!Zv(e))throw new TypeError("Input must be of type AsyncIterable.");return new t(e,"AsyncIterable")}static base32Z(e){return new t(e,"Base32Z")}static base58Btc(e){return new t(e,"Base58Btc")}static base64Url(e){return new t(e,"Base64Url")}static bufferSource(e){return new t(e,"BufferSource")}static hex(e){if(typeof e!="string")throw new TypeError("Hex input must be a string.");if(e.length%2!==0)throw new TypeError("Hex input must have an even number of characters.");return new t(e,"Hex")}static multibase(e){return new t(e,"Multibase")}static object(e){return new t(e,"Object")}static string(e){return new t(e,"String")}static uint8Array(e){return new t(e,"Uint8Array")}toArrayBuffer(){switch(this.format){case"Base58Btc":return lr.baseDecode(this.data).buffer;case"Base64Url":return Zn.baseDecode(this.data).buffer;case"BufferSource":{if(ia(this.data)==="ArrayBuffer")return this.data;if(ArrayBuffer.isView(this.data))return Jv(this.data)?this.data.buffer.slice(this.data.byteOffset,this.data.byteOffset+this.data.byteLength):this.data.buffer;throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":return this.toUint8Array().buffer;case"String":return this.toUint8Array().buffer;case"Uint8Array":return this.data.buffer;default:throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`)}}toArrayBufferAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":return yield(yield this.toBlobAsync()).arrayBuffer();default:throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`)}})}toBase32Z(){switch(this.format){case"Uint8Array":return Y0.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`)}}toBase58Btc(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return lr.baseEncode(e)}case"Multibase":return this.data.substring(1);case"Uint8Array":return lr.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`)}}toBase64Url(){switch(this.format){case"ArrayBuffer":{let e=new Uint8Array(this.data);return Zn.baseEncode(e)}case"BufferSource":{let e=this.toUint8Array();return Zn.baseEncode(e)}case"Object":{let e=JSON.stringify(this.data),r=Ll.encode(e);return Zn.baseEncode(r)}case"String":{let e=Ll.encode(this.data);return Zn.baseEncode(e)}case"Uint8Array":return Zn.baseEncode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`)}}toBlobAsync(){return Qu(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a=[];try{for(var o=!0,s=Xv(this.data),c;c=yield s.next(),e=c.done,!e;o=!0){i=c.value,o=!1;let d=i;a.push(d)}}catch(d){r={error:d}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return new Blob(a)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`)}})}toHex(){let e=Array.from({length:256},(r,n)=>n.toString(16).padStart(2,"0"));switch(this.format){case"ArrayBuffer":{let r=this.toUint8Array();return t.uint8Array(r).toHex()}case"Base64Url":{let r=this.toUint8Array();return t.uint8Array(r).toHex()}case"Uint8Array":{let r="";for(let n=0;n<this.data.length;n++)r+=e[this.data[n]];return r}default:throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`)}}toMultibase(){switch(this.format){case"Base58Btc":return`z${this.data}`;default:throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`)}}toObject(){switch(this.format){case"Base64Url":{let e=Zn.baseDecode(this.data),r=Cs.decode(e);return JSON.parse(r)}case"String":return JSON.parse(this.data);case"Uint8Array":{let e=Cs.decode(this.data);return JSON.parse(e)}default:throw new TypeError(`Conversion from ${this.format} to Object is not supported.`)}}toObjectAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toStringAsync();return JSON.parse(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`)}})}toString(){switch(this.format){case"ArrayBuffer":return Cs.decode(this.data);case"Base64Url":{let e=Zn.baseDecode(this.data);return Cs.decode(e)}case"Object":return JSON.stringify(this.data);case"Uint8Array":return Cs.decode(this.data);default:throw new TypeError(`Conversion from ${this.format} to String is not supported.`)}}toStringAsync(){return Qu(this,void 0,void 0,function*(){var e,r,n,i;switch(this.format){case"AsyncIterable":{let a="";try{for(var o=!0,s=Xv(this.data),c;c=yield s.next(),e=c.done,!e;o=!0){i=c.value,o=!1;let u=i;typeof u=="string"?a+=u:a+=Cs.decode(u,{stream:!0})}}catch(u){r={error:u}}finally{try{!o&&!e&&(n=s.return)&&(yield n.call(s))}finally{if(r)throw r.error}}return a+=Cs.decode(void 0,{stream:!1}),a}default:throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`)}})}toUint8Array(){switch(this.format){case"ArrayBuffer":return new Uint8Array(this.data);case"Base32Z":return Y0.baseDecode(this.data);case"Base58Btc":return lr.baseDecode(this.data);case"Base64Url":return Zn.baseDecode(this.data);case"BufferSource":{let e=ia(this.data);if(e==="Uint8Array")return this.data;if(e==="ArrayBuffer")return new Uint8Array(this.data);if(ArrayBuffer.isView(this.data))return new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength);throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`)}case"Hex":{let e=new Uint8Array(this.data.length/2);for(let r=0;r<this.data.length;r+=2){let n=parseInt(this.data.substring(r,r+2),16);if(isNaN(n))throw new TypeError("Input is not a valid hexadecimal string.");e[r/2]=n}return e}case"Object":{let e=JSON.stringify(this.data);return Ll.encode(e)}case"String":return Ll.encode(this.data);default:throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`)}}toUint8ArrayAsync(){return Qu(this,void 0,void 0,function*(){switch(this.format){case"AsyncIterable":{let e=yield this.toArrayBufferAsync();return new Uint8Array(e)}default:throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`)}})}};l();var ed;(function(t){t.Debug="debug",t.Silent="silent"})(ed||(ed={}));var J0=class{constructor(){this.logLevel=ed.Silent}setLogLevel(e){this.logLevel=e}log(e){this.info(e)}info(e){this.logLevel!==ed.Silent&&console.info(e)}error(e){this.logLevel!==ed.Silent&&console.error(e)}},c6=new J0;typeof window<"u"&&(window.web5logger=c6);l();l();l();l();var Pi={};Sf(Pi,{decode:()=>oa,encodeTo:()=>Ls,encodingLength:()=>Ps});l();l();var a6=t1,Qv=128,u6=127,d6=~u6,f6=Math.pow(2,31);function t1(t,e,r){e=e||[],r=r||0;for(var n=r;t>=f6;)e[r++]=t&255|Qv,t/=128;for(;t&d6;)e[r++]=t&255|Qv,t>>>=7;return e[r]=t|0,t1.bytes=r-n+1,e}var l6=Z0,h6=128,e1=127;function Z0(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw Z0.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&e1)<<i:(s&e1)*Math.pow(2,i),i+=7}while(s>=h6);return Z0.bytes=o-n,r}var p6=Math.pow(2,7),y6=Math.pow(2,14),g6=Math.pow(2,21),m6=Math.pow(2,28),w6=Math.pow(2,35),b6=Math.pow(2,42),x6=Math.pow(2,49),E6=Math.pow(2,56),v6=Math.pow(2,63),S6=function(t){return t<p6?1:t<y6?2:t<g6?3:t<m6?4:t<w6?5:t<b6?6:t<x6?7:t<E6?8:t<v6?9:10},A6={encode:a6,decode:l6,encodingLength:S6},T6=A6,td=T6;function oa(t,e=0){return[td.decode(t,e),td.decode.bytes]}function Ls(t,e,r=0){return td.encode(t,e,r),e}function Ps(t){return td.encodingLength(t)}function X0(t,e){let r=e.byteLength,n=Ps(t),i=n+Ps(r),o=new Uint8Array(i+r);return Ls(t,o,0),Ls(r,o,n),o.set(e,i),new sa(t,r,e,o)}function r1(t){let e=na(t),[r,n]=oa(e),[i,o]=oa(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new sa(r,i,s,e)}function n1(t,e){if(t===e)return!0;{let r=e;return t.code===r.code&&t.size===r.size&&r.bytes instanceof Uint8Array&&Wv(t.bytes,r.bytes)}}var sa=class{code;size;digest;bytes;constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();function i1(t,e){let{bytes:r,version:n}=t;switch(n){case 0:return B6(r,eg(t),e??lr.encoder);default:return I6(r,eg(t),e??Xu.encoder)}}var o1=new WeakMap;function eg(t){let e=o1.get(t);if(e==null){let r=new Map;return o1.set(t,r),r}return e}var tg=class t{code;version;multihash;bytes;"/";constructor(e,r,n,i){this.code=r,this.version=e,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:r}=this;if(e!==rd)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(r.code!==R6)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return t.createV0(r)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:r}=this.multihash,n=X0(e,r);return t.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return t.equals(this,e)}static equals(e,r){let n=r;return n!=null&&e.code===n.code&&e.version===n.version&&n1(e.multihash,n.multihash)}toString(e){return i1(this,e)}toJSON(){return{"/":i1(this)}}link(){return this}[Symbol.toStringTag]="CID";[Symbol.for("nodejs.util.inspect.custom")](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let r=e;if(r instanceof t)return r;if(r["/"]!=null&&r["/"]===r.bytes||r.asCID===r){let{version:n,code:i,multihash:o,bytes:s}=r;return new t(n,i,o,s??s1(n,i,o.bytes))}else if(r[U6]===!0){let{version:n,multihash:i,code:o}=r,s=r1(i);return t.create(n,o,s)}else return null}static create(e,r,n){if(typeof r!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(r!==rd)throw new Error(`Version 0 CID must use dag-pb (code: ${rd}) block encoding`);return new t(e,r,n,n.bytes)}case 1:{let i=s1(e,r,n.bytes);return new t(e,r,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return t.create(0,rd,e)}static createV1(e,r){return t.create(1,e,r)}static decode(e){let[r,n]=t.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return r}static decodeFirst(e){let r=t.inspectBytes(e),n=r.size-r.multihashSize,i=na(e.subarray(n,n+r.multihashSize));if(i.byteLength!==r.multihashSize)throw new Error("Incorrect length");let o=i.subarray(r.multihashSize-r.digestSize),s=new sa(r.multihashCode,r.digestSize,o,i);return[r.version===0?t.createV0(s):t.createV1(r.codec,s),e.subarray(r.size)]}static inspectBytes(e){let r=0,n=()=>{let[f,h]=oa(e.subarray(r));return r+=h,f},i=n(),o=rd;if(i===18?(i=0,r=0):o=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let s=r,c=n(),a=n(),u=r+a,d=u-s;return{version:i,codec:o,multihashCode:c,digestSize:a,multihashSize:d,size:u}}static parse(e,r){let[n,i]=_6(e,r),o=t.decode(i);if(o.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return eg(o).set(n,e),o}};function _6(t,e){switch(t[0]){case"Q":{let r=e??lr;return[lr.prefix,r.decode(`${lr.prefix}${t}`)]}case lr.prefix:{let r=e??lr;return[lr.prefix,r.decode(t)]}case Xu.prefix:{let r=e??Xu;return[Xu.prefix,r.decode(t)]}default:{if(e==null)throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");return[t[0],e.decode(t)]}}}function B6(t,e,r){let{prefix:n}=r;if(n!==lr.prefix)throw Error(`Cannot string encode V0 in ${r.name} encoding`);let i=e.get(n);if(i==null){let o=r.encode(t).slice(1);return e.set(n,o),o}else return i}function I6(t,e,r){let{prefix:n}=r,i=e.get(n);if(i==null){let o=r.encode(t);return e.set(n,o),o}else return i}var rd=112,R6=18;function s1(t,e,r){let n=Ps(t),i=n+Ps(e),o=new Uint8Array(i+r.byteLength);return Ls(t,o,0),Ls(e,o,n),o.set(r,i),o}var U6=Symbol.for("@ipld/js-cid/CID");l();l();l();l();l();l();var zt=class t{static addPrefix(e){var r;let{code:n,data:i,name:o}=e;if(!(o?!n:n))throw new Error("Either 'name' or 'code' must be defined, but not both.");if(n=t.codeToName.has(n)?n:t.nameToCode.get(o),n===void 0)throw new Error(`Unsupported multicodec: ${(r=e.name)!==null&&r!==void 0?r:e.code}`);let s=Pi.encodingLength(n),c=new Uint8Array(s+i.byteLength);return c.set(i,s),Pi.encodeTo(n,c),c}static getCodeFromData(e){let{prefixedData:r}=e,[n,i]=Pi.decode(r);return n}static getCodeFromName(e){let{name:r}=e,n=t.nameToCode.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static getNameFromCode(e){let{code:r}=e,n=t.codeToName.get(r);if(n===void 0)throw new Error(`Unsupported multicodec: ${r}`);return n}static registerCodec(e){t.codeToName.set(e.code,e.name),t.nameToCode.set(e.name,e.code)}static removePrefix(e){let{prefixedData:r}=e,[n,i]=Pi.decode(r),o=t.codeToName.get(n);if(o===void 0)throw new Error(`Unsupported multicodec: ${n}`);return{code:n,data:r.slice(i),name:o}}};zt.codeToName=new Map;zt.nameToCode=new Map;zt.registerCodec({code:237,name:"ed25519-pub"});zt.registerCodec({code:4864,name:"ed25519-priv"});zt.registerCodec({code:236,name:"x25519-pub"});zt.registerCodec({code:4866,name:"x25519-priv"});zt.registerCodec({code:231,name:"secp256k1-pub"});zt.registerCodec({code:4865,name:"secp256k1-priv"});l();function rg(t){Object.keys(t).forEach(e=>{t[e]===void 0?delete t[e]:typeof t[e]=="object"&&rg(t[e])})}l();var PU=Pn(zg(),1),Xs=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})};var dh=class{constructor(){this.store=new Map}clear(){return Xs(this,void 0,void 0,function*(){this.store.clear()})}close(){return Xs(this,void 0,void 0,function*(){})}delete(e){return Xs(this,void 0,void 0,function*(){return this.store.delete(e)})}get(e){return Xs(this,void 0,void 0,function*(){return this.store.get(e)})}has(e){return Xs(this,void 0,void 0,function*(){return this.store.has(e)})}list(){return Xs(this,void 0,void 0,function*(){return Array.from(this.store.values())})}set(e,r){return Xs(this,void 0,void 0,function*(){this.store.set(e,r)})}};l();l();var ek=Pn(sw(),1);var tk=Pn(sw(),1);l();l();l();l();l();function rk(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function cw(t,...e){if(!rk(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function aw(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function hT(t,e){cw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var Da=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;var qh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),_n=(t,e)=>t<<32-e|t>>>e;var wj=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function nk(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function uw(t){return typeof t=="string"&&(t=nk(t)),cw(t),t}var Vh=class{clone(){return this._cloneInto()}},bj={}.toString;function pT(t){let e=n=>t().update(uw(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function yT(t=32){if(Da&&typeof Da.getRandomValues=="function")return Da.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function ik(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}var gT=(t,e,r)=>t&e^~t&r,mT=(t,e,r)=>t&e^t&r^e&r,Fh=class extends Vh{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=qh(this.buffer)}update(e){aw(this);let{view:r,buffer:n,blockLen:i}=this;e=uw(e);let o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=qh(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){aw(this),hT(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;ik(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=qh(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.length=i,e.pos=c,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var ok=new Uint32Array([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]),Fo=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),jo=new Uint32Array(64),dw=class extends Fh{constructor(){super(64,32,8,!1),this.A=Fo[0]|0,this.B=Fo[1]|0,this.C=Fo[2]|0,this.D=Fo[3]|0,this.E=Fo[4]|0,this.F=Fo[5]|0,this.G=Fo[6]|0,this.H=Fo[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)jo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=jo[f-15],p=jo[f-2],g=_n(h,7)^_n(h,18)^h>>>3,y=_n(p,17)^_n(p,19)^p>>>10;jo[f]=y+jo[f-7]+g+jo[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=_n(c,6)^_n(c,11)^_n(c,25),p=d+h+gT(c,a,u)+ok[f]+jo[f]|0,y=(_n(n,2)^_n(n,13)^_n(n,22))+mT(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){jo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Wo=pT(()=>new dw);var sk=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},ka=class{static digest(e){return sk(this,arguments,void 0,function*({data:r}){return Wo(r)})}};l();var ci=class{};var ck=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},jh=class extends ci{digest(e){return ck(this,arguments,void 0,function*({algorithm:r,data:n}){switch(r){case"SHA-256":return yield ka.digest({data:n})}})}};l();l();l();l();l();l();function wT(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}function ak(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function fw(t,...e){if(!ak(t))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}function bT(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");wT(t.outputLen),wT(t.blockLen)}function Na(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function xT(t,e){fw(t);let r=e.outputLen;if(t.length<r)throw new Error(`digestInto() expects output buffer of length at least ${r}`)}l();l();var Wh=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ET(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Gh=t=>new DataView(t.buffer,t.byteOffset,t.byteLength),Bn=(t,e)=>t<<32-e|t>>>e,uk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!uk)throw new Error("Non little-endian hardware is not supported");function lw(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function Cd(t){if(typeof t=="string"&&(t=lw(t)),!ET(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}function zh(...t){let e=0;for(let n=0;n<t.length;n++){let i=t[n];if(!ET(i))throw new Error("Uint8Array expected");e+=i.length}let r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}return r}var Ca=class{clone(){return this._cloneInto()}},Fj={}.toString;function Yh(t){let e=n=>t().update(Cd(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Ld(t=32){if(Wh&&typeof Wh.getRandomValues=="function")return Wh.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}function dk(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);let i=BigInt(32),o=BigInt(4294967295),s=Number(r>>i&o),c=Number(r&o),a=n?4:0,u=n?0:4;t.setUint32(e+a,s,n),t.setUint32(e+u,c,n)}var La=class extends Ca{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Gh(this.buffer)}update(e){Na(this);let{view:r,buffer:n,blockLen:i}=this;e=Cd(e);let o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Gh(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Na(this),xT(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,this.buffer.subarray(s).fill(0),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;dk(n,i-8,BigInt(this.length*8),o),this.process(n,0);let c=Gh(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.length=i,e.pos=c,e.finished=o,e.destroyed=s,i%r&&e.buffer.set(n),e}};var fk=(t,e,r)=>t&e^~t&r,lk=(t,e,r)=>t&e^t&r^e&r,hk=new Uint32Array([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]),Go=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),zo=new Uint32Array(64),hw=class extends La{constructor(){super(64,32,8,!1),this.A=Go[0]|0,this.B=Go[1]|0,this.C=Go[2]|0,this.D=Go[3]|0,this.E=Go[4]|0,this.F=Go[5]|0,this.G=Go[6]|0,this.H=Go[7]|0}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)zo[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=zo[f-15],p=zo[f-2],g=Bn(h,7)^Bn(h,18)^h>>>3,y=Bn(p,17)^Bn(p,19)^p>>>10;zo[f]=y+zo[f-7]+g+zo[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=Bn(c,6)^Bn(c,11)^Bn(c,25),p=d+h+fk(c,a,u)+hk[f]+zo[f]|0,y=(Bn(n,2)^Bn(n,13)^Bn(n,22))+lk(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){zo.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}};var Jh=Yh(()=>new hw);l();var Xh={};Sf(Xh,{bitGet:()=>xk,bitLen:()=>bk,bitMask:()=>Pd,bitSet:()=>Ek,bytesToHex:()=>Ji,bytesToNumberBE:()=>Zi,bytesToNumberLE:()=>Rn,concatBytes:()=>Qi,createHmacDrbg:()=>gw,ensureBytes:()=>Fe,equalBytes:()=>mk,hexToBytes:()=>dc,hexToNumber:()=>yw,isBytes:()=>In,numberToBytesBE:()=>pr,numberToBytesLE:()=>Xi,numberToHexUnpadded:()=>TT,numberToVarBytesBE:()=>gk,utf8ToBytes:()=>wk,validateObject:()=>rn});l();var AT=BigInt(0),Zh=BigInt(1),pk=BigInt(2);function In(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var yk=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ji(t){if(!In(t))throw new Error("Uint8Array expected");let e="";for(let r=0;r<t.length;r++)e+=yk[t[r]];return e}function TT(t){let e=t.toString(16);return e.length&1?`0${e}`:e}function yw(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return BigInt(t===""?"0":`0x${t}`)}var Yi={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function vT(t){if(t>=Yi._0&&t<=Yi._9)return t-Yi._0;if(t>=Yi._A&&t<=Yi._F)return t-(Yi._A-10);if(t>=Yi._a&&t<=Yi._f)return t-(Yi._a-10)}function dc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,r=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(r);for(let i=0,o=0;i<r;i++,o+=2){let s=vT(t.charCodeAt(o)),c=vT(t.charCodeAt(o+1));if(s===void 0||c===void 0){let a=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+o)}n[i]=s*16+c}return n}function Zi(t){return yw(Ji(t))}function Rn(t){if(!In(t))throw new Error("Uint8Array expected");return yw(Ji(Uint8Array.from(t).reverse()))}function pr(t,e){return dc(t.toString(16).padStart(e*2,"0"))}function Xi(t,e){return pr(t,e).reverse()}function gk(t){return dc(TT(t))}function Fe(t,e,r){let n;if(typeof e=="string")try{n=dc(e)}catch(o){throw new Error(`${t} must be valid hex string, got "${e}". Cause: ${o}`)}else if(In(e))n=Uint8Array.from(e);else throw new Error(`${t} must be hex string or Uint8Array`);let i=n.length;if(typeof r=="number"&&i!==r)throw new Error(`${t} expected ${r} bytes, got ${i}`);return n}function Qi(...t){let e=0;for(let i=0;i<t.length;i++){let o=t[i];if(!In(o))throw new Error("Uint8Array expected");e+=o.length}let r=new Uint8Array(e),n=0;for(let i=0;i<t.length;i++){let o=t[i];r.set(o,n),n+=o.length}return r}function mk(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}function wk(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function bk(t){let e;for(e=0;t>AT;t>>=Zh,e+=1);return e}function xk(t,e){return t>>BigInt(e)&Zh}var Ek=(t,e,r)=>t|(r?Zh:AT)<<BigInt(e),Pd=t=>(pk<<BigInt(t-1))-Zh,pw=t=>new Uint8Array(t),ST=t=>Uint8Array.from(t);function gw(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let n=pw(t),i=pw(t),o=0,s=()=>{n.fill(1),i.fill(0),o=0},c=(...f)=>r(i,n,...f),a=(f=pw())=>{i=c(ST([0]),f),n=c(),f.length!==0&&(i=c(ST([1]),f),n=c())},u=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");let f=0,h=[];for(;f<e;){n=c();let p=n.slice();h.push(p),f+=n.length}return Qi(...h)};return(f,h)=>{s(),a(f);let p;for(;!(p=h(u()));)a();return s(),p}}var vk={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||In(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function rn(t,e,r={}){let n=(i,o,s)=>{let c=vk[o];if(typeof c!="function")throw new Error(`Invalid validator "${o}", expected function`);let a=t[i];if(!(s&&a===void 0)&&!c(a,t))throw new Error(`Invalid param ${String(i)}=${a} (${typeof a}), expected ${o}`)};for(let[i,o]of Object.entries(e))n(i,o,!1);for(let[i,o]of Object.entries(r))n(i,o,!0);return t}var Tt=BigInt(0),Xe=BigInt(1),fc=BigInt(2),Sk=BigInt(3),mw=BigInt(4),_T=BigInt(5),BT=BigInt(8),Ak=BigInt(9),Tk=BigInt(16);function _e(t,e){let r=t%e;return r>=Tt?r:e+r}function ww(t,e,r){if(r<=Tt||e<Tt)throw new Error("Expected power/modulo > 0");if(r===Xe)return Tt;let n=Xe;for(;e>Tt;)e&Xe&&(n=n*t%r),t=t*t%r,e>>=Xe;return n}function je(t,e,r){let n=t;for(;e-- >Tt;)n*=n,n%=r;return n}function Qh(t,e){if(t===Tt||e<=Tt)throw new Error(`invert: expected positive integers, got n=${t} mod=${e}`);let r=_e(t,e),n=e,i=Tt,o=Xe,s=Xe,c=Tt;for(;r!==Tt;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==Xe)throw new Error("invert: does not exist");return _e(i,e)}function _k(t){let e=(t-Xe)/fc,r,n,i;for(r=t-Xe,n=0;r%fc===Tt;r/=fc,n++);for(i=fc;i<t&&ww(i,e,t)!==t-Xe;i++);if(n===1){let s=(t+Xe)/mw;return function(a,u){let d=a.pow(u,s);if(!a.eql(a.sqr(d),u))throw new Error("Cannot find square root");return d}}let o=(r+Xe)/fc;return function(c,a){if(c.pow(a,e)===c.neg(c.ONE))throw new Error("Cannot find square root");let u=n,d=c.pow(c.mul(c.ONE,i),r),f=c.pow(a,o),h=c.pow(a,r);for(;!c.eql(h,c.ONE);){if(c.eql(h,c.ZERO))return c.ZERO;let p=1;for(let y=c.sqr(h);p<u&&!c.eql(y,c.ONE);p++)y=c.sqr(y);let g=c.pow(d,Xe<<BigInt(u-p-1));d=c.sqr(g),f=c.mul(f,g),h=c.mul(h,d),u=p}return f}}function Bk(t){if(t%mw===Sk){let e=(t+Xe)/mw;return function(n,i){let o=n.pow(i,e);if(!n.eql(n.sqr(o),i))throw new Error("Cannot find square root");return o}}if(t%BT===_T){let e=(t-_T)/BT;return function(n,i){let o=n.mul(i,fc),s=n.pow(o,e),c=n.mul(i,s),a=n.mul(n.mul(c,fc),s),u=n.mul(c,n.sub(a,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return t%Tk,_k(t)}var IT=(t,e)=>(_e(t,e)&Xe)===Xe,Ik=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function bw(t){let e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Ik.reduce((n,i)=>(n[i]="function",n),e);return rn(t,r)}function Rk(t,e,r){if(r<Tt)throw new Error("Expected power > 0");if(r===Tt)return t.ONE;if(r===Xe)return e;let n=t.ONE,i=e;for(;r>Tt;)r&Xe&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Xe;return n}function Uk(t,e){let r=new Array(e.length),n=e.reduce((o,s,c)=>t.is0(s)?o:(r[c]=o,t.mul(o,s)),t.ONE),i=t.inv(n);return e.reduceRight((o,s,c)=>t.is0(s)?o:(r[c]=t.mul(o,r[c]),t.mul(o,s)),i),r}function xw(t,e){let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Pa(t,e,r=!1,n={}){if(t<=Tt)throw new Error(`Expected Field ORDER > 0, got ${t}`);let{nBitLength:i,nByteLength:o}=xw(t,e);if(o>2048)throw new Error("Field lengths over 2048 bytes are not supported");let s=Bk(t),c=Object.freeze({ORDER:t,BITS:i,BYTES:o,MASK:Pd(i),ZERO:Tt,ONE:Xe,create:a=>_e(a,t),isValid:a=>{if(typeof a!="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof a}`);return Tt<=a&&a<t},is0:a=>a===Tt,isOdd:a=>(a&Xe)===Xe,neg:a=>_e(-a,t),eql:(a,u)=>a===u,sqr:a=>_e(a*a,t),add:(a,u)=>_e(a+u,t),sub:(a,u)=>_e(a-u,t),mul:(a,u)=>_e(a*u,t),pow:(a,u)=>Rk(c,a,u),div:(a,u)=>_e(a*Qh(u,t),t),sqrN:a=>a*a,addN:(a,u)=>a+u,subN:(a,u)=>a-u,mulN:(a,u)=>a*u,inv:a=>Qh(a,t),sqrt:n.sqrt||(a=>s(c,a)),invertBatch:a=>Uk(c,a),cmov:(a,u,d)=>d?u:a,toBytes:a=>r?Xi(a,o):pr(a,o),fromBytes:a=>{if(a.length!==o)throw new Error(`Fp.fromBytes: expected ${o}, got ${a.length}`);return r?Rn(a):Zi(a)}});return Object.freeze(c)}function RT(t,e){if(!t.isOdd)throw new Error("Field doesn't have isOdd");let r=t.sqrt(e);return t.isOdd(r)?t.neg(r):r}function UT(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Ew(t){let e=UT(t);return e+Math.ceil(e/2)}function OT(t,e,r=!1){let n=t.length,i=UT(e),o=Ew(e);if(n<16||n<o||n>1024)throw new Error(`expected ${o}-1024 bytes of input, got ${n}`);let s=r?Zi(t):Rn(t),c=_e(s,e-Xe)+Xe;return r?Xi(c,i):pr(c,i)}l();l();var Dk=BigInt(0),vw=BigInt(1);function ep(t,e){let r=(i,o)=>{let s=o.negate();return i?s:o},n=i=>{let o=Math.ceil(e/i)+1,s=2**(i-1);return{windows:o,windowSize:s}};return{constTimeNegate:r,unsafeLadder(i,o){let s=t.ZERO,c=i;for(;o>Dk;)o&vw&&(s=s.add(c)),c=c.double(),o>>=vw;return s},precomputeWindow(i,o){let{windows:s,windowSize:c}=n(o),a=[],u=i,d=u;for(let f=0;f<s;f++){d=u,a.push(d);for(let h=1;h<c;h++)d=d.add(u),a.push(d);u=d.double()}return a},wNAF(i,o,s){let{windows:c,windowSize:a}=n(i),u=t.ZERO,d=t.BASE,f=BigInt(2**i-1),h=2**i,p=BigInt(i);for(let g=0;g<c;g++){let y=g*a,E=Number(s&f);s>>=p,E>a&&(E-=h,s+=vw);let S=y,I=y+Math.abs(E)-1,A=g%2!==0,O=E<0;E===0?d=d.add(r(A,o[S])):u=u.add(r(O,o[I]))}return{p:u,f:d}},wNAFCached(i,o,s,c){let a=i._WINDOW_SIZE||1,u=o.get(i);return u||(u=this.precomputeWindow(i,a),a!==1&&o.set(i,c(u))),this.wNAF(a,u,s)}}}function Md(t){return bw(t.Fp),rn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...xw(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function kk(t){let e=Md(t);rn(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});let{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}return Object.freeze({...e})}var{bytesToNumberBE:Nk,hexToBytes:Ck}=Xh,lc={Err:class extends Error{constructor(e=""){super(e)}},_parseInt(t){let{Err:e}=lc;if(t.length<2||t[0]!==2)throw new e("Invalid signature integer tag");let r=t[1],n=t.subarray(2,r+2);if(!r||n.length!==r)throw new e("Invalid signature integer: wrong length");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{d:Nk(n),l:t.subarray(r+2)}},toSig(t){let{Err:e}=lc,r=typeof t=="string"?Ck(t):t;if(!In(r))throw new Error("ui8a expected");let n=r.length;if(n<2||r[0]!=48)throw new e("Invalid signature tag");if(r[1]!==n-2)throw new e("Invalid signature: incorrect length");let{d:i,l:o}=lc._parseInt(r.subarray(2)),{d:s,l:c}=lc._parseInt(o);if(c.length)throw new e("Invalid signature: left bytes after parsing");return{r:i,s}},hexFromSig(t){let e=u=>Number.parseInt(u[0],16)&8?"00"+u:u,r=u=>{let d=u.toString(16);return d.length&1?`0${d}`:d},n=e(r(t.s)),i=e(r(t.r)),o=n.length/2,s=i.length/2,c=r(o),a=r(s);return`30${r(s+o+4)}02${a}${i}02${c}${n}`}},eo=BigInt(0),nn=BigInt(1),fW=BigInt(2),DT=BigInt(3),lW=BigInt(4);function Lk(t){let e=kk(t),{Fp:r}=e,n=e.toBytes||((g,y,E)=>{let S=y.toAffine();return Qi(Uint8Array.from([4]),r.toBytes(S.x),r.toBytes(S.y))}),i=e.fromBytes||(g=>{let y=g.subarray(1),E=r.fromBytes(y.subarray(0,r.BYTES)),S=r.fromBytes(y.subarray(r.BYTES,2*r.BYTES));return{x:E,y:S}});function o(g){let{a:y,b:E}=e,S=r.sqr(g),I=r.mul(S,g);return r.add(r.add(I,r.mul(g,y)),E)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function s(g){return typeof g=="bigint"&&eo<g&&g<e.n}function c(g){if(!s(g))throw new Error("Expected valid bigint: 0 < bigint < curve.n")}function a(g){let{allowedPrivateKeyLengths:y,nByteLength:E,wrapPrivateKey:S,n:I}=e;if(y&&typeof g!="bigint"){if(In(g)&&(g=Ji(g)),typeof g!="string"||!y.includes(g.length))throw new Error("Invalid key");g=g.padStart(E*2,"0")}let A;try{A=typeof g=="bigint"?g:Zi(Fe("private key",g,E))}catch{throw new Error(`private key must be ${E} bytes, hex or bigint, not ${typeof g}`)}return S&&(A=_e(A,I)),c(A),A}let u=new Map;function d(g){if(!(g instanceof f))throw new Error("ProjectivePoint expected")}class f{constructor(y,E,S){if(this.px=y,this.py=E,this.pz=S,y==null||!r.isValid(y))throw new Error("x required");if(E==null||!r.isValid(E))throw new Error("y required");if(S==null||!r.isValid(S))throw new Error("z required")}static fromAffine(y){let{x:E,y:S}=y||{};if(!y||!r.isValid(E)||!r.isValid(S))throw new Error("invalid affine point");if(y instanceof f)throw new Error("projective point not allowed");let I=A=>r.eql(A,r.ZERO);return I(E)&&I(S)?f.ZERO:new f(E,S,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(y){let E=r.invertBatch(y.map(S=>S.pz));return y.map((S,I)=>S.toAffine(E[I])).map(f.fromAffine)}static fromHex(y){let E=f.fromAffine(i(Fe("pointHex",y)));return E.assertValidity(),E}static fromPrivateKey(y){return f.BASE.multiply(a(y))}_setWindowSize(y){this._WINDOW_SIZE=y,u.delete(this)}assertValidity(){if(this.is0()){if(e.allowInfinityPoint&&!r.is0(this.py))return;throw new Error("bad point: ZERO")}let{x:y,y:E}=this.toAffine();if(!r.isValid(y)||!r.isValid(E))throw new Error("bad point: x or y not FE");let S=r.sqr(E),I=o(y);if(!r.eql(S,I))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){let{y}=this.toAffine();if(r.isOdd)return!r.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(y){d(y);let{px:E,py:S,pz:I}=this,{px:A,py:O,pz:T}=y,M=r.eql(r.mul(E,T),r.mul(A,I)),q=r.eql(r.mul(S,T),r.mul(O,I));return M&&q}negate(){return new f(this.px,r.neg(this.py),this.pz)}double(){let{a:y,b:E}=e,S=r.mul(E,DT),{px:I,py:A,pz:O}=this,T=r.ZERO,M=r.ZERO,q=r.ZERO,j=r.mul(I,I),$=r.mul(A,A),X=r.mul(O,O),Q=r.mul(I,A);return Q=r.add(Q,Q),q=r.mul(I,O),q=r.add(q,q),T=r.mul(y,q),M=r.mul(S,X),M=r.add(T,M),T=r.sub($,M),M=r.add($,M),M=r.mul(T,M),T=r.mul(Q,T),q=r.mul(S,q),X=r.mul(y,X),Q=r.sub(j,X),Q=r.mul(y,Q),Q=r.add(Q,q),q=r.add(j,j),j=r.add(q,j),j=r.add(j,X),j=r.mul(j,Q),M=r.add(M,j),X=r.mul(A,O),X=r.add(X,X),j=r.mul(X,Q),T=r.sub(T,j),q=r.mul(X,$),q=r.add(q,q),q=r.add(q,q),new f(T,M,q)}add(y){d(y);let{px:E,py:S,pz:I}=this,{px:A,py:O,pz:T}=y,M=r.ZERO,q=r.ZERO,j=r.ZERO,$=e.a,X=r.mul(e.b,DT),Q=r.mul(E,A),G=r.mul(S,O),_=r.mul(I,T),D=r.add(E,S),x=r.add(A,O);D=r.mul(D,x),x=r.add(Q,G),D=r.sub(D,x),x=r.add(E,I);let U=r.add(A,T);return x=r.mul(x,U),U=r.add(Q,_),x=r.sub(x,U),U=r.add(S,I),M=r.add(O,T),U=r.mul(U,M),M=r.add(G,_),U=r.sub(U,M),j=r.mul($,x),M=r.mul(X,_),j=r.add(M,j),M=r.sub(G,j),j=r.add(G,j),q=r.mul(M,j),G=r.add(Q,Q),G=r.add(G,Q),_=r.mul($,_),x=r.mul(X,x),G=r.add(G,_),_=r.sub(Q,_),_=r.mul($,_),x=r.add(x,_),Q=r.mul(G,x),q=r.add(q,Q),Q=r.mul(U,x),M=r.mul(D,M),M=r.sub(M,Q),Q=r.mul(D,G),j=r.mul(U,j),j=r.add(j,Q),new f(M,q,j)}subtract(y){return this.add(y.negate())}is0(){return this.equals(f.ZERO)}wNAF(y){return p.wNAFCached(this,u,y,E=>{let S=r.invertBatch(E.map(I=>I.pz));return E.map((I,A)=>I.toAffine(S[A])).map(f.fromAffine)})}multiplyUnsafe(y){let E=f.ZERO;if(y===eo)return E;if(c(y),y===nn)return this;let{endo:S}=e;if(!S)return p.unsafeLadder(this,y);let{k1neg:I,k1:A,k2neg:O,k2:T}=S.splitScalar(y),M=E,q=E,j=this;for(;A>eo||T>eo;)A&nn&&(M=M.add(j)),T&nn&&(q=q.add(j)),j=j.double(),A>>=nn,T>>=nn;return I&&(M=M.negate()),O&&(q=q.negate()),q=new f(r.mul(q.px,S.beta),q.py,q.pz),M.add(q)}multiply(y){c(y);let E=y,S,I,{endo:A}=e;if(A){let{k1neg:O,k1:T,k2neg:M,k2:q}=A.splitScalar(E),{p:j,f:$}=this.wNAF(T),{p:X,f:Q}=this.wNAF(q);j=p.constTimeNegate(O,j),X=p.constTimeNegate(M,X),X=new f(r.mul(X.px,A.beta),X.py,X.pz),S=j.add(X),I=$.add(Q)}else{let{p:O,f:T}=this.wNAF(E);S=O,I=T}return f.normalizeZ([S,I])[0]}multiplyAndAddUnsafe(y,E,S){let I=f.BASE,A=(T,M)=>M===eo||M===nn||!T.equals(I)?T.multiplyUnsafe(M):T.multiply(M),O=A(this,E).add(A(y,S));return O.is0()?void 0:O}toAffine(y){let{px:E,py:S,pz:I}=this,A=this.is0();y==null&&(y=A?r.ONE:r.inv(I));let O=r.mul(E,y),T=r.mul(S,y),M=r.mul(I,y);if(A)return{x:r.ZERO,y:r.ZERO};if(!r.eql(M,r.ONE))throw new Error("invZ was invalid");return{x:O,y:T}}isTorsionFree(){let{h:y,isTorsionFree:E}=e;if(y===nn)return!0;if(E)return E(f,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){let{h:y,clearCofactor:E}=e;return y===nn?this:E?E(f,this):this.multiplyUnsafe(e.h)}toRawBytes(y=!0){return this.assertValidity(),n(f,this,y)}toHex(y=!0){return Ji(this.toRawBytes(y))}}f.BASE=new f(e.Gx,e.Gy,r.ONE),f.ZERO=new f(r.ZERO,r.ONE,r.ZERO);let h=e.nBitLength,p=ep(f,e.endo?Math.ceil(h/2):h);return{CURVE:e,ProjectivePoint:f,normPrivateKeyToScalar:a,weierstrassEquation:o,isWithinCurveOrder:s}}function Pk(t){let e=Md(t);return rn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function kT(t){let e=Pk(t),{Fp:r,n}=e,i=r.BYTES+1,o=2*r.BYTES+1;function s(x){return eo<x&&x<r.ORDER}function c(x){return _e(x,n)}function a(x){return Qh(x,n)}let{ProjectivePoint:u,normPrivateKeyToScalar:d,weierstrassEquation:f,isWithinCurveOrder:h}=Lk({...e,toBytes(x,U,L){let N=U.toAffine(),R=r.toBytes(N.x),C=Qi;return L?C(Uint8Array.from([U.hasEvenY()?2:3]),R):C(Uint8Array.from([4]),R,r.toBytes(N.y))},fromBytes(x){let U=x.length,L=x[0],N=x.subarray(1);if(U===i&&(L===2||L===3)){let R=Zi(N);if(!s(R))throw new Error("Point is not on curve");let C=f(R),P=r.sqrt(C),V=(P&nn)===nn;return(L&1)===1!==V&&(P=r.neg(P)),{x:R,y:P}}else if(U===o&&L===4){let R=r.fromBytes(N.subarray(0,r.BYTES)),C=r.fromBytes(N.subarray(r.BYTES,2*r.BYTES));return{x:R,y:C}}else throw new Error(`Point of length ${U} was invalid. Expected ${i} compressed bytes or ${o} uncompressed bytes`)}}),p=x=>Ji(pr(x,e.nByteLength));function g(x){let U=n>>nn;return x>U}function y(x){return g(x)?c(-x):x}let E=(x,U,L)=>Zi(x.slice(U,L));class S{constructor(U,L,N){this.r=U,this.s=L,this.recovery=N,this.assertValidity()}static fromCompact(U){let L=e.nByteLength;return U=Fe("compactSignature",U,L*2),new S(E(U,0,L),E(U,L,2*L))}static fromDER(U){let{r:L,s:N}=lc.toSig(Fe("DER",U));return new S(L,N)}assertValidity(){if(!h(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!h(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(U){return new S(this.r,this.s,U)}recoverPublicKey(U){let{r:L,s:N,recovery:R}=this,C=q(Fe("msgHash",U));if(R==null||![0,1,2,3].includes(R))throw new Error("recovery id invalid");let P=R===2||R===3?L+e.n:L;if(P>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");let V=R&1?"03":"02",J=u.fromHex(V+p(P)),z=a(P),W=c(-C*z),Y=c(N*z),Z=u.BASE.multiplyAndAddUnsafe(J,W,Y);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return g(this.s)}normalizeS(){return this.hasHighS()?new S(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return dc(this.toDERHex())}toDERHex(){return lc.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return dc(this.toCompactHex())}toCompactHex(){return p(this.r)+p(this.s)}}let I={isValidPrivateKey(x){try{return d(x),!0}catch{return!1}},normPrivateKeyToScalar:d,randomPrivateKey:()=>{let x=Ew(e.n);return OT(e.randomBytes(x),e.n)},precompute(x=8,U=u.BASE){return U._setWindowSize(x),U.multiply(BigInt(3)),U}};function A(x,U=!0){return u.fromPrivateKey(x).toRawBytes(U)}function O(x){let U=In(x),L=typeof x=="string",N=(U||L)&&x.length;return U?N===i||N===o:L?N===2*i||N===2*o:x instanceof u}function T(x,U,L=!0){if(O(x))throw new Error("first arg must be private key");if(!O(U))throw new Error("second arg must be public key");return u.fromHex(U).multiply(d(x)).toRawBytes(L)}let M=e.bits2int||function(x){let U=Zi(x),L=x.length*8-e.nBitLength;return L>0?U>>BigInt(L):U},q=e.bits2int_modN||function(x){return c(M(x))},j=Pd(e.nBitLength);function $(x){if(typeof x!="bigint")throw new Error("bigint expected");if(!(eo<=x&&x<j))throw new Error(`bigint expected < 2^${e.nBitLength}`);return pr(x,e.nByteLength)}function X(x,U,L=Q){if(["recovered","canonical"].some(ee=>ee in L))throw new Error("sign() legacy options not supported");let{hash:N,randomBytes:R}=e,{lowS:C,prehash:P,extraEntropy:V}=L;C==null&&(C=!0),x=Fe("msgHash",x),P&&(x=Fe("prehashed msgHash",N(x)));let J=q(x),z=d(U),W=[$(z),$(J)];if(V!=null){let ee=V===!0?R(r.BYTES):V;W.push(Fe("extraEntropy",ee))}let Y=Qi(...W),Z=J;function ue(ee){let ce=M(ee);if(!h(ce))return;let Ie=a(ce),Pe=u.BASE.multiply(ce).toAffine(),Ge=c(Pe.x);if(Ge===eo)return;let wt=c(Ie*c(Z+Ge*z));if(wt===eo)return;let pi=(Pe.x===Ge?0:2)|Number(Pe.y&nn),uo=wt;return C&&g(wt)&&(uo=y(wt),pi^=1),new S(Ge,uo,pi)}return{seed:Y,k2sig:ue}}let Q={lowS:e.lowS,prehash:!1},G={lowS:e.lowS,prehash:!1};function _(x,U,L=Q){let{seed:N,k2sig:R}=X(x,U,L),C=e;return gw(C.hash.outputLen,C.nByteLength,C.hmac)(N,R)}u.BASE._setWindowSize(8);function D(x,U,L,N=G){let R=x;if(U=Fe("msgHash",U),L=Fe("publicKey",L),"strict"in N)throw new Error("options.strict was renamed to lowS");let{lowS:C,prehash:P}=N,V,J;try{if(typeof R=="string"||In(R))try{V=S.fromDER(R)}catch(Pe){if(!(Pe instanceof lc.Err))throw Pe;V=S.fromCompact(R)}else if(typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint"){let{r:Pe,s:Ge}=R;V=new S(Pe,Ge)}else throw new Error("PARSE");J=u.fromHex(L)}catch(Pe){if(Pe.message==="PARSE")throw new Error("signature must be Signature instance, Uint8Array or hex string");return!1}if(C&&V.hasHighS())return!1;P&&(U=e.hash(U));let{r:z,s:W}=V,Y=q(U),Z=a(W),ue=c(Y*Z),ee=c(z*Z),ce=u.BASE.multiplyAndAddUnsafe(J,ue,ee)?.toAffine();return ce?c(ce.x)===z:!1}return{CURVE:e,getPublicKey:A,getSharedSecret:T,sign:_,verify:D,ProjectivePoint:u,Signature:S,utils:I}}l();l();var tp=class extends Ca{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,bT(e);let n=Cd(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(n.length>i?e.create().update(n).digest():n);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),o.fill(0)}update(e){return Na(this),this.iHash.update(e),this}digestInto(e){Na(this),fw(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Sw=(t,e,r)=>new tp(t,e).update(r).digest();Sw.create=(t,e)=>new tp(t,e);function Mk(t){return{hash:t,hmac:(e,...r)=>Sw(t,e,zh(...r)),randomBytes:Ld}}function rp(t,e){let r=n=>kT({...t,...Mk(n)});return Object.freeze({...r(e),create:r})}var LT=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),NT=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Kk=BigInt(1),Aw=BigInt(2),CT=(t,e)=>(t+e/Aw)/e;function $k(t){let e=LT,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=je(d,r,e)*d%e,h=je(f,r,e)*d%e,p=je(h,Aw,e)*u%e,g=je(p,i,e)*p%e,y=je(g,o,e)*g%e,E=je(y,c,e)*y%e,S=je(E,a,e)*E%e,I=je(S,c,e)*y%e,A=je(I,r,e)*d%e,O=je(A,s,e)*g%e,T=je(O,n,e)*u%e,M=je(T,Aw,e);if(!Tw.eql(Tw.sqr(M),t))throw new Error("Cannot find square root");return M}var Tw=Pa(LT,void 0,void 0,{sqrt:$k}),yr=rp({a:BigInt(0),b:BigInt(7),Fp:Tw,n:NT,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{let e=NT,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Kk*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,s=BigInt("0x100000000000000000000000000000000"),c=CT(o*t,e),a=CT(-n*t,e),u=_e(t-c*r-a*i,e),d=_e(-c*n-a*o,e),f=u>s,h=d>s;if(f&&(u=e-u),h&&(d=e-d),u>s||d>s)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}}},Jh),BW=BigInt(0);var IW=yr.ProjectivePoint;l();l();function PT(t){let e=n=>{if(n!==null&&typeof n=="object"&&!Array.isArray(n)){let i=Object.keys(n).sort(),o={};for(let s of i)o[s]=e(n[s]);return o}return n},r=e(t);return JSON.stringify(r)}var Hk=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},_w="urn:jwk:";function ge(t){return Hk(this,arguments,void 0,function*({jwk:e}){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);rg(n);let i=PT(n),o=ne.string(i).toUint8Array(),s=yield ka.digest({data:o});return ne.uint8Array(s).toBase64Url()})}function ai(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="EC"||typeof t.d!="string"||typeof t.x!="string")}function Ma(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t)||"d"in t||t.kty!=="EC"||typeof t.x!="string")}function ui(t){return!(!t||typeof t!="object"||!("kty"in t&&"crv"in t&&"x"in t&&"d"in t)||t.kty!=="OKP"||typeof t.d!="string"||typeof t.x!="string")}function Ka(t){return!(!t||typeof t!="object"||"d"in t||!("kty"in t&&"crv"in t&&"x"in t)||t.kty!=="OKP"||typeof t.x!="string")}function MT(t){if(!t||typeof t!="object")return!1;switch(t.kty){case"EC":case"OKP":case"RSA":return"d"in t;case"oct":return"k"in t;default:return!1}}var Kt=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Vk=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Ot=class t{static adjustSignatureToLowS(e){return Kt(this,arguments,void 0,function*({signature:r}){let n=yr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return Kt(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"secp256k1",x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static compressPublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){return yr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return Kt(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=yield t.getCurvePoint({keyBytes:n}),o={kty:"EC",crv:"secp256k1",x:ne.uint8Array(i.x).toBase64Url(),y:ne.uint8Array(i.y).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertDerToCompactSignature(e){return Kt(this,arguments,void 0,function*({derSignature:r}){return yr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){return yr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return Kt(this,void 0,void 0,function*(){let e=yr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Kt(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="secp256k1"))throw new Error("Secp256k1: The provided key is not a secp256k1 private JWK.");let{d:i}=r,o=Vk(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Kt(this,arguments,void 0,function*({privateKey:r}){if(!ai(r))throw new Error("Secp256k1: The provided key is not a valid EC private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Kt(this,arguments,void 0,function*({publicKey:r}){if(!(Ma(r)&&r.y))throw new Error("Secp256k1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ne.base64Url(r.x).toUint8Array(),o=ne.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...o])})}static sharedSecret(e){return Kt(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return yr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return Kt(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=Wo(r);return yr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return Kt(this,arguments,void 0,function*({privateKeyBytes:r}){return yr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return Kt(this,arguments,void 0,function*({publicKeyBytes:r}){try{yr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return Kt(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=Wo(i);return yr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return Kt(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=yr.getPublicKey(r));let n=yr.ProjectivePoint.fromHex(r),i=pr(n.x,32),o=pr(n.y,32);return{x:i,y:o}})}};l();l();var KT=Pa(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),qk=KT.create(BigInt("-3")),Fk=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),jk=rp({a:qk,b:Fk,Fp:KT,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},Jh),Nr=jk;var $t=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Wk=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},Ht=class t{static adjustSignatureToLowS(e){return $t(this,arguments,void 0,function*({signature:r}){let n=Nr.Signature.fromCompact(r);return n.hasHighS()?n.normalizeS().toCompactRawBytes():r})}static bytesToPrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){let n=yield t.getCurvePoint({keyBytes:r}),i={kty:"EC",crv:"P-256",x:ne.uint8Array(n.x).toBase64Url(),y:ne.uint8Array(n.y).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static compressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return Nr.ProjectivePoint.fromHex(r).toRawBytes(!0)})}static computePublicKey(e){return $t(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=yield t.getCurvePoint({keyBytes:n}),o={kty:"EC",crv:"P-256",x:ne.uint8Array(i.x).toBase64Url(),y:ne.uint8Array(i.y).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertDerToCompactSignature(e){return $t(this,arguments,void 0,function*({derSignature:r}){return Nr.Signature.fromDER(r).toCompactRawBytes()})}static decompressPublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){return Nr.ProjectivePoint.fromHex(r).toRawBytes(!1)})}static generateKey(){return $t(this,void 0,void 0,function*(){let e=Nr.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return $t(this,arguments,void 0,function*({key:r}){var n;if(!(ai(r)&&r.crv==="P-256"))throw new Error("Secp256r1: The provided key is not a 'P-256' private JWK.");let{d:i}=r,o=Wk(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return $t(this,arguments,void 0,function*({privateKey:r}){if(!ai(r))throw new Error("Secp256r1: The provided key is not a valid EC private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return $t(this,arguments,void 0,function*({publicKey:r}){if(!(Ma(r)&&r.y))throw new Error("Secp256r1: The provided key is not a valid EC public key.");let n=new Uint8Array([4]),i=ne.base64Url(r.x).toUint8Array(),o=ne.base64Url(r.y).toUint8Array();return new Uint8Array([...n,...i,...o])})}static sharedSecret(e){return $t(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return Nr.getSharedSecret(i,o,!0).slice(1)})}static sign(e){return $t(this,arguments,void 0,function*({data:r,key:n}){let i=yield t.privateKeyToBytes({privateKey:n}),o=Wo(r);return Nr.sign(o,i).toCompactRawBytes()})}static validatePrivateKey(e){return $t(this,arguments,void 0,function*({privateKeyBytes:r}){return Nr.utils.isValidPrivateKey(r)})}static validatePublicKey(e){return $t(this,arguments,void 0,function*({publicKeyBytes:r}){try{Nr.ProjectivePoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return $t(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r}),s=Wo(i);return Nr.verify(n,s,o,{lowS:!1})})}static getCurvePoint(e){return $t(this,arguments,void 0,function*({keyBytes:r}){r.byteLength===32&&(r=Nr.getPublicKey(r));let n=Nr.ProjectivePoint.fromHex(r),i=pr(n.x,32),o=pr(n.y,32);return{x:i,y:o}})}};var Kd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},$d=class extends ci{computePublicKey(e){return Kd(this,arguments,void 0,function*({key:r}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield Ot.computePublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Ht.computePublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Kd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"ES256K":case"secp256k1":{let n=yield Ot.generateKey();return n.alg="ES256K",n}case"ES256":case"secp256r1":{let n=yield Ht.generateKey();return n.alg="ES256",n}}})}getPublicKey(e){return Kd(this,arguments,void 0,function*({key:r}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":{let n=yield Ot.getPublicKey({key:r});return n.alg="ES256K",n}case"P-256":{let n=yield Ht.getPublicKey({key:r});return n.alg="ES256",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Kd(this,arguments,void 0,function*({key:r,data:n}){if(!ai(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) private key.");switch(r.crv){case"secp256k1":return yield Ot.sign({key:r,data:n});case"P-256":return yield Ht.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Kd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Ma(r))throw new TypeError("Invalid key provided. Must be an elliptic curve (EC) public key.");switch(r.crv){case"secp256k1":return yield Ot.verify({key:r,signature:n,data:i});case"P-256":return yield Ht.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};l();l();l();l();l();var np=BigInt(4294967295),Bw=BigInt(32);function $T(t,e=!1){return e?{h:Number(t&np),l:Number(t>>Bw&np)}:{h:Number(t>>Bw&np)|0,l:Number(t&np)|0}}function Gk(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){let{h:o,l:s}=$T(t[i],e);[r[i],n[i]]=[o,s]}return[r,n]}var zk=(t,e)=>BigInt(t>>>0)<<Bw|BigInt(e>>>0),Yk=(t,e,r)=>t>>>r,Jk=(t,e,r)=>t<<32-r|e>>>r,Zk=(t,e,r)=>t>>>r|e<<32-r,Xk=(t,e,r)=>t<<32-r|e>>>r,Qk=(t,e,r)=>t<<64-r|e>>>r-32,eN=(t,e,r)=>t>>>r-32|e<<64-r,tN=(t,e)=>e,rN=(t,e)=>t,nN=(t,e,r)=>t<<r|e>>>32-r,iN=(t,e,r)=>e<<r|t>>>32-r,oN=(t,e,r)=>e<<r-32|t>>>64-r,sN=(t,e,r)=>t<<r-32|e>>>64-r;function cN(t,e,r,n){let i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}var aN=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),uN=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,dN=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),fN=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,lN=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),hN=(t,e,r,n,i,o)=>e+r+n+i+o+(t/2**32|0)|0;var pN={fromBig:$T,split:Gk,toBig:zk,shrSH:Yk,shrSL:Jk,rotrSH:Zk,rotrSL:Xk,rotrBH:Qk,rotrBL:eN,rotr32H:tN,rotr32L:rN,rotlSH:nN,rotlSL:iN,rotlBH:oN,rotlBL:sN,add:cN,add3L:aN,add3H:uN,add4L:dN,add4H:fN,add5H:hN,add5L:lN},le=pN;var[yN,gN]=le.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Yo=new Uint32Array(80),Jo=new Uint32Array(80),Iw=class extends La{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){let{Ah:e,Al:r,Bh:n,Bl:i,Ch:o,Cl:s,Dh:c,Dl:a,Eh:u,El:d,Fh:f,Fl:h,Gh:p,Gl:g,Hh:y,Hl:E}=this;return[e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,E]}set(e,r,n,i,o,s,c,a,u,d,f,h,p,g,y,E){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=o|0,this.Cl=s|0,this.Dh=c|0,this.Dl=a|0,this.Eh=u|0,this.El=d|0,this.Fh=f|0,this.Fl=h|0,this.Gh=p|0,this.Gl=g|0,this.Hh=y|0,this.Hl=E|0}process(e,r){for(let A=0;A<16;A++,r+=4)Yo[A]=e.getUint32(r),Jo[A]=e.getUint32(r+=4);for(let A=16;A<80;A++){let O=Yo[A-15]|0,T=Jo[A-15]|0,M=le.rotrSH(O,T,1)^le.rotrSH(O,T,8)^le.shrSH(O,T,7),q=le.rotrSL(O,T,1)^le.rotrSL(O,T,8)^le.shrSL(O,T,7),j=Yo[A-2]|0,$=Jo[A-2]|0,X=le.rotrSH(j,$,19)^le.rotrBH(j,$,61)^le.shrSH(j,$,6),Q=le.rotrSL(j,$,19)^le.rotrBL(j,$,61)^le.shrSL(j,$,6),G=le.add4L(q,Q,Jo[A-7],Jo[A-16]),_=le.add4H(G,M,X,Yo[A-7],Yo[A-16]);Yo[A]=_|0,Jo[A]=G|0}let{Ah:n,Al:i,Bh:o,Bl:s,Ch:c,Cl:a,Dh:u,Dl:d,Eh:f,El:h,Fh:p,Fl:g,Gh:y,Gl:E,Hh:S,Hl:I}=this;for(let A=0;A<80;A++){let O=le.rotrSH(f,h,14)^le.rotrSH(f,h,18)^le.rotrBH(f,h,41),T=le.rotrSL(f,h,14)^le.rotrSL(f,h,18)^le.rotrBL(f,h,41),M=f&p^~f&y,q=h&g^~h&E,j=le.add5L(I,T,q,gN[A],Jo[A]),$=le.add5H(j,S,O,M,yN[A],Yo[A]),X=j|0,Q=le.rotrSH(n,i,28)^le.rotrBH(n,i,34)^le.rotrBH(n,i,39),G=le.rotrSL(n,i,28)^le.rotrBL(n,i,34)^le.rotrBL(n,i,39),_=n&o^n&c^o&c,D=i&s^i&a^s&a;S=y|0,I=E|0,y=p|0,E=g|0,p=f|0,g=h|0,{h:f,l:h}=le.add(u|0,d|0,$|0,X|0),u=c|0,d=a|0,c=o|0,a=s|0,o=n|0,s=i|0;let x=le.add3L(X,G,D);n=le.add3H(x,$,Q,_),i=x|0}({h:n,l:i}=le.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:o,l:s}=le.add(this.Bh|0,this.Bl|0,o|0,s|0),{h:c,l:a}=le.add(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:d}=le.add(this.Dh|0,this.Dl|0,u|0,d|0),{h:f,l:h}=le.add(this.Eh|0,this.El|0,f|0,h|0),{h:p,l:g}=le.add(this.Fh|0,this.Fl|0,p|0,g|0),{h:y,l:E}=le.add(this.Gh|0,this.Gl|0,y|0,E|0),{h:S,l:I}=le.add(this.Hh|0,this.Hl|0,S|0,I|0),this.set(n,i,o,s,c,a,u,d,f,h,p,g,y,E,S,I)}roundClean(){Yo.fill(0),Jo.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var Rw=Yh(()=>new Iw);l();var Un=BigInt(0),Cr=BigInt(1),ip=BigInt(2),mN=BigInt(8),wN={zip215:!0};function bN(t){let e=Md(t);return rn(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function op(t){let e=bN(t),{Fp:r,n,prehash:i,hash:o,randomBytes:s,nByteLength:c,h:a}=e,u=ip<<BigInt(c*8)-Cr,d=r.create,f=e.uvRatio||((N,R)=>{try{return{isValid:!0,value:r.sqrt(N*r.inv(R))}}catch{return{isValid:!1,value:Un}}}),h=e.adjustScalarBytes||(N=>N),p=e.domain||((N,R,C)=>{if(R.length||C)throw new Error("Contexts/pre-hash are not supported");return N}),g=N=>typeof N=="bigint"&&Un<N,y=(N,R)=>g(N)&&g(R)&&N<R,E=N=>N===Un||y(N,u);function S(N,R){if(y(N,R))return N;throw new Error(`Expected valid scalar < ${R}, got ${typeof N} ${N}`)}function I(N){return N===Un?N:S(N,n)}let A=new Map;function O(N){if(!(N instanceof T))throw new Error("ExtendedPoint expected")}class T{constructor(R,C,P,V){if(this.ex=R,this.ey=C,this.ez=P,this.et=V,!E(R))throw new Error("x required");if(!E(C))throw new Error("y required");if(!E(P))throw new Error("z required");if(!E(V))throw new Error("t required")}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(R){if(R instanceof T)throw new Error("extended point not allowed");let{x:C,y:P}=R||{};if(!E(C)||!E(P))throw new Error("invalid affine point");return new T(C,P,Cr,d(C*P))}static normalizeZ(R){let C=r.invertBatch(R.map(P=>P.ez));return R.map((P,V)=>P.toAffine(C[V])).map(T.fromAffine)}_setWindowSize(R){this._WINDOW_SIZE=R,A.delete(this)}assertValidity(){let{a:R,d:C}=e;if(this.is0())throw new Error("bad point: ZERO");let{ex:P,ey:V,ez:J,et:z}=this,W=d(P*P),Y=d(V*V),Z=d(J*J),ue=d(Z*Z),ee=d(W*R),ce=d(Z*d(ee+Y)),Ie=d(ue+d(C*d(W*Y)));if(ce!==Ie)throw new Error("bad point: equation left != right (1)");let Pe=d(P*V),Ge=d(J*z);if(Pe!==Ge)throw new Error("bad point: equation left != right (2)")}equals(R){O(R);let{ex:C,ey:P,ez:V}=this,{ex:J,ey:z,ez:W}=R,Y=d(C*W),Z=d(J*V),ue=d(P*W),ee=d(z*V);return Y===Z&&ue===ee}is0(){return this.equals(T.ZERO)}negate(){return new T(d(-this.ex),this.ey,this.ez,d(-this.et))}double(){let{a:R}=e,{ex:C,ey:P,ez:V}=this,J=d(C*C),z=d(P*P),W=d(ip*d(V*V)),Y=d(R*J),Z=C+P,ue=d(d(Z*Z)-J-z),ee=Y+z,ce=ee-W,Ie=Y-z,Pe=d(ue*ce),Ge=d(ee*Ie),wt=d(ue*Ie),pi=d(ce*ee);return new T(Pe,Ge,pi,wt)}add(R){O(R);let{a:C,d:P}=e,{ex:V,ey:J,ez:z,et:W}=this,{ex:Y,ey:Z,ez:ue,et:ee}=R;if(C===BigInt(-1)){let uu=d((J-V)*(Z+Y)),yf=d((J+V)*(Z-Y)),du=d(yf-uu);if(du===Un)return this.double();let gf=d(z*ip*ee),mf=d(W*ip*ue),qr=mf+gf,lo=yf+uu,fu=mf-gf,wf=d(qr*du),us=d(lo*fu),bf=d(qr*fu),Jp=d(du*lo);return new T(wf,us,Jp,bf)}let ce=d(V*Y),Ie=d(J*Z),Pe=d(W*P*ee),Ge=d(z*ue),wt=d((V+J)*(Y+Z)-ce-Ie),pi=Ge-Pe,uo=Ge+Pe,au=d(Ie-C*ce),pf=d(wt*pi),Yp=d(uo*au),fo=d(wt*au),Vr=d(pi*uo);return new T(pf,Yp,Vr,fo)}subtract(R){return this.add(R.negate())}wNAF(R){return j.wNAFCached(this,A,R,T.normalizeZ)}multiply(R){let{p:C,f:P}=this.wNAF(S(R,n));return T.normalizeZ([C,P])[0]}multiplyUnsafe(R){let C=I(R);return C===Un?q:this.equals(q)||C===Cr?this:this.equals(M)?this.wNAF(C).p:j.unsafeLadder(this,C)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}isTorsionFree(){return j.unsafeLadder(this,n).is0()}toAffine(R){let{ex:C,ey:P,ez:V}=this,J=this.is0();R==null&&(R=J?mN:r.inv(V));let z=d(C*R),W=d(P*R),Y=d(V*R);if(J)return{x:Un,y:Cr};if(Y!==Cr)throw new Error("invZ was invalid");return{x:z,y:W}}clearCofactor(){let{h:R}=e;return R===Cr?this:this.multiplyUnsafe(R)}static fromHex(R,C=!1){let{d:P,a:V}=e,J=r.BYTES;R=Fe("pointHex",R,J);let z=R.slice(),W=R[J-1];z[J-1]=W&-129;let Y=Rn(z);Y===Un||(C?S(Y,u):S(Y,r.ORDER));let Z=d(Y*Y),ue=d(Z-Cr),ee=d(P*Z-V),{isValid:ce,value:Ie}=f(ue,ee);if(!ce)throw new Error("Point.fromHex: invalid y coordinate");let Pe=(Ie&Cr)===Cr,Ge=(W&128)!==0;if(!C&&Ie===Un&&Ge)throw new Error("Point.fromHex: x=0 and x_0=1");return Ge!==Pe&&(Ie=d(-Ie)),T.fromAffine({x:Ie,y:Y})}static fromPrivateKey(R){return Q(R).point}toRawBytes(){let{x:R,y:C}=this.toAffine(),P=Xi(C,r.BYTES);return P[P.length-1]|=R&Cr?128:0,P}toHex(){return Ji(this.toRawBytes())}}T.BASE=new T(e.Gx,e.Gy,Cr,d(e.Gx*e.Gy)),T.ZERO=new T(Un,Cr,Cr,Un);let{BASE:M,ZERO:q}=T,j=ep(T,c*8);function $(N){return _e(N,n)}function X(N){return $(Rn(N))}function Q(N){let R=c;N=Fe("private key",N,R);let C=Fe("hashed private key",o(N),2*R),P=h(C.slice(0,R)),V=C.slice(R,2*R),J=X(P),z=M.multiply(J),W=z.toRawBytes();return{head:P,prefix:V,scalar:J,point:z,pointBytes:W}}function G(N){return Q(N).pointBytes}function _(N=new Uint8Array,...R){let C=Qi(...R);return X(o(p(C,Fe("context",N),!!i)))}function D(N,R,C={}){N=Fe("message",N),i&&(N=i(N));let{prefix:P,scalar:V,pointBytes:J}=Q(R),z=_(C.context,P,N),W=M.multiply(z).toRawBytes(),Y=_(C.context,W,J,N),Z=$(z+Y*V);I(Z);let ue=Qi(W,Xi(Z,r.BYTES));return Fe("result",ue,c*2)}let x=wN;function U(N,R,C,P=x){let{context:V,zip215:J}=P,z=r.BYTES;N=Fe("signature",N,2*z),R=Fe("message",R),i&&(R=i(R));let W=Rn(N.slice(z,2*z)),Y,Z,ue;try{Y=T.fromHex(C,J),Z=T.fromHex(N.slice(0,z),J),ue=M.multiplyUnsafe(W)}catch{return!1}if(!J&&Y.isSmallOrder())return!1;let ee=_(V,Z.toRawBytes(),Y.toRawBytes(),R);return Z.add(Y.multiplyUnsafe(ee)).subtract(ue).clearCofactor().equals(T.ZERO)}return M._setWindowSize(8),{CURVE:e,getPublicKey:G,sign:D,verify:U,ExtendedPoint:T,utils:{getExtendedPublicKey:Q,randomPrivateKey:()=>s(r.BYTES),precompute(N=8,R=T.BASE){return R._setWindowSize(N),R.multiply(BigInt(3)),R}}}}l();var Hd=BigInt(0),Uw=BigInt(1);function xN(t){return rn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function HT(t){let e=xN(t),{P:r}=e,n=A=>_e(A,r),i=e.montgomeryBits,o=Math.ceil(i/8),s=e.nByteLength,c=e.adjustScalarBytes||(A=>A),a=e.powPminus2||(A=>ww(A,r-BigInt(2),r));function u(A,O,T){let M=n(A*(O-T));return O=n(O-M),T=n(T+M),[O,T]}function d(A){if(typeof A=="bigint"&&Hd<=A&&A<r)return A;throw new Error("Expected valid scalar 0 < scalar < CURVE.P")}let f=(e.a-BigInt(2))/BigInt(4);function h(A,O){let T=d(A),M=d(O),q=T,j=Uw,$=Hd,X=T,Q=Uw,G=Hd,_;for(let x=BigInt(i-1);x>=Hd;x--){let U=M>>x&Uw;G^=U,_=u(G,j,X),j=_[0],X=_[1],_=u(G,$,Q),$=_[0],Q=_[1],G=U;let L=j+$,N=n(L*L),R=j-$,C=n(R*R),P=N-C,V=X+Q,J=X-Q,z=n(J*L),W=n(V*R),Y=z+W,Z=z-W;X=n(Y*Y),Q=n(q*n(Z*Z)),j=n(N*C),$=n(P*(N+n(f*P)))}_=u(G,j,X),j=_[0],X=_[1],_=u(G,$,Q),$=_[0],Q=_[1];let D=a($);return n(j*D)}function p(A){return Xi(n(A),o)}function g(A){let O=Fe("u coordinate",A,o);return s===32&&(O[31]&=127),Rn(O)}function y(A){let O=Fe("scalar",A),T=O.length;if(T!==o&&T!==s)throw new Error(`Expected ${o} or ${s} bytes, got ${T}`);return Rn(c(O))}function E(A,O){let T=g(O),M=y(A),q=h(T,M);if(q===Hd)throw new Error("Invalid private or public key received");return p(q)}let S=p(e.Gu);function I(A){return E(A,S)}return{scalarMult:E,scalarMultBase:I,getSharedSecret:(A,O)=>E(A,O),getPublicKey:A=>I(A),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:S}}var Vd=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),VT=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752"),UG=BigInt(0),EN=BigInt(1),Ow=BigInt(2),vN=BigInt(5),qT=BigInt(10),SN=BigInt(20),AN=BigInt(40),FT=BigInt(80);function jT(t){let e=Vd,n=t*t%e*t%e,i=je(n,Ow,e)*n%e,o=je(i,EN,e)*t%e,s=je(o,vN,e)*o%e,c=je(s,qT,e)*s%e,a=je(c,SN,e)*c%e,u=je(a,AN,e)*a%e,d=je(u,FT,e)*u%e,f=je(d,FT,e)*u%e,h=je(f,qT,e)*s%e;return{pow_p_5_8:je(h,Ow,e)*t%e,b2:n}}function WT(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function TN(t,e){let r=Vd,n=_e(e*e*e,r),i=_e(n*n*e,r),o=jT(t*i).pow_p_5_8,s=_e(t*n*o,r),c=_e(e*s*s,r),a=s,u=_e(s*VT,r),d=c===t,f=c===_e(-t,r),h=c===_e(-t*VT,r);return d&&(s=a),(f||h)&&(s=u),IT(s,r)&&(s=_e(-s,r)),{isValid:d||f,value:s}}var on=Pa(Vd,void 0,!0),qd={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:on,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:BigInt(8),Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Rw,randomBytes:Ld,adjustScalarBytes:WT,uvRatio:TN},Zo=op(qd);function GT(t,e,r){if(e.length>255)throw new Error("Context is too big");return zh(lw("SigEd25519 no Ed25519 collisions"),new Uint8Array([r?1:0,e.length]),e,t)}var OG=op({...qd,domain:GT}),DG=op({...qd,domain:GT,prehash:Rw}),hc=HT({P:Vd,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{let e=Vd,{pow_p_5_8:r,b2:n}=jT(t);return _e(je(r,BigInt(3),e)*n,e)},adjustScalarBytes:WT,randomBytes:Ld});function zT(t){let{y:e}=Zo.ExtendedPoint.fromHex(t),r=BigInt(1);return on.toBytes(on.create((r+e)*on.inv(r-e)))}function YT(t){let e=qd.hash(t.subarray(0,32));return qd.adjustScalarBytes(e).subarray(0,32)}var _N=(on.ORDER+BigInt(3))/BigInt(8),kG=on.pow(Ow,_N),NG=on.sqrt(on.neg(on.ONE)),CG=(on.ORDER-BigInt(5))/BigInt(8),LG=BigInt(486662);var PG=RT(on,on.neg(BigInt(486664)));var MG=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),KG=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),$G=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),HG=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952");var VG=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var sn=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},BN=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},_t=class t{static bytesToPrivateKey(e){return sn(this,arguments,void 0,function*({privateKeyBytes:r}){let n=Zo.getPublicKey(r),i={crv:"Ed25519",d:ne.uint8Array(r).toBase64Url(),kty:"OKP",x:ne.uint8Array(n).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return sn(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield ge({jwk:n}),n})}static computePublicKey(e){return sn(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=Zo.getPublicKey(n),o={kty:"OKP",crv:"Ed25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static convertPrivateKeyToX25519(e){return sn(this,arguments,void 0,function*({privateKey:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=YT(n),o=hc.getPublicKey(i),s={kty:"OKP",crv:"X25519",d:ne.uint8Array(i).toBase64Url(),x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static convertPublicKeyToX25519(e){return sn(this,arguments,void 0,function*({publicKey:r}){let n=yield t.publicKeyToBytes({publicKey:r});if(!(yield t.validatePublicKey({publicKeyBytes:n})))throw new Error("Ed25519: Invalid public key.");let o=zT(n),s={kty:"OKP",crv:"X25519",x:ne.uint8Array(o).toBase64Url()};return s.kid=yield ge({jwk:s}),s})}static generateKey(){return sn(this,void 0,void 0,function*(){let e=Zo.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return sn(this,arguments,void 0,function*({key:r}){var n;if(!(ui(r)&&r.crv==="Ed25519"))throw new Error("Ed25519: The provided key is not an Ed25519 private JWK.");let{d:i}=r,o=BN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return sn(this,arguments,void 0,function*({privateKey:r}){if(!ui(r))throw new Error("Ed25519: The provided key is not a valid OKP private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return sn(this,arguments,void 0,function*({publicKey:r}){if(!Ka(r))throw new Error("Ed25519: The provided key is not a valid OKP public key.");return ne.base64Url(r.x).toUint8Array()})}static sign(e){return sn(this,arguments,void 0,function*({key:r,data:n}){let i=yield t.privateKeyToBytes({privateKey:r});return Zo.sign(n,i)})}static validatePublicKey(e){return sn(this,arguments,void 0,function*({publicKeyBytes:r}){try{Zo.ExtendedPoint.fromHex(r).assertValidity()}catch{return!1}return!0})}static verify(e){return sn(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=yield t.publicKeyToBytes({publicKey:r});return Zo.verify(n,i,o)})}};var Fd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},sp=class extends ci{computePublicKey(e){return Fd(this,arguments,void 0,function*({key:r}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield _t.computePublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}generateKey(e){return Fd(this,arguments,void 0,function*({algorithm:r}){switch(r){case"Ed25519":{let n=yield _t.generateKey();return n.alg="EdDSA",n}}})}getPublicKey(e){return Fd(this,arguments,void 0,function*({key:r}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":{let n=yield _t.getPublicKey({key:r});return n.alg="EdDSA",n}default:throw new Error(`Unsupported curve: ${r.crv}`)}})}sign(e){return Fd(this,arguments,void 0,function*({key:r,data:n}){if(!ui(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) private key.");switch(r.crv){case"Ed25519":return yield _t.sign({key:r,data:n});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}verify(e){return Fd(this,arguments,void 0,function*({key:r,signature:n,data:i}){if(!Ka(r))throw new TypeError("Invalid key provided. Must be an octet key pair (OKP) public key.");switch(r.crv){case"Ed25519":return yield _t.verify({key:r,signature:n,data:i});default:throw new Error(`Unsupported curve: ${r.crv}`)}})}};var to=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Dw={Ed25519:{implementation:sp,names:["Ed25519"]},secp256k1:{implementation:$d,names:["ES256K","secp256k1"]},secp256r1:{implementation:$d,names:["ES256","secp256r1"]},"SHA-256":{implementation:jh,names:["SHA-256"]}},Xt=class{constructor(e){var r;this._algorithmInstances=new Map,this._keyStore=(r=e?.keyStore)!==null&&r!==void 0?r:new dh}digest(e){return to(this,arguments,void 0,function*({algorithm:r,data:n}){return yield this.getAlgorithm({algorithm:r}).digest({algorithm:r,data:n})})}exportKey(e){return to(this,arguments,void 0,function*({keyUri:r}){return yield this.getPrivateKey({keyUri:r})})}generateKey(e){return to(this,arguments,void 0,function*({algorithm:r}){let i=yield this.getAlgorithm({algorithm:r}).generateKey({algorithm:r});if(i?.kid===void 0)throw new Error("Generated key is missing a required property: kid");let o=`${_w}${i.kid}`;return yield this._keyStore.set(o,i),o})}getKeyUri(e){return to(this,arguments,void 0,function*({key:r}){let n=yield ge({jwk:r});return`${_w}${n}`})}getPublicKey(e){return to(this,arguments,void 0,function*({keyUri:r}){let n=yield this.getPrivateKey({keyUri:r}),i=this.getAlgorithmName({key:n});return yield this.getAlgorithm({algorithm:i}).getPublicKey({key:n})})}importKey(e){return to(this,arguments,void 0,function*({key:r}){var n;if(!MT(r))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let i=structuredClone(r);(n=i.kid)!==null&&n!==void 0||(i.kid=yield ge({jwk:i}));let o=yield this.getKeyUri({key:i});return yield this._keyStore.set(o,i),o})}sign(e){return to(this,arguments,void 0,function*({keyUri:r,data:n}){let i=yield this.getPrivateKey({keyUri:r}),o=this.getAlgorithmName({key:i});return this.getAlgorithm({algorithm:o}).sign({data:n,key:i})})}verify(e){return to(this,arguments,void 0,function*({key:r,signature:n,data:i}){let o=this.getAlgorithmName({key:r});return this.getAlgorithm({algorithm:o}).verify({key:r,signature:n,data:i})})}getAlgorithm({algorithm:e}){var r;let n=(r=Dw[e])===null||r===void 0?void 0:r.implementation;if(!n)throw new Error(`Algorithm not supported: ${e}`);return this._algorithmInstances.has(n)||this._algorithmInstances.set(n,new n),this._algorithmInstances.get(n)}getAlgorithmName({key:e}){let r=e.alg,n=e.crv;for(let i in Dw){let o=Dw[i];if(r&&o.names.includes(r))return i;if(n&&o.names.includes(n))return i}throw new Error(`Unable to determine algorithm based on provided input: alg=${r}, crv=${n}`)}getPrivateKey(e){return to(this,arguments,void 0,function*({keyUri:r}){let n=yield this._keyStore.get(r);if(!n)throw new Error(`Key not found: ${r}`);return n})}};l();var cp=class t{static getJoseSignatureAlgorithmFromPublicKey(e){let r={Ed25519:"EdDSA","P-256":"ES256","P-384":"ES384","P-521":"ES512",secp256k1:"ES256K"};if(e.alg&&Object.values(r).includes(e.alg))return e.alg;if(e.crv&&Object.keys(r).includes(e.crv))return r[e.crv];throw new Error(`Unable to determine algorithm based on provided input: alg=${e.alg}, crv=${e.crv}. Supported 'alg' values: ${Object.values(r).join(", ")}. Supported 'crv' values: ${Object.keys(r).join(", ")}.`)}static randomBytes(e){return yT(e)}static randomUuid(){return Da.randomUUID()}static randomPin({length:e}){if(3>e||e>10)throw new Error("randomPin() can securely generate a PIN between 3 to 10 digits.");let r=Math.pow(10,e)-1,n;if(e<=6){let i=Math.pow(10,e);do{let o=t.randomBytes(Math.ceil(e/2));n=new DataView(o.buffer).getUint16(0,!1)%i}while(n>r)}else{let i=Math.pow(10,10);do{let o=t.randomBytes(4);n=new DataView(o.buffer).getUint32(0,!1)%i}while(n>r)}return n.toString().padStart(e,"0")}};l();l();l();l();l();l();l();l();l();l();var Xo=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},IN=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},$a=class t{static bytesToPrivateKey(e){return Xo(this,arguments,void 0,function*({privateKeyBytes:r}){let n=hc.getPublicKey(r),i={kty:"OKP",crv:"X25519",d:ne.uint8Array(r).toBase64Url(),x:ne.uint8Array(n).toBase64Url()};return i.kid=yield ge({jwk:i}),i})}static bytesToPublicKey(e){return Xo(this,arguments,void 0,function*({publicKeyBytes:r}){let n={kty:"OKP",crv:"X25519",x:ne.uint8Array(r).toBase64Url()};return n.kid=yield ge({jwk:n}),n})}static computePublicKey(e){return Xo(this,arguments,void 0,function*({key:r}){let n=yield t.privateKeyToBytes({privateKey:r}),i=hc.getPublicKey(n),o={kty:"OKP",crv:"X25519",x:ne.uint8Array(i).toBase64Url()};return o.kid=yield ge({jwk:o}),o})}static generateKey(){return Xo(this,void 0,void 0,function*(){let e=hc.utils.randomPrivateKey(),r=yield t.bytesToPrivateKey({privateKeyBytes:e});return r.kid=yield ge({jwk:r}),r})}static getPublicKey(e){return Xo(this,arguments,void 0,function*({key:r}){var n;if(!(ui(r)&&r.crv==="X25519"))throw new Error("X25519: The provided key is not an X25519 private JWK.");let{d:i}=r,o=IN(r,["d"]);return(n=o.kid)!==null&&n!==void 0||(o.kid=yield ge({jwk:o})),o})}static privateKeyToBytes(e){return Xo(this,arguments,void 0,function*({privateKey:r}){if(!ui(r))throw new Error("X25519: The provided key is not a valid OKP private key.");return ne.base64Url(r.d).toUint8Array()})}static publicKeyToBytes(e){return Xo(this,arguments,void 0,function*({publicKey:r}){if(!Ka(r))throw new Error("X25519: The provided key is not a valid OKP public key.");return ne.base64Url(r.x).toUint8Array()})}static sharedSecret(e){return Xo(this,arguments,void 0,function*({privateKeyA:r,publicKeyB:n}){if("x"in r&&"x"in n&&r.x===n.x)throw new Error("X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.");let i=yield t.privateKeyToBytes({privateKey:r}),o=yield t.publicKeyToBytes({publicKey:n});return hc.getSharedSecret(i,o)})}};l();l();l();function Lr(t){if(typeof t=="string"&&t.length!==0)return t.split("#").pop()}function Cw({didDocument:t}){var e,r;if(!t)throw new TypeError("Required parameter missing: 'didDocument'");let n=[];return n.push(...(r=(e=t.verificationMethod)===null||e===void 0?void 0:e.filter(Nw))!==null&&r!==void 0?r:[]),Object.keys(Li).forEach(i=>{var o,s;n.push(...(s=(o=t[i])===null||o===void 0?void 0:o.filter(Nw))!==null&&s!==void 0?s:[])}),n}function JT({didDocument:t}){let r=Cw({didDocument:t}).map(n=>n.type);return[...new Set(r)]}function ZT({didDocument:t,methodId:e}){let r=[];return Object.keys(Li).forEach(n=>{if(Array.isArray(t[n])){let i=t[n],o=Lr(e);i.some(c=>{let a=Lr(c)===o,u=Nw(c)&&Lr(c.id)===o;return a||u})&&r.push(n)}}),r}function XT(t){return!t||typeof t!="object"||t===null?!1:"id"in t&&"type"in t&&"serviceEndpoint"in t}function Nw(t){return!(!t||typeof t!="object"||t===null||!("id"in t&&"type"in t&&"controller"in t)||typeof t.id!="string"||typeof t.type!="string"||typeof t.controller!="string")}function Lw({keyBytes:t,multicodecCode:e,multicodecName:r}){let n=zt.addPrefix({code:e,data:t,name:r}),i=ne.uint8Array(n).toBase58Btc();return ne.base58Btc(i).toMultibase()}function Pw({multibaseKeyId:t}){try{let e=ne.multibase(t).toBase58Btc(),r=ne.base58Btc(e).toUint8Array(),{code:n,data:i,name:o}=zt.removePrefix({prefixedData:r});return{keyBytes:i,multicodecCode:n,multicodecName:o}}catch{throw new re(ie.InvalidDid,`Invalid multibase identifier: ${t}`)}}var jd=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},gr=class t{constructor({uri:e,document:r,metadata:n,keyManager:i}){this.uri=e,this.document=r,this.metadata=n,this.keyManager=i}export(){return jd(this,void 0,void 0,function*(){if(!(Array.isArray(this.document.verificationMethod)&&this.document.verificationMethod.length>0))throw new Error(`DID document for '${this.uri}' is missing verification methods`);let e=JSON.parse(JSON.stringify({uri:this.uri,document:this.document,metadata:this.metadata}));if("exportKey"in this.keyManager&&typeof this.keyManager.exportKey=="function"){let r=[];for(let n of this.document.verificationMethod){if(!n.publicKeyJwk)throw new Error(`Verification method '${n.id}' does not contain a public key in JWK format`);let i=yield this.keyManager.getKeyUri({key:n.publicKeyJwk}),o=yield this.keyManager.exportKey({keyUri:i});r.push(Object.assign({},o))}e.privateKeys=r}return e})}getSigner(e){return jd(this,void 0,void 0,function*(){var r;let n=(r=this.document.verificationMethod)===null||r===void 0?void 0:r.find(a=>{var u,d;return Lr(a.id)===((u=Lr(e?.methodId))!==null&&u!==void 0?u:Lr((d=this.document.assertionMethod)===null||d===void 0?void 0:d[0]))});if(!(n&&n.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");let i=yield this.keyManager.getKeyUri({key:n.publicKeyJwk}),o=yield this.keyManager.getPublicKey({keyUri:i}),s=this.keyManager;return{algorithm:cp.getJoseSignatureAlgorithmFromPublicKey(o),keyId:n.id,sign(a){return jd(this,arguments,void 0,function*({data:u}){return yield s.sign({data:u,keyUri:i})})},verify(a){return jd(this,arguments,void 0,function*({data:u,signature:d}){return yield s.verify({data:u,key:o,signature:d})})}}})}static import(e){return jd(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){var i;let o=Cw({didDocument:r.document});if(o.length===0)throw new re(ie.InvalidDidDocument,"At least one verification method is required but 0 were given");for(let c of(i=r.privateKeys)!==null&&i!==void 0?i:[]){let a=yield n.getKeyUri({key:c});(yield n.getPublicKey({keyUri:a}).then(()=>!0).catch(()=>!1))||(yield n.importKey({key:c}))}for(let c of o){if(!c.publicKeyJwk)throw new Error(`Verification method '${c.id}' does not contain a public key in JWK format`);let a=yield n.getKeyUri({key:c.publicKeyJwk});yield n.getPublicKey({keyUri:a})}return new t({uri:r.uri,document:r.document,metadata:r.metadata,keyManager:n})})}};l();l();l();l();l();var Mw="0123456789abcdef",e_=[],QT=[];for(let t=0;t<256;t++)e_[t]=Mw[t>>4&15]+Mw[t&15],t<16&&(t<10?QT[48+t]=t:QT[87+t]=t);var Kw=t=>{let e=t.length,r="",n=0;for(;n<e;)r+=e_[t[n++]];return r};var t_=(t,e=0)=>{let r=t.length||0;if(!e){let s=r;for(;s--;)e+=t[s].length}let n=new Uint8Array(e),i=e,o=r;for(;o--;)i-=t[o].length,n.set(t[o],i);return n};l();var r_="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",UN=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(Wd=0;Wd<r_.length;Wd++)UN[r_.charCodeAt(Wd)]=Wd;var Wd;var ON=new TextDecoder,$w=(t,e)=>e?new TextDecoder(e).decode(t):ON.decode(t),DN=new TextEncoder,cn=t=>DN.encode(t);var n_=typeof window<"u"?window:self,i_=n_.crypto||n_.msCrypto||{},VY=i_.subtle||i_.webkitSubtle;l();function Ha(t){let e=t<0?1:0;return t=Math.abs(Number(t||1)),Math.floor(Math.log10(t))+1+e}function ap(t){return ArrayBuffer.isView(t)?"arraybufferview":Array.isArray(t)?"array":t instanceof Number?"number":t instanceof Boolean?"boolean":t instanceof Set?"set":t instanceof Map?"map":t instanceof String?"string":t instanceof ArrayBuffer?"arraybuffer":typeof t}function Be(t,e,r){let n=[],i=null;return Be._encode(n,t),i=t_(n),Be.bytes=i.length,ArrayBuffer.isView(e)?(e.set(i,r),e):i}Be.bytes=-1;Be._floatConversionDetected=!1;Be._encode=function(t,e){if(e!=null)switch(ap(e)){case"object":Be.dict(t,e);break;case"map":Be.dictMap(t,e);break;case"array":Be.list(t,e);break;case"set":Be.listSet(t,e);break;case"string":Be.string(t,e);break;case"number":Be.number(t,e);break;case"boolean":Be.number(t,e);break;case"arraybufferview":Be.buffer(t,new Uint8Array(e.buffer,e.byteOffset,e.byteLength));break;case"arraybuffer":Be.buffer(t,new Uint8Array(e));break}};var up=new Uint8Array([101]),o_=new Uint8Array([100]),s_=new Uint8Array([108]);Be.buffer=function(t,e){t.push(cn(e.length+":"),e)};Be.string=function(t,e){t.push(cn(cn(e).byteLength+":"+e))};Be.number=function(t,e){if(Number.isInteger(e))return t.push(cn("i"+BigInt(e)+"e"));let r=2147483648,n=e/r<<0,i=e%r<<0,o=n*r+i;t.push(cn("i"+o+"e")),o!==e&&!Be._floatConversionDetected&&(Be._floatConversionDetected=!0,console.warn('WARNING: Possible data corruption detected with value "'+e+'":','Bencoding only defines support for integers, value was converted to "'+o+'"'),console.trace())};Be.dict=function(t,e){t.push(o_);let r=0,n,i=Object.keys(e).sort(),o=i.length;for(;r<o;r++)n=i[r],e[n]!=null&&(Be.string(t,n),Be._encode(t,e[n]));t.push(up)};Be.dictMap=function(t,e){t.push(o_);let r=Array.from(e.keys()).sort();for(let n of r)e.get(n)!=null&&(ArrayBuffer.isView(n)?Be._encode(t,n):Be.string(t,String(n)),Be._encode(t,e.get(n)));t.push(up)};Be.list=function(t,e){let r=0,n=e.length;for(t.push(s_);r<n;r++)e[r]!=null&&Be._encode(t,e[r]);t.push(up)};Be.listSet=function(t,e){t.push(s_);for(let r of e)r!=null&&Be._encode(t,r);t.push(up)};var c_=Be;l();var kN=105,NN=58,CN=100,LN=108,Hw=101;function a_(t,e,r){let n=0,i=1;for(let o=e;o<r;o++){let s=t[o];if(s<58&&s>=48){n=n*10+(s-48);continue}if(!(o===e&&s===43)){if(o===e&&s===45){i=-1;continue}if(s===46)break;throw new Error("not a number: buffer["+o+"] = "+s)}}return n*i}function de(t,e,r,n){return t==null||t.length===0?null:(typeof e!="number"&&n==null&&(n=e,e=void 0),typeof r!="number"&&n==null&&(n=r,r=void 0),de.position=0,de.encoding=n||null,de.data=ArrayBuffer.isView(t)?new Uint8Array(t.slice(e,r)):cn(t),de.bytes=de.data.length,de.next())}de.bytes=0;de.position=0;de.data=null;de.encoding=null;de.next=function(){switch(de.data[de.position]){case CN:return de.dictionary();case LN:return de.list();case kN:return de.integer();default:return de.buffer()}};de.find=function(t){let e=de.position,r=de.data.length,n=de.data;for(;e<r;){if(n[e]===t)return e;e++}throw new Error('Invalid data: Missing delimiter "'+String.fromCharCode(t)+'" [0x'+t.toString(16)+"]")};de.dictionary=function(){de.position++;let t={};for(;de.data[de.position]!==Hw;){let e=de.buffer(),r=$w(e);r.includes("\uFFFD")&&(r=Kw(e)),t[r]=de.next()}return de.position++,t};de.list=function(){de.position++;let t=[];for(;de.data[de.position]!==Hw;)t.push(de.next());return de.position++,t};de.integer=function(){let t=de.find(Hw),e=a_(de.data,de.position+1,t);return de.position+=t+1-de.position,e};de.buffer=function(){let t=de.find(NN),e=a_(de.data,de.position,t),r=++t+e;return de.position=r,de.encoding?$w(de.data.slice(t,r)):de.data.slice(t,r)};var u_=de;l();function PN(t){let e=2;for(let r of t)e+=dp(r);return e}function MN(t){let e=2;for(let[r,n]of t){let i=cn(r).byteLength;e+=Ha(i)+1+i,e+=dp(n)}return e}function KN(t){let e=2,r=Object.keys(t);for(let n=0;n<r.length;n++){let i=cn(r[n]).byteLength;e+=Ha(i)+1+i,e+=dp(t[r[n]])}return e}function $N(t){let e=cn(t).byteLength;return Ha(e)+1+e}function HN(t){let e=t.byteLength-t.byteOffset;return Ha(e)+1+e}function dp(t){if(t==null)return 0;let r=ap(t);switch(r){case"arraybufferview":return HN(t);case"string":return $N(t);case"array":case"set":return PN(t);case"number":return 1+Ha(Math.floor(t))+1;case"bigint":return 1+t.toString().length+1;case"object":return KN(t);case"map":return MN(t);default:throw new TypeError(`Unsupported value of type "${r}"`)}}var Vw=dp;var VN=Vw,qw={encode:c_,decode:u_,byteLength:Vw,encodingLength:VN};l();l();var qN=/^(\d{1,3}\.){3,3}\d{1,3}$/;var FN=/^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;var On={name:"v4",size:4,isFormat:t=>qN.test(t),encode(t,e,r){r=~~r,e=e||new Uint8Array(r+4);let n=t.length,i=0;for(let o=0;o<n;){let s=t.charCodeAt(o++);s===46?(e[r++]=i,i=0):i=i*10+(s-48)}return e[r]=i,e},decode(t,e){return e=~~e,`${t[e++]}.${t[e++]}.${t[e++]}.${t[e]}`}},ro={name:"v6",size:16,isFormat:t=>t.length>0&&FN.test(t),encode(t,e,r){r=~~r;let n=r+16,i=-1,o=0,s=0,c=!0,a=!1;e=e||new Uint8Array(r+16);for(let u=0;u<t.length;u++){let d=t.charCodeAt(u);d===58?(c?i!==-1?(r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2):r<n&&(i=r):(a===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2),o=0,s=0),c=!0,a=!1):d===46?(r<n&&(e[r]=s),r++,s=0,o=0,c=!1,a=!0):(c=!1,d>=97?d-=87:d>=65?d-=55:(d-=48,s=s*10+d),o=(o<<4)+d)}if(c===!1)a===!0?(r<n&&(e[r]=s),r++):(r<n&&(e[r]=o>>8),r<n-1&&(e[r+1]=o&255),r+=2);else if(i===0)r<n&&(e[r]=0),r<n-1&&(e[r+1]=0),r+=2;else if(i!==-1){r+=2;for(let u=Math.min(r-1,n-1);u>=i+2;u--)e[u]=e[u-2];e[i]=0,e[i+1]=0,i=r}if(i!==r&&i!==-1)for(r>n-2&&(r=n-2);n>i;)e[--n]=r<n&&r>i?e[--r]:0;else for(;r<n;)e[r++]=0;return e},decode(t,e){e=~~e;let r="";for(let n=0;n<16;n+=2)n!==0&&(r+=":"),r+=(t[e+n]<<8|t[e+n+1]).toString(16);return r.replace(/(^|:)0(:0)*:0(:|$)/,"$1::$3").replace(/:{3,4}/,"::")}};function d_(t){if(On.isFormat(t))return On.size;if(ro.isFormat(t))return ro.size;throw Error(`Invalid ip address: ${t}`)}function f_(t){return d_(t)===On.size?1:2}function l_(t,e,r){r=~~r;let n=d_(t);return typeof e=="function"&&(e=e(r+n)),n===On.size?On.encode(t,e,r):ro.encode(t,e,r)}function h_(t,e,r){if(e=~~e,r=r||t.length-e,r===On.size)return On.decode(t,e,r);if(r===ro.size)return ro.decode(t,e,r);throw Error(`Invalid buffer size needs to be ${On.size} for v4 or ${ro.size} for v6.`)}l();function Gd(t){switch(t){case 1:return"A";case 10:return"NULL";case 28:return"AAAA";case 18:return"AFSDB";case 42:return"APL";case 257:return"CAA";case 60:return"CDNSKEY";case 59:return"CDS";case 37:return"CERT";case 5:return"CNAME";case 49:return"DHCID";case 32769:return"DLV";case 39:return"DNAME";case 48:return"DNSKEY";case 43:return"DS";case 55:return"HIP";case 13:return"HINFO";case 45:return"IPSECKEY";case 25:return"KEY";case 36:return"KX";case 29:return"LOC";case 15:return"MX";case 35:return"NAPTR";case 2:return"NS";case 47:return"NSEC";case 50:return"NSEC3";case 51:return"NSEC3PARAM";case 12:return"PTR";case 46:return"RRSIG";case 17:return"RP";case 24:return"SIG";case 6:return"SOA";case 99:return"SPF";case 33:return"SRV";case 44:return"SSHFP";case 32768:return"TA";case 249:return"TKEY";case 52:return"TLSA";case 250:return"TSIG";case 16:return"TXT";case 252:return"AXFR";case 251:return"IXFR";case 41:return"OPT";case 255:return"ANY"}return"UNKNOWN_"+t}function Va(t){switch(t.toUpperCase()){case"A":return 1;case"NULL":return 10;case"AAAA":return 28;case"AFSDB":return 18;case"APL":return 42;case"CAA":return 257;case"CDNSKEY":return 60;case"CDS":return 59;case"CERT":return 37;case"CNAME":return 5;case"DHCID":return 49;case"DLV":return 32769;case"DNAME":return 39;case"DNSKEY":return 48;case"DS":return 43;case"HIP":return 55;case"HINFO":return 13;case"IPSECKEY":return 45;case"KEY":return 25;case"KX":return 36;case"LOC":return 29;case"MX":return 15;case"NAPTR":return 35;case"NS":return 2;case"NSEC":return 47;case"NSEC3":return 50;case"NSEC3PARAM":return 51;case"PTR":return 12;case"RRSIG":return 46;case"RP":return 17;case"SIG":return 24;case"SOA":return 6;case"SPF":return 99;case"SRV":return 33;case"SSHFP":return 44;case"TA":return 32768;case"TKEY":return 249;case"TLSA":return 52;case"TSIG":return 250;case"TXT":return 16;case"AXFR":return 252;case"IXFR":return 251;case"OPT":return 41;case"ANY":return 255;case"*":return 255}return t.toUpperCase().startsWith("UNKNOWN_")?parseInt(t.slice(8)):0}l();function p_(t){switch(t){case 0:return"NOERROR";case 1:return"FORMERR";case 2:return"SERVFAIL";case 3:return"NXDOMAIN";case 4:return"NOTIMP";case 5:return"REFUSED";case 6:return"YXDOMAIN";case 7:return"YXRRSET";case 8:return"NXRRSET";case 9:return"NOTAUTH";case 10:return"NOTZONE";case 11:return"RCODE_11";case 12:return"RCODE_12";case 13:return"RCODE_13";case 14:return"RCODE_14";case 15:return"RCODE_15"}return"RCODE_"+t}l();function y_(t){switch(t){case 0:return"QUERY";case 1:return"IQUERY";case 2:return"STATUS";case 3:return"OPCODE_3";case 4:return"NOTIFY";case 5:return"UPDATE";case 6:return"OPCODE_6";case 7:return"OPCODE_7";case 8:return"OPCODE_8";case 9:return"OPCODE_9";case 10:return"OPCODE_10";case 11:return"OPCODE_11";case 12:return"OPCODE_12";case 13:return"OPCODE_13";case 14:return"OPCODE_14";case 15:return"OPCODE_15"}return"OPCODE_"+t}l();function Fw(t){switch(t){case 1:return"IN";case 2:return"CS";case 3:return"CH";case 4:return"HS";case 255:return"ANY"}return"UNKNOWN_"+t}function jw(t){switch(t.toUpperCase()){case"IN":return 1;case"CS":return 2;case"CH":return 3;case"HS":return 4;case"ANY":return 255}return 0}l();function g_(t){switch(t){case 1:return"LLQ";case 2:return"UL";case 3:return"NSID";case 5:return"DAU";case 6:return"DHU";case 7:return"N3U";case 8:return"CLIENT_SUBNET";case 9:return"EXPIRE";case 10:return"COOKIE";case 11:return"TCP_KEEPALIVE";case 12:return"PADDING";case 13:return"CHAIN";case 14:return"KEY_TAG";case 26946:return"DEVICEID"}return t<0?null:`OPTION_${t}`}function Ww(t){if(typeof t=="number")return t;if(!t)return-1;switch(t.toUpperCase()){case"OPTION_0":return 0;case"LLQ":return 1;case"UL":return 2;case"NSID":return 3;case"OPTION_4":return 4;case"DAU":return 5;case"DHU":return 6;case"N3U":return 7;case"CLIENT_SUBNET":return 8;case"EXPIRE":return 9;case"COOKIE":return 10;case"TCP_KEEPALIVE":return 11;case"PADDING":return 12;case"CHAIN":return 13;case"KEY_TAG":return 14;case"DEVICEID":return 26946;case"OPTION_65535":return 65535}let e=t.match(/_(\d+)$/);return e?parseInt(e[1],10):-1}l();l();function Gw(t){let e=0,r=t.length;for(let n=0;n<r;n+=1){let i=t.charCodeAt(n);if(i<=127)e+=1;else if(i<=2047)e+=2;else if((i&63488)!==55296)e+=3;else{let o=n+1;o===r||i>=56320||(t.charCodeAt(o)&64512)!==56320?e+=3:(n=o,e+=4)}}return e}function qa(t,e,r){let n=t.length;r==null&&(r=0),e===void 0&&(e=new Uint8Array(Gw(t)+r));let i=r;for(let o=0;o<n;o+=1){let s=t.charCodeAt(o);if(s<=127)e[i++]=s;else if(s<=2047)e[i++]=192|(s&1984)>>6,e[i++]=128|s&63;else if((s&63488)!==55296)e[i++]=224|(s&61440)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63;else{let c=o+1;if(c===n||s>=56320)e[i++]=239,e[i++]=191,e[i++]=189;else{let a=t.charCodeAt(c);(a&64512)!==56320?(e[i++]=239,e[i++]=191,e[i++]=189):(o=c,s=65536|(s&1023)<<10|a&1023,e[i++]=240|(s&1835008)>>18,e[i++]=128|(s&258048)>>12,e[i++]=128|(s&4032)>>6,e[i++]=128|s&63)}}}return qa.bytes=i-r,e}qa.bytes=0;function Fa(t,e,r){let n="";e==null&&(e=0),r==null&&(r=t.length);for(let i=e;i<r;){let o=t[i++],s;if(o<=128)s=o;else if(o>191&&o<224)s=(o&31)<<6|t[i++]&63;else if(o>239&&o<365){s=((o&7)<<18|(t[i++]&63)<<12|(t[i++]&63)<<6|t[i++]&63)-65536;let c=55296|s>>10&1023;n+=String.fromCharCode(c),s=56320|s&1023}else s=(o&15)<<12|(t[i++]&63)<<6|t[i++]&63;n+=String.fromCharCode(s)}return Fa.bytes=r-e,n}Fa.bytes=0;var Qo=t=>t instanceof Uint8Array;function no(t){return typeof t=="string"?Gw(t):t.byteLength}function fp(t){return t instanceof Uint8Array?t:Array.isArray(t)?new Uint8Array(t):qa(t)}function lp(t,e,r){if(typeof e!="string")throw new Error("unknown input type");return qa(e,t,r),qa.bytes}var zd={},m_=new Array(255);for(let t=0;t<=15;t+=1){let e=t.toString(16),r=e.toUpperCase();for(let n=0;n<=15;n+=1){let i=n.toString(16),o=i.toUpperCase(),s=t<<4|n,c=`${e}${i}`;m_[s]=c,zd[c]=s,zd[`${r}${i}`]=s,zd[`${e}${o}`]=s,zd[`${r}${o}`]=s}}function w_(t,e,r){let n="";for(let i=e;i<r;){let o=t[i++];n+=m_[o]}return n}function zw(t){return t.length>>>1}function b_(t,e,r,n){let i=0;for(;r<n;){let o=e.substr(i,2),s=zd[o];if(s===void 0)return;t[r++]=s,i+=2}return t}var XN=Math.pow(2,24),QN=Math.pow(2,16),eC=Math.pow(2,8),di=(t,e)=>t[e]*XN+t[e+1]*QN+t[e+2]*eC+t[e+3],he=(t,e)=>t[e]<<8|t[e+1],fi=(t,e,r)=>(e=+e,t[r+3]=e,e=e>>>8,t[r+2]=e,e=e>>>8,t[r+1]=e,e=e>>>8,t[r]=e,r+4),ae=(t,e,r)=>(t[r]=e>>8,t[r+1]=e&255,r+2);function mr(t,e,r,n,i){return r<0&&(n-=r,r=0),n<0&&(n=0),i<0?new Uint8Array(0):r>=e.length||n>=i?0:tC(t,e,r,n,i)}function tC(t,e,r,n,i){i-n>e.length-r&&(i=n+e.length-r);let o=i-n,s=t.length-n;return o>s&&(o=s),(n!==0||i<t.length)&&(t=new Uint8Array(t.buffer,t.byteOffset+n,o)),e.set(t,r),o}var nC=0,x_=32768,Jw=32768,iC=~Jw,v_=32768,oC=~v_;function Ke({bytes:t=0,encode:e,decode:r,encodingLength:n}){return e.bytes=t,r.bytes=t,{encode:e,decode:r,encodingLength:n||(()=>t)}}var se=Ke({encode(t,e,r){e||(e=new Uint8Array(se.encodingLength(t))),r||(r=0);let n=r,i=t.replace(/^\.|\.$/gm,"");if(i.length){let o=i.split(".");for(let s=0;s<o.length;s++){let c=lp(e,o[s],r+1);e[r]=c,r+=c+1}}return e[r++]=0,se.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=[],n=e,i=0,o=0,s=!1;for(;;){if(e>=t.length)throw new Error("Cannot decode name (buffer overflow)");let c=t[e++];if(o+=s?0:1,c===0)break;if(c&192)if((c&192)===192){if(e+1>t.length)throw new Error("Cannot decode name (buffer overflow)");let a=he(t,e-1)-49152;if(a>=n)throw new Error("Cannot decode name (bad pointer)");e=a,n=a,o+=s?0:1,s=!0}else throw new Error("Cannot decode name (bad label)");else{if(e+c>t.length)throw new Error("Cannot decode name (buffer overflow)");if(i+=c+1,i>254)throw new Error("Cannot decode name (name too long)");r.push(Fa(t,e,e+c)),e+=c,o+=s?0:c}}return se.decode.bytes=o,r.length===0?".":r.join(".")},encodingLength(t){return t==="."||t===".."?1:no(t.replace(/^\.|\.$/gm,""))+2}}),Bt=Ke({encode(t,e,r){e||(e=new Uint8Array(Bt.encodingLength(t))),r||(r=0);let n=lp(e,t,r+1);return e[r]=n,Bt.encode.bytes=n+1,e},decode(t,e){e||(e=0);let r=t[e],n=Fa(t,e+1,e+1+r);return Bt.decode.bytes=r+1,n},encodingLength(t){return no(t)+1}}),ja=Ke({bytes:12,encode(t,e,r){e||(e=new Uint8Array(ja.encodingLength(t))),r||(r=0);let n=(t.flags||0)&32767,i=t.type==="response"?x_:nC;return ae(e,t.id||0,r),ae(e,n|i,r+2),ae(e,t.questions.length,r+4),ae(e,t.answers.length,r+6),ae(e,t.authorities.length,r+8),ae(e,t.additionals.length,r+10),e},decode(t,e){if(e||(e=0),t.length<12)throw new Error("Header must be 12 bytes");let r=he(t,e+2);return{id:he(t,e),type:r&x_?"response":"query",flags:r&32767,flag_qr:(r>>15&1)===1,opcode:y_(r>>11&15),flag_aa:(r>>10&1)===1,flag_tc:(r>>9&1)===1,flag_rd:(r>>8&1)===1,flag_ra:(r>>7&1)===1,flag_z:(r>>6&1)===1,flag_ad:(r>>5&1)===1,flag_cd:(r>>4&1)===1,rcode:p_(r&15),questions:new Array(he(t,e+4)),answers:new Array(he(t,e+6)),authorities:new Array(he(t,e+8)),additionals:new Array(he(t,e+10))}},encodingLength(){return 12}}),pp=Ke({encode(t,e,r){e||(e=new Uint8Array(pp.encodingLength(t))),r||(r=0);let n=t.length;return ae(e,n,r),mr(t,e,r+2,0,n),pp.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=he(t,e),n=t.slice(e+2,e+2+r);return pp.decode.bytes=r+2,n},encodingLength(t){return t.length+2}}),yp=Ke({encode(t,e,r){return e||(e=new Uint8Array(yp.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),yp.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=he(t,e),n=se.decode(t,e+2);return yp.decode.bytes=r+2,n},encodingLength(t){return se.encodingLength(t)+2}}),gp=Ke({encode(t,e,r){e||(e=new Uint8Array(gp.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.mname,e,r),r+=se.encode.bytes,se.encode(t.rname,e,r),r+=se.encode.bytes,fi(e,t.serial||0,r),r+=4,fi(e,t.refresh||0,r),r+=4,fi(e,t.retry||0,r),r+=4,fi(e,t.expire||0,r),r+=4,fi(e,t.minimum||0,r),r+=4,ae(e,r-n-2,n),gp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mname=se.decode(t,e),e+=se.decode.bytes,n.rname=se.decode(t,e),e+=se.decode.bytes,n.serial=di(t,e),e+=4,n.refresh=di(t,e),e+=4,n.retry=di(t,e),e+=4,n.expire=di(t,e),e+=4,n.minimum=di(t,e),e+=4,gp.decode.bytes=e-r,n},encodingLength(t){return 22+se.encodingLength(t.mname)+se.encodingLength(t.rname)}}),mp=Ke({encode(t,e,r){Array.isArray(t)||(t=[t]);for(let i=0;i<t.length;i++)if(typeof t[i]=="string"&&(t[i]=fp(t[i])),!Qo(t[i]))throw new Error("Must be a Buffer");e||(e=new Uint8Array(mp.encodingLength(t))),r||(r=0);let n=r;return r+=2,t.forEach(function(i){e[r++]=i.length,mr(i,e,r,0,i.length),r+=i.length}),ae(e,r-n-2,n),mp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=he(t,e);e+=2;let i=[];for(;n>0;){let o=t[e++];if(--n,n<o)throw new Error("Buffer overflow");i.push(t.slice(e,e+o)),e+=o,n-=o}return mp.decode.bytes=e-r,i},encodingLength(t){Array.isArray(t)||(t=[t]);let e=2;return t.forEach(function(r){typeof r=="string"?e+=no(r)+1:e+=r.length+1}),e}}),wp=Ke({encode(t,e,r){e||(e=new Uint8Array(wp.encodingLength(t))),r||(r=0),typeof t=="string"&&(t=fp(t)),t||(t=new Uint8Array(0));let n=r;r+=2;let i=t.length;return mr(t,e,r,0,i),r+=i,ae(e,r-n-2,n),wp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=he(t,e);e+=2;let i=t.slice(e,e+n);return e+=n,wp.decode.bytes=e-r,i},encodingLength(t){return t?(Qo(t)?t.length:no(t))+2:2}}),bp=Ke({encode(t,e,r){e||(e=new Uint8Array(bp.encodingLength(t))),r||(r=0);let n=r;return r+=2,Bt.encode(t.cpu,e,r),r+=Bt.encode.bytes,Bt.encode(t.os,e,r),r+=Bt.encode.bytes,ae(e,r-n-2,n),bp.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.cpu=Bt.decode(t,e),e+=Bt.decode.bytes,n.os=Bt.decode(t,e),e+=Bt.decode.bytes,bp.decode.bytes=e-r,n},encodingLength(t){return Bt.encodingLength(t.cpu)+Bt.encodingLength(t.os)+2}}),za=Ke({encode(t,e,r){return e||(e=new Uint8Array(za.encodingLength(t))),r||(r=0),se.encode(t,e,r+2),ae(e,se.encode.bytes,r),za.encode.bytes=se.encode.bytes+2,e},decode(t,e){e||(e=0);let r=se.decode(t,e+2);return za.decode.bytes=se.decode.bytes+2,r},encodingLength(t){return se.encodingLength(t)+2}}),xp=Ke({encode(t,e,r){e||(e=new Uint8Array(xp.encodingLength(t))),r||(r=0),ae(e,t.priority||0,r+2),ae(e,t.weight||0,r+4),ae(e,t.port||0,r+6),se.encode(t.target,e,r+8);let n=se.encode.bytes+6;return ae(e,n,r),xp.encode.bytes=n+2,e},decode(t,e){e||(e=0);let r=he(t,e),n={};return n.priority=he(t,e+2),n.weight=he(t,e+4),n.port=he(t,e+6),n.target=se.decode(t,e+8),xp.decode.bytes=r+2,n},encodingLength(t){return 8+se.encodingLength(t.target)}}),es=Ke({encode(t,e,r){let n=es.encodingLength(t);return e||(e=new Uint8Array(es.encodingLength(t))),r||(r=0),t.issuerCritical&&(t.flags=es.ISSUER_CRITICAL),ae(e,n-2,r),r+=2,e[r]=t.flags||0,r+=1,Bt.encode(t.tag,e,r),r+=Bt.encode.bytes,lp(e,t.value,r),r+=no(t.value),es.encode.bytes=n,e},decode(t,e){e||(e=0);let r=he(t,e);e+=2;let n=e,i={};return i.flags=t[e],e+=1,i.tag=Bt.decode(t,e),e+=Bt.decode.bytes,i.value=Fa(t,e,n+r),i.issuerCritical=!!(i.flags&es.ISSUER_CRITICAL),es.decode.bytes=r+2,i},encodingLength(t){return Bt.encodingLength(t.tag)+Bt.encodingLength(t.value)+2}});es.ISSUER_CRITICAL=128;var Ep=Ke({encode(t,e,r){e||(e=new Uint8Array(Ep.encodingLength(t))),r||(r=0);let n=r;return r+=2,ae(e,t.preference||0,r),r+=2,se.encode(t.exchange,e,r),r+=se.encode.bytes,ae(e,r-n-2,n),Ep.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.preference=he(t,e),e+=2,n.exchange=se.decode(t,e),e+=se.decode.bytes,Ep.decode.bytes=e-r,n},encodingLength(t){return 4+se.encodingLength(t.exchange)}}),S_=Ke({encode(t,e,r){return e||(e=new Uint8Array(S_.encodingLength(t))),r||(r=0),ae(e,4,r),r+=2,On.encode(t,e,r),e},decode(t,e){return e||(e=0),e+=2,On.decode(t,e)},bytes:6}),vp=Ke({encode(t,e,r){return e||(e=new Uint8Array(vp.encodingLength(t))),r||(r=0),ae(e,16,r),r+=2,ro.encode(t,e,r),vp.encode.bytes=18,e},decode(t,e){e||(e=0),e+=2;let r=ro.decode(t,e);return vp.decode.bytes=18,r},bytes:18}),E_=t=>new Uint8Array(t),io=Ke({encode(t,e,r){e||(e=new Uint8Array(io.encodingLength(t))),r||(r=0);let n=r,i=Ww(t.code);if(ae(e,i,r),r+=2,t.data)ae(e,t.data.length,r),r+=2,mr(t.data,e,r),r+=t.data.length;else switch(i){case 8:{let o=t.sourcePrefixLength||0,s=t.family||f_(t.ip,E_),c=l_(t.ip,E_),a=Math.ceil(o/8);ae(e,a+4,r),r+=2,ae(e,s,r),r+=2,e[r++]=o,e[r++]=t.scopePrefixLength||0,mr(c,e,r,0,a),r+=a}break;case 11:t.timeout?(ae(e,2,r),r+=2,ae(e,t.timeout,r),r+=2):(ae(e,0,r),r+=2);break;case 12:{let o=t.length||0;ae(e,o,r),r+=2,e.fill(0,r,r+o),r+=o}break;case 14:{let o=t.tags.length*2;ae(e,o,r),r+=2;for(let s of t.tags)ae(e,s,r),r+=2}break;default:throw new Error(`Unknown roption code: ${t.code}`)}return io.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={};r.code=he(t,e),r.type=g_(r.code),e+=2;let n=he(t,e);switch(e+=2,r.data=t.slice(e,e+n),r.code){case 8:r.family=he(t,e),e+=2,r.sourcePrefixLength=t[e++],r.scopePrefixLength=t[e++];{let i=new Uint8Array(r.family===1?4:16);mr(t,i,0,e,e+n-4),r.ip=h_(i)}break;case 11:n>0&&(r.timeout=he(t,e),e+=2);break;case 14:r.tags=[];for(let i=0;i<n;i+=2)r.tags.push(he(t,e)),e+=2}return io.decode.bytes=n+4,r},encodingLength(t){if(t.data)return t.data.length+4;switch(Ww(t.code)){case 8:{let r=t.sourcePrefixLength||0;return Math.ceil(r/8)+8}case 11:return typeof t.timeout=="number"?6:4;case 12:return t.length+4;case 14:return 4+t.tags.length*2}throw new Error(`Unknown roption code: ${t.code}`)}}),ts=Ke({encode(t,e,r){e||(e=new Uint8Array(ts.encodingLength(t))),r||(r=0);let n=r,i=Ga(t,io);return ae(e,i,r),r=ef(t,io,e,r+2),ts.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r=e,n=[],i=he(t,e);e+=2;let o=0;for(;i>0;)n[o++]=io.decode(t,e),e+=io.decode.bytes,i-=io.decode.bytes;return ts.decode.bytes=e-r,n},encodingLength(t){return 2+Ga(t||[],io)}}),li=Ke({encode(t,e,r){e||(e=new Uint8Array(li.encodingLength(t))),r||(r=0);let n=r,i=t.key;if(!Qo(i))throw new Error("Key must be a Buffer");return r+=2,ae(e,t.flags,r),r+=2,e[r]=li.PROTOCOL_DNSSEC,r+=1,e[r]=t.algorithm,r+=1,mr(i,e,r,0,i.length),r+=i.length,li.encode.bytes=r-n,ae(e,li.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);if(e+=2,n.flags=he(t,e),e+=2,t[e]!==li.PROTOCOL_DNSSEC)throw new Error("Protocol must be 3");return e+=1,n.algorithm=t[e],e+=1,n.key=t.slice(e,r+i+2),e+=n.key.length,li.decode.bytes=e-r,n},encodingLength(t){return 6+no(t.key)}});li.PROTOCOL_DNSSEC=3;li.ZONE_KEY=128;li.SECURE_ENTRYPOINT=32768;var Yd=Ke({encode(t,e,r){e||(e=new Uint8Array(Yd.encodingLength(t))),r||(r=0);let n=r,i=t.signature;if(!Qo(i))throw new Error("Signature must be a Buffer");return r+=2,ae(e,Va(t.typeCovered),r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.labels,r+=1,fi(e,t.originalTTL,r),r+=4,fi(e,t.expiration,r),r+=4,fi(e,t.inception,r),r+=4,ae(e,t.keyTag,r),r+=2,se.encode(t.signersName,e,r),r+=se.encode.bytes,mr(i,e,r,0,i.length),r+=i.length,Yd.encode.bytes=r-n,ae(e,Yd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.typeCovered=Gd(he(t,e)),e+=2,n.algorithm=t[e],e+=1,n.labels=t[e],e+=1,n.originalTTL=di(t,e),e+=4,n.expiration=di(t,e),e+=4,n.inception=di(t,e),e+=4,n.keyTag=he(t,e),e+=2,n.signersName=se.decode(t,e),e+=se.decode.bytes,n.signature=t.slice(e,r+i+2),e+=n.signature.length,Yd.decode.bytes=e-r,n},encodingLength(t){return 20+se.encodingLength(t.signersName)+no(t.signature)}}),Jd=Ke({encode(t,e,r){e||(e=new Uint8Array(Jd.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.mbox||".",e,r),r+=se.encode.bytes,se.encode(t.txt||".",e,r),r+=se.encode.bytes,Jd.encode.bytes=r-n,ae(e,Jd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};return e+=2,n.mbox=se.decode(t,e)||".",e+=se.decode.bytes,n.txt=se.decode(t,e)||".",e+=se.decode.bytes,Jd.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.mbox||".")+se.encodingLength(t.txt||".")}}),Pr=Ke({encode(t,e,r){e||(e=new Uint8Array(Pr.encodingLength(t))),r||(r=0);let n=r,i=[];for(let o=0;o<t.length;o++){let s=Va(t[o]);i[s>>8]===void 0&&(i[s>>8]=[]),i[s>>8][s>>3&31]|=1<<7-(s&7)}for(let o=0;o<i.length;o++)if(i[o]!==void 0){let s=fp(i[o]);e[r]=o,r+=1,e[r]=s.length,r+=1,mr(s,e,r,0,s.length),r+=s.length}return Pr.encode.bytes=r-n,e},decode(t,e,r){e||(e=0);let n=e,i=[];for(;e-n<r;){let o=t[e];e+=1;let s=t[e];e+=1;for(let c=0;c<s;c++){let a=t[e+c];for(let u=0;u<8;u++)if(a&1<<7-u){let d=Gd(o<<8|c<<3|u);i.push(d)}}e+=s}return Pr.decode.bytes=e-n,i},encodingLength(t){let e=[];for(let n=0;n<t.length;n++){let i=Va(t[n]);e[i>>8]=Math.max(e[i>>8]||0,i&255)}let r=0;for(let n=0;n<e.length;n++)e[n]!==void 0&&(r+=2+Math.ceil((e[n]+1)/8));return r}}),Zd=Ke({encode(t,e,r){e||(e=new Uint8Array(Zd.encodingLength(t))),r||(r=0);let n=r;return r+=2,se.encode(t.nextDomain,e,r),r+=se.encode.bytes,Pr.encode(t.rrtypes,e,r),r+=Pr.encode.bytes,Zd.encode.bytes=r-n,ae(e,Zd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.nextDomain=se.decode(t,e),e+=se.decode.bytes,n.rrtypes=Pr.decode(t,e,i-(e-r)),e+=Pr.decode.bytes,Zd.decode.bytes=e-r,n},encodingLength(t){return 2+se.encodingLength(t.nextDomain)+Pr.encodingLength(t.rrtypes)}}),Xd=Ke({encode(t,e,r){e||(e=new Uint8Array(Xd.encodingLength(t))),r||(r=0);let n=r,i=t.salt;if(!Qo(i))throw new Error("salt must be a Buffer");let o=t.nextDomain;if(!Qo(o))throw new Error("nextDomain must be a Buffer");return r+=2,e[r]=t.algorithm,r+=1,e[r]=t.flags,r+=1,ae(e,t.iterations,r),r+=2,e[r]=i.length,r+=1,mr(i,e,r,0,i.length),r+=i.length,e[r]=o.length,r+=1,mr(o,e,r,0,o.length),r+=o.length,Pr.encode(t.rrtypes,e,r),r+=Pr.encode.bytes,Xd.encode.bytes=r-n,ae(e,Xd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);e+=2,n.algorithm=t[e],e+=1,n.flags=t[e],e+=1,n.iterations=he(t,e),e+=2;let o=t[e];e+=1,n.salt=t.slice(e,e+o),e+=o;let s=t[e];return e+=1,n.nextDomain=t.slice(e,e+s),e+=s,n.rrtypes=Pr.decode(t,e,i-(e-r)),e+=Pr.decode.bytes,Xd.decode.bytes=e-r,n},encodingLength(t){return 8+t.salt.length+t.nextDomain.length+Pr.encodingLength(t.rrtypes)}}),Qd=Ke({encode(t,e,r){e||(e=new Uint8Array(Qd.encodingLength(t))),r||(r=0);let n=r,i=t.digest;if(!Qo(i))throw new Error("Digest must be a Buffer");return r+=2,ae(e,t.keyTag,r),r+=2,e[r]=t.algorithm,r+=1,e[r]=t.digestType,r+=1,mr(i,e,r,0,i.length),r+=i.length,Qd.encode.bytes=r-n,ae(e,Qd.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={},i=he(t,e);return e+=2,n.keyTag=he(t,e),e+=2,n.algorithm=t[e],e+=1,n.digestType=t[e],e+=1,n.digest=t.slice(e,r+i+2),e+=n.digest.length,Qd.decode.bytes=e-r,n},encodingLength(t){return 6+no(t.digest)}}),Wa=Ke({encode(t,e,r){e||(e=new Uint8Array(Wa.encodingLength(t))),r||(r=0);let n=r;r+=2,e[r]=t.algorithm,r+=1,e[r]=t.hash,r+=1;let i=zw(t.fingerprint),o=Zw(t.hash);if(i!==o)throw new Error(`Invalid length of fingerprint "${t.fingerprint}" for hashType=${t.hash}: ${i} != ${o}`);return b_(e,t.fingerprint,r,r+=i),Wa.encode.bytes=r-n,ae(e,Wa.encode.bytes-2,n),e},decode(t,e){e||(e=0);let r=e,n={};e+=2,n.algorithm=t[e],e+=1,n.hash=t[e],e+=1;let i=Zw(n.hash);return n.fingerprint=w_(t,e,e+i),e+=i,Wa.decode.bytes=e-r,n},encodingLength(t){return 4+zw(t.fingerprint)}});function Zw(t){if(t===1)return 20;if(t===2)return 32;throw new Error(`Invalid hashType=${t}, supported=1,2`)}Wa.getFingerprintLengthForHashType=Zw;function Yw(t){switch(t.toUpperCase()){case"A":return S_;case"PTR":return za;case"CNAME":return za;case"DNAME":return za;case"TXT":return mp;case"NULL":return wp;case"AAAA":return vp;case"SRV":return xp;case"HINFO":return bp;case"CAA":return es;case"NS":return yp;case"SOA":return gp;case"MX":return Ep;case"OPT":return ts;case"DNSKEY":return li;case"RRSIG":return Yd;case"RP":return Jd;case"NSEC":return Zd;case"NSEC3":return Xd;case"SSHFP":return Wa;case"DS":return Qd}return pp}var an=Ke({encode(t,e,r){e||(e=new Uint8Array(an.encodingLength(t))),r||(r=0);let n=r;if(se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Va(t.type),r),t.type.toUpperCase()==="OPT"){if(t.name!==".")throw new Error("OPT name must be root.");ae(e,t.udpPayloadSize||4096,r+2),e[r+4]=t.extendedRcode||0,e[r+5]=t.ednsVersion||0,ae(e,t.flags||0,r+6),r+=8,ts.encode(t.options||[],e,r),r+=ts.encode.bytes}else{let i=jw(t.class===void 0?"IN":t.class);t.flush&&(i|=Jw),ae(e,i,r+2),fi(e,t.ttl||0,r+4),r+=8;let o=Yw(t.type);o.encode(t.data,e,r),r+=o.encode.bytes}return an.encode.bytes=r-n,e},decode(t,e){e||(e=0);let r={},n=e;if(r.name=se.decode(t,e),e+=se.decode.bytes,r.type=Gd(he(t,e)),r.type==="OPT")r.udpPayloadSize=he(t,e+2),r.extendedRcode=t[e+4],r.ednsVersion=t[e+5],r.flags=he(t,e+6),r.flag_do=(r.flags>>15&1)===1,r.options=ts.decode(t,e+8),e+=8+ts.decode.bytes;else{let i=he(t,e+2);r.ttl=di(t,e+4),r.class=Fw(i&iC),r.flush=!!(i&Jw);let o=Yw(r.type);r.data=o.decode(t,e+8),e+=8+o.decode.bytes}return an.decode.bytes=e-n,r},encodingLength(t){let e=t.data!==null&&t.data!==void 0?t.data:t.options;return se.encodingLength(t.name)+8+Yw(t.type).encodingLength(e)}}),Ya=Ke({encode(t,e,r){e||(e=new Uint8Array(Ya.encodingLength(t))),r||(r=0);let n=r;return se.encode(t.name,e,r),r+=se.encode.bytes,ae(e,Va(t.type),r),r+=2,ae(e,jw(t.class===void 0?"IN":t.class),r),r+=2,Ya.encode.bytes=r-n,t},decode(t,e){e||(e=0);let r=e,n={};return n.name=se.decode(t,e),e+=se.decode.bytes,n.type=Gd(he(t,e)),e+=2,n.class=Fw(he(t,e)),e+=2,!!(n.class&v_)&&(n.class&=oC),Ya.decode.bytes=e-r,n},encodingLength(t){return se.encodingLength(t.name)+4}});var A_=1024;var Vt={encode:function(t,e,r){let n=!e;n&&(e=new Uint8Array(sC(t))),r||(r=0);let i=r;return t.questions||(t.questions=[]),t.answers||(t.answers=[]),t.authorities||(t.authorities=[]),t.additionals||(t.additionals=[]),ja.encode(t,e,r),r+=ja.encode.bytes,r=ef(t.questions,Ya,e,r),r=ef(t.answers,an,e,r),r=ef(t.authorities,an,e,r),r=ef(t.additionals,an,e,r),Vt.encode.bytes=r-i,n&&tf.bytes!==e.length?e.slice(0,tf.bytes):e},decode:function(t,e){e||(e=0);let r=e,n=ja.decode(t,e);return e+=ja.decode.bytes,e=hp(n.questions,Ya,t,e),e=hp(n.answers,an,t,e),e=hp(n.authorities,an,t,e),e=hp(n.additionals,an,t,e),Vt.decode.bytes=e-r,n},encodingLength:function(t){return ja.encodingLength(t)+Ga(t.questions||[],Ya)+Ga(t.answers||[],an)+Ga(t.authorities||[],an)+Ga(t.additionals||[],an)}};Vt.encode.bytes=0;Vt.decode.bytes=0;function Sp(t,e){if(t.questions)throw new Error("Only one .question object expected instead of a .questions array!");let r=Object.assign({type:e},t);return r.question&&(r.questions=[r.question],delete r.question),r}var Ap={encode:function(t,e,r){return e=Vt.encode(Sp(t,"query"),e,r),Ap.encode.bytes=Vt.encode.bytes,e},decode:function(t,e){let r=Vt.decode(t,e);return Ap.decode.bytes=Vt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Vt.encodingLength(Sp(t,"query"))}};Ap.encode.bytes=0;Ap.decode.bytes=0;var Tp={encode:function(t,e,r){return e=Vt.encode(Sp(t,"response"),e,r),Tp.encode.bytes=Vt.encode.bytes,e},decode:function(t,e){let r=Vt.decode(t,e);return Tp.decode.bytes=Vt.decode.bytes,r.questions&&(r.question=r.questions[0],delete r.questions),r},encodingLength:function(t){return Vt.encodingLength(Sp(t,"response"))}};Tp.encode.bytes=0;Tp.decode.bytes=0;var tf=Vt.encode,_p=Vt.decode,sC=Vt.encodingLength;function T_(t){let e=tf(t),r=new Uint8Array(2+e.byteLength);return ae(r,e.byteLength),mr(e,r,2,0,e.length),T_.bytes=r.byteLength,r}T_.bytes=0;function __(t){let e=he(t,0);if(t.byteLength<e+2)return null;let r=_p(t.slice(2));return __.bytes=_p.bytes,r}__.bytes=0;function Ga(t,e){let r=0;for(let n=0;n<t.length;n++)r+=e.encodingLength(t[n]);return r}function ef(t,e,r,n){for(let i=0;i<t.length;i++)e.encode(t[i],r,n),n+=e.encode.bytes;return n}function hp(t,e,r,n){for(let i=0;i<t.length;i++)t[i]=e.decode(r,n),n+=e.decode.bytes;return n}l();var B_=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},un=class{static getSigningMethod(e){return B_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement getSigningMethod()")})}static resolve(e,r){return B_(this,void 0,void 0,function*(){throw new Error("Not implemented: Classes extending DidMethod must implement resolve()")})}};var kt=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},I_=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},R_="https://diddht.tbddev.org",cC=0,rs=7200,Bp=";",or=",",Xw;(function(t){t[t.Discoverable=0]="Discoverable",t[t.Organization=1]="Organization",t[t.Government=2]="Government",t[t.Corporation=3]="Corporation",t[t.LocalBusiness=4]="LocalBusiness",t[t.SoftwarePackage=5]="SoftwarePackage",t[t.WebApp=6]="WebApp",t[t.FinancialInstitution=7]="FinancialInstitution"})(Xw||(Xw={}));var sr;(function(t){t[t.Ed25519=0]="Ed25519",t[t.secp256k1=1]="secp256k1",t[t.secp256r1=2]="secp256r1",t[t.X25519=3]="X25519"})(sr||(sr={}));var Qw;(function(t){t.authentication="auth",t.assertionMethod="asm",t.capabilityDelegation="del",t.capabilityInvocation="inv",t.keyAgreement="agm"})(Qw||(Qw={}));var O_={Ed25519:sr.Ed25519,ES256K:sr.secp256k1,ES256:sr.secp256r1,"P-256":sr.secp256r1,secp256k1:sr.secp256k1,secp256r1:sr.secp256r1,X25519:sr.X25519},U_={[sr.Ed25519]:"EdDSA",[sr.secp256k1]:"ES256K",[sr.secp256r1]:"ES256",[sr.X25519]:"ECDH-ES+A256KW"},rf=class t extends un{static create(){return kt(this,arguments,void 0,function*({keyManager:e=new Xt,options:r={}}={}){var n,i,o,s,c,a,u,d,f,h,p;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in O_)))throw new Error("One or more verification method algorithms are not supported");let g=(i=r.verificationMethods)===null||i===void 0?void 0:i.filter(T=>"id"in T).map(T=>T.id);if(g&&g.length!==new Set(g).size)throw new Error("One or more verification method IDs are not unique");if(!((o=r.services)===null||o===void 0)&&o.some(T=>!T.id||!T.type||!T.serviceEndpoint))throw new Error("One or more services are missing required properties");let y=yield e.generateKey({algorithm:"Ed25519"}),E=yield e.getPublicKey({keyUri:y}),S=yield Dt.identityKeyToIdentifier({identityKey:E}),I=Object.assign(Object.assign({id:S},r.alsoKnownAs&&{alsoKnownAs:r.alsoKnownAs}),r.controllers&&{controller:r.controllers}),A=[...(s=r.verificationMethods)!==null&&s!==void 0?s:[]];A?.some(T=>{var M;return((M=T.id)===null||M===void 0?void 0:M.split("#").pop())==="0"})||A.unshift({algorithm:"Ed25519",id:"0",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]});for(let T of A){let M=T.id&&T.id.split("#").pop()==="0"?y:yield e.generateKey({algorithm:T.algorithm}),q=yield e.getPublicKey({keyUri:M}),j=(a=(c=T.id)!==null&&c!==void 0?c:q.kid)!==null&&a!==void 0?a:yield ge({jwk:q});j=`${S}#${Lr(j)}`,(u=I.verificationMethod)!==null&&u!==void 0||(I.verificationMethod=[]),I.verificationMethod.push({id:j,type:"JsonWebKey",controller:(d=T.controller)!==null&&d!==void 0?d:S,publicKeyJwk:q});for(let $ of(f=T.purposes)!==null&&f!==void 0?f:[])I[$]||(I[$]=[]),I[$].push(j)}(h=r.services)===null||h===void 0||h.forEach(T=>{var M;(M=I.service)!==null&&M!==void 0||(I.service=[]),T.id=`${S}#${T.id.split("#").pop()}`,I.service.push(T)});let O=new gr({uri:S,document:I,metadata:Object.assign({published:!1},r.types&&{types:r.types}),keyManager:e});if(!((p=r.publish)!==null&&p!==void 0)||p){let T=yield t.publish({did:O,gatewayUri:r.gatewayUri});O.metadata=T.didDocumentMetadata}return O})}static import(e){return kt(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){var i;let o=me.parse(r.uri);if(o?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let s=yield gr.import({portableDid:r,keyManager:n});if(!(!((i=s.document.verificationMethod)===null||i===void 0)&&i.some(c=>{var a;return((a=c.id)===null||a===void 0?void 0:a.split("#").pop())==="0"})))throw new re(ie.InvalidDidDocument,"DID document must contain an Identity Key");return s})}static getSigningMethod(e){return kt(this,arguments,void 0,function*({didDocument:r,methodId:n="#0"}){var i;let o=me.parse(r.id);if(o&&o.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${o.method}`);let s=(i=r.verificationMethod)===null||i===void 0?void 0:i.find(c=>{var a,u;return Lr(c.id)===((a=Lr(n))!==null&&a!==void 0?a:Lr((u=r.assertionMethod)===null||u===void 0?void 0:u[0]))});if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static publish(e){return kt(this,arguments,void 0,function*({did:r,gatewayUri:n=R_}){return yield Ip.put({did:r,gatewayUri:n})})}static resolve(e){return kt(this,arguments,void 0,function*(r,n={}){var i;let o=(i=n?.gatewayUri)!==null&&i!==void 0?i:R_;try{yield Dt.identifierToIdentityKey({didUri:r});let{didDocument:s,didDocumentMetadata:c}=yield Ip.get({didUri:r,gatewayUri:o});return Object.assign(Object.assign({},ft),{didDocument:s,didDocumentMetadata:c})}catch(s){if(!(s instanceof re))throw new Error(s);return Object.assign(Object.assign({},ft),{didResolutionMetadata:Object.assign({error:s.code},s.message&&{errorMessage:s.message})})}})}};rf.methodName="dht";var Ip=class t{static get(e){return kt(this,arguments,void 0,function*({didUri:r,gatewayUri:n}){let i=Dt.identifierToIdentityKeyBytes({didUri:r}),o=yield t.pkarrGet({gatewayUri:n,publicKeyBytes:i}),s=yield Dt.parseBep44GetMessage({bep44Message:o}),c=yield t.fromDnsPacket({didUri:r,dnsPacket:s});return c.didDocumentMetadata.versionId=o.seq.toString(),c})}static put(e){return kt(this,arguments,void 0,function*({did:r,gatewayUri:n}){let i=yield t.toDnsPacket({didDocument:r.document,didMetadata:r.metadata,authoritativeGatewayUris:[n]}),o=yield Dt.createBep44PutMessage({dnsPacket:i,publicKeyBytes:Dt.identifierToIdentityKeyBytes({didUri:r.uri}),signer:yield r.getSigner({methodId:"0"})}),s=yield t.pkarrPut({gatewayUri:n,bep44Message:o});return{didDocument:r.document,didDocumentMetadata:Object.assign(Object.assign({},r.metadata),{published:s,versionId:o.seq.toString()}),didRegistrationMetadata:{}}})}static pkarrGet(e){return kt(this,arguments,void 0,function*({gatewayUri:r,publicKeyBytes:n}){let i=ne.uint8Array(n).toBase32Z(),o=new URL(i,r).href,s;try{if(s=yield fetch(o,{method:"GET"}),!s.ok)throw new re(ie.NotFound,`Pkarr record not found for: ${i}`)}catch(u){throw u instanceof re?u:new re(ie.InternalError,`Failed to fetch Pkarr record: ${u.message}`)}let c=yield s.arrayBuffer();if(!c)throw new re(ie.NotFound,`Pkarr record not found for: ${i}`);if(c.byteLength<72)throw new re(ie.InvalidDidDocumentLength,`Pkarr response must be at least 72 bytes but got: ${c.byteLength}`);if(c.byteLength>1072)throw new re(ie.InvalidDidDocumentLength,`Pkarr response exceeds 1000 byte limit: ${c.byteLength}`);return{k:n,seq:Number(new DataView(c).getBigUint64(64)),sig:new Uint8Array(c,0,64),v:new Uint8Array(c,72)}})}static pkarrPut(e){return kt(this,arguments,void 0,function*({gatewayUri:r,bep44Message:n}){let i=ne.uint8Array(n.k).toBase32Z(),o=new URL(i,r).href,s=new Uint8Array(n.v.length+72);s.set(n.sig,0),new DataView(s.buffer).setBigUint64(n.sig.length,BigInt(n.seq)),s.set(n.v,n.sig.length+8);let c;try{c=yield fetch(o,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:s})}catch(a){throw new re(ie.InternalError,`Failed to put Pkarr record for identifier ${i}: ${a.message}`)}return c.ok})}static fromDnsPacket(e){return kt(this,arguments,void 0,function*({didUri:r,dnsPacket:n}){var i,o,s;let c={id:r},a={published:!0},u=new Map;for(let d of(i=n?.answers)!==null&&i!==void 0?i:[]){if(d.type!=="TXT")continue;let f=d.name.split(".")[0].substring(1);switch(!0){case f.startsWith("aka"):{let h=Dt.parseTxtDataToString(d.data);c.alsoKnownAs=h.split(or);break}case f.startsWith("cnt"):{let h=Dt.parseTxtDataToString(d.data);c.controller=h.includes(or)?h.split(or):h;break}case f.startsWith("k"):{let{id:h,t:p,k:g,c:y,a:E}=Dt.parseTxtDataToObject(d.data),S=ne.base64Url(g).toUint8Array(),I=sr[Number(p)],A=yield Dt.keyConverter(I).bytesToPublicKey({publicKeyBytes:S});A.alg=E||U_[Number(p)];let O=f==="k0"?"0":h!==void 0?h:yield ge({jwk:A});(o=c.verificationMethod)!==null&&o!==void 0||(c.verificationMethod=[]);let T=`${r}#${O}`;c.verificationMethod.push({id:T,type:"JsonWebKey",controller:y??r,publicKeyJwk:A}),u.set(f,T);break}case f.startsWith("s"):{let h=Dt.parseTxtDataToObject(d.data),{id:p,t:g,se:y}=h,E=I_(h,["id","t","se"]),S=y.includes(or)?y.split(or):[y],I=Object.fromEntries(Object.entries(E).map(([A,O])=>[A,O.includes(or)?O.split(or):O]));(s=c.service)!==null&&s!==void 0||(c.service=[]),c.service.push(Object.assign(Object.assign({},I),{id:`${r}#${p}`,type:g,serviceEndpoint:S}));break}case f.startsWith("typ"):{let{id:h}=Dt.parseTxtDataToObject(d.data);a.types=h.split(or).map(p=>Number(p));break}case f.startsWith("did"):{let h=I=>I.split(or).map(A=>u.get(A)).filter(A=>typeof A=="string"),{auth:p,asm:g,del:y,inv:E,agm:S}=Dt.parseTxtDataToObject(d.data);p&&(c.authentication=h(p)),g&&(c.assertionMethod=h(g)),y&&(c.capabilityDelegation=h(y)),E&&(c.capabilityInvocation=h(E)),S&&(c.keyAgreement=h(S));break}}}return{didDocument:c,didDocumentMetadata:a,didResolutionMetadata:{}}})}static toDnsPacket(e){return kt(this,arguments,void 0,function*({didDocument:r,didMetadata:n,authoritativeGatewayUris:i,previousDidProof:o}){var s,c,a,u,d;let f=[],h=[],p=new Map,g=[],y=[];if(o!==void 0){let{signature:I,previousDid:A}=o;yield Dt.validatePreviousDidProof({newDid:r.id,previousDidProof:o}),f.push({type:"TXT",name:"_prv._did.",ttl:rs,data:`id=${A};s=${I}`})}if(r.alsoKnownAs&&f.push({type:"TXT",name:"_aka._did.",ttl:rs,data:r.alsoKnownAs.join(or)}),r.controller){let I=Array.isArray(r.controller)?r.controller.join(or):r.controller;f.push({type:"TXT",name:"_cnt._did.",ttl:rs,data:I})}for(let[I,A]of(c=(s=r.verificationMethod)===null||s===void 0?void 0:s.entries())!==null&&c!==void 0?c:[]){let O=`k${I}`;y.push(O);let T=A.id.split("#").pop();p.set(T,O);let M=A.publicKeyJwk;if(!(M?.crv&&M.crv in O_))throw new re(ie.InvalidPublicKeyType,`Verification method '${A.id}' contains an unsupported key type: ${(a=M?.crv)!==null&&a!==void 0?a:"undefined"}`);let q=sr[M.crv],j=yield Dt.keyConverter(M.crv).publicKeyToBytes({publicKey:M}),$=ne.uint8Array(j).toBase64Url(),X=[`t=${q}`,`k=${$}`];T!=="0"&&(yield ge({jwk:M}))!==T&&X.unshift(`id=${T}`),M.alg!==U_[q]&&X.push(`a=${M.alg}`),A.controller!==r.id&&X.push(`c=${A.controller}`),f.push({type:"TXT",name:`_${O}._did.`,ttl:rs,data:X.join(Bp)})}(u=r.service)===null||u===void 0||u.forEach((I,A)=>{let O=`s${A}`;g.push(O);let{id:T,type:M,serviceEndpoint:q}=I,j=I_(I,["id","type","serviceEndpoint"]);T=Lr(T),q=Array.isArray(q)?q.join(","):q;let X=Object.entries(Object.assign({id:T,t:M,se:q},j)).map(([G,_])=>`${G}=${_}`).join(Bp),Q=Dt.chunkDataIfNeeded(X);f.push({type:"TXT",name:`_${O}._did.`,ttl:rs,data:Q})});let E=[`v=${cC}`];if(y.length&&E.push(`vm=${y.join(or)}`),Object.keys(Li).forEach(I=>{var A;let O=(A=r[I])===null||A===void 0?void 0:A.map(T=>p.get(T.split("#").pop()));if(O){let T=Qw[I];E.push(`${T}=${O.join(or)}`)}}),g.length&&E.push(`svc=${g.join(or)}`),!((d=n.types)===null||d===void 0)&&d.length){let A=n.types.map(O=>typeof O=="string"?Xw[O]:O);f.push({type:"TXT",name:"_typ._did.",ttl:rs,data:`id=${A.join(or)}`})}f.push({type:"TXT",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:rs,data:E.join(Bp)});for(let I of i||[])h.push({type:"NS",name:"_did."+t.getUniqueDidSuffix(r.id)+".",ttl:rs,data:I+"."});return{id:0,type:"response",flags:A_,answers:[...f,...h]}})}static getUniqueDidSuffix(e){return e.split(":")[2]}},Dt=class t{static createBep44PutMessage(e){return kt(this,arguments,void 0,function*({dnsPacket:r,publicKeyBytes:n,signer:i}){let o=Math.ceil(Date.now()/1e3),s=tf(r),c=qw.encode({seq:o,v:s}).subarray(1,-1);if(c.length>1e3)throw new re(ie.InvalidDidDocumentLength,`DNS packet exceeds the 1000 byte maximum size: ${c.length} bytes`);let a=yield i.sign({data:c});return{k:n,seq:o,sig:a,v:s}})}static identifierToIdentityKey(e){return kt(this,arguments,void 0,function*({didUri:r}){let n=t.identifierToIdentityKeyBytes({didUri:r});return yield _t.bytesToPublicKey({publicKeyBytes:n})})}static identifierToIdentityKeyBytes({didUri:e}){let r=me.parse(e);if(!r)throw new re(ie.InvalidDid,`Invalid DID URI: ${e}`);if(r.method!==rf.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${r.method}`);let n;try{n=ne.base32Z(r.id).toUint8Array()}catch{throw new re(ie.InvalidPublicKey,"Failed to decode method-specific identifier")}if(n.length!==32)throw new re(ie.InvalidPublicKeyLength,`Invalid public key length: ${n.length}`);return n}static identityKeyToIdentifier(e){return kt(this,arguments,void 0,function*({identityKey:r}){let n=yield _t.publicKeyToBytes({publicKey:r}),i=ne.uint8Array(n).toBase32Z();return`did:${rf.methodName}:${i}`})}static keyConverter(e){let n={Ed25519:_t,"P-256":{publicKeyToBytes:i=>kt(this,[i],void 0,function*({publicKey:o}){let s=yield Ht.publicKeyToBytes({publicKey:o});return yield Ht.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Ht.bytesToPublicKey,privateKeyToBytes:Ht.privateKeyToBytes,bytesToPrivateKey:Ht.bytesToPrivateKey},secp256k1:{publicKeyToBytes:i=>kt(this,[i],void 0,function*({publicKey:o}){let s=yield Ot.publicKeyToBytes({publicKey:o});return yield Ot.compressPublicKey({publicKeyBytes:s})}),bytesToPublicKey:Ot.bytesToPublicKey,privateKeyToBytes:Ot.privateKeyToBytes,bytesToPrivateKey:Ot.bytesToPrivateKey},X25519:$a}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static parseBep44GetMessage(e){return kt(this,arguments,void 0,function*({bep44Message:r}){let n=yield _t.bytesToPublicKey({publicKeyBytes:r.k}),i=qw.encode({seq:r.seq,v:r.v}).subarray(1,-1);if(!(yield _t.verify({key:n,signature:r.sig,data:i})))throw new re(ie.InvalidSignature,"Invalid signature for DHT BEP44 message");return _p(r.v)})}static parseTxtDataToObject(e){return this.parseTxtDataToString(e).split(Bp).reduce((r,n)=>{let[i,o]=n.split("=");return r[i]=o,r},{})}static parseTxtDataToString(e){if(typeof e=="string")return e;if(e instanceof Uint8Array)return ne.uint8Array(e).toString();if(Array.isArray(e))return e.map(r=>this.parseTxtDataToString(r)).join("");throw new re(ie.InternalError,"Pkarr returned DNS TXT record with invalid data type")}static validatePreviousDidProof(e){return kt(this,arguments,void 0,function*({newDid:r,previousDidProof:n}){let i=yield t.identifierToIdentityKey({didUri:n.previousDid}),o=t.identifierToIdentityKeyBytes({didUri:r}),s=ne.base64Url(n.signature).toUint8Array();if(!(yield _t.verify({key:i,data:o,signature:s})))throw new re(ie.InvalidPreviousDidProof,"The previous DID proof is invalid.")})}static chunkDataIfNeeded(e){if(e.length<=255)return e;let r=[];for(let n=0;n<e.length;n+=255)r.push(e.slice(n,n+255));return r}};l();l();l();l();l();var We={DeltaExceedsMaximumSize:"DeltaExceedsMaximumSize",DidDocumentPublicKeyIdDuplicated:"DidDocumentPublicKeyIdDuplicated",DidDocumentPublicKeyMissingOrIncorrectType:"DidDocumentPublicKeyMissingOrIncorrectType",DidDocumentServiceIdDuplicated:"DidDocumentServiceIdDuplicated",DidSuffixIncorrectLength:"DidSuffixIncorrectLength",EncodedStringIncorrectEncoding:"EncodedStringIncorrectEncoding",IdNotUsingBase64UrlCharacterSet:"IdNotUsingBase64UrlCharacterSet",IdTooLong:"IdTooLong",JwkEs256kMissingOrInvalidCrv:"JwkEs256kMissingOrInvalidCrv",JwkEs256kMissingOrInvalidKty:"JwkEs256kMissingOrInvalidKty",JwkEs256kHasIncorrectLengthOfX:"JwkEs256kHasIncorrectLengthOfX",JwkEs256kHasIncorrectLengthOfY:"JwkEs256kHasIncorrectLengthOfY",JwkEs256kHasIncorrectLengthOfD:"JwkEs256kHasIncorrectLengthOfD",MultihashStringNotAMultihash:"MultihashStringNotAMultihash",MultihashUnsupportedHashAlgorithm:"MultihashUnsupportedHashAlgorithm",PublicKeyJwkEs256kHasUnexpectedProperty:"PublicKeyJwkEs256kHasUnexpectedProperty",PublicKeyPurposeDuplicated:"PublicKeyPurposeDuplicated",ServiceEndpointCannotBeAnArray:"ServiceEndpointCannotBeAnArray",ServiceEndpointStringNotValidUri:"ServiceEndpointStringNotValidUri",ServiceTypeTooLong:"ServiceTypeTooLong"};l();var Le=class extends Error{constructor(e,r){super(`${e}: ${r}`),this.code=e,Object.setPrototypeOf(this,new.target.prototype)}};l();l();l();l();var VJ=new Uint8Array(0);var eb=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")};l();var tb=class{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},rb=class{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return D_(this,e)}},nb=class{constructor(e){this.decoders=e}or(e){return D_(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}},D_=(t,e)=>new nb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}}),ib=class{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new tb(e,r,n),this.decoder=new rb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}},aC=({name:t,prefix:e,encode:r,decode:n})=>new ib(t,e,r,n);var uC=(t,e,r,n)=>{let i={};for(let d=0;d<e.length;++d)i[e[d]]=d;let o=t.length;for(;t[o-1]==="=";)--o;let s=new Uint8Array(o*r/8|0),c=0,a=0,u=0;for(let d=0;d<o;++d){let f=i[t[d]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<r|f,c+=r,c>=8&&(c-=8,s[u++]=255&a>>c)}if(c>=r||255&a<<8-c)throw new SyntaxError("Unexpected end of data");return s},dC=(t,e,r)=>{let n=e[e.length-1]==="=",i=(1<<r)-1,o="",s=0,c=0;for(let a=0;a<t.length;++a)for(c=c<<8|t[a],s+=8;s>r;)s-=r,o+=e[i&c>>s];if(s&&(o+=e[i&c<<r-s]),n)for(;o.length*r&7;)o+="=";return o},nf=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>aC({prefix:e,name:t,encode(i){return dC(i,n,r)},decode(i){return uC(i,n,r,t)}});var QJ=nf({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),eZ=nf({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),of=nf({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),tZ=nf({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var wr=class t{static encode(e){return of.baseEncode(e)}static decodeAsBytes(e,r){if(!t.isBase64UrlString(e))throw new Le(We.EncodedStringIncorrectEncoding,`Given ${r} must be base64url string.`);return of.baseDecode(e)}static decodeAsString(e,r){let n=t.decodeAsBytes(e,r);return t.bytesToString(n)}static isBase64UrlString(e){return/^[A-Za-z0-9_-]+$/.test(e)}static stringToBytes(e){return new TextEncoder().encode(e)}static bytesToString(e){return new TextDecoder().decode(e)}};l();var q_=Pn(N_(),1);l();l();var ob;(function(t){t.Public="public",t.Private="private"})(ob||(ob={}));var Mr=ob;var It=class{static validateEs256kOperationKey(e,r){let n=new Set(["kty","crv","x","y"]);r===Mr.Private&&n.add("d");for(let i in e)if(!n.has(i))throw new Le(We.PublicKeyJwkEs256kHasUnexpectedProperty,`SECP256K1 JWK key has unexpected property '${i}'.`);if(e.crv!=="secp256k1")throw new Le(We.JwkEs256kMissingOrInvalidCrv,`SECP256K1 JWK 'crv' property must be 'secp256k1' but got '${e.crv}.'`);if(e.kty!=="EC")throw new Le(We.JwkEs256kMissingOrInvalidKty,`SECP256K1 JWK 'kty' property must be 'EC' but got '${e.kty}.'`);if(e.x.length!==43)throw new Le(We.JwkEs256kHasIncorrectLengthOfX,"SECP256K1 JWK 'x' property must be 43 bytes.");if(e.y.length!==43)throw new Le(We.JwkEs256kHasIncorrectLengthOfY,"SECP256K1 JWK 'y' property must be 43 bytes.");if(r===Mr.Private&&(e.d===void 0||e.d.length!==43))throw new Le(We.JwkEs256kHasIncorrectLengthOfD,"SECP256K1 JWK 'd' property must be 43 bytes.")}static validateId(e){if(e.length>50)throw new Le(We.IdTooLong,`Key ID length ${e.length} exceed max allowed length of 50.`);if(!wr.isBase64UrlString(e))throw new Le(We.IdNotUsingBase64UrlCharacterSet,`Key ID '${e}' is not a Base64URL string.`)}static validatePublicKeyPurposes(e){if(e===void 0)return;let r=new Set;for(let n of e){if(r.has(n))throw new Le(We.PublicKeyPurposeDuplicated,`Public key purpose '${n}' already specified.`);r.add(n)}}};l();var sf=class{};sf.hashAlgorithmInMultihashCode=18;sf.maxCanonicalizedDeltaSizeInBytes=1e3;var cr=sf;l();var P_=Pn(L_(),1);var Dn=class t{static canonicalizeAsBytes(e){let r=t.removeAllUndefinedProperties(e),n=P_.default(r);return wr.stringToBytes(n)}static removeAllUndefinedProperties(e){for(let r in e)typeof e[r]=="object"?t.removeAllUndefinedProperties(e[r]):e[r]===void 0&&delete e[r];return e}};l();l();l();l();var fC=$_,M_=128,lC=127,hC=~lC,pC=Math.pow(2,31);function $_(t,e,r){e=e||[],r=r||0;for(var n=r;t>=pC;)e[r++]=t&255|M_,t/=128;for(;t&hC;)e[r++]=t&255|M_,t>>>=7;return e[r]=t|0,$_.bytes=r-n+1,e}var yC=sb,gC=128,K_=127;function sb(t,n){var r=0,n=n||0,i=0,o=n,s,c=t.length;do{if(o>=c)throw sb.bytes=0,new RangeError("Could not decode varint");s=t[o++],r+=i<28?(s&K_)<<i:(s&K_)*Math.pow(2,i),i+=7}while(s>=gC);return sb.bytes=o-n,r}var mC=Math.pow(2,7),wC=Math.pow(2,14),bC=Math.pow(2,21),xC=Math.pow(2,28),EC=Math.pow(2,35),vC=Math.pow(2,42),SC=Math.pow(2,49),AC=Math.pow(2,56),TC=Math.pow(2,63),_C=function(t){return t<mC?1:t<wC?2:t<bC?3:t<xC?4:t<EC?5:t<vC?6:t<SC?7:t<AC?8:t<TC?9:10},BC={encode:fC,decode:yC,encodingLength:_C},IC=BC,cf=IC;var cb=(t,e=0)=>[cf.decode(t,e),cf.decode.bytes],ab=(t,e,r=0)=>(cf.encode(t,e,r),e),ub=t=>cf.encodingLength(t);var db=(t,e)=>{let r=e.byteLength,n=ub(t),i=n+ub(r),o=new Uint8Array(i+r);return ab(t,o,0),ab(r,o,n),o.set(e,i),new Up(t,r,e,o)},H_=t=>{let e=eb(t),[r,n]=cb(e),[i,o]=cb(e.subarray(n)),s=e.subarray(n+o);if(s.byteLength!==i)throw new Error("Incorrect length");return new Up(r,i,s,e)};var Up=class{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}};l();l();var lb=({name:t,code:e,encode:r})=>new fb(t,e,r),fb=class{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){let r=this.encode(e);return r instanceof Uint8Array?db(this.code,r):r.then(n=>db(this.code,n))}else throw Error("Unknown type, must be binary type")}};var V_=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Op=lb({name:"sha2-256",code:18,encode:V_("SHA-256")}),CZ=lb({name:"sha2-512",code:19,encode:V_("SHA-512")});var af=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Nt=class t{static hash(e,r){return af(this,void 0,void 0,function*(){let n;switch(r){case 18:n=(yield Op.digest(e)).bytes;break;default:throw new Le(We.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static hashAsNonMultihashBytes(e,r){return af(this,void 0,void 0,function*(){let n;switch(r){case 18:n=yield Op.encode(e);break;default:throw new Le(We.MultihashUnsupportedHashAlgorithm,`Hash algorithm defined in multihash code ${r} is not supported.`)}return n})}static canonicalizeThenHashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=Dn.canonicalizeAsBytes(e);return yield t.hashThenEncode(n,r)})}static canonicalizeThenDoubleHashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=Dn.canonicalizeAsBytes(e),i=yield t.hashAsNonMultihashBytes(n,r);return yield t.hashThenEncode(i,r)})}static hashThenEncode(e,r){return af(this,void 0,void 0,function*(){let n=yield t.hash(e,r);return wr.encode(n)})}static validateEncodedHashComputedUsingSupportedHashAlgorithm(e,r){let n,i=wr.decodeAsBytes(e,r);try{n=H_(i)}catch{throw new Le(We.MultihashStringNotAMultihash,`Given ${r} string '${e}' is not a multihash after decoding.`)}let o=cr.hashAlgorithmInMultihashCode;if(o!==n.code)throw new Le(We.MultihashUnsupportedHashAlgorithm,`Given ${r} uses unsupported multihash algorithm with code ${n.code}, should use ${o} or change IonSdkConfig to desired hashing algorithm.`)}};l();var hb;(function(t){t.Create="create",t.Update="update",t.Deactivate="deactivate",t.Recover="recover"})(hb||(hb={}));var uf=hb;l();var pb;(function(t){t.Replace="replace",t.AddPublicKeys="add-public-keys",t.RemovePublicKeys="remove-public-keys",t.AddServices="add-services",t.RemoveServices="remove-services"})(pb||(pb={}));var pc=pb;var Dp=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},ns=class t{static createCreateRequest(e){return Dp(this,void 0,void 0,function*(){let r=e.recoveryKey,n=e.updateKey,i=e.document.publicKeys,o=e.document.services;It.validateEs256kOperationKey(r,Mr.Public),It.validateEs256kOperationKey(n,Mr.Public),t.validateDidDocumentKeys(i),t.validateServices(o);let s=cr.hashAlgorithmInMultihashCode,c=[{action:pc.Replace,document:e.document}],a={updateCommitment:yield Nt.canonicalizeThenDoubleHashThenEncode(n,s),patches:c};t.validateDeltaSize(a);let d={deltaHash:yield Nt.canonicalizeThenHashThenEncode(a,s),recoveryCommitment:yield Nt.canonicalizeThenDoubleHashThenEncode(r,s)};return{type:uf.Create,suffixData:d,delta:a}})}static createDeactivateRequest(e){return Dp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.recoveryPublicKey,Mr.Public);let r=cr.hashAlgorithmInMultihashCode,n=yield Nt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i={didSuffix:e.didSuffix,recoveryKey:e.recoveryPublicKey},o=yield e.signer.sign({alg:"ES256K"},i);return{type:uf.Deactivate,didSuffix:e.didSuffix,revealValue:n,signedData:o}})}static createRecoverRequest(e){return Dp(this,void 0,void 0,function*(){t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.recoveryPublicKey,Mr.Public),It.validateEs256kOperationKey(e.nextRecoveryPublicKey,Mr.Public),It.validateEs256kOperationKey(e.nextUpdatePublicKey,Mr.Public),t.validateDidDocumentKeys(e.document.publicKeys),t.validateServices(e.document.services);let r=cr.hashAlgorithmInMultihashCode,n=yield Nt.canonicalizeThenHashThenEncode(e.recoveryPublicKey,r),i=[{action:pc.Replace,document:e.document}],o=yield Nt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,r),s={patches:i,updateCommitment:o},c=yield Nt.canonicalizeThenHashThenEncode(s,r),u={recoveryCommitment:yield Nt.canonicalizeThenDoubleHashThenEncode(e.nextRecoveryPublicKey,r),recoveryKey:e.recoveryPublicKey,deltaHash:c},d=yield e.signer.sign({alg:"ES256K"},u);return{type:uf.Recover,didSuffix:e.didSuffix,revealValue:n,delta:s,signedData:d}})}static createUpdateRequest(e){return Dp(this,void 0,void 0,function*(){if(t.validateDidSuffix(e.didSuffix),It.validateEs256kOperationKey(e.updatePublicKey,Mr.Public),It.validateEs256kOperationKey(e.nextUpdatePublicKey,Mr.Public),t.validateServices(e.servicesToAdd),t.validateDidDocumentKeys(e.publicKeysToAdd),e.idsOfServicesToRemove!==void 0)for(let g of e.idsOfServicesToRemove)It.validateId(g);if(e.idsOfPublicKeysToRemove!==void 0)for(let g of e.idsOfPublicKeysToRemove)It.validateId(g);let r=[],n=e.servicesToAdd;if(n!==void 0&&n.length>0){let g={action:pc.AddServices,services:n};r.push(g)}let i=e.idsOfServicesToRemove;if(i!==void 0&&i.length>0){let g={action:pc.RemoveServices,ids:i};r.push(g)}let o=e.publicKeysToAdd;if(o!==void 0&&o.length>0){let g={action:pc.AddPublicKeys,publicKeys:o};r.push(g)}let s=e.idsOfPublicKeysToRemove;if(s!==void 0&&s.length>0){let g={action:pc.RemovePublicKeys,ids:s};r.push(g)}let c=cr.hashAlgorithmInMultihashCode,a=yield Nt.canonicalizeThenHashThenEncode(e.updatePublicKey,c),u=yield Nt.canonicalizeThenDoubleHashThenEncode(e.nextUpdatePublicKey,c),d={patches:r,updateCommitment:u},f=yield Nt.canonicalizeThenHashThenEncode(d,c),h={updateKey:e.updatePublicKey,deltaHash:f},p=yield e.signer.sign({alg:"ES256K"},h);return{type:uf.Update,didSuffix:e.didSuffix,revealValue:a,delta:d,signedData:p}})}static validateDidSuffix(e){Nt.validateEncodedHashComputedUsingSupportedHashAlgorithm(e,"didSuffix")}static validateDidDocumentKeys(e){if(e===void 0)return;let r=new Set;for(let n of e){if(Array.isArray(n.publicKeyJwk))throw new Le(We.DidDocumentPublicKeyMissingOrIncorrectType,"DID Document key 'publicKeyJwk' property is not a non-array object.");if(It.validateId(n.id),r.has(n.id))throw new Le(We.DidDocumentPublicKeyIdDuplicated,`DID Document key with ID '${n.id}' already exists.`);r.add(n.id),It.validatePublicKeyPurposes(n.purposes)}}static validateServices(e){if(e!==void 0&&e.length!==0){let r=new Set;for(let n of e){if(t.validateService(n),r.has(n.id))throw new Le(We.DidDocumentServiceIdDuplicated,"Service id has to be unique");r.add(n.id)}}}static validateService(e){It.validateId(e.id);let r=30;if(e.type.length>r){let n=`Service endpoint type length ${e.type.length} exceeds max allowed length of ${r}.`;throw new Le(We.ServiceTypeTooLong,n)}if(Array.isArray(e.serviceEndpoint)){let n="Service endpoint value cannot be an array.";throw new Le(We.ServiceEndpointCannotBeAnArray,n)}if(typeof e.serviceEndpoint=="string"&&q_.parse(e.serviceEndpoint).error!==void 0)throw new Le(We.ServiceEndpointStringNotValidUri,`Service endpoint string '${e.serviceEndpoint}' is not a URI.`)}static validateDeltaSize(e){let r=Dn.canonicalizeAsBytes(e);if(r.length>cr.maxCanonicalizedDeltaSizeInBytes){let n=`Delta of ${r.length} bytes exceeded limit of ${cr.maxCanonicalizedDeltaSizeInBytes} bytes.`;throw new Le(We.DeltaExceedsMaximumSize,n)}}};var F_=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},Ja=class t{static createLongFormDid(e){return F_(this,void 0,void 0,function*(){let r=yield ns.createCreateRequest(e),n=yield t.computeDidUniqueSuffix(r.suffixData),i;cr.network===void 0||cr.network==="mainnet"?i=`did:ion:${n}`:i=`did:ion:${cr.network}:${n}`;let o={suffixData:r.suffixData,delta:r.delta},s=Dn.canonicalizeAsBytes(o),c=wr.encode(s);return`${i}:${c}`})}static computeDidUniqueSuffix(e){return F_(this,void 0,void 0,function*(){let r=Dn.canonicalizeAsBytes(e),n=yield Nt.hash(r,cr.hashAlgorithmInMultihashCode);return wr.encode(n)})}};l();l();var j_;(function(t){t.Mainnet="mainnet",t.Testnet="test"})(j_||(j_={}));l();var W_;(function(t){t.Authentication="authentication",t.AssertionMethod="assertionMethod",t.CapabilityInvocation="capabilityInvocation",t.CapabilityDelegation="capabilityDelegation",t.KeyAgreement="keyAgreement"})(W_||(W_={}));l();var is=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},hi;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(hi||(hi={}));var OC={Ed25519:hi.Ed25519,ES256K:hi.secp256k1,ES256:hi.secp256r1,"P-256":hi.secp256r1,secp256k1:hi.secp256k1,secp256r1:hi.secp256r1},G_="https://ion.tbd.engineering",yb=class t extends un{static create(){return is(this,arguments,void 0,function*({keyManager:e=new Xt,options:r={}}={}){var n,i,o,s,c,a,u;if(!((n=r.verificationMethods)===null||n===void 0)&&n.some(T=>!(T.algorithm in OC)))throw new Error("One or more verification method algorithms are not supported");let d=(i=r.verificationMethods)===null||i===void 0?void 0:i.filter(T=>"id"in T).map(T=>T.id);if(d&&d.length!==new Set(d).size)throw new Error("One or more verification method IDs are not unique");if(!((o=r.services)===null||o===void 0)&&o.some(T=>!T.id||!T.type||!T.serviceEndpoint))throw new Error("One or more services are missing required properties");let f={algorithm:"Ed25519",purposes:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]},h=[];for(let T of(s=r.verificationMethods)!==null&&s!==void 0?s:[f]){let M=yield e.generateKey({algorithm:T.algorithm}),q=yield e.getPublicKey({keyUri:M});h.push({id:T.id,publicKeyJwk:q,purposes:(c=T.purposes)!==null&&c!==void 0?c:["authentication","assertionMethod","capabilityDelegation","capabilityInvocation"]})}let p=yield e.generateKey({algorithm:hi.secp256k1}),g=yield e.getPublicKey({keyUri:p}),y=yield e.generateKey({algorithm:hi.secp256k1}),E=yield e.getPublicKey({keyUri:y}),S=yield yc.computeLongFormDidUri({recoveryKey:g,updateKey:E,services:(a=r.services)!==null&&a!==void 0?a:[],verificationMethods:h}),{didDocument:I,didResolutionMetadata:A}=yield t.resolve(S,{gatewayUri:r.gatewayUri});if(I===null)throw new Error(`Unable to resolve DID during creation: ${A?.error}`);let O=new gr({uri:S,document:I,metadata:{published:!1,canonicalId:S.split(":",3).join(":"),recoveryKey:g,updateKey:E},keyManager:e});if(!((u=r.publish)!==null&&u!==void 0)||u){let T=yield t.publish({did:O,gatewayUri:r.gatewayUri});O.metadata=T.didDocumentMetadata}return O})}static getSigningMethod(e){return is(this,arguments,void 0,function*({didDocument:r,methodId:n}){var i;let o=me.parse(r.id);if(o&&o.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${o.method}`);let s=(i=r.verificationMethod)===null||i===void 0?void 0:i.find(c=>{var a;return c.id===(n??((a=r.assertionMethod)===null||a===void 0?void 0:a[0]))});if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static import(e){return is(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");return yield gr.import({portableDid:r,keyManager:n})})}static publish(e){return is(this,arguments,void 0,function*({did:r,gatewayUri:n=G_}){var i,o,s;let c=(o=(i=r.document.verificationMethod)===null||i===void 0?void 0:i.map(d=>({id:d.id,publicKeyJwk:d.publicKeyJwk,purposes:ZT({didDocument:r.document,methodId:d.id})})))!==null&&o!==void 0?o:[],a=yield yc.createIonDocument({services:(s=r.document.service)!==null&&s!==void 0?s:[],verificationMethods:c}),u=yield yc.constructCreateRequest({ionDocument:a,recoveryKey:r.metadata.recoveryKey,updateKey:r.metadata.updateKey});try{let d=yc.appendPathToUrl({baseUrl:n,path:"/operations"}),f=yield fetch(d,{method:"POST",mode:"cors",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return{didDocument:r.document,didDocumentMetadata:Object.assign(Object.assign({},r.metadata),{published:f.ok}),didRegistrationMetadata:{}}}catch{return{didDocument:null,didDocumentMetadata:{published:!1},didRegistrationMetadata:{error:ie.InternalError,errorMessage:`Failed to publish DID document for: ${r.uri}`}}}})}static resolve(e){return is(this,arguments,void 0,function*(r,n={}){var i,o;let s=me.parse(r);if(!s)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"invalidDid"}});if(s.method!==t.methodName)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"methodNotSupported"}});let c=(i=n?.gatewayUri)!==null&&i!==void 0?i:G_;try{let a=yc.appendPathToUrl({baseUrl:c,path:`/identifiers/${r}`}),u=yield fetch(a);if(!u.ok)throw new re(ie.NotFound,`Unable to find DID document for: ${r}`);let{didDocument:d,didDocumentMetadata:f}=yield u.json();return Object.assign(Object.assign(Object.assign({},ft),d&&{didDocument:d}),{didDocumentMetadata:Object.assign({published:(o=f?.method)===null||o===void 0?void 0:o.published},f)})}catch(a){if(!(a instanceof re))throw new Error(a);return Object.assign(Object.assign({},ft),{didResolutionMetadata:Object.assign({error:a.code},a.message&&{errorMessage:a.message})})}})}};yb.methodName="ion";var yc=class t{static appendPathToUrl({baseUrl:e,path:r}){let n=new URL(e);return n.pathname=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",n.pathname+=r.startsWith("/")?r.substring(1):r,n.toString()}static computeLongFormDidUri(e){return is(this,arguments,void 0,function*({recoveryKey:r,updateKey:n,services:i,verificationMethods:o}){let s=yield t.createIonDocument({services:i,verificationMethods:o}),c=t.normalizeJwk(r),a=t.normalizeJwk(n);return yield Ja.createLongFormDid({document:s,recoveryKey:c,updateKey:a})})}static constructCreateRequest(e){return is(this,arguments,void 0,function*({ionDocument:r,recoveryKey:n,updateKey:i}){return yield ns.createCreateRequest({document:r,recoveryKey:t.normalizeJwk(n),updateKey:t.normalizeJwk(i)})})}static createIonDocument(e){return is(this,arguments,void 0,function*({services:r,verificationMethods:n}){var i,o;let s=[];for(let u of n){let d=(o=(i=u.id)!==null&&i!==void 0?i:u.publicKeyJwk.kid)!==null&&o!==void 0?o:yield ge({jwk:u.publicKeyJwk});d=`${d.split("#").pop()}`;let f={id:d,publicKeyJwk:t.normalizeJwk(u.publicKeyJwk),purposes:u.purposes,type:"JsonWebKey2020"};s.push(f)}let c=r.map(u=>Object.assign(Object.assign({},u),{id:`${u.id.split("#").pop()}`}));return{publicKeys:s,services:c}})}static normalizeJwk(e){let r=e.kty,n;if(r==="EC")n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};else if(r==="oct")n={k:e.k,kty:e.kty};else if(r==="OKP")n={crv:e.crv,kty:e.kty,x:e.x};else if(r==="RSA")n={e:e.e,kty:e.kty,n:e.n};else throw new Error(`Unsupported key type: ${r}`);return n}};l();var kp=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},gb=class t extends un{static create(){return kp(this,arguments,void 0,function*({keyManager:e=new Xt,options:r={}}={}){var n,i,o,s;if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let c=(s=(n=r.algorithm)!==null&&n!==void 0?n:(o=(i=r.verificationMethods)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.algorithm)!==null&&s!==void 0?s:"Ed25519",a=yield e.generateKey({algorithm:c}),u=yield e.getPublicKey({keyUri:a}),d=ne.object(u).toBase64Url(),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f)).didDocument;return new gr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return kp(this,arguments,void 0,function*({didDocument:r}){var n;let i=me.parse(r.id);if(i&&i.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${i.method}`);let[o]=(n=r.verificationMethod)!==null&&n!==void 0?n:[];if(!(o&&o.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return o})}static import(e){return kp(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield gr.import({portableDid:r,keyManager:n});if(o.document.verificationMethod.length!==1)throw new re(ie.InvalidDidDocument,"DID document must contain exactly one verification method");return o})}static resolve(e,r){return kp(this,void 0,void 0,function*(){let n=me.parse(e),i;try{i=ne.base64Url(n.id).toObject()}catch{}if(!n||!i)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"methodNotSupported"}});let o={"@context":["https://www.w3.org/ns/did/v1"],id:n.uri},s=`${o.id}#0`;switch(o.verificationMethod=[{id:s,type:"JsonWebKey",controller:o.id,publicKeyJwk:i}],o.authentication=[s],o.assertionMethod=[s],o.capabilityInvocation=[s],o.capabilityDelegation=[s],o.keyAgreement=[s],i.use){case"sig":{delete o.keyAgreement;break}case"enc":{delete o.authentication,delete o.assertionMethod,delete o.capabilityInvocation,delete o.capabilityDelegation;break}}return Object.assign(Object.assign({},ft),{didDocument:o})})}};gb.methodName="jwk";l();var kn=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},oo;(function(t){t.Ed25519="Ed25519",t.secp256k1="secp256k1",t.secp256r1="secp256r1",t.X25519="X25519"})(oo||(oo={}));var mb={Ed25519VerificationKey2020:"https://w3id.org/security/suites/ed25519-2020/v1",JsonWebKey2020:"https://w3id.org/security/suites/jws-2020/v1",X25519KeyAgreementKey2020:"https://w3id.org/security/suites/x25519-2020/v1"},DC={Ed25519:oo.Ed25519,ES256K:oo.secp256k1,ES256:oo.secp256r1,"P-256":oo.secp256r1,secp256k1:oo.secp256k1,secp256r1:oo.secp256r1,X25519:oo.X25519},wb=class t extends un{static create(){return kn(this,arguments,void 0,function*({keyManager:e=new Xt,options:r={}}={}){var n,i,o,s;if(r.algorithm&&r.verificationMethods)throw new Error("The 'algorithm' and 'verificationMethods' options are mutually exclusive");if(r.verificationMethods&&r.verificationMethods.length!==1)throw new Error("The 'verificationMethods' option must contain exactly one entry");let c=(s=(n=r.algorithm)!==null&&n!==void 0?n:(o=(i=r.verificationMethods)===null||i===void 0?void 0:i[0])===null||o===void 0?void 0:o.algorithm)!==null&&s!==void 0?s:"Ed25519",a=yield e.generateKey({algorithm:c}),u=yield e.getPublicKey({keyUri:a}),d=yield br.publicKeyToMultibaseId({publicKey:u}),f=`did:${t.methodName}:${d}`,p=(yield t.resolve(f,r)).didDocument;return new gr({uri:f,document:p,metadata:{},keyManager:e})})}static getSigningMethod(e){return kn(this,arguments,void 0,function*({didDocument:r}){var n;let i=me.parse(r.id);if(i&&i.method!==this.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${i.method}`);let[o]=r.assertionMethod||[],s=(n=r.verificationMethod)===null||n===void 0?void 0:n.find(c=>c.id===o);if(!(s&&s.publicKeyJwk))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return s})}static import(e){return kn(this,arguments,void 0,function*({portableDid:r,keyManager:n=new Xt}){let i=me.parse(r.uri);if(i?.method!==t.methodName)throw new re(ie.MethodNotSupported,"Method not supported");let o=yield gr.import({portableDid:r,keyManager:n});if(o.document.verificationMethod.length!==1)throw new re(ie.InvalidDidDocument,"DID document must contain exactly one verification method");return o})}static resolve(e,r){return kn(this,void 0,void 0,function*(){try{let n=yield t.createDocument({didUri:e,options:r});return Object.assign(Object.assign({},ft),{didDocument:n})}catch(n){if(!(n instanceof re))throw new Error(n);return Object.assign(Object.assign({},ft),{didResolutionMetadata:Object.assign({error:n.code},n.message&&{errorMessage:n.message})})}})}static createDocument(e){return kn(this,arguments,void 0,function*({didUri:r,options:n={}}){let{defaultContext:i="https://www.w3.org/ns/did/v1",enableEncryptionKeyDerivation:o=!1,enableExperimentalPublicKeyTypes:s=!1,publicKeyFormat:c="JsonWebKey2020"}=n,a={id:""},u=me.parse(r);if(!u)throw new re(ie.InvalidDid,`Invalid DID URI: ${r}`);let d=u.id;if(u.method!==t.methodName)throw new re(ie.MethodNotSupported,`Method not supported: ${u.method}`);if(!t.validateIdentifier(u))throw new re(ie.InvalidDid,`Invalid DID URI: ${r}`);let f=yield t.createSignatureMethod({didUri:r,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:c}});if(a.id=u.uri,a.verificationMethod=[f],a.authentication=[f.id],a.assertionMethod=[f.id],a.capabilityInvocation=[f.id],a.capabilityDelegation=[f.id],o===!0){let g=c==="Ed25519VerificationKey2020"?"X25519KeyAgreementKey2020":"JsonWebKey2020",y=yield this.createEncryptionMethod({didUri:r,multibaseValue:d,options:{enableExperimentalPublicKeyTypes:s,publicKeyFormat:g}});a.verificationMethod.push(y),a.keyAgreement=[y.id]}let h=[i];return JT({didDocument:a}).forEach(g=>{let y=mb[g];h.push(y)}),a["@context"]=h,a})}static createEncryptionMethod(e){return kn(this,arguments,void 0,function*({didUri:r,multibaseValue:n,options:i}){let{enableExperimentalPublicKeyTypes:o,publicKeyFormat:s}=i,c={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:u}=yield t.deriveEncryptionKey({multibaseValue:n}),d=a.byteLength,f=br.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(d!==f)throw new re(ie.InvalidPublicKeyLength,`Expected ${d} bytes. Actual: ${f}`);let h=Lw({keyBytes:a,multicodecCode:u});c.id=`${r}#${h}`;try{new URL(c.id)}catch{throw new re(ie.InvalidDidUrl,"Verification Method ID is not a valid DID URL.")}if(!(s in mb))throw new re(ie.UnsupportedPublicKeyType,`Unsupported format: ${s}`);if(o===!1&&!["Multikey","JsonWebKey2020","X25519KeyAgreementKey2020"].includes(s))throw new re(ie.InvalidPublicKeyType,`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(c.type=s,c.controller=r,s==="X25519KeyAgreementKey2020"&&(c.publicKeyMultibase=h),s==="JsonWebKey2020"){let{crv:g}=yield br.multicodecToJwk({code:u});c.publicKeyJwk=yield br.keyConverter(g).bytesToPublicKey({publicKeyBytes:a})}return c})}static createSignatureMethod(e){return kn(this,arguments,void 0,function*({didUri:r,multibaseValue:n,options:i}){let{enableExperimentalPublicKeyTypes:o,publicKeyFormat:s}=i,c={id:"",type:"",controller:""},{keyBytes:a,multicodecCode:u,multicodecName:d}=Pw({multibaseKeyId:n}),f=a.byteLength,h=br.MULTICODEC_PUBLIC_KEY_LENGTH[u];if(f!==h)throw new re(ie.InvalidPublicKeyLength,`Expected ${f} bytes. Actual: ${h}`);let p=!1;switch(d){case"secp256k1-pub":p=yield Ot.validatePublicKey({publicKeyBytes:a});break;case"ed25519-pub":p=yield _t.validatePublicKey({publicKeyBytes:a});break;case"x25519-pub":p=!0;break}if(!p)throw new re(ie.InvalidPublicKey,"Invalid public key detected.");c.id=`${r}#${n}`;try{new URL(c.id)}catch{throw new re(ie.InvalidDidUrl,"Verification Method ID is not a valid DID URL.")}if(!(s in mb))throw new re(ie.UnsupportedPublicKeyType,`Unsupported format: ${s}`);if(o===!1&&!["Multikey","JsonWebKey2020","Ed25519VerificationKey2020"].includes(s))throw new re(ie.InvalidPublicKeyType,`Specified '${s}' without setting enableExperimentalPublicKeyTypes to true.`);if(c.type=s,c.controller=r,s==="Ed25519VerificationKey2020"&&(c.publicKeyMultibase=n),s==="JsonWebKey2020"){let{crv:y}=yield br.multicodecToJwk({code:u});c.publicKeyJwk=yield br.keyConverter(y).bytesToPublicKey({publicKeyBytes:a})}return c})}static deriveEncryptionKey(e){return kn(this,arguments,void 0,function*({multibaseValue:r}){let n={keyBytes:new Uint8Array,multicodecCode:0},{keyBytes:i,multicodecCode:o}=Pw({multibaseKeyId:r});if(o===237){let s=yield br.keyConverter("Ed25519").bytesToPublicKey({publicKeyBytes:i}),c=yield _t.convertPublicKeyToX25519({publicKey:s});n={keyBytes:yield br.keyConverter("Ed25519").publicKeyToBytes({publicKey:c}),multicodecCode:236}}return n})}static validateIdentifier(e){let{method:r,id:n}=e,[i]=e.uri.split(":",1);return i==="did"&&r==="key"&&Number("1")>0&&ia(n)==="String"&&n.startsWith("z")}};wb.methodName="key";var br=class t{static jwkToMulticodec(e){return kn(this,arguments,void 0,function*({jwk:r}){let n=[];r.crv&&(n.push(r.crv),r.d?n.push("private"):n.push("public"));let i=n.join(":"),o=t.JWK_TO_MULTICODEC[i];if(o===void 0)throw new Error(`Unsupported JWK to Multicodec conversion: '${i}'`);return{code:zt.getCodeFromName({name:o}),name:o}})}static keyCompressor(e){let n={"P-256":Ht.compressPublicKey,secp256k1:Ot.compressPublicKey}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static keyConverter(e){let n={Ed25519:_t,"P-256":Ht,secp256k1:Ot,X25519:$a}[e];if(!n)throw new re(ie.InvalidPublicKeyType,`Unsupported curve: ${e}`);return n}static multicodecToJwk(e){return kn(this,arguments,void 0,function*({code:r,name:n}){if(!(n?!r:r))throw new Error("Either 'name' or 'code' must be defined, but not both.");n=n===void 0?zt.getNameFromCode({code:r}):n;let i=n,o=t.MULTICODEC_TO_JWK[i];if(o===void 0)throw new Error("Unsupported Multicodec to JWK conversion");return Object.assign({},o)})}static publicKeyToMultibaseId(e){return kn(this,arguments,void 0,function*({publicKey:r}){var n;if(!(r?.crv&&r.crv in DC))throw new re(ie.InvalidPublicKeyType,`Public key contains an unsupported key type: ${(n=r?.crv)!==null&&n!==void 0?n:"undefined"}`);let i=yield t.keyConverter(r.crv).publicKeyToBytes({publicKey:r});/^(secp256k1|P-256|P-384|P-521)$/.test(r.crv)&&(i=yield t.keyCompressor(r.crv)({publicKeyBytes:i}));let{name:o}=yield t.jwkToMulticodec({jwk:r});return Lw({keyBytes:i,multicodecName:o})})}};br.JWK_TO_MULTICODEC={"Ed25519:public":"ed25519-pub","Ed25519:private":"ed25519-priv","secp256k1:public":"secp256k1-pub","secp256k1:private":"secp256k1-priv","X25519:public":"x25519-pub","X25519:private":"x25519-priv"};br.MULTICODEC_PUBLIC_KEY_LENGTH={231:33,236:32,237:32};br.MULTICODEC_TO_JWK={"ed25519-pub":{crv:"Ed25519",kty:"OKP",x:""},"ed25519-priv":{crv:"Ed25519",kty:"OKP",x:"",d:""},"secp256k1-pub":{crv:"secp256k1",kty:"EC",x:"",y:""},"secp256k1-priv":{crv:"secp256k1",kty:"EC",x:"",y:"",d:""},"x25519-pub":{crv:"X25519",kty:"OKP",x:""},"x25519-priv":{crv:"X25519",kty:"OKP",x:"",d:""}};l();var kC=function(t,e,r,n){function i(o){return o instanceof r?o:new r(function(s){s(o)})}return new(r||(r=Promise))(function(o,s){function c(d){try{u(n.next(d))}catch(f){s(f)}}function a(d){try{u(n.throw(d))}catch(f){s(f)}}function u(d){d.done?o(d.value):i(d.value).then(c,a)}u((n=n.apply(t,e||[])).next())})},bb=class t extends un{static resolve(e,r){return kC(this,void 0,void 0,function*(){let n=me.parse(e);if(!n)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"invalidDid"}});if(n.method!==t.methodName)return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"methodNotSupported"}});let i=`https://${n.id.replace(/:/g,"/")}`;i=decodeURIComponent(i);let o=n.id.includes(":")?`${i}/did.json`:`${i}/.well-known/did.json`;try{let s=yield fetch(o);if(!s.ok)throw new Error("HTTP error status code returned");let c=yield s.json();return Object.assign(Object.assign({},ft),{didDocument:c})}catch{return Object.assign(Object.assign({},ft),{didResolutionMetadata:{error:"notFound"}})}})}};bb.methodName="web";l();var KC=Pn(Y_(),1),$C=Pn(zg(),1);l();l();var Kr=class t{static extractDidFragment(e){if(typeof e=="string"&&e.length!==0)return e}static isDidVerificationMethod(e){return!(!e||typeof e!="object"||e===null||!("id"in e&&"type"in e&&"controller"in e)||typeof e.id!="string"||typeof e.type!="string"||typeof e.controller!="string")}static isDidService(e){return!(!e||typeof e!="object"||e===null||!("id"in e&&"type"in e&&"serviceEndpoint"in e)||typeof e.id!="string"||typeof e.type!="string"||typeof e.serviceEndpoint!="string")}static getVerificationMethods(e){if(!e)throw new TypeError("Required parameter missing: 'didDocument'");let r=[];return r.push(...e.verificationMethod?.filter(t.isDidVerificationMethod)??[]),Object.keys(Li).forEach(n=>{r.push(...e[n]?.filter(t.isDidVerificationMethod)??[])}),r}static deriveRootCapability(e){return{"@context":"https://w3id.org/zcap/v1",id:`urn:zcap:root:${encodeURIComponent(e)}`,controller:e,invocationTarget:e}}static dereferenceZcapId(e){let r={},[n,i,o,s]=e.split(":")??[];if([n,i,o,s].length!==4)throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!n||n!=="urn")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!i||i!=="zcap")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);if(!o||o!=="root")throw new re(ie.InvalidDid,`Invalid capabilityId: ${e}`);let a=decodeURIComponent(s);return r.id=e,r.controller=a,r.invocationTarget=a,r}};l();l();l();l();l();l();l();function J_(t,e,r){return t&e^~t&r}function Z_(t,e,r){return t&e^t&r^e&r}var Cp=class{blockLen;outputLen;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,r,n,i){this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Bl(this.buffer)}update(e){Xc(this),ve(e);let{view:r,buffer:n,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let c=Math.min(i-this.pos,o-s);if(c===i){let a=Bl(e);for(;i<=o-s;s+=i)this.process(a,s);continue}n.set(e.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Xc(this),_v(e,this),this.finished=!0;let{buffer:r,view:n,blockLen:i,isLE:o}=this,{pos:s}=this;r[s++]=128,Os(this.buffer.subarray(s)),this.padOffset>i-s&&(this.process(n,0),s=0);for(let f=s;f<i;f++)r[f]=0;n.setBigUint64(i-8,BigInt(this.length*8),o),this.process(n,0);let c=Bl(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let u=a/4,d=this.get();if(u>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)c.setUint32(4*f,d[f],o)}digest(){let{buffer:e,outputLen:r}=this;this.digestInto(e);let n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:r,buffer:n,length:i,finished:o,destroyed:s,pos:c}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=c,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}},so=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var HC=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]),os=new Uint32Array(64),xb=class extends Cp{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:r,C:n,D:i,E:o,F:s,G:c,H:a}=this;return[e,r,n,i,o,s,c,a]}set(e,r,n,i,o,s,c,a){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=a|0}process(e,r){for(let f=0;f<16;f++,r+=4)os[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){let h=os[f-15],p=os[f-2],g=xn(h,7)^xn(h,18)^h>>>3,y=xn(p,17)^xn(p,19)^p>>>10;os[f]=y+os[f-7]+g+os[f-16]|0}let{A:n,B:i,C:o,D:s,E:c,F:a,G:u,H:d}=this;for(let f=0;f<64;f++){let h=xn(c,6)^xn(c,11)^xn(c,25),p=d+h+J_(c,a,u)+HC[f]+os[f]|0,y=(xn(n,2)^xn(n,13)^xn(n,22))+Z_(n,i,o)|0;d=u,u=a,a=c,c=s+p|0,s=o,o=i,i=n,n=p+y|0}n=n+this.A|0,i=i+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,d=d+this.H|0,this.set(n,i,o,s,c,a,u,d)}roundClean(){Os(os)}destroy(){this.set(0,0,0,0,0,0,0,0),Os(this.buffer)}},Eb=class extends xb{A=so[0]|0;B=so[1]|0;C=so[2]|0;D=so[3]|0;E=so[4]|0;F=so[5]|0;G=so[6]|0;H=so[7]|0;constructor(){super(32)}};var Lp=Iv(()=>new Eb,Rv(1));l();l();var ar=BigInt(0),Qt=BigInt(1),mc=BigInt(2),eB=BigInt(3),tB=BigInt(4),rB=BigInt(5),VC=BigInt(7),nB=BigInt(8),qC=BigInt(9),iB=BigInt(16);function Nn(t,e){let r=t%e;return r>=ar?r:e+r}function $r(t,e,r){let n=t;for(;e-- >ar;)n*=n,n%=r;return n}function X_(t,e){if(t===ar)throw new Error("invert: expected non-zero number");if(e<=ar)throw new Error("invert: expected positive modulus, got "+e);let r=Nn(t,e),n=e,i=ar,o=Qt,s=Qt,c=ar;for(;r!==ar;){let u=n/r,d=n%r,f=i-s*u,h=o-c*u;n=r,r=d,i=s,o=c,s=f,c=h}if(n!==Qt)throw new Error("invert: does not exist");return Nn(i,e)}function Sb(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function oB(t,e){let r=(t.ORDER+Qt)/tB,n=t.pow(e,r);return Sb(t,n,e),n}function FC(t,e){let r=(t.ORDER-rB)/nB,n=t.mul(e,mc),i=t.pow(n,r),o=t.mul(e,i),s=t.mul(t.mul(o,mc),i),c=t.mul(o,t.sub(s,t.ONE));return Sb(t,c,e),c}function jC(t){let e=eu(t),r=sB(t),n=r(e,e.neg(e.ONE)),i=r(e,n),o=r(e,e.neg(n)),s=(t+VC)/iB;return(c,a)=>{let u=c.pow(a,s),d=c.mul(u,n),f=c.mul(u,i),h=c.mul(u,o),p=c.eql(c.sqr(d),a),g=c.eql(c.sqr(f),a);u=c.cmov(u,d,p),d=c.cmov(h,f,g);let y=c.eql(c.sqr(d),a),E=c.cmov(u,d,y);return Sb(c,E,a),E}}function sB(t){if(t<eB)throw new Error("sqrt is not defined for small field");let e=t-Qt,r=0;for(;e%mc===ar;)e/=mc,r++;let n=mc,i=eu(t);for(;Q_(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return oB;let o=i.pow(n,e),s=(e+Qt)/mc;return function(a,u){if(a.is0(u))return u;if(Q_(a,u)!==1)throw new Error("Cannot find square root");let d=r,f=a.mul(a.ONE,o),h=a.pow(u,e),p=a.pow(u,s);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let g=1,y=a.sqr(h);for(;!a.eql(y,a.ONE);)if(g++,y=a.sqr(y),g===d)throw new Error("Cannot find square root");let E=Qt<<BigInt(d-g-1),S=a.pow(f,E);d=g,f=a.sqr(S),h=a.mul(h,f),p=a.mul(p,S)}return p}}function WC(t){return t%tB===eB?oB:t%nB===rB?FC:t%iB===qC?jC(t):sB(t)}var GC=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ab(t){let e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=GC.reduce((n,i)=>(n[i]="function",n),e);return Ju(t,r),t}function zC(t,e,r){if(r<ar)throw new Error("invalid exponent, negatives unsupported");if(r===ar)return t.ONE;if(r===Qt)return e;let n=t.ONE,i=e;for(;r>ar;)r&Qt&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Qt;return n}function Pp(t,e,r=!1){let n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((s,c,a)=>t.is0(c)?s:(n[a]=s,t.mul(s,c)),t.ONE),o=t.inv(i);return e.reduceRight((s,c,a)=>t.is0(c)?s:(n[a]=t.mul(s,n[a]),t.mul(s,c)),o),n}function Q_(t,e){let r=(t.ORDER-Qt)/mc,n=t.pow(e,r),i=t.eql(n,t.ONE),o=t.eql(n,t.ZERO),s=t.eql(n,t.neg(t.ONE));if(!i&&!o&&!s)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function YC(t,e){e!==void 0&&Yn(e);let r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}var vb=class{ORDER;BITS;BYTES;isLE;ZERO=ar;ONE=Qt;_lengths;_sqrt;_mod;constructor(e,r={}){if(e<=ar)throw new Error("invalid field: expected ORDER > 0, got "+e);let n;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(n=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=r.allowedLengths?.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));let{nBitLength:i,nByteLength:o}=YC(e,n);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=i,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return Nn(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ar<=e&&e<this.ORDER}is0(e){return e===ar}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Qt)===Qt}neg(e){return Nn(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return Nn(e*e,this.ORDER)}add(e,r){return Nn(e+r,this.ORDER)}sub(e,r){return Nn(e-r,this.ORDER)}mul(e,r){return Nn(e*r,this.ORDER)}pow(e,r){return zC(this,e,r)}div(e,r){return Nn(e*X_(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return X_(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=WC(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?N0(e,this.BYTES):Rl(e,this.BYTES)}fromBytes(e,r=!1){ve(e);let{_lengths:n,BYTES:i,isLE:o,ORDER:s,_mod:c}=this;if(n){if(!n.includes(e.length)||e.length>i)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let u=new Uint8Array(i);u.set(e,o?0:u.length-e.length),e=u}if(e.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let a=o?k0(e):Uo(e);if(c&&(a=Nn(a,s)),!r&&!this.isValid(a))throw new Error("invalid field element: outside of range 0..ORDER");return a}invertBatch(e){return Pp(this,e)}cmov(e,r,n){return n?r:e}};function eu(t,e={}){return new vb(t,e)}function cB(t){if(typeof t!="bigint")throw new Error("field order must be bigint");let e=t.toString(2).length;return Math.ceil(e/8)}function Tb(t){let e=cB(t);return e+Math.ceil(e/2)}function Mp(t,e,r=!1){ve(t);let n=t.length,i=cB(e),o=Tb(e);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);let s=r?k0(t):Uo(t),c=Nn(s,e-Qt)+Qt;return r?N0(c,i):Rl(c,i)}var tu=BigInt(0),wc=BigInt(1);function df(t,e){let r=e.negate();return t?r:e}function Rb(t,e){let r=Pp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function fB(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function _b(t,e){fB(t,e);let r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,o=Yu(t),s=BigInt(t);return{windows:r,windowSize:n,mask:o,maxNumber:i,shiftBy:s}}function aB(t,e,r){let{windowSize:n,mask:i,maxNumber:o,shiftBy:s}=r,c=Number(t&i),a=t>>s;c>n&&(c-=o,a+=wc);let u=e*n,d=u+Math.abs(c)-1,f=c===0,h=c<0,p=e%2!==0;return{nextN:a,offset:d,isZero:f,isNeg:h,isNegF:p,offsetF:u}}var Bb=new WeakMap,lB=new WeakMap;function Ib(t){return lB.get(t)||1}function uB(t){if(t!==tu)throw new Error("invalid wNAF")}var Kp=class{BASE;ZERO;Fn;bits;constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>tu;)r&wc&&(n=n.add(i)),i=i.double(),r>>=wc;return n}precomputeWindow(e,r){let{windows:n,windowSize:i}=_b(r,this.bits),o=[],s=e,c=s;for(let a=0;a<n;a++){c=s,o.push(c);for(let u=1;u<i;u++)c=c.add(s),o.push(c);s=c.double()}return o}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,o=this.BASE,s=_b(e,this.bits);for(let c=0;c<s.windows;c++){let{nextN:a,offset:u,isZero:d,isNeg:f,isNegF:h,offsetF:p}=aB(n,c,s);n=a,d?o=o.add(df(h,r[p])):i=i.add(df(f,r[u]))}return uB(n),{p:i,f:o}}wNAFUnsafe(e,r,n,i=this.ZERO){let o=_b(e,this.bits);for(let s=0;s<o.windows&&n!==tu;s++){let{nextN:c,offset:a,isZero:u,isNeg:d}=aB(n,s,o);if(n=c,!u){let f=r[a];i=i.add(d?f.negate():f)}}return uB(n),i}getPrecomputes(e,r,n){let i=Bb.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Bb.set(r,i))),i}cached(e,r,n){let i=Ib(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){let o=Ib(e);return o===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,e,n),r,i)}createCache(e,r){fB(r,this.bits),lB.set(e,r),Bb.delete(e)}hasCache(e){return Ib(e)!==1}};function hB(t,e,r,n){let i=e,o=t.ZERO,s=t.ZERO;for(;r>tu||n>tu;)r&wc&&(o=o.add(i)),n&wc&&(s=s.add(i)),i=i.double(),r>>=wc,n>>=wc;return{p1:o,p2:s}}function dB(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ab(e),e}else return eu(t,{isLE:r})}function pB(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(let a of["p","n","h"]){let u=e[a];if(!(typeof u=="bigint"&&u>tu))throw new Error(`CURVE.${a} must be positive bigint`)}let i=dB(e.p,r.Fp,n),o=dB(e.n,r.Fn,n),c=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(let a of c)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:o}}function $p(t,e){return function(n){let i=t(n);return{secretKey:i,publicKey:e(i)}}}l();l();var Hp=class{oHash;iHash;blockLen;outputLen;finished=!1;destroyed=!1;constructor(e,r){if(_l(e),ve(r,void 0,"key"),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 n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Os(i)}update(e){return Xc(this),this.iHash.update(e),this}digestInto(e){Xc(this),ve(e,this.outputLen,"output"),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||=Object.create(Object.getPrototypeOf(this),{});let{oHash:r,iHash:n,finished:i,destroyed:o,blockLen:s,outputLen:c}=this;return e=e,e.finished=i,e.destroyed=o,e.blockLen=s,e.outputLen=c,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Ub=(t,e,r)=>new Hp(t,e).update(r).digest();Ub.create=(t,e)=>new Hp(t,e);var yB=(t,e)=>(t+(t>=0?e:-e)/gB)/e;function JC(t,e,r){let[[n,i],[o,s]]=e,c=yB(s*t,r),a=yB(-i*t,r),u=t-c*n-a*o,d=-c*i-a*s,f=u<co,h=d<co;f&&(u=-u),h&&(d=-d);let p=Yu(Math.ceil(C0(r)/2))+ru;if(u<co||u>=p||d<co||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:d}}function Db(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ob(t,e){let r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Gu(r.lowS,"lowS"),Gu(r.prehash,"prehash"),r.format!==void 0&&Db(r.format),r}var kb=class extends Error{constructor(e=""){super(e)}},ss={Err:kb,_tlv:{encode:(t,e)=>{let{Err:r}=ss;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");let n=e.length/2,i=zu(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");let o=n>127?zu(i.length/2|128):"";return zu(t)+o+i+e},decode(t,e){let{Err:r}=ss,n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");let i=e[n++],o=!!(i&128),s=0;if(!o)s=i;else{let a=i&127;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");let u=e.subarray(n,n+a);if(u.length!==a)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(let d of u)s=s<<8|d;if(n+=a,s<128)throw new r("tlv.decode(long): not minimal encoding")}let c=e.subarray(n,n+s);if(c.length!==s)throw new r("tlv.decode: wrong value length");return{v:c,l:e.subarray(n+s)}}},_int:{encode(t){let{Err:e}=ss;if(t<co)throw new e("integer: negative integers are not allowed");let r=zu(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){let{Err:e}=ss;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Uo(t)}},toSig(t){let{Err:e,_int:r,_tlv:n}=ss,i=ve(t,void 0,"signature"),{v:o,l:s}=n.decode(48,i);if(s.length)throw new e("invalid signature: left bytes after parsing");let{v:c,l:a}=n.decode(2,o),{v:u,l:d}=n.decode(2,a);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(c),s:r.decode(u)}},hexFromSig(t){let{_tlv:e,_int:r}=ss,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),o=n+i;return e.encode(48,o)}},co=BigInt(0),ru=BigInt(1),gB=BigInt(2),Vp=BigInt(3),ZC=BigInt(4);function mB(t,e={}){let r=pB("weierstrass",t,e),{Fp:n,Fn:i}=r,o=r.CURVE,{h:s,n:c}=o;Ju(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});let{endo:a}=e;if(a&&(!n.is0(o.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');let u=bB(n,i);function d(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(G,_,D){let{x,y:U}=_.toAffine(),L=n.toBytes(x);if(Gu(D,"isCompressed"),D){d();let N=!n.isOdd(U);return fr(wB(N),L)}else return fr(Uint8Array.of(4),L,n.toBytes(U))}function h(G){ve(G,void 0,"Point");let{publicKey:_,publicKeyUncompressed:D}=u,x=G.length,U=G[0],L=G.subarray(1);if(x===_&&(U===2||U===3)){let N=n.fromBytes(L);if(!n.isValid(N))throw new Error("bad point: is not on curve, wrong x");let R=y(N),C;try{C=n.sqrt(R)}catch(J){let z=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}d();let P=n.isOdd(C);return(U&1)===1!==P&&(C=n.neg(C)),{x:N,y:C}}else if(x===D&&U===4){let N=n.BYTES,R=n.fromBytes(L.subarray(0,N)),C=n.fromBytes(L.subarray(N,N*2));if(!E(R,C))throw new Error("bad point: is not on curve");return{x:R,y:C}}else throw new Error(`bad point: got length ${x}, expected compressed=${_} or uncompressed=${D}`)}let p=e.toBytes||f,g=e.fromBytes||h;function y(G){let _=n.sqr(G),D=n.mul(_,G);return n.add(n.add(D,n.mul(G,o.a)),o.b)}function E(G,_){let D=n.sqr(_),x=y(G);return n.eql(D,x)}if(!E(o.Gx,o.Gy))throw new Error("bad curve params: generator point");let S=n.mul(n.pow(o.a,Vp),ZC),I=n.mul(n.sqr(o.b),BigInt(27));if(n.is0(n.add(S,I)))throw new Error("bad curve params: a or b");function A(G,_,D=!1){if(!n.isValid(_)||D&&n.is0(_))throw new Error(`bad point coordinate ${G}`);return _}function O(G){if(!(G instanceof $))throw new Error("Weierstrass Point expected")}function T(G){if(!a||!a.basises)throw new Error("no endo");return JC(G,a.basises,i.ORDER)}let M=L0((G,_)=>{let{X:D,Y:x,Z:U}=G;if(n.eql(U,n.ONE))return{x:D,y:x};let L=G.is0();_==null&&(_=L?n.ONE:n.inv(U));let N=n.mul(D,_),R=n.mul(x,_),C=n.mul(U,_);if(L)return{x:n.ZERO,y:n.ZERO};if(!n.eql(C,n.ONE))throw new Error("invZ was invalid");return{x:N,y:R}}),q=L0(G=>{if(G.is0()){if(e.allowInfinityPoint&&!n.is0(G.Y))return;throw new Error("bad point: ZERO")}let{x:_,y:D}=G.toAffine();if(!n.isValid(_)||!n.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(_,D))throw new Error("bad point: equation left != right");if(!G.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function j(G,_,D,x,U){return D=new $(n.mul(D.X,G),D.Y,D.Z),_=df(x,_),D=df(U,D),_.add(D)}class ${static BASE=new $(o.Gx,o.Gy,n.ONE);static ZERO=new $(n.ZERO,n.ONE,n.ZERO);static Fp=n;static Fn=i;X;Y;Z;constructor(_,D,x){this.X=A("x",_),this.Y=A("y",D,!0),this.Z=A("z",x),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){let{x:D,y:x}=_||{};if(!_||!n.isValid(D)||!n.isValid(x))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return n.is0(D)&&n.is0(x)?$.ZERO:new $(D,x,n.ONE)}static fromBytes(_){let D=$.fromAffine(g(ve(_,void 0,"point")));return D.assertValidity(),D}static fromHex(_){return $.fromBytes(ks(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,D=!0){return Q.createCache(this,_),D||this.multiply(Vp),this}assertValidity(){q(this)}hasEvenY(){let{y:_}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(_)}equals(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.eql(n.mul(D,R),n.mul(L,U)),P=n.eql(n.mul(x,R),n.mul(N,U));return C&&P}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){let{a:_,b:D}=o,x=n.mul(D,Vp),{X:U,Y:L,Z:N}=this,R=n.ZERO,C=n.ZERO,P=n.ZERO,V=n.mul(U,U),J=n.mul(L,L),z=n.mul(N,N),W=n.mul(U,L);return W=n.add(W,W),P=n.mul(U,N),P=n.add(P,P),R=n.mul(_,P),C=n.mul(x,z),C=n.add(R,C),R=n.sub(J,C),C=n.add(J,C),C=n.mul(R,C),R=n.mul(W,R),P=n.mul(x,P),z=n.mul(_,z),W=n.sub(V,z),W=n.mul(_,W),W=n.add(W,P),P=n.add(V,V),V=n.add(P,V),V=n.add(V,z),V=n.mul(V,W),C=n.add(C,V),z=n.mul(L,N),z=n.add(z,z),V=n.mul(z,W),R=n.sub(R,V),P=n.mul(z,J),P=n.add(P,P),P=n.add(P,P),new $(R,C,P)}add(_){O(_);let{X:D,Y:x,Z:U}=this,{X:L,Y:N,Z:R}=_,C=n.ZERO,P=n.ZERO,V=n.ZERO,J=o.a,z=n.mul(o.b,Vp),W=n.mul(D,L),Y=n.mul(x,N),Z=n.mul(U,R),ue=n.add(D,x),ee=n.add(L,N);ue=n.mul(ue,ee),ee=n.add(W,Y),ue=n.sub(ue,ee),ee=n.add(D,U);let ce=n.add(L,R);return ee=n.mul(ee,ce),ce=n.add(W,Z),ee=n.sub(ee,ce),ce=n.add(x,U),C=n.add(N,R),ce=n.mul(ce,C),C=n.add(Y,Z),ce=n.sub(ce,C),V=n.mul(J,ee),C=n.mul(z,Z),V=n.add(C,V),C=n.sub(Y,V),V=n.add(Y,V),P=n.mul(C,V),Y=n.add(W,W),Y=n.add(Y,W),Z=n.mul(J,Z),ee=n.mul(z,ee),Y=n.add(Y,Z),Z=n.sub(W,Z),Z=n.mul(J,Z),ee=n.add(ee,Z),W=n.mul(Y,ee),P=n.add(P,W),W=n.mul(ce,ee),C=n.mul(ue,C),C=n.sub(C,W),W=n.mul(ue,Y),V=n.mul(ce,V),V=n.add(V,W),new $(C,P,V)}subtract(_){return this.add(_.negate())}is0(){return this.equals($.ZERO)}multiply(_){let{endo:D}=e;if(!i.isValidNot0(_))throw new Error("invalid scalar: out of range");let x,U,L=N=>Q.cached(this,N,R=>Rb($,R));if(D){let{k1neg:N,k1:R,k2neg:C,k2:P}=T(_),{p:V,f:J}=L(R),{p:z,f:W}=L(P);U=J.add(W),x=j(D.beta,V,z,N,C)}else{let{p:N,f:R}=L(_);x=N,U=R}return Rb($,[x,U])[0]}multiplyUnsafe(_){let{endo:D}=e,x=this;if(!i.isValid(_))throw new Error("invalid scalar: out of range");if(_===co||x.is0())return $.ZERO;if(_===ru)return x;if(Q.hasCache(this))return this.multiply(_);if(D){let{k1neg:U,k1:L,k2neg:N,k2:R}=T(_),{p1:C,p2:P}=hB($,x,L,R);return j(D.beta,C,P,U,N)}else return Q.unsafe(x,_)}toAffine(_){return M(this,_)}isTorsionFree(){let{isTorsionFree:_}=e;return s===ru?!0:_?_($,this):Q.unsafe(this,c).is0()}clearCofactor(){let{clearCofactor:_}=e;return s===ru?this:_?_($,this):this.multiplyUnsafe(s)}isSmallOrder(){return this.multiplyUnsafe(s).is0()}toBytes(_=!0){return Gu(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Ds(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let X=i.BITS,Q=new Kp($,e.endo?Math.ceil(X/2):X);return $.BASE.precompute(8),$}function wB(t){return Uint8Array.of(t?2:3)}function bB(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function XC(t,e={}){let{Fn:r}=t,n=e.randomBytes||Ns,i=Object.assign(bB(t.Fp,r),{seed:Tb(r.ORDER)});function o(p){try{let g=r.fromBytes(p);return r.isValidNot0(g)}catch{return!1}}function s(p,g){let{publicKey:y,publicKeyUncompressed:E}=i;try{let S=p.length;return g===!0&&S!==y||g===!1&&S!==E?!1:!!t.fromBytes(p)}catch{return!1}}function c(p=n(i.seed)){return Mp(ve(p,i.seed,"seed"),r.ORDER)}function a(p,g=!0){return t.BASE.multiply(r.fromBytes(p)).toBytes(g)}function u(p){let{secretKey:g,publicKey:y,publicKeyUncompressed:E}=i;if(!Wu(p)||"_lengths"in r&&r._lengths||g===y)return;let S=ve(p,void 0,"key").length;return S===y||S===E}function d(p,g,y=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(g)===!1)throw new Error("second arg must be public key");let E=r.fromBytes(p);return t.fromBytes(g).multiply(E).toBytes(y)}let f={isValidSecretKey:o,isValidPublicKey:s,randomSecretKey:c},h=$p(c,a);return Object.freeze({getPublicKey:a,getSharedSecret:d,keygen:h,Point:t,utils:f,lengths:i})}function xB(t,e,r={}){_l(e),Ju(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);let n=r.randomBytes||Ns,i=r.hmac||((D,x)=>Ub(e,D,x)),{Fp:o,Fn:s}=t,{ORDER:c,BITS:a}=s,{keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p}=XC(t,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=c*gB<o.ORDER;function E(D){let x=c>>ru;return D>x}function S(D,x){if(!s.isValidNot0(x))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return x}function I(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function A(D,x){Db(x);let U=p.signature,L=x==="compact"?U:x==="recovered"?U+1:void 0;return ve(D,L)}class O{r;s;recovery;constructor(x,U,L){if(this.r=S("r",x),this.s=S("s",U),L!=null){if(I(),![0,1,2,3].includes(L))throw new Error("invalid recovery id");this.recovery=L}Object.freeze(this)}static fromBytes(x,U=g.format){A(x,U);let L;if(U==="der"){let{r:P,s:V}=ss.toSig(ve(x));return new O(P,V)}U==="recovered"&&(L=x[0],U="compact",x=x.subarray(1));let N=p.signature/2,R=x.subarray(0,N),C=x.subarray(N,N*2);return new O(s.fromBytes(R),s.fromBytes(C),L)}static fromHex(x,U){return this.fromBytes(ks(x),U)}assertRecovery(){let{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new O(this.r,this.s,x)}recoverPublicKey(x){let{r:U,s:L}=this,N=this.assertRecovery(),R=N===2||N===3?U+c:U;if(!o.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");let C=o.toBytes(R),P=t.fromBytes(fr(wB((N&1)===0),C)),V=s.inv(R),J=M(ve(x,void 0,"msgHash")),z=s.create(-J*V),W=s.create(L*V),Y=t.BASE.multiplyUnsafe(z).add(P.multiplyUnsafe(W));if(Y.is0())throw new Error("invalid recovery: point at infinify");return Y.assertValidity(),Y}hasHighS(){return E(this.s)}toBytes(x=g.format){if(Db(x),x==="der")return ks(ss.hexFromSig(this));let{r:U,s:L}=this,N=s.toBytes(U),R=s.toBytes(L);return x==="recovered"?(I(),fr(Uint8Array.of(this.assertRecovery()),N,R)):fr(N,R)}toHex(x){return Ds(this.toBytes(x))}}let T=r.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");let U=Uo(x),L=x.length*8-a;return L>0?U>>BigInt(L):U},M=r.bits2int_modN||function(x){return s.create(T(x))},q=Yu(a);function j(D){return kv("num < 2^"+a,D,co,q),s.toBytes(D)}function $(D,x){return ve(D,void 0,"message"),x?ve(e(D),void 0,"prehashed message"):D}function X(D,x,U){let{lowS:L,prehash:N,extraEntropy:R}=Ob(U,g);D=$(D,N);let C=M(D),P=s.fromBytes(x);if(!s.isValidNot0(P))throw new Error("invalid private key");let V=[j(P),j(C)];if(R!=null&&R!==!1){let Y=R===!0?n(p.secretKey):R;V.push(ve(Y,void 0,"extraEntropy"))}let J=fr(...V),z=C;function W(Y){let Z=T(Y);if(!s.isValidNot0(Z))return;let ue=s.inv(Z),ee=t.BASE.multiply(Z).toAffine(),ce=s.create(ee.x);if(ce===co)return;let Ie=s.create(ue*s.create(z+ce*P));if(Ie===co)return;let Pe=(ee.x===ce?0:2)|Number(ee.y&ru),Ge=Ie;return L&&E(Ie)&&(Ge=s.neg(Ie),Pe^=1),new O(ce,Ge,y?void 0:Pe)}return{seed:J,k2sig:W}}function Q(D,x,U={}){let{seed:L,k2sig:N}=X(D,x,U);return Nv(e.outputLen,s.BYTES,i)(L,N).toBytes(U.format)}function G(D,x,U,L={}){let{lowS:N,prehash:R,format:C}=Ob(L,g);if(U=ve(U,void 0,"publicKey"),x=$(x,R),!Wu(D)){let P=D instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}A(D,C);try{let P=O.fromBytes(D,C),V=t.fromBytes(U);if(N&&P.hasHighS())return!1;let{r:J,s:z}=P,W=M(x),Y=s.inv(z),Z=s.create(W*Y),ue=s.create(J*Y),ee=t.BASE.multiplyUnsafe(Z).add(V.multiplyUnsafe(ue));return ee.is0()?!1:s.create(ee.x)===J}catch{return!1}}function _(D,x,U={}){let{prehash:L}=Ob(U,g);return x=$(x,L),O.fromBytes(D,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:u,getPublicKey:d,getSharedSecret:f,utils:h,lengths:p,Point:t,sign:Q,verify:G,recoverPublicKey:_,Signature:O,hash:e})}var jp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},QC={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},eL=BigInt(0),Nb=BigInt(2);function tL(t){let e=jp.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),s=BigInt(23),c=BigInt(44),a=BigInt(88),u=t*t*t%e,d=u*u*t%e,f=$r(d,r,e)*d%e,h=$r(f,r,e)*d%e,p=$r(h,Nb,e)*u%e,g=$r(p,i,e)*p%e,y=$r(g,o,e)*g%e,E=$r(y,c,e)*y%e,S=$r(E,a,e)*E%e,I=$r(S,c,e)*y%e,A=$r(I,r,e)*d%e,O=$r(A,s,e)*g%e,T=$r(O,n,e)*u%e,M=$r(T,Nb,e);if(!qp.eql(qp.sqr(M),t))throw new Error("Cannot find square root");return M}var qp=eu(jp.p,{sqrt:tL}),bc=mB(jp,{Fp:qp,endo:QC}),dn=xB(bc,Lp),EB={};function Fp(t,...e){let r=EB[t];if(r===void 0){let n=Lp(Dv(t));r=fr(n,n),EB[t]=r}return Lp(fr(r,...e))}var Lb=t=>t.toBytes(!0).slice(1),Pb=t=>t%Nb===eL;function Cb(t){let{Fn:e,BASE:r}=bc,n=e.fromBytes(t),i=r.multiply(n);return{scalar:Pb(i.y)?n:e.neg(n),bytes:Lb(i)}}function SB(t){let e=qp;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");let r=e.create(t*t),n=e.create(r*t+BigInt(7)),i=e.sqrt(n);Pb(i)||(i=e.neg(i));let o=bc.fromAffine({x:t,y:i});return o.assertValidity(),o}var ff=Uo;function AB(...t){return bc.Fn.create(ff(Fp("BIP0340/challenge",...t)))}function vB(t){return Cb(t).bytes}function rL(t,e,r=Ns(32)){let{Fn:n}=bc,i=ve(t,void 0,"message"),{bytes:o,scalar:s}=Cb(e),c=ve(r,32,"auxRand"),a=n.toBytes(s^ff(Fp("BIP0340/aux",c))),u=Fp("BIP0340/nonce",a,o,i),{bytes:d,scalar:f}=Cb(u),h=AB(d,o,i),p=new Uint8Array(64);if(p.set(d,0),p.set(n.toBytes(n.create(f+h*s)),32),!TB(p,i,o))throw new Error("sign: Invalid signature produced");return p}function TB(t,e,r){let{Fp:n,Fn:i,BASE:o}=bc,s=ve(t,64,"signature"),c=ve(e,void 0,"message"),a=ve(r,32,"publicKey");try{let u=SB(ff(a)),d=ff(s.subarray(0,32));if(!n.isValidNot0(d))return!1;let f=ff(s.subarray(32,64));if(!i.isValidNot0(f))return!1;let h=AB(i.toBytes(d),Lb(u),c),p=o.multiplyUnsafe(f).add(u.multiplyUnsafe(i.neg(h))),{x:g,y}=p.toAffine();return!(p.is0()||!Pb(y)||g!==d)}catch{return!1}}var Wp=(()=>{let r=(n=Ns(48))=>Mp(n,jp.n);return{keygen:$p(r,vB),getPublicKey:vB,sign:rL,verify:TB,Point:bc,utils:{randomSecretKey:r,taggedHash:Fp,lift_x:SB,pointToBytes:Lb},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})();l();function nL(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function BB(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function Mb(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function IB(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Kb(t){if(!Array.isArray(t))throw new Error("array expected")}function RB(t,e){if(!BB(!0,e))throw new Error(`${t}: array of strings expected`)}function iL(t,e){if(!BB(!1,e))throw new Error(`${t}: array of numbers expected`)}function oL(...t){let e=o=>o,r=(o,s)=>c=>o(s(c)),n=t.map(o=>o.encode).reduceRight(r,e),i=t.map(o=>o.decode).reduce(r,e);return{encode:n,decode:i}}function sL(t){let e=typeof t=="string"?t.split(""):t,r=e.length;RB("alphabet",e);let n=new Map(e.map((i,o)=>[i,o]));return{encode:i=>(Kb(i),i.map(o=>{if(!Number.isSafeInteger(o)||o<0||o>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${o}". Allowed: ${t}`);return e[o]})),decode:i=>(Kb(i),i.map(o=>{Mb("alphabet.decode",o);let s=n.get(o);if(s===void 0)throw new Error(`Unknown letter: "${o}". Allowed: ${t}`);return s}))}}function cL(t=""){return Mb("join",t),{encode:e=>(RB("join.decode",e),e.join(t)),decode:e=>(Mb("join.decode",e),e.split(t))}}function _B(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Kb(t),!t.length)return[];let n=0,i=[],o=Array.from(t,c=>{if(IB(c),c<0||c>=e)throw new Error(`invalid integer: ${c}`);return c}),s=o.length;for(;;){let c=0,a=!0;for(let u=n;u<s;u++){let d=o[u],f=e*c,h=f+d;if(!Number.isSafeInteger(h)||f/e!==c||h-d!==f)throw new Error("convertRadix: carry overflow");let p=h/r;c=h%r;let g=Math.floor(p);if(o[u]=g,!Number.isSafeInteger(g)||g*r+c!==h)throw new Error("convertRadix: carry overflow");if(a)g?a=!1:n=u;else continue}if(i.push(c),a)break}for(let c=0;c<t.length-1&&t[c]===0;c++)i.push(0);return i.reverse()}function aL(t){IB(t);let e=2**8;return{encode:r=>{if(!nL(r))throw new Error("radix.encode input should be Uint8Array");return _B(Array.from(r),e,t)},decode:r=>(iL("radix.decode",r),Uint8Array.from(_B(r,t,e)))}}var uL=t=>oL(aL(58),sL(t),cL("")),nu=uL("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");var UB=new Uint8Array([231,1]),ht=class t{#e;#t={prefix:UB,key:[],encoded:""};constructor(e){let r=e instanceof Uint8Array?e:Ar(e);if(!r||r.length!==33)throw new Bs("Invalid argument: byte length must be 33 (compressed)","CONSTRUCTOR_ERROR",{keyBytes:r});if(!dn.utils.isValidPublicKey(r))throw new Bs("Invalid argument: not a valid secp256k1 compressed point","CONSTRUCTOR_ERROR",{keyBytes:r});this.#e=new Uint8Array(r),this.#t.encoded=this.encode(),this.#t.key=[...this.#t.prefix,...this.compressed]}get compressed(){return new Uint8Array(this.#e)}get uncompressed(){return dn.Point.fromBytes(this.compressed).toBytes(!1)}get xOnly(){return this.compressed.slice(1)}get parity(){let e=this.compressed[0];if(![2,3].includes(e))throw new Bs("Invalid state: parity byte must be 2 or 3","PARITY_ERROR",{parity:e});return e}get isEven(){return this.parity===2}get x(){return this.compressed.slice(1,33)}get y(){return this.uncompressed.slice(33,65)}get multibase(){return{prefix:new Uint8Array(this.#t.prefix),key:[...this.#t.key],encoded:this.#t.encoded}}get hex(){return Ct(this.compressed)}get point(){return{x:this.x,y:this.y}}bip340(){return this.xOnly}decode(){return nu.decode(this.multibase.encoded.slice(1))}encode(){let e=Array.from(this.compressed),r=Array.from(UB);return r.push(...e),"z"+nu.encode(Uint8Array.from(r))}verify(e,r,n){if(n??={scheme:"schnorr"},n.scheme==="ecdsa")return dn.verify(e,r,this.compressed);if(n.scheme==="schnorr")return Wp.verify(e,r,this.x);throw new Bs(`Invalid scheme: ${n.scheme}.`,"VERIFY_SIGNATURE_ERROR",n)}equals(e){return Qc(this.compressed,e.compressed)}toJSON(){return{hex:this.hex,multibase:this.multibase,point:{x:Array.from(this.x),y:Array.from(this.y),parity:this.parity}}}static isValid(e){try{return new t(e),!0}catch{return!1}}static fromJSON(e){return new t(Uint8Array.from([e.point.parity,...e.point.x]))}};l();var OB=new Uint8Array([129,38]),dL=Ct(Oe(OB)),Hr=class t{#e;#t;#n;constructor(e){let r=e instanceof Uint8Array,n=typeof e=="bigint";if(!r&&!n)throw new jn("Invalid entropy: must be a valid byte array (32) or bigint","CONSTRUCTOR_ERROR");if(r&&e.length===32&&(this.#e=new Uint8Array(e),this.#t=t.toSecret(this.#e)),n&&e>=1n&&e<dn.Point.Fn.ORDER&&(this.#e=t.toBytes(e),this.#t=e),!this.#e||this.#e.length!==32)throw new jn("Invalid bytes: must be a valid 32-byte secret key","CONSTRUCTOR_ERROR");if(!this.#t||this.#t<1n||this.#t>=dn.Point.Fn.ORDER)throw new jn("Invalid seed: must be valid bigint","CONSTRUCTOR_ERROR");this.#n=this.encode()}destroy(){this.#e&&this.#e.fill(0),this.#t=void 0,this.#n=""}get bytes(){return new Uint8Array(this.#e)}get seed(){return BigInt(this.#t)}get hex(){return Ct(this.bytes)}get multibase(){return this.#n}encode(){let e=Array.from(this.bytes),r=Array.from(OB);return r.push(...e),"z"+nu.encode(Uint8Array.from(r))}equals(e){return Qc(this.bytes,e.bytes)}computePublicKey(){return new ht(dn.getPublicKey(this.bytes))}toJSON(){return{type:"Secp256k1SecretKey"}}exportJSON(){return{bytes:Array.from(this.bytes),seed:this.seed.toString(),hex:this.hex}}toString(){return"[Secp256k1SecretKey]"}[Symbol.for("nodejs.util.inspect.custom")](){return"[Secp256k1SecretKey]"}isValid(){return dn.utils.isValidSecretKey(this.bytes)}hasValidPublicKey(){try{return this.computePublicKey(),!0}catch{return!1}}sign(e,r){if(r??={scheme:"schnorr"},r.scheme==="ecdsa")return dn.sign(e,this.bytes);if(r.scheme==="schnorr")return Wp.sign(e,this.bytes);throw new jn(`Invalid scheme: ${r.scheme}.`,"SIGN_ERROR",r)}static decode(e){let r=nu.decode(e.slice(1));if(r.length!==34)throw new jn("Invalid argument: must be 34 byte secretKeyMultibase","DECODE_MULTIBASE_ERROR");let n=r.slice(0,2);if(Ct(Oe(n))!==dL)throw new jn(`Invalid prefix: malformed multibase prefix ${n}`,"DECODE_MULTIBASE_ERROR");return r}static fromJSON(e){return new t(new Uint8Array(e.bytes))}static toSecret(e){return e.reduce((r,n)=>r<<8n|BigInt(n),0n)}static toBytes(e){let r=Uint8Array.from({length:32},(n,i)=>Number(e>>BigInt(8*(31-i))&BigInt(255)));if(!dn.utils.isValidSecretKey(r))throw new jn("Invalid secret key: secret out of valid range","SET_PRIVATE_KEY_ERROR");return new Uint8Array(r)}static fromBigInt(e){return new t(t.toBytes(e))}static random(){let e;do e=Tr(32);while(!dn.utils.isValidSecretKey(e));return e}static generate(){let e=this.random();return new t(e)}static getPublicKey(e){return new t(e).computePublicKey()}};var ao=class t{#e;#t;constructor(e={}){if(!e.publicKey&&!e.secretKey)throw new wn("Argument missing: must at least provide a publicKey","CONSTRUCTOR_ERROR");if(e.secretKey instanceof Uint8Array?this.#e=new Hr(e.secretKey):e.secretKey instanceof Hr&&(this.#e=e.secretKey),e.publicKey instanceof ht?this.#t=e.publicKey:e.publicKey instanceof Uint8Array?this.#t=new ht(e.publicKey):this.#t=this.#e.computePublicKey(),this.#e&&e.publicKey){let r=this.#e.computePublicKey();if(!this.#t.equals(r))throw new wn("Public key does not match secret key","CONSTRUCTOR_ERROR")}}get secretKey(){if(!this.#e)throw new wn("Secret key not available","SECRET_KEY_ERROR");if(!this.#e.isValid())throw new wn("Secret key is not valid","SECRET_KEY_ERROR");return this.#e}set publicKey(e){if(this.#e){let r=this.#e.computePublicKey();if(!e.equals(r))throw new wn("Public key does not match secret key","PUBLIC_KEY_ERROR")}this.#t=e}get publicKey(){return this.#t}get hasSecretKey(){return!!this.#e}get raw(){return{public:this.publicKey.compressed,secret:this.#e?this.#e.bytes:void 0}}get hex(){return{public:this.publicKey.hex,secret:this.#e?this.#e.hex:void 0}}get multibase(){return{publicKeyMultibase:this.#t.multibase.encoded,secretKeyMultibase:this.#e?this.#e.multibase:""}}toJSON(){return{publicKey:this.publicKey.toJSON()}}exportJSON(){if(!this.#e)throw new wn("Cannot export: secret key required. Use publicKey.toJSON() for public-key-only pairs.","SERIALIZE_ERROR");return{secretKey:this.#e.exportJSON(),publicKey:this.publicKey.toJSON()}}[Symbol.for("nodejs.util.inspect.custom")](){return`[SchnorrKeyPair ${this.publicKey.hex}]`}static fromJSON(e){return new t({secretKey:Hr.fromJSON(e.secretKey),publicKey:ht.fromJSON(e.publicKey)})}static fromSecret(e){let r=typeof e=="string"?Ar(e):e;if(r.length!==32)throw new wn("Invalid arg: must be 32 byte secret key","FROM_SECRET_KEY_ERROR");let n=new Hr(r),i=n.computePublicKey();return new t({secretKey:n,publicKey:i})}static fromBigInt(e){let r=Hr.fromBigInt(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}static toHex(e){return Ct(e)}static equals(e,r){return e.publicKey.equals(r.publicKey)}static generate(){let e=Hr.random(),r=new Hr(e),n=r.computePublicKey();return new t({secretKey:r,publicKey:n})}};l();l();l();var xr=class t{static encode(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r;if(!(n in _o))throw new mt('Expected "idType" to be "KEY" or "EXTERNAL"',Lt,{idType:n});if(i!==1)throw new mt('Expected "version" to be 1',Lt,{version:i});if(typeof o!="string")throw new mt('Expected "network" to be a known network name',Lt,{network:o});let s=qu[o];if(s===void 0)throw new mt('Invalid "network" name',Lt,{network:o});if(n==="KEY")try{new ht(e)}catch{throw new mt('Expected "genesisBytes" to be a valid compressed secp256k1 public key',Lt,{genesisBytes:e})}else if(e.length!==32)throw new mt('Expected "genesisBytes" to be a 32-byte hash for EXTERNAL identifiers',Lt,{genesisBytes:e});let c=n==="KEY"?"k":"x",a=i-1<<4|s,u=new Uint8Array([a,...e]);return`did:btcr2:${Hc.encodeFromBytes(c,u)}`}static decode(e){let r=e.split(":");if(r.length!==3)throw new mt(`Invalid did: ${e}`,Lt,{identifier:e});let[n,i,o]=r;if(n!=="did")throw new mt(`Invalid did: ${e}`,Lt,{identifier:e});if(i!=="btcr2")throw new mt(`Invalid did method: ${i}`,pl,{identifier:e});if(!o)throw new mt(`Invalid method-specific id: ${e}`,Lt,{identifier:e});let{prefix:s,bytes:c}=Hc.decodeToBytes(o);if(!["x","k"].includes(s))throw new mt(`Invalid hrp: ${s}`,Lt,{identifier:e});if(!c||c.length<1)throw new mt(`Failed to decode id: ${o}`,Lt,{identifier:e});let a=s==="k"?"KEY":"EXTERNAL",u=c[0]>>>4;if(u!==0)throw new mt(`Invalid btcr2_version (expected 0): ${u}`,Lt,{identifier:e});let d=1,f=c[0]&15,h=qu[f],p;if(typeof h=="string")p=h;else if(f>=12&&f<=14)p=f-11;else throw new mt(`Invalid network: ${f}`,Lt,{identifier:e});let g=c.slice(1);if(a==="KEY")try{new ht(g)}catch{throw new mt(`Invalid genesisBytes: ${g}`,Lt,{identifier:e})}else if(g.length!==32)throw new mt(`Invalid genesisBytes: ${g}`,Lt,{identifier:e});return{idType:a,hrp:s,version:d,network:p,genesisBytes:g}}static generate(){let e=ao.generate(),r=this.encode(e.publicKey.compressed,{idType:"KEY",version:1,network:"regtest"});return{keyPair:e.exportJSON(),did:r}}static getPublicKey(e){let{idType:r,genesisBytes:n}=t.decode(e);if(r!=="KEY")throw new mt(`Cannot extract public key from EXTERNAL DID: ${e}. EXTERNAL DIDs encode a document hash, not a public key.`,Lt,{did:e,idType:r});return new ht(n)}static isValid(e){try{return this.decode(e),!0}catch{return!1}}};var fn=class{static parseBitcoinAddress(e){if(!e.startsWith("bitcoin:"))throw new tt("Invalid Bitcoin URI format","BEACON_SERVICE_ERROR",{uri:e});return e.replace("bitcoin:","").split("?")[0]}static isBeaconService(e){return!(!Kr.isDidService(e)||!["SingletonBeacon","CASBeacon","SMTBeacon"].includes(e.type)||[e.serviceEndpoint].flat().some(r=>typeof r=="string"&&!r.startsWith("bitcoin:")))}static getBeaconServices(e){return e.service.filter(this.isBeaconService)??[]}static createBeaconServices(e,r){try{return["p2pkh","p2wpkh","p2tr"].map(i=>this.createBeaconService(e,i,r))}catch(n){throw new rr("Failed to create beacon services: "+n.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:r})}}static createBeaconService(e,r,n){try{let i=xr.decode(e),o=Io(i.network),s=i.genesisBytes,c=`${e}#initial${r.toUpperCase()}`,u=`bitcoin:${r==="p2tr"?Ss(s.slice(1,33),void 0,o).address:r==="p2wpkh"?vs(s,o).address:ki(s,o).address}`;return{id:c,type:n,serviceEndpoint:u}}catch(i){throw new rr("Failed to create beacon service: "+i.message,"BEACON_SERVICE_ERROR",{did:e,beaconType:n})}}static generateBeaconServices({id:e,publicKey:r,network:n,beaconType:i}){try{let o=ki(r,n).address,s=vs(r,n).address,c=Ss(r.slice(1,33),void 0,n).address;if(!o||!s||!c)throw new Gt("Failed to generate bitcoin addresses");return[{id:`${e}#initialP2PKH`,type:i,serviceEndpoint:`bitcoin:${o}`},{id:`${e}#initialP2WPKH`,type:i,serviceEndpoint:`bitcoin:${s}`},{id:`${e}#initialP2TR`,type:i,serviceEndpoint:`bitcoin:${c}`}]}catch(o){throw new rr("Failed to create beacon services: "+o.message,"BEACON_SERVICE_ERROR",{id:e,publicKey:r,network:n,beaconType:i})}}static parseBeaconServiceEndpoint(e){return{...e,serviceEndpoint:e.serviceEndpoint.replace("bitcoin:","")}}static getBeaconServicesMap(e){return new Map(e.map(this.parseBeaconServiceEndpoint).map(r=>[r.serviceEndpoint,r]))}static getBeaconServiceIds(e){return this.getBeaconServices(e).map(r=>r.id)}};function DB(t){if(!t)return null;let e=t.trim().split(/\s+/);if(e.length!==3||e[0]!=="OP_RETURN"||e[1]!=="OP_PUSHBYTES_32")return null;let r=e[2];return/^[0-9a-fA-F]{64}$/.test(r)?r.toLowerCase():null}var kB=class{static async indexer(e,r){let n=new Map,i=await r.rest.block.count();for(let o of e){n.set(o,[]);let s=await r.rest.address.getTxs(fn.parseBitcoinAddress(o.serviceEndpoint));if(!(!s||!s.length))for(let c of s){let a=c.vout.slice(-1)[0];if(!a)continue;let u=DB(a.scriptpubkey_asm);if(!u)continue;let d=i-c.status.block_height+1;n.get(o)?.push({tx:c,signalBytes:u,blockMetadata:{confirmations:d,height:c.status.block_height,time:c.status.block_time}})}}return n}static async fullnode(e,r){let n=new Map;for(let u of e)n.set(u,[]);let i=r.rpc;if(!i)throw new rt("RPC connection is not available","RPC_CONNECTION_ERROR",r);let o=await i.getBlockCount(),s=fn.getBeaconServicesMap(e),c=0,a=await r.rpc.getBlock({height:c});for(console.info("Searching for beacon signals, please wait ...");a.height<=o;){for(let u of a.tx)if(u.txid!==_0)for(let d of u.vin){if(d.coinbase||d.txinwitness&&d.txinwitness.length===1&&d.txinwitness[0]===T0||!d.txid||d.vout===void 0)continue;let f=await i.getRawTransaction(d.txid,2);if(!f.vout[d.vout])continue;let h=f.vout[d.vout].scriptPubKey;if(!h.address)continue;let p=s.get(h.address);if(!p)continue;let g=f.vout[d.vout].scriptPubKey.asm,y=DB(g);y&&(console.info(`Tx ${u.txid} contains beacon service address ${h.address} and OP_RETURN!`,u),n.get(p)?.push({tx:u,signalBytes:y,blockMetadata:{height:a.height,time:a.time,confirmations:a.confirmations}}))}if(c+=1,c>o){console.info(`Chain tip reached ${c}, breaking ...`);break}a=await i.getBlock({height:c})}return n}};l();l();l();l();l();l();l();var Vte=new Uint8Array(0);function NB(t){if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")}l();function fL(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var o=t.charAt(i),s=o.charCodeAt(0);if(r[s]!==255)throw new TypeError(o+" is ambiguous");r[s]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),d=Math.log(256)/Math.log(c);function f(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,E=0,S=0,I=g.length;S!==I&&g[S]===0;)S++,y++;for(var A=(I-S)*d+1>>>0,O=new Uint8Array(A);S!==I;){for(var T=g[S],M=0,q=A-1;(T!==0||M<E)&&q!==-1;q--,M++)T+=256*O[q]>>>0,O[q]=T%c>>>0,T=T/c>>>0;if(T!==0)throw new Error("Non-zero carry");E=M,S++}for(var j=A-E;j!==A&&O[j]===0;)j++;for(var $=a.repeat(y);j<A;++j)$+=t.charAt(O[j]);return $}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var E=0,S=0;g[y]===a;)E++,y++;for(var I=(g.length-y)*u+1>>>0,A=new Uint8Array(I);g[y];){var O=r[g.charCodeAt(y)];if(O===255)return;for(var T=0,M=I-1;(O!==0||T<S)&&M!==-1;M--,T++)O+=c*A[M]>>>0,A[M]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=T,y++}if(g[y]!==" "){for(var q=I-S;q!==I&&A[q]===0;)q++;for(var j=new Uint8Array(E+(I-q)),$=E;q!==I;)j[$++]=A[q++];return j}}}function p(g){var y=h(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:p}}var lL=fL,hL=lL,CB=hL;var $b=class{name;prefix;baseEncode;constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Hb=class{name;prefix;baseDecode;prefixCodePoint;constructor(e,r,n){this.name=e,this.prefix=r;let i=r.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return LB(this,e)}},Vb=class{decoders;constructor(e){this.decoders=e}or(e){return LB(this,e)}decode(e){let r=e[0],n=this.decoders[r];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};function LB(t,e){return new Vb({...t.decoders??{[t.prefix]:t},...e.decoders??{[e.prefix]:e}})}var qb=class{name;prefix;baseEncode;baseDecode;encoder;decoder;constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new $b(e,r,n),this.decoder=new Hb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};function pL({name:t,prefix:e,encode:r,decode:n}){return new qb(t,e,r,n)}function Fb({name:t,prefix:e,alphabet:r}){let{encode:n,decode:i}=CB(r,t);return pL({prefix:e,name:t,encode:n,decode:o=>NB(i(o))})}var lf=Fb({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Xte=Fb({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});l();var iu=class{cryptosuite;constructor(e){this.cryptosuite=e}addProof(e,r){let n=this.cryptosuite.createProof(e,r);if(!n.type||!n.verificationMethod||!n.proofPurpose)throw new Jr("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Ao,{config:r,proof:n});if(r.domain&&n.domain!==r.domain)throw new Jr("Domain mismatch: proof.domain !== config.domain",Ao,{config:r,proof:n});if(r.challenge&&n.challenge!==r.challenge)throw new Jr("Challenge mismatch options and challenge passed",Ao,{config:r,proof:n});let i=e;return i.proof=n,i}verifyProof(e,r,n,i,o){let s=JSON.parse(e),c=s.proof;if(!c.type||!c.verificationMethod||!c.proofPurpose)throw new Jr("Invalid proof: missing proof.type, proof.verificationMethod and/or proof.proofPurpose",Wn,s);if(r&&r!==c.proofPurpose)throw new Jr("Proof purpose mismatch: proof.proofPurpose !== expectedPurpose",Wn,{proof:c,expectedPurpose:r});if(o&&o!==c.challenge)throw new Jr("Challenge mismatch: proof.challenge !== expectedChallenge","INVALID_CHALLENGE_ERROR",{proof:c,expectedChallenge:o});if(i){if(Array.isArray(i)&&i.length){if(i.length!==c.domain?.length)throw new Jr("Domain mismatch: expectedDomain length does not match proof.domain length",Wn,{proof:c,expectedDomain:i});if(i.every(u=>c.domain?.includes(u)))throw new Jr("Domain mismatch: expectedDomain and proof.domain do not match",Wn,{proof:c,expectedDomain:i})}else if(c.domain!==i)throw new Jr("Domain mismatch: proof.domain !== expectedDomain",Wn,{proof:c,expectedDomain:i})}let a=this.cryptosuite.verifyProof(s);return a.mediaType=n,a}};var ou=class{type="DataIntegrityProof";cryptosuite="bip340-jcs-2025";multikey;constructor(e){this.multikey=e}toDataIntegrityProof(){return new iu(this)}createProof(e,r){r["@context"]=e["@context"]??r["@context"];let n=this.proofConfiguration(r),i=this.transformDocument(e,r),o=this.generateHash(n,i),s=this.proofSerialization(o,r),c=r;return c.proofValue=lf.encode(s),c.cryptosuite=this.cryptosuite,c.type=this.type,c}verifyProof(e){let{proof:r,...n}=e,{proofValue:i,...o}=r,s=this.transformDocument(n,o),c=this.proofConfiguration(o),a=this.generateHash(c,s),u=lf.decode(e.proof.proofValue),d=this.proofVerification(a,u,o);return{verified:d,verifiedDocument:d?e:void 0}}transformDocument(e,r){if(r.type!==this.type)throw new tt("Type mismatch: config.type !== this.type",Wn,{config:r,this:this});if(r.cryptosuite!==this.cryptosuite)throw new tt("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Wn,{config:r,this:this});return tr(e)}generateHash(e,r){let n=Oe(ws(e)),i=Oe(ws(r)),o=ut(n,i);return Oe(o)}proofConfiguration(e){if(e.type!==this.type)throw new So("Type mismatch: config.type !== this.type",Ao,{config:e,this:this});if(e.cryptosuite!==this.cryptosuite)throw new So("Cryptosuite mismatch: config.cryptosuite !== this.cryptosuite",Ao,{config:e,this:this});if(e.created&&!Bo.isValidXsdDateTime(e.created))throw new So('Invalid config: "created" must be a valid XMLSchema DateTime string',Ao,e);return tr(e)}proofSerialization(e,r){if(r.verificationMethod!==this.multikey.fullId())throw new So("Id mismatch: config.verificationMethod !== this.multikey.fullId()",av,{config:r,this:this});return this.multikey.sign(e)}proofVerification(e,r,n){if(n.verificationMethod!==this.multikey.fullId())throw new So("Id mismatch: config.verificationMethod !== this.multikey.fullId()",Wn,{config:n,this:this});return this.multikey.verify(r,e)}};l();l();l();var cs=class t{static type="Multikey";id;controller;#e;#t;constructor({id:e,controller:r,keyPair:n,externalSigner:i}){if(!n)throw new bn('Argument missing: "keyPair" required',"CONSTRUCTOR_ERROR");if(!n.publicKey)throw new bn('Argument missing: "keyPair" must contain a "publicKey"',"CONSTRUCTOR_ERROR");if(i){let o=i.publicKey,s=n.publicKey.compressed;if(o.length!==s.length||!o.every((c,a)=>c===s[a]))throw new bn("externalSigner.publicKey does not match keyPair.publicKey.compressed","CONSTRUCTOR_ERROR")}this.id=e,this.controller=r,this.#e=n,this.#t=i}get keyPair(){return this.#e}get publicKey(){return this.#e.publicKey}get secretKey(){try{return this.#e.secretKey}catch{throw new bn("Cannot get: no secretKey","PRIVATE_KEY_ERROR")}}toCryptosuite(){return new ou(this)}sign(e){if(this.#t)return this.#t.sign(e,"bip340");if(!this.signer)throw new bn("Cannot sign: no secretKey","SIGN_ERROR");return Ir.sign(e,this.secretKey.bytes,Tr(32))}verify(e,r){return Ir.verify(e,r,this.publicKey.x)}fullId(){return this.id.startsWith("#")?`${this.controller}${this.id}`:this.id}toVerificationMethod(){return{id:this.id,type:t.type,controller:this.controller,publicKeyMultibase:this.publicKey.multibase.encoded}}get signer(){return!!this.#t||!!this.#e.secretKey}toJSON(){return{id:this.id,controller:this.controller,fullId:this.fullId(),signer:this.signer,keyPair:this.keyPair.exportJSON(),verificationMethod:this.toVerificationMethod()}}static create({id:e,controller:r,keyPair:n}){return new t({id:e,controller:r,keyPair:n})}static fromSecretKey(e,r,n){let i=new Hr(n),o=i.computePublicKey(),s=new ao({publicKey:o,secretKey:i});return new t({id:e,controller:r,keyPair:s})}static fromSigner(e,r,n){let i=new ht(n.publicKey),o=new ao({publicKey:i});return new t({id:e,controller:r,keyPair:o,externalSigner:n})}static fromPublicKey({id:e,controller:r,publicKeyBytes:n}){let i=new ht(n),o=new ao({publicKey:i});return new t({id:e,controller:r,keyPair:o})}static fromVerificationMethod({id:e,controller:r,publicKeyMultibase:n}){if(!n)throw new bn("Invalid publicKeyMultibase: cannot be undefined",yl,{publicKeyMultibase:n});let i=lf.decode(n);if(i.length!==35)throw new bn(`Invalid publicKeyMultibase length: ${i.length}`,yl,{publicKeyMultibase:n});if(i[0]!==231||i[1]!==1)throw new bn(`Invalid publicKeyMultibase prefix: expected secp256k1 multicodec [0xe7, 0x01], got [0x${i[0]?.toString(16)??"??"}, 0x${i[1]?.toString(16)??"??"}]`,yl,{publicKeyMultibase:n});let o=i.slice(2),s=new ao({publicKey:o});return new t({id:e,controller:r,keyPair:s})}};l();l();l();l();l();var yL=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],su="Multikey",cu="zQ3s",ln="did:btcr2:_",Pre="",gL=/did:btcr2:(x1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]*)/g;function mL(t){if(!Kr.isDidVerificationMethod(t))return!1;let{type:e,publicKeyMultibase:r}=t;return e===su&&typeof r=="string"&&r.startsWith(cu)}var jb=class{id;type;controller;publicKeyMultibase;secretKeyMultibase;constructor({id:e,type:r,controller:n,publicKeyMultibase:i,secretKeyMultibase:o}){if(r!==su)throw new Ze(`Invalid verification method: type must be "${su}"`,Ue,{id:e,type:r});if(typeof i!="string"||!i.startsWith(cu))throw new Ze(`Invalid verification method: publicKeyMultibase must start with "${cu}"`,Ue,{id:e,publicKeyMultibase:i});this.id=e,this.type=r,this.controller=n,this.publicKeyMultibase=i,this.secretKeyMultibase=o,o||delete this.secretKeyMultibase}},hn=class t{id;"@context"=["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"];verificationMethod;authentication;assertionMethod;capabilityInvocation;capabilityDelegation;service;deactivated;constructor(e){if(!e.id)throw new Ze("DID Document must have an id",Ue,e);let r=e.id.includes("k1")?_o.KEY:_o.EXTERNAL,n=e.id===ln,{id:i,verificationMethod:o,service:s}=e;if(!n){if(!t.isValidId(i))throw new Ze(`Invalid id: ${i}`,Ue,e);if(!t.isValidVerificationMethods(o))throw new Ze("Invalid verificationMethod: "+o,Ue,e);if(!t.isValidServices(s))throw new Ze("Invalid service: "+s,Ue,e)}if(this.id=e.id,this.verificationMethod=e.verificationMethod||[],this.service=e.service||[],this["@context"]=e["@context"]||["https://www.w3.org/ns/did/v1.1","https://btcr2.dev/context/v1"],r===_o.KEY){let c=`${this.id}#initialKey`;this.authentication=e.authentication||[c],this.assertionMethod=e.assertionMethod||[c],this.capabilityInvocation=e.capabilityInvocation||[c],this.capabilityDelegation=e.capabilityDelegation||[c]}else this.authentication=e.authentication,this.assertionMethod=e.assertionMethod,this.capabilityInvocation=e.capabilityInvocation,this.capabilityDelegation=e.capabilityDelegation;t.sanitize(this),n?this.validateGenesis():t.validate(this)}toJSON(){return{id:this.id,"@context":this["@context"],verificationMethod:this.verificationMethod,authentication:this.authentication,assertionMethod:this.assertionMethod,capabilityInvocation:this.capabilityInvocation,capabilityDelegation:this.capabilityDelegation,service:this.service,deactivated:this.deactivated}}static fromKeyIdentifier(e,r,n){e=e.includes("#")?e:`${e}#initialKey`;let i={id:e,verificationMethod:[new jb({id:e,type:"Multikey",controller:e,publicKeyMultibase:r})],service:n};return new t(i)}static fromExternalIdentifier(e){return new t(e)}static sanitize(e){for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}static isValid(e){if(!this.isValidContext(e?.["@context"]))throw new Ze('Invalid "@context"',Ue,e);if(!this.isValidId(e?.id))throw new Ze('Invalid "id"',Ue,e);if(!this.isValidVerificationMethods(e?.verificationMethod))throw new Ze('Invalid "verificationMethod"',Ue,e);if(!this.isValidServices(e?.service))throw new Ze('Invalid "service"',Ue,e);if(!this.isValidVerificationRelationships(e))throw new Ze("Invalid verification relationships",Ue,e);return!0}static isValidContext(e){return!Array.isArray(e)||e.length===0?!1:yL.every(r=>e.includes(r))}static isValidId(e){if(typeof e!="string")return!1;try{return xr.decode(e),!0}catch{return!1}}static isValidVerificationMethods(e){return Array.isArray(e)&&e.every(mL)}static isValidServices(e){return Array.isArray(e)&&e.every(XT)}static isValidVerificationRelationships(e){let r=["authentication","assertionMethod","capabilityInvocation","capabilityDelegation"],n=Object.keys(e);return r.filter(o=>n.includes(o)).every(o=>{let s=e[o];return s&&Array.isArray(s)&&s.every(c=>typeof c=="string"||Kr.isDidVerificationMethod(c))})}static validate(e){return e.id===ln?e.validateGenesis():t.isValid(e),e}validateGenesis(){if(this.id!==ln)throw new Ze("Invalid GenesisDocument ID",Ue,this);if(!this.verificationMethod.every(e=>e.id.includes(ln)&&e.controller===ln))throw new Ze("Invalid GenesisDocument verificationMethod",Ue,this);if(!this.service.every(e=>e.id.includes(ln)))throw new Ze("Invalid GenesisDocument service",Ue,this);if(!t.isValidVerificationRelationships(this))throw new Ze("Invalid GenesisDocument assertionMethod",Ue,this);return!0}toIntermediate(){if(this.id.includes("k1"))throw new Ze("Cannot convert a key identifier to an intermediate document",Ue,this);return new Wb(this)}},Wb=class t extends hn{constructor(e){super(e)}toDidDocument(e){let r=JSON.stringify(this).replaceAll(ln,e),n=JSON.parse(r);return new hn(n)}static fromDidDocument(e){let r=Us.cloneReplace(e,gL,ln);return new t(r)}static create(e,r,n){return new t({id:ln,...r,verificationMethod:e,service:n})}static fromPublicKey(e,r){let n=new ht(e),i=ln,o=ki(n.compressed,Io(r)).address,s=[{id:`${i}#service-0`,serviceEndpoint:`bitcoin:${o}`,type:"SingletonBeacon"}],c={authentication:[`${i}#key-0`],assertionMethod:[`${i}#key-0`],capabilityInvocation:[`${i}#key-0`],capabilityDelegation:[`${i}#key-0`]},a=[{id:`${i}#key-0`,type:"Multikey",controller:i,publicKeyMultibase:n.multibase.encoded}];return t.create(a,c,s)}static fromJSON(e){return new t(e)}static toGenesisBytes(e){return To(tr(e))}};var Gp=class t{#e={phase:"Construct"};#t;#n;#r;#o;#i;constructor(e){this.#t=e.sourceDocument,this.#n=e.patches,this.#r=e.sourceVersionId,this.#o=e.verificationMethod,this.#i=e.beaconService}static construct(e,r,n){let i={"@context":["https://w3id.org/security/v2","https://w3id.org/zcap/v1","https://w3id.org/json-ld-patch/v1","https://btcr2.dev/context/v1"],patch:r,targetHash:"",targetVersionId:n+1,sourceHash:Gn(e)},o=Zc.apply(e,r);if(o.id!==e.id)throw new vt(`Patches must not change the DID document id (source "${e.id}" to target "${o.id}").`,Ne,{sourceId:e.id,targetId:o.id});try{hn.isValid(o)}catch(s){throw new vt("Error validating targetDocument: "+(s instanceof Error?s.message:String(s)),Ne,o)}return i.targetHash=Gn(o),i}static sign(e,r,n,i){if(!e.startsWith("did:btcr2:"))throw new vt(`Expected a did:btcr2 identifier for the root capability; got "${e}".`,Ne,{did:e});let o=n.controller,s=n.id.indexOf("#");if(s<0)throw new vt(`Verification method id must contain a fragment (e.g. "${n.id}#initialKey"); got "${n.id}".`,Ne,{verificationMethodId:n.id});let c=n.id.slice(s),a=cs.fromSigner(c,o,i),u=a.publicKey.multibase.encoded;if(n.publicKeyMultibase&&u!==n.publicKeyMultibase)throw new vt(`Signing key does not match verification method "${n.id}": the signer's public key differs from the method's published publicKeyMultibase.`,Ne,{verificationMethodId:n.id,expected:n.publicKeyMultibase,actual:u});let d={"@context":["https://w3id.org/security/v2","https://w3id.org/zcap/v1","https://w3id.org/json-ld-patch/v1","https://btcr2.dev/context/v1"],cryptosuite:"bip340-jcs-2025",type:"DataIntegrityProof",verificationMethod:n.id,proofPurpose:"capabilityInvocation",capability:`urn:zcap:root:${encodeURIComponent(e)}`,capabilityAction:"Write"};return a.toCryptosuite().toDataIntegrityProof().addProof(r,d)}static async announce(e,r,n,i){return ra.establish(e).broadcastSignal(r,n,i)}#s(){return t.construct(this.#t,this.#n,this.#r)}advance(){for(;;)switch(this.#e.phase){case"Construct":{let e=this.#s();this.#e={phase:"Sign",unsignedUpdate:e};continue}case"Sign":return{status:"action-required",needs:[{kind:"NeedSigningKey",verificationMethodId:this.#o.id,unsignedUpdate:this.#e.unsignedUpdate}]};case"Fund":return{status:"action-required",needs:[{kind:"NeedFunding",beaconAddress:this.#i.serviceEndpoint.replace("bitcoin:",""),beaconService:this.#i}]};case"Broadcast":return{status:"action-required",needs:[{kind:"NeedBroadcast",beaconService:this.#i,signedUpdate:this.#e.signedUpdate}]};case"Complete":return{status:"complete",result:{signedUpdate:this.#e.signedUpdate}}}}provide(e,r){switch(e.kind){case"NeedSigningKey":{if(this.#e.phase!=="Sign")throw new vt(`Cannot provide NeedSigningKey: updater phase is ${this.#e.phase}, expected Sign.`,Ne,{phase:this.#e.phase});if(!r)throw new vt("NeedSigningKey requires a Signer.",Ne);let n=this.#e.unsignedUpdate,i=t.sign(this.#t.id,n,this.#o,r);this.#e={phase:"Fund",unsignedUpdate:n,signedUpdate:i};break}case"NeedFunding":{if(this.#e.phase!=="Fund")throw new vt(`Cannot provide NeedFunding: updater phase is ${this.#e.phase}, expected Fund.`,Ne,{phase:this.#e.phase});if(r!==void 0){let n=r;if(typeof n.utxoCount!="number"||!Number.isFinite(n.utxoCount)||n.utxoCount<1)throw new vt(`NeedFunding proof must have utxoCount >= 1; got ${String(n.utxoCount)}.`,Ne,{utxoCount:n.utxoCount})}this.#e={phase:"Broadcast",unsignedUpdate:this.#e.unsignedUpdate,signedUpdate:this.#e.signedUpdate};break}case"NeedBroadcast":{if(this.#e.phase!=="Broadcast")throw new vt(`Cannot provide NeedBroadcast: updater phase is ${this.#e.phase}, expected Broadcast.`,Ne,{phase:this.#e.phase});this.#e={phase:"Complete",signedUpdate:this.#e.signedUpdate};break}}}};var zp=class{static methodName="btcr2";static create(e,r){let{idType:n,version:i=1,network:o="bitcoin"}=r||{};if(!n)throw new tt("idType is required for creating a did:btcr2 identifier",Ue,r);return xr.encode(e,{idType:n,version:i,network:o})}static resolve(e,r={}){let n=xr.decode(e),i=as.sidecarData(r.sidecar),o=n.hrp===Sl.k?as.deterministic(n):null;return new as(n,i,o,{versionId:r.versionId,versionTime:r.versionTime,genesisDocument:r.sidecar?.genesisDocument,maxDiscoveryRounds:r.maxDiscoveryRounds})}static update({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethodId:i,beaconId:o}){if(!e.capabilityInvocation?.some(a=>a===i))throw new vt("Invalid verificationMethodId: not authorized for capabilityInvocation",Ue,e);let s=this.getSigningMethod(e,i);if(!s)throw new vt("Invalid verificationMethod: not found in source document",Ue,{sourceDocument:e,verificationMethodId:i});if(s.type!==su)throw new vt(`Invalid verificationMethod: verificationMethod.type must be "${su}"`,Ue,s);if(!s.publicKeyMultibase?.startsWith(cu))throw new vt(`Invalid verificationMethodId: publicKeyMultibase prefix must start with "${cu}"`,Ue,s);let c=e.service.filter(a=>a.id===o).filter(a=>!!a).shift();if(!c)throw new vt("No beacon service found for provided beaconId",Ne,{sourceDocument:e,beaconId:o});return new Gp({sourceDocument:e,patches:r,sourceVersionId:n,verificationMethod:s,beaconService:c})}static getSigningMethod(e,r){r??="#initialKey";let n=me.parse(e.id);if(n&&n.method!==this.methodName)throw new tt(`Method not supported: ${n.method}`,pl,{identifier:e.id});let i=e.verificationMethod?.find(o=>Kr.extractDidFragment(o.id)===(Kr.extractDidFragment(r)??Kr.extractDidFragment(e.assertionMethod?.[0])));if(!(i&&i.publicKeyMultibase))throw new re(ie.InternalError,"A verification method intended for signing could not be determined from the DID Document");return i}};function hf(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function wL(t){return hf(t)&&Object.values(t).every(e=>typeof e=="string")}function bL(t){return hf(t)?Array.isArray(t.patch)&&typeof t.sourceHash=="string"&&typeof t.targetHash=="string"&&typeof t.targetVersionId=="number"&&hf(t.proof):!1}function xL(t){return hf(t)?typeof t.id=="string"&&typeof t.collapsed=="string"&&Array.isArray(t.hashes):!1}var as=class t{#e;#t;#n;#r;#o;#i;#s=null;#f=new Map;#l=new Set;#d=new Set;#c=[];#a=null;#h=1;#y=[];#u;#p=0;constructor(e,r,n,i){this.#e=e,this.#o=r,this.#i=n,this.#t=i?.versionId,this.#n=i?.versionTime;let o=i?.maxDiscoveryRounds;this.#u=typeof o=="number"&&o>0?o:1/0,i?.genesisDocument&&(this.#s=i.genesisDocument),this.#r=n?"BeaconDiscovery":"GenesisDocument"}static deterministic(e){let r=e.genesisBytes,n=xr.encode(r,e),{multibase:i}=new ht(r),o=fn.generateBeaconServices({id:n,publicKey:r,network:Io(e.network),beaconType:"SingletonBeacon"});return new hn({id:n,verificationMethod:[{id:`${n}#initialKey`,type:"Multikey",controller:n,publicKeyMultibase:i.encoded}],service:o})}static external(e,r){let n=Yc(r);if(!vu(e.genesisBytes,n))throw new rt("Initial document mismatch: genesisBytes !== genesisDocumentHash",Ue,{genesisBytes:Zr(e.genesisBytes,"hex"),genesisDocumentHash:Zr(n,"hex")});let i=xr.encode(e.genesisBytes,e),o=JSON.parse(JSON.stringify(r).replaceAll(ln,i));return new hn(o)}static sidecarData(e={}){let r=new Map;if(e.updates?.length)for(let o of e.updates)r.set(Gn(o,{encoding:"hex"}),o);let n=new Map;if(e.casUpdates?.length)for(let o of e.casUpdates)n.set(Gn(o,{encoding:"hex"}),o);let i=new Map;if(e.smtProofs?.length)for(let o of e.smtProofs)i.set(Zr(Is(o.id,"base64urlnopad"),"hex"),o);return{updateMap:r,casMap:n,smtMap:i}}static updates(e,r,n,i,o={currentVersionId:1,updateHashHistory:[]}){let s=o.currentVersionId,c=o.updateHashHistory,a=r.sort(([d,f],[h,p])=>d.targetVersionId-h.targetVersionId||f.height-p.height),u={didDocument:e,metadata:{versionId:`${s}`,confirmations:0,updated:"",deactivated:e.deactivated||!1}};for(let[d,f]of a){let h=Yc(u.didDocument),p=Bo.blocktimeToTimestamp(f.time);if(u.metadata.updated=Bo.toISOStringNonFractional(p),u.metadata.confirmations=f.confirmations,n&&p>Bo.dateStringToTimestamp(n))return u;if(d.targetVersionId<=s){this.confirmDuplicate(d,c);continue}if(d.targetVersionId===s+1){let y=Is(d.sourceHash,"base64urlnopad");if(!vu(y,h))throw new rt("Hash mismatch: update.sourceHash !== currentDocumentHash",Ne,{sourceHash:d.sourceHash,currentDocumentHash:Zr(h,"hex")});u.didDocument=this.applyUpdate(u.didDocument,d);let E=Us.deleteKeys(d,["proof"]);c.push(Yc(E))}else throw new rt("Version Id Mismatch: targetVersionId cannot be > currentVersionId + 1",g0,{targetVersionId:d.targetVersionId,currentVersionId:s+1});s++,u.metadata.versionId=`${s}`;let g=Number(i);if(!isNaN(g)&&g<=s)return u;if(u.didDocument.deactivated)return u.metadata.deactivated=u.didDocument.deactivated,u}return u}static confirmDuplicate(e,r){let{proof:n,...i}=e,o=Yc(i),s=r[e.targetVersionId-2];if(!vu(s,o))throw new rt("Invalid duplicate: unsigned update hash does not match historical hash",g0,{unsignedUpdateHash:Zr(o,"hex"),historicalHash:Zr(s,"hex")})}static applyUpdate(e,r){let n=r.proof?.capability;if(!n)throw new rt("No root capability found in update",Ne,r);let i=Kr.dereferenceZcapId(n),{invocationTarget:o,controller:s}=i;if(![o,s].every(S=>S===e.id))throw new rt("Invalid root capability",Ne,{rootCapability:i,currentDocument:e});let c=r.proof?.verificationMethod;if(!c)throw new rt("No verificationMethod found in update",Ne,r);let a=zp.getSigningMethod(e,c),u=cs.fromVerificationMethod(a),d=new ou(u),f=tr(r),p=new iu(d).verifyProof(f,"capabilityInvocation");if(!p.verified)throw new rt("Invalid update: proof not verified",Ne,p);let g=Zc.apply(e,r.patch);hn.validate(g);let y=Yc(g),E=Is(r.targetHash);if(!vu(E,y))throw new rt("Invalid update: update.targetHash !== currentDocumentHash",Ne,{updateTargetHash:E,currentDocumentHash:y});return g}resolve(){for(;;)switch(this.#r){case"GenesisDocument":{if(this.#s){this.#i=t.external(this.#e,this.#s),this.#s=null,this.#r="BeaconDiscovery";continue}return{status:"action-required",needs:[{kind:"NeedGenesisDocument",genesisHash:Zr(this.#e.genesisBytes,"hex")}]}}case"BeaconDiscovery":{let r=fn.getBeaconServices(this.#i).filter(n=>{let i=fn.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)});if(r.length>0){for(let n of r){let i=fn.parseBitcoinAddress(n.serviceEndpoint);this.#d.add(i)}return{status:"action-required",needs:[{kind:"NeedBeaconSignals",beaconServices:r}]}}this.#r="BeaconProcess";continue}case"BeaconProcess":{let e=[];for(let[r,n]of this.#f){if(this.#l.has(r.id)||!n.length)continue;let o=ra.establish(r).processSignals(n,this.#o);o.needs.length>0?e.push(...o.needs):(this.#c.push(...o.updates),this.#l.add(r.id))}if(e.length>0)return{status:"action-required",needs:e};this.#r="ApplyUpdates";continue}case"ApplyUpdates":{if(this.#c.length>0&&(this.#a=t.updates(this.#i,this.#c,this.#n,this.#t,{currentVersionId:this.#h,updateHashHistory:this.#y}),this.#h=Number(this.#a.metadata.versionId),this.#i=this.#a.didDocument,this.#c=[],fn.getBeaconServices(this.#i).some(n=>{let i=fn.parseBitcoinAddress(n.serviceEndpoint);return!this.#d.has(i)}))){if(++this.#p>this.#u)throw new rt(`Exceeded the configured maximum of ${this.#u} beacon-discovery rounds. Raise or remove ResolutionOptions.maxDiscoveryRounds to resolve this DID.`,cv,{maxDiscoveryRounds:this.#u,discoveryRounds:this.#p});this.#r="BeaconDiscovery";continue}this.#r="Complete";continue}case"Complete":return{status:"resolved",result:this.#a??{didDocument:this.#i,metadata:{versionId:this.#t??"1",deactivated:this.#i.deactivated||!1}}}}}provide(e,r){switch(e.kind){case"NeedGenesisDocument":{if(!hf(r))throw new rt("Provided data for NeedGenesisDocument must be a document object.",Ne,{kind:e.kind});this.#s=r;break}case"NeedBeaconSignals":{if(!(r instanceof Map))throw new rt("Provided data for NeedBeaconSignals must be a Map of beacon services to signals.",Ne,{kind:e.kind});for(let[n,i]of r)this.#f.set(n,i);break}case"NeedCASAnnouncement":{if(!wL(r))throw new rt("Provided data for NeedCASAnnouncement is not a CAS announcement.",Ne,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.announcementHash)throw new rt(`CAS announcement hash mismatch: expected ${e.announcementHash}, got ${n}.`,Ne,{expected:e.announcementHash,actual:n});this.#o.casMap.set(n,r);break}case"NeedSignedUpdate":{if(!bL(r))throw new rt("Provided data for NeedSignedUpdate is not a signed BTCR2 update.",Ne,{kind:e.kind});let n=Gn(r,{encoding:"hex"});if(n!==e.updateHash)throw new rt(`Signed update hash mismatch: expected ${e.updateHash}, got ${n}.`,Ne,{expected:e.updateHash,actual:n});this.#o.updateMap.set(n,r);break}case"NeedSMTProof":{if(!xL(r))throw new rt("Provided data for NeedSMTProof is not an SMT proof.",Ne,{kind:e.kind});let n=Zr(Is(r.id,"base64urlnopad"),"hex");if(n!==e.smtRootHash)throw new rt(`SMT proof root hash mismatch: expected ${e.smtRootHash}, got ${n}`,Ne,{expected:e.smtRootHash,actual:n});this.#o.smtMap.set(e.smtRootHash,r);break}}}};function EL(t){let e=t.capabilityInvocation?.[0];if(e===void 0)throw new Ze("Cannot derive aggregation communication key: capabilityInvocation is absent",Ue,{id:t.id});let r=typeof e=="string"?t.verificationMethod?.find(n=>n.id===e):e;if(!r)throw new Ze(`Cannot derive aggregation communication key: capabilityInvocation[0] "${e}" does not resolve to a verification method`,Ue,{id:t.id,invocation:e});return cs.fromVerificationMethod(r).publicKey}function bne(t,e){try{let r=xr.decode(t);if(r.idType==="KEY")return new ht(r.genesisBytes);if(e?.genesisDocument){let n=as.external(r,e.genesisDocument);return EL(n)}}catch{}}l();l();l();var PB=class{document={};constructor(e){if(!e.id)throw new Ze('Missing required "id" property',Ue,e);this.document.id=e.id,this.document.verificationMethod=e.verificationMethod??[],e["@context"]&&(this.document["@context"]=e["@context"])}withAuthentication(e){return e&&(this.document.authentication=e),this}withAssertionMethod(e){return e&&(this.document.assertionMethod=e),this}withCapabilityInvocation(e){return e&&(this.document.capabilityInvocation=e),this}withCapabilityDelegation(e){return e&&(this.document.capabilityDelegation=e),this}withService(e){return e&&(this.document.service=e),this}build(){let e=new hn(this.document);for(let r of Object.keys(e))e[r]===void 0&&delete e[r];return e}};export{hv as AggregateBeaconError,Kr as Appendix,Pre as BECH32M_CHARS,yL as BTCR2_DID_DOCUMENT_CONTEXT,rr as BeaconError,ra as BeaconFactory,kB as BeaconSignalDiscovery,fn as BeaconUtils,Al as CASBeacon,pv as CASBeaconError,gv as CHANGE_OUTPUT_VBYTES,I0 as DEFAULT_FEE_ESTIMATOR,gL as DID_REGEX,mv as DUST_LIMIT_SATS,zp as DidBtcr2,hn as DidDocument,PB as DidDocumentBuilder,jb as DidVerificationMethod,Wb as GenesisDocument,ln as ID_PLACEHOLDER_VALUE,xr as Identifier,cu as MULTIKEY_PUBLIC_KEY_MULTIBASE_PREFIX,su as MULTIKEY_VERIFICATION_METHOD_TYPE,$R as P2PKH_BEACON_TX_VSIZE,MR as P2TR_BEACON_TX_VSIZE,KR as P2WPKH_BEACON_TX_VSIZE,as as Resolver,HR as SINGLETON_BEACON_TX_VSIZE,Nl as SMTBeacon,Fu as SMTBeaconError,R0 as SPENDABLE_DUST_LIMIT_SATS,Ro as SinglePartyBeacon,Tl as SingletonBeacon,lv as SingletonBeaconError,ju as StaticFeeEstimator,Gp as Updater,wv as beaconTxVsize,T7 as buildAggregationBeaconTx,VR as deriveSingletonAddress,bv as detectSingletonScriptKind,DB as extractOpReturnSignal,EL as getAggregationCommunicationKey,mL as isMultikeyVerificationMethod,vv as opReturnScript,bne as resolveBtcr2SenderPk,xv as resolveChangeAddress,FR as selectSpendableUtxo};
4
4
  /*! Bundled license information:
5
5
 
6
6
  ieee754/index.js: